diff --git a/README.md b/README.md index 154df8298fab5ecf322016157858e08cd1bccbe1..d268dc2f3d02cfb0bc6aa2e2f0fa644f6ef6dc4b 100644 --- a/README.md +++ b/README.md @@ -1,3 +1,69 @@ --- license: apache-2.0 +task_categories: + - text-generation +language: + - en +tags: + - code-generation + - software-engineering + - benchmark + - long-horizon + - harbor +size_categories: + - n<1K +configs: + - config_name: default + data_files: + - split: train + path: tasks_overview.jsonl --- + +# LoLBench + +LoLBench (Long-horizon Tasks on Large Software Projects) evaluates coding agents on complex, repository-level software engineering tasks. This dataset export contains only the 100 Harbor-format tasks prepared from the repository's `artifact` branch. + +The source task directories are included at the dataset root. The `tasks_overview.jsonl` file provides a compact dataset-viewer representation similar to RoadmapBench. + +## Dataset viewer schema + +| Column | Description | +| --- | --- | +| `task_id` | Harbor task identifier. | +| `language` | Normalized implementation language or language combination. | +| `domain` | Broad software-project domain. | +| `instruction` | Complete contents of the task's `instruction.md`. | +| `f2p` | Overall fail-to-pass suite as test selectors only. | +| `p2p` | Overall pass-to-pass suite as test selectors only. | +| `solution` | Complete contents of `solution/solution.patch`. | + +`f2p` and `p2p` use the canonical overall suite: the original selectors followed by the augmented selectors in execution order. Repeated selectors are retained because they are part of the executed suite. These columns do not contain test implementations or test patch contents. + +## Task layout + +Each task directory contains the Harbor task definition and its associated assets: + +```text +/ +├── environment/ +├── solution/ +│ └── solution.patch +├── tests/ +├── instruction.md +├── README.md +└── task.toml +``` + +The task metadata records the upstream repository, base commit, target merge/solution commit, and published container image. The canonical verifier mode is `union`, which evaluates the overall original-plus-augmented test suites represented in the viewer. + +## Provenance and validation + +This export was prepared from source commit `679d4983b9aa131cd79b9abfb2cdca30d4eb0329` on the `artifact` branch. During export, task identifiers, repository metadata, full base and target commit SHAs, source-audit metadata, selector types, recorded asset checksums, and required task files were checked for consistency. All 200 declared base and merge commit references resolved against their upstream GitHub repositories. + +On 2026-09-19, the current `linux/amd64` image for every task was pulled from Docker Hub and the ground-truth `solution/solution.patch` was evaluated in canonical `union` mode. All 100/100 tasks resolved with reward `1.0`: F2P passed 2,234/2,234 selectors and P2P passed 5,660/5,660 selectors. + +The [`validation/dockerhub_validation.json`](validation/dockerhub_validation.json) manifest records the immutable Docker Hub index and `linux/amd64` platform digest used for every task, together with its verifier totals and validation timestamp. It is validation metadata only and is intentionally excluded from the dataset-viewer configuration. In the 11 task specifications that exposed Docker Hub metadata at the top level, those fields describe the current `lolbench-linux` image; nested, dated `harbor_validation_summary` objects remain unchanged as historical arm64 validation evidence. + +Export-time consistency corrections expanded two abbreviated Kubernetes target SHAs, synchronized seven solution-patch checksums and nine other packaged test-asset checksums, and replaced the stale `cpython_5` base reference with the actual parent of its declared squash merge. The corrected `cpython_5` solution patch was also checked to apply cleanly to that base. JDK verifier launchers were made architecture-aware for both `x86_64` and `aarch64`, and all packaged verifier shell scripts passed syntax checks. + +LoLBench-authored benchmark metadata and tooling are released under Apache-2.0. Individual upstream projects and incorporated materials remain subject to their respective licenses. diff --git a/TypeScript_1/README.md b/TypeScript_1/README.md new file mode 100644 index 0000000000000000000000000000000000000000..31726216f07b11c38f8f1d5b0b1dc9c723795963 --- /dev/null +++ b/TypeScript_1/README.md @@ -0,0 +1,87 @@ +# LoLBench Harbor Task: TypeScript_1 + +This is a Harbor-format LoLBench task generated from `TypeScript_Issue-47920_satisfies-operator-to-ensure-an-expression-matches-some-type-safe-upcast_PR-46827`. + +Selected source instance: + +- Harbor ID: `TypeScript_1` +- PR: `microsoft/TypeScript#46827` +- Base commit: `07157914eb26a6e9abdcda7255c4094c9efff4cd` +- Test modes: `orig, aug, union` +- Default/canonical mode: `union` +- Harbor image: `smartdub26/lolbench-linux:TypeScript_1-1.0.0` +- Docker Hub image: `smartdub26/lolbench-linux:TypeScript_1-1.0.0` + +## Image Setup + +Prefer the published Docker Hub image when it is available. Harbor refers to +the image as `smartdub26/lolbench-linux:TypeScript_1-1.0.0`, so Docker can pull it +directly when it is not present locally: + +```bash +docker pull smartdub26/lolbench-linux:TypeScript_1-1.0.0 +``` + +Only if the Docker Hub image is unavailable, build the single task image +locally: + +```bash +docker build -t lolbench/typescript_1:1.0.0 harbor_tasks/TypeScript_1/environment +docker tag lolbench/typescript_1:1.0.0 smartdub26/lolbench-linux:TypeScript_1-1.0.0 +``` + +The image contains the processed source tree at the base commit under +`/workspace/typescript`. Harbor must not mount a host source checkout +for the agent. + +## Run an Agent + +```bash +.harbor-venv/bin/harbor run \ + -p harbor_tasks/TypeScript_1 \ + -a codex \ + -m "" \ + --job-name TypeScript_1_agent_union \ + --jobs-dir harbor_runs/TypeScript_1 \ + --no-delete \ + --n-concurrent 1 \ + --ve LOLBENCH_SUITE=union +``` + +After implementing the requirement, the agent must clean any test-file edits +and run: + +```bash +lolbench-submit +``` + +## Evaluate a Patch + +Choose one mode with `LOLBENCH_SUITE=orig`, `aug`, or `union`; if unset, the +task defaults to `union`. + +```bash +PATCH="$(pwd)/path/to/solution.patch" + +.harbor-venv/bin/harbor run \ + -p harbor_tasks/TypeScript_1 \ + -a oracle \ + --job-name TypeScript_1_eval_union \ + --jobs-dir harbor_runs/TypeScript_1 \ + --no-delete \ + --n-concurrent 1 \ + --mounts '[{"type":"bind","source":"'"$PATCH"'","target":"/candidate/solution.patch","read_only":true}]' \ + --ae LOLBENCH_ORACLE_PATCH=/candidate/solution.patch \ + --ve LOLBENCH_SUITE=union +``` + +Outputs: + +```bash +find harbor_runs/TypeScript_1/TypeScript_1_eval_union -path '*/verifier/agent_report.json' -print +find harbor_runs/TypeScript_1/TypeScript_1_eval_union -path '*/verifier/reward.json' -print +``` + +`tests/docker-compose.yaml` is a verifier-only Harbor overlay. It mounts +`tests/`, `tests/private/`, and `solution/` into the separate verifier +container; none of those paths are mounted into the agent container. diff --git a/TypeScript_1/environment/Dockerfile b/TypeScript_1/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..95aa4f7ecee8eb448a740c480732bc5f47411e80 --- /dev/null +++ b/TypeScript_1/environment/Dockerfile @@ -0,0 +1,104 @@ +# LoLBench eval image: TypeScript PR-46827 (satisfies operator) +# Requirement: https://github.com/microsoft/TypeScript/issues/47920 +# base_commit: 07157914eb26a6e9abdcda7255c4094c9efff4cd +# (parent of the squash-merge 164dddc4 on main) +# +# Agent-facing contract (the agent only ever produces a solution.patch; +# the evaluator runs the container): +# +# docker run --rm \ +# --network=none \ +# -v $(pwd)/solution.patch:/in/solution.patch:ro \ +# -v $(pwd)/out:/out \ +# lolbench/apache-ts-pr-46827:1 +# +# Layered build: +# layer 1: ubuntu:22.04 +# layer 2: lolbench/typescript-base:1 (Node 16 + git + build deps) +# layer 3: THIS image (TS @ base + npm install + gulp local) + +ARG BASE_IMAGE=lolbench/typescript-base:1 +FROM ${BASE_IMAGE} + +ARG BASE_COMMIT=07157914eb26a6e9abdcda7255c4094c9efff4cd + +RUN mkdir -p /opt/lolbench/private /in /out /workspace + +WORKDIR /workspace +RUN git init typescript && \ + cd typescript && \ + git remote add origin https://github.com/microsoft/TypeScript.git && \ + git fetch --no-tags origin ${BASE_COMMIT} && \ + git checkout ${BASE_COMMIT} && \ + git ls-files -z > /tmp/typescript-base-files && \ + git config user.email lolbench@local && \ + git config user.name lolbench && \ + if ! git diff --quiet || ! git diff --cached --quiet || [ -n "$(git ls-files --others --exclude-standard)" ]; then \ + git add -A && git -c commit.gpgsign=false commit -q -m "LoLBench environment overlay"; \ + fi && \ + git tag -f base && git tag -f lolbench-base && \ + git for-each-ref --format='%(refname)' refs/heads refs/remotes refs/tags | \ + while read ref; do \ + case "$ref" in refs/tags/base|refs/tags/lolbench-base) ;; *) git update-ref -d "$ref" ;; esac; \ + done && \ + ( git remote remove origin 2>/dev/null || true ) && \ + rm -f .git/FETCH_HEAD && \ + git reflog expire --expire=now --all && \ + git repack -Ad && \ + git prune --expire=now && \ + rm /tmp/typescript-base-files && \ + git config --global --add safe.directory /workspace/typescript + +# ---- Install deps + build TypeScript from the base sources. +# The runtests harness needs both built/local/* (the compiled tsc and +# test runners) AND node_modules/* installed. npm install is ~3 min, +# gulp local is ~5 min, gulp tests is ~2 min on a 4-core host. +RUN cd /workspace/typescript && \ + npm install --no-progress --no-fund --no-audit && \ + npx gulp local && \ + npx gulp tests + +# ---- Eval bundle ------------------------------------------------------ + +# Harbor runtime adapter: keep the image public/agent-safe. +RUN mkdir -p /opt/lolbench /logs/artifacts /logs/agent /logs/verifier /in /out && \ + if ! id -u agent >/dev/null 2>&1; then useradd -m -s /bin/bash agent; fi +COPY metadata.json /opt/lolbench/metadata.json +COPY lolbench-submit /usr/local/bin/lolbench-submit +RUN chmod +x /usr/local/bin/lolbench-submit && \ + git config --global --add safe.directory /workspace/typescript && \ + if [ -d /workspace/typescript/.git ]; then \ + cd /workspace/typescript && LC_ALL=C git ls-files --others --exclude-standard | LC_ALL=C sort > /opt/lolbench/base_untracked.txt; \ + else \ + : > /opt/lolbench/base_untracked.txt; \ + fi && \ + chown -R agent:agent /workspace/typescript /logs +ENV HOME=/home/agent +# Local-reference hardening: retain only the approved base history. +RUN git config --system --add safe.directory /workspace/typescript && \ + cd /workspace/typescript && \ + git for-each-ref --format='%(refname)' refs/heads refs/remotes refs/tags | \ + while read ref; do \ + case "$ref" in refs/tags/base|refs/tags/lolbench-base) ;; *) git update-ref -d "$ref" ;; esac; \ + done && \ + ( git remote remove origin 2>/dev/null || true ) && \ + rm -f .git/FETCH_HEAD && \ + git reflog expire --expire=now --all && \ + git repack -Ad && \ + git prune --expire=now && \ + unreachable=$(git fsck --unreachable --no-reflogs) && \ + test -z "$unreachable" && \ + chown -R agent:agent .git +# Keep npm executable but remove cached/global copies of TypeScript sources. +RUN rm -rf /root/.npm /home/agent/.npm && \ + rm -f /usr/local/bin/tsc /usr/local/bin/tsserver /usr/bin/tsc /usr/bin/tsserver && \ + for p in /usr/local/lib/node_modules /usr/lib/node_modules; do \ + if [ -d "$p" ]; then \ + find "$p" -mindepth 1 -maxdepth 1 -type d -iname typescript -exec rm -rf '{}' +; \ + chown -R root:root "$p"; chmod -R go-w "$p"; chmod 0711 "$p"; \ + fi; \ + done +USER agent +WORKDIR /workspace/typescript +ENV LOLBENCH_INSTANCE_ID=TypeScript_1 +ENV LOLBENCH_SOURCE_SLUG=TypeScript_Issue-47920_satisfies-operator-to-ensure-an-expression-matches-some-type-safe-upcast_PR-46827 diff --git a/TypeScript_1/environment/docker-compose.yaml b/TypeScript_1/environment/docker-compose.yaml new file mode 100644 index 0000000000000000000000000000000000000000..7ed45f87dc9faf9df284f5b10d6d2289781ff254 --- /dev/null +++ b/TypeScript_1/environment/docker-compose.yaml @@ -0,0 +1,3 @@ +services: + main: + pull_policy: missing diff --git a/TypeScript_1/environment/lolbench-submit b/TypeScript_1/environment/lolbench-submit new file mode 100644 index 0000000000000000000000000000000000000000..b3426184f1a568aaf145f148348c3c5e85cfa773 --- /dev/null +++ b/TypeScript_1/environment/lolbench-submit @@ -0,0 +1,33 @@ +#!/usr/bin/env bash +set -euo pipefail +export LC_ALL=C + +repo=${1:-$PWD} +out=${LOLBENCH_PATCH_OUT:-/logs/artifacts/solution.patch} + +mkdir -p "$(dirname "$out")" +cd "$repo" + +baseline=/opt/lolbench/base_untracked.txt +current=$(mktemp) +new_files=$(mktemp) +trap 'rm -f "$current" "$new_files"' EXIT + +git ls-files --others --exclude-standard | sort > "$current" +if [ -f "$baseline" ]; then + comm -13 "$baseline" "$current" > "$new_files" +else + cp "$current" "$new_files" +fi + +if [ -s "$new_files" ]; then + xargs -r git add -N -- < "$new_files" +fi + +git diff --binary > "$out" + +if [ ! -s "$out" ]; then + echo "warning: wrote an empty solution patch to $out" >&2 +else + echo "wrote solution patch to $out" +fi diff --git a/TypeScript_1/environment/metadata.json b/TypeScript_1/environment/metadata.json new file mode 100644 index 0000000000000000000000000000000000000000..14c5723fa3ec2de299225227520ab212b18dca40 --- /dev/null +++ b/TypeScript_1/environment/metadata.json @@ -0,0 +1,22 @@ +{ + "instance_id": "TypeScript_1", + "source_instance_id": "TypeScript_Issue-47920_satisfies-operator-to-ensure-an-expression-matches-some-type-safe-upcast_PR-46827", + "source_slug": "TypeScript_Issue-47920_satisfies-operator-to-ensure-an-expression-matches-some-type-safe-upcast_PR-46827", + "docker_slug": "TypeScript_Issue-47920_satisfies-operator-to-ensure-an-expression-matches-some-type-safe-upcast_PR-46827", + "dockerhub_image": "smartdub26/lolbench-linux:TypeScript_1-1.0.0", + "project": "TypeScript", + "repo": "microsoft/TypeScript", + "requirement_doc": "https://github.com/microsoft/TypeScript/issues/47920", + "pr_link": "https://github.com/microsoft/TypeScript/pull/46827", + "base_commit": "07157914eb26a6e9abdcda7255c4094c9efff4cd", + "merge_commit": "a73f1c7ce4b97bf13e6c3f2341412b0216d92933", + "source_history_policy": "ancestors-only", + "lolbench_test_modes": [ + "orig", + "aug", + "union" + ], + "default_lolbench_suite": "union", + "canonical_lolbench_suite": "union", + "augmentation_available": true +} diff --git a/TypeScript_1/environment/source_audit.json b/TypeScript_1/environment/source_audit.json new file mode 100644 index 0000000000000000000000000000000000000000..d0a46b2006cebaeba8133d6d1d2016d07726e33a --- /dev/null +++ b/TypeScript_1/environment/source_audit.json @@ -0,0 +1,7 @@ +{ + "source_policy": "dockerfile_fetch_pruned_ancestor_history", + "local_reference_policy": "auxiliary_sources_removed_execute_only", + "base_commit": "07157914eb26a6e9abdcda7255c4094c9efff4cd", + "repo": "microsoft/TypeScript", + "note": "The Dockerfile fetches only the declared base history, removes refs/remotes/reflogs, repacks and prunes unreachable objects, asserts that git fsck finds no unreachable object, removes auxiliary reference sources, and makes remaining auxiliary toolchains root-owned and non-enumerable to the agent." +} diff --git a/TypeScript_1/instruction.md b/TypeScript_1/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..a320b5c4181c6c99238bbbfbe90703c7b844f229 --- /dev/null +++ b/TypeScript_1/instruction.md @@ -0,0 +1,362 @@ +You are working in `/workspace/typescript`, a source tree checked out at +the base commit for this task. Implement the requested behavior in the source +tree, then run: + +```bash +lolbench-submit +``` + +Do not stop after editing files, running tests, or describing the solution. The +task is complete only when `lolbench-submit` has created +`/logs/artifacts/solution.patch`. If that file does not exist, continue +working and run `lolbench-submit` again. + +That command writes your implementation diff to +`/logs/artifacts/solution.patch`, which is the artifact the Harbor verifier +will grade. Before running `lolbench-submit`, clean or revert any test files +you created or modified; test files must not be included in the final +`solution.patch`. + +This environment has no outbound internet access — `curl`/`wget`, `git fetch`/`clone`, package installs, and web fetch/search will all fail. Implement the requirements using only the code already in the workspace and your own knowledge; do not attempt to fetch or search external resources. + +Now please implement the following requirements in the source tree: + +--- + +# "satisfies" operator to ensure an expression matches some type (feedback reset) + +# Feature Update - February 2022 + +This is a feedback reset for #7481 to get a fresh start and clarify where we are with this feature. I really thought this was going to be simpler, but it's turned out to be a bit of a rat's nest! + +Let's start with what kind of scenarios we think need to be addressed. + +## Scenario Candidates + +First, here's a review of scenarios I've collected from reading the linked issue and its many duplicates. **Please post if you have other scenarios that seem relevant**. I'll go into it later, but *not all these scenarios can be satisfied at once* for reasons that will hopefully become obvious. + +### Safe Upcast + +Frequently in places where control flow analysis hits some limitation (hi #9998), it's desirable to "undo" the specificity of an initializer. A good example would be +```ts +let a = false; +upd(); +if (a === true) { +// ^^^ error, true and false have no overlap + // ... +} +function upd() { + if (someCondition) a = true; +} +``` +The canonical recommendation is to type-assert the initializer: +```ts +let a = false as boolean; +``` +but there's limited type safety here since you could accidently downcast without realizing it: +```ts +type Animal = { kind: "cat", meows: true } | { kind: "dog", barks: true }; +let p = { kind: "cat" } as Animal; // Missing meows! +upd(); +if (p.kind === "dog") { + +} else { + p.meows; // Reported 'true', actually 'undefined' +} +function upd() { + if (Math.random() > 0.5) p = { kind: "dog", barks: true }; +} +``` + +The safest workaround is to have a dummy function, `function up(arg: T): T`: +```ts +let a = up(true); +``` +which is unfortunate due to having unnecessary runtime impact. + +Instead, we would presumably write +```ts +let p = { kind: "cat", meows: true } satisfies Animal; +``` + +### Property Name Constraining + +We might want to make a lookup table where the property keys must come from some predefined subset, but not lose type information about what each property's value was: +```ts +type Keys = 'a' | 'b' | 'c' | 'd'; + +const p = { + a: 0, + b: "hello", + x: 8 // Should error, 'x' isn't in 'Keys' +}; + +// Should be OK -- retain info that a is number and b is string +let a = p.a.toFixed(); +let b = p.b.substr(1); +// Should error even though 'd' is in 'Keys' +let d = p.d; +``` +There is no obvious workaround here today. + +Instead, we would presumably write +```ts +const p = { + a: 0, + b: "hello", + x: 8 // Should error, 'x' isn't in 'Keys' +} satisfies Partial>; +// using 'Partial' to indicate it's OK 'd' is missing +``` + +### Property Name Fulfillment + +Same as Property Name Constraining, except we might want to ensure that we get *all* of the keys: + +```ts +type Keys = 'a' | 'b' | 'c' | 'd'; + +const p = { + a: 0, + b: "hello", + c: true + // Should error because 'd' is missing +}; +// Should be OK +const t: boolean = p.c; +``` + +The closest available workaround is: +```ts +const dummy: Record = p; +``` +but this assignment a) has runtime impact and b) will not detect excess properties. + +Instead, we would presumably write +```ts +const p = { + a: 0, + b: "hello", + c: true + // will error because 'd' is missing +} satisfies Record; +``` + +### Property Value Conformance + +This is the flipside of Property Name Constraining - we might want to make sure that all *property values* in an object conform to some type, but still keep record of which keys are present: +```ts +type Facts = { [key: string]: boolean }; +declare function checkTruths(x: Facts): void; +declare function checkM(x: { m: boolean }): void; +const x = { + m: true +}; + +// Should be OK +checkTruths(x); +// Should be OK +fn(x); +// Should fail under --noIndexSignaturePropertyAccess +console.log(x.z); +// Should be OK under --noUncheckedIndexedAccess +const m: boolean = x.m; + +// Should be 'm' +type M = keyof typeof x; + +// Should be able to detect a failure here +const x2 = { + m: true, + s: "false" +}; +``` + +Another example +```ts +export type Color = { r: number, g: number, b: number }; + +// All of these should be Colors, but I only use some of them here. +export const Palette = { + white: { r: 255, g: 255, b: 255}, + black: { r: 0, g: 0, d: 0}, // <- oops! 'd' in place of 'b' + blue: { r: 0, g: 0, b: 255 }, +}; +``` + +Here, we would presumably write +```ts +const Palette = { + white: { r: 255, g: 255, b: 255}, + black: { r: 0, g: 0, d: 0}, // <- error is now detected + blue: { r: 0, g: 0, b: 255 }, +} satisfies Record; +``` + +### Ensure Interface Implementation + +We might want to leverage type inference, but still check that something conforms to an interface and use that interface to provide contextual typing: +```ts +type Movable = { + move(distance: number): void; +}; + +const car = { + start() { }, + move(d) { + // d should be number + }, + stop() { } +}; +``` + +Here, we would presumably write +```ts +const car = { + start() { }, + move(d) { + // d: number + }, + stop() { } +} satisfies Moveable; +``` + +### Optional Member Conformance + +We might want to initialize a value conforming to some weakly-typed interface: +```ts +type Point2d = { x: number, y: number }; +// Undesirable behavior today with type annotation +const a: Partial = { x: 10 }; +// Errors, but should be OK -- we know x is there +console.log(a.x.toFixed()); +// OK, but should be an error -- we know y is missing +let p = a.y; +``` + +### Optional Member Addition + +Conversely, we might want to safely initialize a variable according to some type but retain information about the members which aren't present: +```ts +type Point2d = { x: number, y: number }; +const a: Partial = { x: 10 }; +// Should be OK +a.x.toFixed(); +// Should be OK, y is present, just not initialized +a.y = 3; +``` + +### Contextual Typing + +TypeScript has a process called *contextual typing* in which expressions which would otherwise not have an inferrable type can get an inferred type from context: +```ts +// a: implicit any +const f1 = a => { }; + +// a: string +const f2: (s: string) => void = a => { }; +``` + +In all of the above scenarios, contextual typing would always be appropriate. For example, in *Property Value Conformance* +```ts +type Predicates = { [s: string]: (n: number) => boolean }; + +const p: Predicates = { + isEven: n => n % 2 === 0, + isOdd: n => n % 2 === 1 +}; +``` +Contextually providing the `n` parameters a `number` type is clearly desirable. In most other places than parameters, the contextual typing of an expression is not directly observable except insofar as normally-disallowed assignments become allowable. + +## Desired Behavior Rundown + +There are three plausible contenders for what to infer for the type of an `e satisfies T` expression: + * `typeof e` + * `T` + * `T & typeof e` + +*SATA: Same As Type Annotation - `const v = e satisfies T` would do the same as `const v: T = e`, thus no additional value is provided + +|Scenario|`T`|`typeof e`|`T & typeof e`| +|--------|---|----------|--------------| +|Safe Upcast|✔|❌ (undoes the upcasting)|❌ (undoes the upcasting)| +|Property Name Constraining|❌ (SATA)|✔|✔| +|Property Name Fulfillment|❌ (SATA)|✔|✔| +|Ensure Interface Implementation|❌ (SATA)|✔|✔| +|Optional Member Conformance|❌ (SATA)|✔|❌ (members appear when not desired)| +|Optional Member Addition|❌ (SATA)|❌ (members do not appear when desired)|✔| +|Contextual Typing|✔|✔|✔| + +### Discussion + +Given the value of the other scenarios, I think *safe upcast* needs to be discarded. One could imagine other solutions to this problem, e.g. marking a particular variable as "volatile" such that narrowings no longer apply to it, or simply by having better side-effect tracking. + +### Excess Properties + +A sidenote here on excess properties. Consider this case: +```ts +type Point = { + x: number, + y: number +}; +const origin = { + x: 0, + y: 0, + z: 0 // OK or error? +} satisifes Point; +``` + +Is `z` an excess property? + +One argument says yes, because in other positions where that object literal was used where a `Point` was expected, it would be. Additionally, if we want to detect typos (as in the *property name constraining* scenario), then detecting excess properties is mandatory. + +The other argument says no, because the point of excess property checks is to detect properties which are "lost" due to not having their presence captured by the type system, and the design of the `satisfies` operator is specifically for scenarios where the ultimate type of all properties *is* captured somewhere. + +I think on balance, the "yes" argument is stronger. If we don't flag excess properties, then the *property name constraining* scenario can't be made to work at all. In places where excess properties are expected, `e satisfies (T & Record)` can be written instead. + +However, under this solution, producing the expression type `T & typeof e` becomes very undesirable: +```ts +type Point2d = { x: number, y: number }; +const a = { x: 10, z: 0 } satisfies Partial & Record; +// Arbitrary writes allowed (super bad) +a.blah = 10; +``` + +Side note: It's tempting to say that properties aren't excess if all of the satisfied type's properties are matched. I don't think this is satisfactory because it doesn't really clearly define what would happen with the asserted-to type is `Partial`, which is likely common: +```ts +type Keys = 'a' | 'b' | 'c'; +// Property 'd' might be intentional excess *or* a typo of e.g. 'b' +const v = { a: 0, d: 0 } satisfies Partial>; +``` + +Producing `typeof e` then leads to another problem... + +### The Empty Array Problem + +Under `--strict` (specifically `strictNullChecks && noImplicitAny`), empty arrays in positions where they can't be Evolving Arrays get the type `never[]`. This leads to some somewhat annoying behavior today: +```ts +let m = { value: [] }; +// Error, can't assign 'number' to 'never' +m.value.push(3); +``` + +The `satisfies` operator might be thought to fix this: +```ts +type BoxOfArray = { value: T[] }; +let m = { value: [] } satisfies BoxOfArray +// OK, right? I just said it was OK? +m.value.push(3); +``` + +However, under current semantics (including `m: typeof e`), this still doesn't work, because the type of the array is still `never[]`. + +It seems like this can be fixed with a targeted change to empty arrays, which I've prototyped at #47898. It's possible there are unintended downstream consequences of this (changes like this can often foul up generic inference in ways that aren't obvious), but it seems to be OK for now. + +## TL;DR + +It seems like the best place we could land is: + * Contextually type empty arrays + * Disallow excess properties (unless you write `T & Record`) + * Use `typeof e` as the expression type instead of `T` or `T & typeof e` + +Does this seem right? What did I miss? diff --git a/TypeScript_1/solution/solution.patch b/TypeScript_1/solution/solution.patch new file mode 100644 index 0000000000000000000000000000000000000000..5f2428a79f0b8c957c2138f645a2ebe83081910b --- /dev/null +++ b/TypeScript_1/solution/solution.patch @@ -0,0 +1,507 @@ +diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts +index 0999b8b4eb..321592bcd4 100644 +--- a/src/compiler/checker.ts ++++ b/src/compiler/checker.ts +@@ -27506,6 +27506,8 @@ namespace ts { + } + case SyntaxKind.NonNullExpression: + return getContextualType(parent as NonNullExpression, contextFlags); ++ case SyntaxKind.SatisfiesExpression: ++ return getTypeFromTypeNode((parent as SatisfiesExpression).type); + case SyntaxKind.ExportAssignment: + return tryGetTypeFromEffectiveTypeNode(parent as ExportAssignment); + case SyntaxKind.JsxExpression: +@@ -32442,6 +32444,20 @@ namespace ts { + } + } + ++ function checkSatisfiesExpression(node: SatisfiesExpression) { ++ checkSourceElement(node.type); ++ ++ const targetType = getTypeFromTypeNode(node.type); ++ if (isErrorType(targetType)) { ++ return targetType; ++ } ++ ++ const exprType = checkExpression(node.expression); ++ checkTypeAssignableToAndOptionallyElaborate(exprType, targetType, node.type, node.expression, Diagnostics.Type_0_does_not_satisfy_the_expected_type_1); ++ ++ return exprType; ++ } ++ + function checkMetaProperty(node: MetaProperty): Type { + checkGrammarMetaProperty(node); + +@@ -35235,6 +35251,8 @@ namespace ts { + return checkNonNullAssertion(node as NonNullExpression); + case SyntaxKind.ExpressionWithTypeArguments: + return checkExpressionWithTypeArguments(node as ExpressionWithTypeArguments); ++ case SyntaxKind.SatisfiesExpression: ++ return checkSatisfiesExpression(node as SatisfiesExpression); + case SyntaxKind.MetaProperty: + return checkMetaProperty(node as MetaProperty); + case SyntaxKind.DeleteExpression: +diff --git a/src/compiler/diagnosticMessages.json b/src/compiler/diagnosticMessages.json +index e1f62fe842..2656c48383 100644 +--- a/src/compiler/diagnosticMessages.json ++++ b/src/compiler/diagnosticMessages.json +@@ -1100,7 +1100,7 @@ + "category": "Error", + "code": 1359 + }, +- "Class constructor may not be a generator.": { ++ "Type '{0}' does not satisfy the expected type '{1}'.": { + "category": "Error", + "code": 1360 + }, +@@ -1132,6 +1132,10 @@ + "category": "Message", + "code": 1367 + }, ++ "Class constructor may not be a generator.": { ++ "category": "Error", ++ "code": 1368 ++ }, + "Did you mean '{0}'?": { + "category": "Message", + "code": 1369 +@@ -6376,6 +6380,10 @@ + "category": "Error", + "code": 8036 + }, ++ "Type satisfaction expressions can only be used in TypeScript files.": { ++ "category": "Error", ++ "code": 8037 ++ }, + + "Declaration emit for this file requires using private name '{0}'. An explicit type annotation may unblock declaration emit.": { + "category": "Error", +diff --git a/src/compiler/emitter.ts b/src/compiler/emitter.ts +index d3008431ab..4e571c49a8 100644 +--- a/src/compiler/emitter.ts ++++ b/src/compiler/emitter.ts +@@ -1763,6 +1763,8 @@ namespace ts { + return emitNonNullExpression(node as NonNullExpression); + case SyntaxKind.ExpressionWithTypeArguments: + return emitExpressionWithTypeArguments(node as ExpressionWithTypeArguments); ++ case SyntaxKind.SatisfiesExpression: ++ return emitSatisfiesExpression(node as SatisfiesExpression); + case SyntaxKind.MetaProperty: + return emitMetaProperty(node as MetaProperty); + case SyntaxKind.SyntheticExpression: +@@ -2846,6 +2848,16 @@ namespace ts { + writeOperator("!"); + } + ++ function emitSatisfiesExpression(node: SatisfiesExpression) { ++ emitExpression(node.expression, /*parenthesizerRules*/ undefined); ++ if (node.type) { ++ writeSpace(); ++ writeKeyword("satisfies"); ++ writeSpace(); ++ emit(node.type); ++ } ++ } ++ + function emitMetaProperty(node: MetaProperty) { + writeToken(node.keywordToken, node.pos, writePunctuation); + writePunctuation("."); +diff --git a/src/compiler/factory/nodeFactory.ts b/src/compiler/factory/nodeFactory.ts +index 399dfd9d64..f072083e15 100644 +--- a/src/compiler/factory/nodeFactory.ts ++++ b/src/compiler/factory/nodeFactory.ts +@@ -222,6 +222,8 @@ namespace ts { + updateAsExpression, + createNonNullExpression, + updateNonNullExpression, ++ createSatisfiesExpression, ++ updateSatisfiesExpression, + createNonNullChain, + updateNonNullChain, + createMetaProperty, +@@ -3142,6 +3144,26 @@ namespace ts { + : node; + } + ++ // @api ++ function createSatisfiesExpression(expression: Expression, type: TypeNode) { ++ const node = createBaseExpression(SyntaxKind.SatisfiesExpression); ++ node.expression = expression; ++ node.type = type; ++ node.transformFlags |= ++ propagateChildFlags(node.expression) | ++ propagateChildFlags(node.type) | ++ TransformFlags.ContainsTypeScript; ++ return node; ++ } ++ ++ // @api ++ function updateSatisfiesExpression(node: SatisfiesExpression, expression: Expression, type: TypeNode) { ++ return node.expression !== expression ++ || node.type !== type ++ ? update(createSatisfiesExpression(expression, type), node) ++ : node; ++ } ++ + // @api + function createNonNullChain(expression: Expression) { + const node = createBaseExpression(SyntaxKind.NonNullExpression); +@@ -5730,6 +5752,7 @@ namespace ts { + case SyntaxKind.ParenthesizedExpression: return updateParenthesizedExpression(outerExpression, expression); + case SyntaxKind.TypeAssertionExpression: return updateTypeAssertion(outerExpression, outerExpression.type, expression); + case SyntaxKind.AsExpression: return updateAsExpression(outerExpression, expression, outerExpression.type); ++ case SyntaxKind.SatisfiesExpression: return updateSatisfiesExpression(outerExpression, expression, outerExpression.type); + case SyntaxKind.NonNullExpression: return updateNonNullExpression(outerExpression, expression); + case SyntaxKind.PartiallyEmittedExpression: return updatePartiallyEmittedExpression(outerExpression, expression); + } +@@ -6465,6 +6488,7 @@ namespace ts { + case SyntaxKind.ArrayBindingPattern: + return TransformFlags.BindingPatternExcludes; + case SyntaxKind.TypeAssertionExpression: ++ case SyntaxKind.SatisfiesExpression: + case SyntaxKind.AsExpression: + case SyntaxKind.PartiallyEmittedExpression: + case SyntaxKind.ParenthesizedExpression: +diff --git a/src/compiler/factory/nodeTests.ts b/src/compiler/factory/nodeTests.ts +index 903dea149a..f44c913640 100644 +--- a/src/compiler/factory/nodeTests.ts ++++ b/src/compiler/factory/nodeTests.ts +@@ -438,6 +438,10 @@ namespace ts { + return node.kind === SyntaxKind.AsExpression; + } + ++ export function isSatisfiesExpression(node: Node): node is SatisfiesExpression { ++ return node.kind === SyntaxKind.SatisfiesExpression; ++ } ++ + export function isNonNullExpression(node: Node): node is NonNullExpression { + return node.kind === SyntaxKind.NonNullExpression; + } +diff --git a/src/compiler/factory/utilities.ts b/src/compiler/factory/utilities.ts +index 9fbbdb165d..7cb707a90a 100644 +--- a/src/compiler/factory/utilities.ts ++++ b/src/compiler/factory/utilities.ts +@@ -437,6 +437,7 @@ namespace ts { + return (kinds & OuterExpressionKinds.Parentheses) !== 0; + case SyntaxKind.TypeAssertionExpression: + case SyntaxKind.AsExpression: ++ case SyntaxKind.SatisfiesExpression: + return (kinds & OuterExpressionKinds.TypeAssertions) !== 0; + case SyntaxKind.NonNullExpression: + return (kinds & OuterExpressionKinds.NonNullAssertions) !== 0; +diff --git a/src/compiler/parser.ts b/src/compiler/parser.ts +index 93939b6f4f..faab2b0620 100644 +--- a/src/compiler/parser.ts ++++ b/src/compiler/parser.ts +@@ -393,6 +393,9 @@ namespace ts { + [SyntaxKind.NonNullExpression]: function forEachChildInNonNullExpression(node: NonNullExpression, cbNode: (node: Node) => T | undefined, _cbNodes?: (nodes: NodeArray) => T | undefined): T | undefined { + return visitNode(cbNode, node.expression); + }, ++ [SyntaxKind.SatisfiesExpression]: function forEachChildInSatisfiesExpression(node: SatisfiesExpression, cbNode: (node: Node) => T | undefined, _cbNodes?: (nodes: NodeArray) => T | undefined): T | undefined { ++ return visitNode(cbNode, node.expression) || visitNode(cbNode, node.type); ++ }, + [SyntaxKind.MetaProperty]: function forEachChildInMetaProperty(node: MetaProperty, cbNode: (node: Node) => T | undefined, _cbNodes?: (nodes: NodeArray) => T | undefined): T | undefined { + return visitNode(cbNode, node.name); + }, +@@ -841,7 +844,6 @@ namespace ts { + if (node === undefined || node.kind <= SyntaxKind.LastToken) { + return; + } +- + const fn = (forEachChildTable as Record>)[node.kind]; + return fn === undefined ? undefined : fn(node, cbNode, cbNodes); + } +@@ -5109,7 +5111,7 @@ namespace ts { + break; + } + +- if (token() === SyntaxKind.AsKeyword) { ++ if (token() === SyntaxKind.AsKeyword || token() === SyntaxKind.SatisfiesKeyword) { + // Make sure we *do* perform ASI for constructs like this: + // var x = foo + // as (Bar) +@@ -5119,8 +5121,10 @@ namespace ts { + break; + } + else { ++ const keywordKind = token(); + nextToken(); +- leftOperand = makeAsExpression(leftOperand, parseType()); ++ leftOperand = keywordKind === SyntaxKind.SatisfiesKeyword ? makeSatisfiesExpression(leftOperand, parseType()) : ++ makeAsExpression(leftOperand, parseType()); + } + } + else { +@@ -5139,6 +5143,10 @@ namespace ts { + return getBinaryOperatorPrecedence(token()) > 0; + } + ++ function makeSatisfiesExpression(left: Expression, right: TypeNode): SatisfiesExpression { ++ return finishNode(factory.createSatisfiesExpression(left, right), left.pos); ++ } ++ + function makeBinaryExpression(left: Expression, operatorToken: BinaryOperatorToken, right: Expression, pos: number): BinaryExpression { + return finishNode(factory.createBinaryExpression(left, operatorToken, right), pos); + } +diff --git a/src/compiler/program.ts b/src/compiler/program.ts +index e7c0f363ea..2c71fde33d 100644 +--- a/src/compiler/program.ts ++++ b/src/compiler/program.ts +@@ -2372,6 +2372,9 @@ namespace ts { + case SyntaxKind.AsExpression: + diagnostics.push(createDiagnosticForNode((node as AsExpression).type, Diagnostics.Type_assertion_expressions_can_only_be_used_in_TypeScript_files)); + return "skip"; ++ case SyntaxKind.SatisfiesExpression: ++ diagnostics.push(createDiagnosticForNode((node as SatisfiesExpression).type, Diagnostics.Type_satisfaction_expressions_can_only_be_used_in_TypeScript_files)); ++ return "skip"; + case SyntaxKind.TypeAssertionExpression: + Debug.fail(); // Won't parse these in a JS file anyway, as they are interpreted as JSX. + } +diff --git a/src/compiler/scanner.ts b/src/compiler/scanner.ts +index 107ff3a143..05ae6268d7 100644 +--- a/src/compiler/scanner.ts ++++ b/src/compiler/scanner.ts +@@ -136,6 +136,7 @@ namespace ts { + require: SyntaxKind.RequireKeyword, + global: SyntaxKind.GlobalKeyword, + return: SyntaxKind.ReturnKeyword, ++ satisfies: SyntaxKind.SatisfiesKeyword, + set: SyntaxKind.SetKeyword, + static: SyntaxKind.StaticKeyword, + string: SyntaxKind.StringKeyword, +diff --git a/src/compiler/transformers/ts.ts b/src/compiler/transformers/ts.ts +index 61b982d7f2..0f27255590 100644 +--- a/src/compiler/transformers/ts.ts ++++ b/src/compiler/transformers/ts.ts +@@ -529,6 +529,9 @@ namespace ts { + // TypeScript type assertions are removed, but their subtrees are preserved. + return visitAssertionExpression(node as AssertionExpression); + ++ case SyntaxKind.SatisfiesExpression: ++ return visitSatisfiesExpression(node as SatisfiesExpression); ++ + case SyntaxKind.CallExpression: + return visitCallExpression(node as CallExpression); + +@@ -1421,6 +1424,11 @@ namespace ts { + return factory.createPartiallyEmittedExpression(expression, node); + } + ++ function visitSatisfiesExpression(node: SatisfiesExpression): Expression { ++ const expression = visitNode(node.expression, visitor, isExpression); ++ return factory.createPartiallyEmittedExpression(expression, node); ++ } ++ + function visitCallExpression(node: CallExpression) { + return factory.updateCallExpression( + node, +diff --git a/src/compiler/types.ts b/src/compiler/types.ts +index 73fefe7637..31bdb48f75 100644 +--- a/src/compiler/types.ts ++++ b/src/compiler/types.ts +@@ -181,6 +181,7 @@ namespace ts { + RequireKeyword, + NumberKeyword, + ObjectKeyword, ++ SatisfiesKeyword, + SetKeyword, + StringKeyword, + SymbolKeyword, +@@ -274,6 +275,7 @@ namespace ts { + NonNullExpression, + MetaProperty, + SyntheticExpression, ++ SatisfiesExpression, + + // Misc + TemplateSpan, +@@ -607,6 +609,7 @@ namespace ts { + | SyntaxKind.OverrideKeyword + | SyntaxKind.RequireKeyword + | SyntaxKind.ReturnKeyword ++ | SyntaxKind.SatisfiesKeyword + | SyntaxKind.SetKeyword + | SyntaxKind.StaticKeyword + | SyntaxKind.StringKeyword +@@ -1007,6 +1010,7 @@ namespace ts { + | ExpressionWithTypeArguments + | AsExpression + | NonNullExpression ++ | SatisfiesExpression + | MetaProperty + | TemplateSpan + | Block +@@ -2815,6 +2819,12 @@ namespace ts { + readonly expression: UnaryExpression; + } + ++ export interface SatisfiesExpression extends Expression { ++ readonly kind: SyntaxKind.SatisfiesExpression; ++ readonly expression: Expression; ++ readonly type: TypeNode; ++ } ++ + export type AssertionExpression = + | TypeAssertion + | AsExpression +@@ -7520,6 +7530,7 @@ namespace ts { + export type OuterExpression = + | ParenthesizedExpression + | TypeAssertion ++ | SatisfiesExpression + | AsExpression + | NonNullExpression + | PartiallyEmittedExpression; +@@ -7856,6 +7867,8 @@ namespace ts { + updateNonNullChain(node: NonNullChain, expression: Expression): NonNullChain; + createMetaProperty(keywordToken: MetaProperty["keywordToken"], name: Identifier): MetaProperty; + updateMetaProperty(node: MetaProperty, name: Identifier): MetaProperty; ++ createSatisfiesExpression(expression: Expression, type: TypeNode): SatisfiesExpression; ++ updateSatisfiesExpression(node: SatisfiesExpression, expression: Expression, type: TypeNode): SatisfiesExpression; + + // + // Misc +diff --git a/src/compiler/utilities.ts b/src/compiler/utilities.ts +index 62a941df1f..c2ff0ab4fc 100644 +--- a/src/compiler/utilities.ts ++++ b/src/compiler/utilities.ts +@@ -1995,6 +1995,7 @@ namespace ts { + case SyntaxKind.TaggedTemplateExpression: + case SyntaxKind.AsExpression: + case SyntaxKind.TypeAssertionExpression: ++ case SyntaxKind.SatisfiesExpression: + case SyntaxKind.NonNullExpression: + case SyntaxKind.ParenthesizedExpression: + case SyntaxKind.FunctionExpression: +@@ -2095,6 +2096,8 @@ namespace ts { + return (parent as ExpressionWithTypeArguments).expression === node && !isPartOfTypeNode(parent); + case SyntaxKind.ShorthandPropertyAssignment: + return (parent as ShorthandPropertyAssignment).objectAssignmentInitializer === node; ++ case SyntaxKind.SatisfiesExpression: ++ return node === (parent as SatisfiesExpression).expression; + default: + return isExpressionNode(parent); + } +@@ -3801,6 +3804,7 @@ namespace ts { + return OperatorPrecedence.Member; + + case SyntaxKind.AsExpression: ++ case SyntaxKind.SatisfiesExpression: + return OperatorPrecedence.Relational; + + case SyntaxKind.ThisKeyword: +@@ -3859,6 +3863,7 @@ namespace ts { + case SyntaxKind.InstanceOfKeyword: + case SyntaxKind.InKeyword: + case SyntaxKind.AsKeyword: ++ case SyntaxKind.SatisfiesKeyword: + return OperatorPrecedence.Relational; + case SyntaxKind.LessThanLessThanToken: + case SyntaxKind.GreaterThanGreaterThanToken: +@@ -5930,7 +5935,8 @@ namespace ts { + case SyntaxKind.PropertyAccessExpression: + case SyntaxKind.NonNullExpression: + case SyntaxKind.PartiallyEmittedExpression: +- node = (node as CallExpression | PropertyAccessExpression | ElementAccessExpression | AsExpression | NonNullExpression | PartiallyEmittedExpression).expression; ++ case SyntaxKind.SatisfiesExpression: ++ node = (node as CallExpression | PropertyAccessExpression | ElementAccessExpression | AsExpression | NonNullExpression | PartiallyEmittedExpression | SatisfiesExpression).expression; + continue; + } + +diff --git a/src/compiler/utilitiesPublic.ts b/src/compiler/utilitiesPublic.ts +index 229620a119..bc80f301e3 100644 +--- a/src/compiler/utilitiesPublic.ts ++++ b/src/compiler/utilitiesPublic.ts +@@ -1642,6 +1642,7 @@ namespace ts { + case SyntaxKind.OmittedExpression: + case SyntaxKind.CommaListExpression: + case SyntaxKind.PartiallyEmittedExpression: ++ case SyntaxKind.SatisfiesExpression: + return true; + default: + return isUnaryExpressionKind(kind); +diff --git a/src/compiler/visitorPublic.ts b/src/compiler/visitorPublic.ts +index 29a112b062..02eeee55ad 100644 +--- a/src/compiler/visitorPublic.ts ++++ b/src/compiler/visitorPublic.ts +@@ -888,13 +888,19 @@ namespace ts { + nodeVisitor(node.type, visitor, isTypeNode)); + }, + ++ [SyntaxKind.SatisfiesExpression]: function visitEachChildOfSatisfiesExpression(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { ++ return context.factory.updateSatisfiesExpression(node, ++ nodeVisitor(node.expression, visitor, isExpression), ++ nodeVisitor(node.type, visitor, isTypeNode)); ++ }, ++ + [SyntaxKind.NonNullExpression]: function visitEachChildOfNonNullExpression(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { + return isOptionalChain(node) ? + context.factory.updateNonNullChain(node, + nodeVisitor(node.expression, visitor, isExpression)) : + context.factory.updateNonNullExpression(node, + nodeVisitor(node.expression, visitor, isExpression)); +- }, ++ }, + + [SyntaxKind.MetaProperty]: function visitEachChildOfMetaProperty(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { + return context.factory.updateMetaProperty(node, +diff --git a/src/services/callHierarchy.ts b/src/services/callHierarchy.ts +index 1cbe4e58ad..5219698a44 100644 +--- a/src/services/callHierarchy.ts ++++ b/src/services/callHierarchy.ts +@@ -449,6 +449,10 @@ namespace ts.CallHierarchy { + recordCallSite(node as AccessExpression); + forEachChild(node, collect); + break; ++ case SyntaxKind.SatisfiesExpression: ++ // do not descend into the type side of an assertion ++ collect((node as SatisfiesExpression).expression); ++ return; + } + + if (isPartOfTypeNode(node)) { +diff --git a/src/services/classifier.ts b/src/services/classifier.ts +index 1b6705efed..ac15be962a 100644 +--- a/src/services/classifier.ts ++++ b/src/services/classifier.ts +@@ -369,6 +369,7 @@ namespace ts { + case SyntaxKind.InstanceOfKeyword: + case SyntaxKind.InKeyword: + case SyntaxKind.AsKeyword: ++ case SyntaxKind.SatisfiesKeyword: + case SyntaxKind.EqualsEqualsToken: + case SyntaxKind.ExclamationEqualsToken: + case SyntaxKind.EqualsEqualsEqualsToken: +diff --git a/src/services/completions.ts b/src/services/completions.ts +index bcc6efca67..36724b760a 100644 +--- a/src/services/completions.ts ++++ b/src/services/completions.ts +@@ -2675,6 +2675,9 @@ namespace ts.Completions { + + case SyntaxKind.ExtendsKeyword: + return parentKind === SyntaxKind.TypeParameter; ++ ++ case SyntaxKind.SatisfiesKeyword: ++ return parentKind === SyntaxKind.SatisfiesExpression; + } + } + return false; +@@ -3962,6 +3965,7 @@ namespace ts.Completions { + return kind === SyntaxKind.AsyncKeyword + || kind === SyntaxKind.AwaitKeyword + || kind === SyntaxKind.AsKeyword ++ || kind === SyntaxKind.SatisfiesKeyword + || kind === SyntaxKind.TypeKeyword + || !isContextualKeyword(kind) && !isClassMemberCompletionKeyword(kind); + } +diff --git a/src/services/formatting/rules.ts b/src/services/formatting/rules.ts +index 76cd5aa6e4..144f97831b 100644 +--- a/src/services/formatting/rules.ts ++++ b/src/services/formatting/rules.ts +@@ -449,5 +449,6 @@ namespace ts.formatting { + case SyntaxKind.TypePredicate: + case SyntaxKind.UnionType: + case SyntaxKind.IntersectionType: ++ case SyntaxKind.SatisfiesExpression: + return true; + diff --git a/TypeScript_1/solution/solve.sh b/TypeScript_1/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..04d2cdd558a05593c6373ab47313e0e441927403 --- /dev/null +++ b/TypeScript_1/solution/solve.sh @@ -0,0 +1,7 @@ +#!/usr/bin/env bash +set -euo pipefail + +cd /workspace/typescript +patch=${LOLBENCH_ORACLE_PATCH:-/solution/solution.patch} +git apply "$patch" +lolbench-submit diff --git a/TypeScript_1/task.toml b/TypeScript_1/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..f15481a97b7a6c2948920f0062e9253fe5208f7b --- /dev/null +++ b/TypeScript_1/task.toml @@ -0,0 +1,60 @@ +schema_version = "1.3" + +[task] +name = "lolbench/TypeScript_1" +description = "Implement TypeScript satisfies operator." +authors = [{ name = "LoLBench maintainers" }] +keywords = ["lolbench", "coding-agent", "typescript"] + +[metadata] +instance_id = "TypeScript_1" +source_instance_id = "TypeScript_Issue-47920_satisfies-operator-to-ensure-an-expression-matches-some-type-safe-upcast_PR-46827" +source_slug = "TypeScript_Issue-47920_satisfies-operator-to-ensure-an-expression-matches-some-type-safe-upcast_PR-46827" +docker_slug = "TypeScript_Issue-47920_satisfies-operator-to-ensure-an-expression-matches-some-type-safe-upcast_PR-46827" +dockerhub_image = "smartdub26/lolbench-linux:TypeScript_1-1.0.0" +project = "TypeScript" +repo = "microsoft/TypeScript" +requirement_doc = "https://github.com/microsoft/TypeScript/issues/47920" +pr_link = "https://github.com/microsoft/TypeScript/pull/46827" +base_commit = "07157914eb26a6e9abdcda7255c4094c9efff4cd" +merge_commit = "a73f1c7ce4b97bf13e6c3f2341412b0216d92933" +test_level = "system" +source_history_policy = "ancestors-only" +lolbench_test_modes = ["orig", "aug", "union"] +default_lolbench_suite = "union" +canonical_lolbench_suite = "union" +augmentation_available = true +verifier_network_policy = "public" +verifier_network_reason = "The Harbor verifier runs in a separate container and may use network access; migrated LoLBench verifier assets are mounted only in the verifier phase." + +[environment] +build_timeout_sec = 3600.0 +docker_image = "smartdub26/lolbench-linux:TypeScript_1-1.0.0" +network_mode = "public" +os = "linux" +cpus = 4 +memory_mb = 7168 +storage_mb = 20480 + +[agent] +timeout_sec = 21600.0 +user = "agent" +network_mode = "allowlist" +allowed_hosts = ["openrouter.ai", "api.openai.com", "api.anthropic.com"] + +[verifier] +timeout_sec = 7200.0 +user = "root" +environment_mode = "separate" +network_mode = "public" + +[verifier.env] +LOLBENCH_SUITE = "union" + +[verifier.environment] +docker_image = "smartdub26/lolbench-linux:TypeScript_1-1.0.0" +network_mode = "public" +os = "linux" +cpus = 4 +memory_mb = 7168 +storage_mb = 20480 diff --git a/TypeScript_1/tests/docker-compose.yaml b/TypeScript_1/tests/docker-compose.yaml new file mode 100644 index 0000000000000000000000000000000000000000..f5091b9298e127a1efbe69deeed699c907e025c1 --- /dev/null +++ b/TypeScript_1/tests/docker-compose.yaml @@ -0,0 +1,16 @@ +services: + main: + pull_policy: missing + volumes: + - type: bind + source: . + target: /tests + read_only: true + - type: bind + source: ./private + target: /opt/lolbench/private + read_only: true + - type: bind + source: ../solution + target: /solution + read_only: true diff --git a/TypeScript_1/tests/private/eval_tests.patch b/TypeScript_1/tests/private/eval_tests.patch new file mode 100644 index 0000000000000000000000000000000000000000..9dc081fc3b020355121273f18965f545463281f6 --- /dev/null +++ b/TypeScript_1/tests/private/eval_tests.patch @@ -0,0 +1,4408 @@ +diff --git a/src/harness/harnessIO.ts b/src/harness/harnessIO.ts +index 2786498d41..505101de93 100644 +--- a/src/harness/harnessIO.ts ++++ b/src/harness/harnessIO.ts +@@ -1382,7 +1382,17 @@ namespace Harness { + } + + const encodedActual = Utils.encodeString(actual); +- if (expected !== encodedActual) { ++ // LoLBench (TypeScript_1): the satisfies PR arbitrarily REPURPOSED diagnostic ++ // code TS1360 for its new "does not satisfy the expected type" message (base ++ // 1360 was "Class constructor may not be a generator."). The numeric code is ++ // compiler-assigned and gold-specific, so for these four satisfies conformance ++ // error baselines we compare on the diagnostic MESSAGE/behaviour and ignore the ++ // exact TS#### number (see docs/lolbench_f2p_requirement_audit.md TypeScript_1). ++ const normalizeSatisfiesDiagCode = (s: string): string => ++ /(^|[\\/])(typeSatisfaction|typeSatisfactionWithDefaultExport|typeSatisfaction_propNameConstraining|typeSatisfaction_propertyNameFulfillment)\.errors\.txt$/.test(relativeFileName) ++ ? s.replace(/error TS\d+:/g, "error TS####:") ++ : s; ++ if (normalizeSatisfiesDiagCode(expected) !== normalizeSatisfiesDiagCode(encodedActual)) { + if (actual === noContent) { + IO.writeFile(actualFileName + ".delete", ""); + } +diff --git a/tests/baselines/reference/api/tsserverlibrary.d.ts b/tests/baselines/reference/api/tsserverlibrary.d.ts +index 89e52380ac..e377bbec17 100644 +--- a/tests/baselines/reference/api/tsserverlibrary.d.ts ++++ b/tests/baselines/reference/api/tsserverlibrary.d.ts +@@ -254,215 +254,217 @@ declare namespace ts { + RequireKeyword = 146, + NumberKeyword = 147, + ObjectKeyword = 148, +- SetKeyword = 149, +- StringKeyword = 150, +- SymbolKeyword = 151, +- TypeKeyword = 152, +- UndefinedKeyword = 153, +- UniqueKeyword = 154, +- UnknownKeyword = 155, +- FromKeyword = 156, +- GlobalKeyword = 157, +- BigIntKeyword = 158, +- OverrideKeyword = 159, +- OfKeyword = 160, +- QualifiedName = 161, +- ComputedPropertyName = 162, +- TypeParameter = 163, +- Parameter = 164, +- Decorator = 165, +- PropertySignature = 166, +- PropertyDeclaration = 167, +- MethodSignature = 168, +- MethodDeclaration = 169, +- ClassStaticBlockDeclaration = 170, +- Constructor = 171, +- GetAccessor = 172, +- SetAccessor = 173, +- CallSignature = 174, +- ConstructSignature = 175, +- IndexSignature = 176, +- TypePredicate = 177, +- TypeReference = 178, +- FunctionType = 179, +- ConstructorType = 180, +- TypeQuery = 181, +- TypeLiteral = 182, +- ArrayType = 183, +- TupleType = 184, +- OptionalType = 185, +- RestType = 186, +- UnionType = 187, +- IntersectionType = 188, +- ConditionalType = 189, +- InferType = 190, +- ParenthesizedType = 191, +- ThisType = 192, +- TypeOperator = 193, +- IndexedAccessType = 194, +- MappedType = 195, +- LiteralType = 196, +- NamedTupleMember = 197, +- TemplateLiteralType = 198, +- TemplateLiteralTypeSpan = 199, +- ImportType = 200, +- ObjectBindingPattern = 201, +- ArrayBindingPattern = 202, +- BindingElement = 203, +- ArrayLiteralExpression = 204, +- ObjectLiteralExpression = 205, +- PropertyAccessExpression = 206, +- ElementAccessExpression = 207, +- CallExpression = 208, +- NewExpression = 209, +- TaggedTemplateExpression = 210, +- TypeAssertionExpression = 211, +- ParenthesizedExpression = 212, +- FunctionExpression = 213, +- ArrowFunction = 214, +- DeleteExpression = 215, +- TypeOfExpression = 216, +- VoidExpression = 217, +- AwaitExpression = 218, +- PrefixUnaryExpression = 219, +- PostfixUnaryExpression = 220, +- BinaryExpression = 221, +- ConditionalExpression = 222, +- TemplateExpression = 223, +- YieldExpression = 224, +- SpreadElement = 225, +- ClassExpression = 226, +- OmittedExpression = 227, +- ExpressionWithTypeArguments = 228, +- AsExpression = 229, +- NonNullExpression = 230, +- MetaProperty = 231, +- SyntheticExpression = 232, +- TemplateSpan = 233, +- SemicolonClassElement = 234, +- Block = 235, +- EmptyStatement = 236, +- VariableStatement = 237, +- ExpressionStatement = 238, +- IfStatement = 239, +- DoStatement = 240, +- WhileStatement = 241, +- ForStatement = 242, +- ForInStatement = 243, +- ForOfStatement = 244, +- ContinueStatement = 245, +- BreakStatement = 246, +- ReturnStatement = 247, +- WithStatement = 248, +- SwitchStatement = 249, +- LabeledStatement = 250, +- ThrowStatement = 251, +- TryStatement = 252, +- DebuggerStatement = 253, +- VariableDeclaration = 254, +- VariableDeclarationList = 255, +- FunctionDeclaration = 256, +- ClassDeclaration = 257, +- InterfaceDeclaration = 258, +- TypeAliasDeclaration = 259, +- EnumDeclaration = 260, +- ModuleDeclaration = 261, +- ModuleBlock = 262, +- CaseBlock = 263, +- NamespaceExportDeclaration = 264, +- ImportEqualsDeclaration = 265, +- ImportDeclaration = 266, +- ImportClause = 267, +- NamespaceImport = 268, +- NamedImports = 269, +- ImportSpecifier = 270, +- ExportAssignment = 271, +- ExportDeclaration = 272, +- NamedExports = 273, +- NamespaceExport = 274, +- ExportSpecifier = 275, +- MissingDeclaration = 276, +- ExternalModuleReference = 277, +- JsxElement = 278, +- JsxSelfClosingElement = 279, +- JsxOpeningElement = 280, +- JsxClosingElement = 281, +- JsxFragment = 282, +- JsxOpeningFragment = 283, +- JsxClosingFragment = 284, +- JsxAttribute = 285, +- JsxAttributes = 286, +- JsxSpreadAttribute = 287, +- JsxExpression = 288, +- CaseClause = 289, +- DefaultClause = 290, +- HeritageClause = 291, +- CatchClause = 292, +- AssertClause = 293, +- AssertEntry = 294, +- ImportTypeAssertionContainer = 295, +- PropertyAssignment = 296, +- ShorthandPropertyAssignment = 297, +- SpreadAssignment = 298, +- EnumMember = 299, +- UnparsedPrologue = 300, +- UnparsedPrepend = 301, +- UnparsedText = 302, +- UnparsedInternalText = 303, +- UnparsedSyntheticReference = 304, +- SourceFile = 305, +- Bundle = 306, +- UnparsedSource = 307, +- InputFiles = 308, +- JSDocTypeExpression = 309, +- JSDocNameReference = 310, +- JSDocMemberName = 311, +- JSDocAllType = 312, +- JSDocUnknownType = 313, +- JSDocNullableType = 314, +- JSDocNonNullableType = 315, +- JSDocOptionalType = 316, +- JSDocFunctionType = 317, +- JSDocVariadicType = 318, +- JSDocNamepathType = 319, +- JSDoc = 320, ++ SatisfiesKeyword = 149, ++ SetKeyword = 150, ++ StringKeyword = 151, ++ SymbolKeyword = 152, ++ TypeKeyword = 153, ++ UndefinedKeyword = 154, ++ UniqueKeyword = 155, ++ UnknownKeyword = 156, ++ FromKeyword = 157, ++ GlobalKeyword = 158, ++ BigIntKeyword = 159, ++ OverrideKeyword = 160, ++ OfKeyword = 161, ++ QualifiedName = 162, ++ ComputedPropertyName = 163, ++ TypeParameter = 164, ++ Parameter = 165, ++ Decorator = 166, ++ PropertySignature = 167, ++ PropertyDeclaration = 168, ++ MethodSignature = 169, ++ MethodDeclaration = 170, ++ ClassStaticBlockDeclaration = 171, ++ Constructor = 172, ++ GetAccessor = 173, ++ SetAccessor = 174, ++ CallSignature = 175, ++ ConstructSignature = 176, ++ IndexSignature = 177, ++ TypePredicate = 178, ++ TypeReference = 179, ++ FunctionType = 180, ++ ConstructorType = 181, ++ TypeQuery = 182, ++ TypeLiteral = 183, ++ ArrayType = 184, ++ TupleType = 185, ++ OptionalType = 186, ++ RestType = 187, ++ UnionType = 188, ++ IntersectionType = 189, ++ ConditionalType = 190, ++ InferType = 191, ++ ParenthesizedType = 192, ++ ThisType = 193, ++ TypeOperator = 194, ++ IndexedAccessType = 195, ++ MappedType = 196, ++ LiteralType = 197, ++ NamedTupleMember = 198, ++ TemplateLiteralType = 199, ++ TemplateLiteralTypeSpan = 200, ++ ImportType = 201, ++ ObjectBindingPattern = 202, ++ ArrayBindingPattern = 203, ++ BindingElement = 204, ++ ArrayLiteralExpression = 205, ++ ObjectLiteralExpression = 206, ++ PropertyAccessExpression = 207, ++ ElementAccessExpression = 208, ++ CallExpression = 209, ++ NewExpression = 210, ++ TaggedTemplateExpression = 211, ++ TypeAssertionExpression = 212, ++ ParenthesizedExpression = 213, ++ FunctionExpression = 214, ++ ArrowFunction = 215, ++ DeleteExpression = 216, ++ TypeOfExpression = 217, ++ VoidExpression = 218, ++ AwaitExpression = 219, ++ PrefixUnaryExpression = 220, ++ PostfixUnaryExpression = 221, ++ BinaryExpression = 222, ++ ConditionalExpression = 223, ++ TemplateExpression = 224, ++ YieldExpression = 225, ++ SpreadElement = 226, ++ ClassExpression = 227, ++ OmittedExpression = 228, ++ ExpressionWithTypeArguments = 229, ++ AsExpression = 230, ++ NonNullExpression = 231, ++ MetaProperty = 232, ++ SyntheticExpression = 233, ++ SatisfiesExpression = 234, ++ TemplateSpan = 235, ++ SemicolonClassElement = 236, ++ Block = 237, ++ EmptyStatement = 238, ++ VariableStatement = 239, ++ ExpressionStatement = 240, ++ IfStatement = 241, ++ DoStatement = 242, ++ WhileStatement = 243, ++ ForStatement = 244, ++ ForInStatement = 245, ++ ForOfStatement = 246, ++ ContinueStatement = 247, ++ BreakStatement = 248, ++ ReturnStatement = 249, ++ WithStatement = 250, ++ SwitchStatement = 251, ++ LabeledStatement = 252, ++ ThrowStatement = 253, ++ TryStatement = 254, ++ DebuggerStatement = 255, ++ VariableDeclaration = 256, ++ VariableDeclarationList = 257, ++ FunctionDeclaration = 258, ++ ClassDeclaration = 259, ++ InterfaceDeclaration = 260, ++ TypeAliasDeclaration = 261, ++ EnumDeclaration = 262, ++ ModuleDeclaration = 263, ++ ModuleBlock = 264, ++ CaseBlock = 265, ++ NamespaceExportDeclaration = 266, ++ ImportEqualsDeclaration = 267, ++ ImportDeclaration = 268, ++ ImportClause = 269, ++ NamespaceImport = 270, ++ NamedImports = 271, ++ ImportSpecifier = 272, ++ ExportAssignment = 273, ++ ExportDeclaration = 274, ++ NamedExports = 275, ++ NamespaceExport = 276, ++ ExportSpecifier = 277, ++ MissingDeclaration = 278, ++ ExternalModuleReference = 279, ++ JsxElement = 280, ++ JsxSelfClosingElement = 281, ++ JsxOpeningElement = 282, ++ JsxClosingElement = 283, ++ JsxFragment = 284, ++ JsxOpeningFragment = 285, ++ JsxClosingFragment = 286, ++ JsxAttribute = 287, ++ JsxAttributes = 288, ++ JsxSpreadAttribute = 289, ++ JsxExpression = 290, ++ CaseClause = 291, ++ DefaultClause = 292, ++ HeritageClause = 293, ++ CatchClause = 294, ++ AssertClause = 295, ++ AssertEntry = 296, ++ ImportTypeAssertionContainer = 297, ++ PropertyAssignment = 298, ++ ShorthandPropertyAssignment = 299, ++ SpreadAssignment = 300, ++ EnumMember = 301, ++ UnparsedPrologue = 302, ++ UnparsedPrepend = 303, ++ UnparsedText = 304, ++ UnparsedInternalText = 305, ++ UnparsedSyntheticReference = 306, ++ SourceFile = 307, ++ Bundle = 308, ++ UnparsedSource = 309, ++ InputFiles = 310, ++ JSDocTypeExpression = 311, ++ JSDocNameReference = 312, ++ JSDocMemberName = 313, ++ JSDocAllType = 314, ++ JSDocUnknownType = 315, ++ JSDocNullableType = 316, ++ JSDocNonNullableType = 317, ++ JSDocOptionalType = 318, ++ JSDocFunctionType = 319, ++ JSDocVariadicType = 320, ++ JSDocNamepathType = 321, ++ JSDoc = 322, + /** @deprecated Use SyntaxKind.JSDoc */ +- JSDocComment = 320, +- JSDocText = 321, +- JSDocTypeLiteral = 322, +- JSDocSignature = 323, +- JSDocLink = 324, +- JSDocLinkCode = 325, +- JSDocLinkPlain = 326, +- JSDocTag = 327, +- JSDocAugmentsTag = 328, +- JSDocImplementsTag = 329, +- JSDocAuthorTag = 330, +- JSDocDeprecatedTag = 331, +- JSDocClassTag = 332, +- JSDocPublicTag = 333, +- JSDocPrivateTag = 334, +- JSDocProtectedTag = 335, +- JSDocReadonlyTag = 336, +- JSDocOverrideTag = 337, +- JSDocCallbackTag = 338, +- JSDocEnumTag = 339, +- JSDocParameterTag = 340, +- JSDocReturnTag = 341, +- JSDocThisTag = 342, +- JSDocTypeTag = 343, +- JSDocTemplateTag = 344, +- JSDocTypedefTag = 345, +- JSDocSeeTag = 346, +- JSDocPropertyTag = 347, +- SyntaxList = 348, +- NotEmittedStatement = 349, +- PartiallyEmittedExpression = 350, +- CommaListExpression = 351, +- MergeDeclarationMarker = 352, +- EndOfDeclarationMarker = 353, +- SyntheticReferenceExpression = 354, +- Count = 355, ++ JSDocComment = 322, ++ JSDocText = 323, ++ JSDocTypeLiteral = 324, ++ JSDocSignature = 325, ++ JSDocLink = 326, ++ JSDocLinkCode = 327, ++ JSDocLinkPlain = 328, ++ JSDocTag = 329, ++ JSDocAugmentsTag = 330, ++ JSDocImplementsTag = 331, ++ JSDocAuthorTag = 332, ++ JSDocDeprecatedTag = 333, ++ JSDocClassTag = 334, ++ JSDocPublicTag = 335, ++ JSDocPrivateTag = 336, ++ JSDocProtectedTag = 337, ++ JSDocReadonlyTag = 338, ++ JSDocOverrideTag = 339, ++ JSDocCallbackTag = 340, ++ JSDocEnumTag = 341, ++ JSDocParameterTag = 342, ++ JSDocReturnTag = 343, ++ JSDocThisTag = 344, ++ JSDocTypeTag = 345, ++ JSDocTemplateTag = 346, ++ JSDocTypedefTag = 347, ++ JSDocSeeTag = 348, ++ JSDocPropertyTag = 349, ++ SyntaxList = 350, ++ NotEmittedStatement = 351, ++ PartiallyEmittedExpression = 352, ++ CommaListExpression = 353, ++ MergeDeclarationMarker = 354, ++ EndOfDeclarationMarker = 355, ++ SyntheticReferenceExpression = 356, ++ Count = 357, + FirstAssignment = 63, + LastAssignment = 78, + FirstCompoundAssignment = 64, +@@ -470,15 +472,15 @@ declare namespace ts { + FirstReservedWord = 81, + LastReservedWord = 116, + FirstKeyword = 81, +- LastKeyword = 160, ++ LastKeyword = 161, + FirstFutureReservedWord = 117, + LastFutureReservedWord = 125, +- FirstTypeNode = 177, +- LastTypeNode = 200, ++ FirstTypeNode = 178, ++ LastTypeNode = 201, + FirstPunctuation = 18, + LastPunctuation = 78, + FirstToken = 0, +- LastToken = 160, ++ LastToken = 161, + FirstTriviaToken = 2, + LastTriviaToken = 7, + FirstLiteralToken = 8, +@@ -487,19 +489,19 @@ declare namespace ts { + LastTemplateToken = 17, + FirstBinaryOperator = 29, + LastBinaryOperator = 78, +- FirstStatement = 237, +- LastStatement = 253, +- FirstNode = 161, +- FirstJSDocNode = 309, +- LastJSDocNode = 347, +- FirstJSDocTagNode = 327, +- LastJSDocTagNode = 347, ++ FirstStatement = 239, ++ LastStatement = 255, ++ FirstNode = 162, ++ FirstJSDocNode = 311, ++ LastJSDocNode = 349, ++ FirstJSDocTagNode = 329, ++ LastJSDocTagNode = 349, + } + export type TriviaSyntaxKind = SyntaxKind.SingleLineCommentTrivia | SyntaxKind.MultiLineCommentTrivia | SyntaxKind.NewLineTrivia | SyntaxKind.WhitespaceTrivia | SyntaxKind.ShebangTrivia | SyntaxKind.ConflictMarkerTrivia; + export type LiteralSyntaxKind = SyntaxKind.NumericLiteral | SyntaxKind.BigIntLiteral | SyntaxKind.StringLiteral | SyntaxKind.JsxText | SyntaxKind.JsxTextAllWhiteSpaces | SyntaxKind.RegularExpressionLiteral | SyntaxKind.NoSubstitutionTemplateLiteral; + export type PseudoLiteralSyntaxKind = SyntaxKind.TemplateHead | SyntaxKind.TemplateMiddle | SyntaxKind.TemplateTail; + export type PunctuationSyntaxKind = SyntaxKind.OpenBraceToken | SyntaxKind.CloseBraceToken | SyntaxKind.OpenParenToken | SyntaxKind.CloseParenToken | SyntaxKind.OpenBracketToken | SyntaxKind.CloseBracketToken | SyntaxKind.DotToken | SyntaxKind.DotDotDotToken | SyntaxKind.SemicolonToken | SyntaxKind.CommaToken | SyntaxKind.QuestionDotToken | SyntaxKind.LessThanToken | SyntaxKind.LessThanSlashToken | SyntaxKind.GreaterThanToken | SyntaxKind.LessThanEqualsToken | SyntaxKind.GreaterThanEqualsToken | SyntaxKind.EqualsEqualsToken | SyntaxKind.ExclamationEqualsToken | SyntaxKind.EqualsEqualsEqualsToken | SyntaxKind.ExclamationEqualsEqualsToken | SyntaxKind.EqualsGreaterThanToken | SyntaxKind.PlusToken | SyntaxKind.MinusToken | SyntaxKind.AsteriskToken | SyntaxKind.AsteriskAsteriskToken | SyntaxKind.SlashToken | SyntaxKind.PercentToken | SyntaxKind.PlusPlusToken | SyntaxKind.MinusMinusToken | SyntaxKind.LessThanLessThanToken | SyntaxKind.GreaterThanGreaterThanToken | SyntaxKind.GreaterThanGreaterThanGreaterThanToken | SyntaxKind.AmpersandToken | SyntaxKind.BarToken | SyntaxKind.CaretToken | SyntaxKind.ExclamationToken | SyntaxKind.TildeToken | SyntaxKind.AmpersandAmpersandToken | SyntaxKind.BarBarToken | SyntaxKind.QuestionQuestionToken | SyntaxKind.QuestionToken | SyntaxKind.ColonToken | SyntaxKind.AtToken | SyntaxKind.BacktickToken | SyntaxKind.HashToken | SyntaxKind.EqualsToken | SyntaxKind.PlusEqualsToken | SyntaxKind.MinusEqualsToken | SyntaxKind.AsteriskEqualsToken | SyntaxKind.AsteriskAsteriskEqualsToken | SyntaxKind.SlashEqualsToken | SyntaxKind.PercentEqualsToken | SyntaxKind.LessThanLessThanEqualsToken | SyntaxKind.GreaterThanGreaterThanEqualsToken | SyntaxKind.GreaterThanGreaterThanGreaterThanEqualsToken | SyntaxKind.AmpersandEqualsToken | SyntaxKind.BarEqualsToken | SyntaxKind.CaretEqualsToken; +- export type KeywordSyntaxKind = SyntaxKind.AbstractKeyword | SyntaxKind.AnyKeyword | SyntaxKind.AsKeyword | SyntaxKind.AssertsKeyword | SyntaxKind.AssertKeyword | SyntaxKind.AsyncKeyword | SyntaxKind.AwaitKeyword | SyntaxKind.BigIntKeyword | SyntaxKind.BooleanKeyword | SyntaxKind.BreakKeyword | SyntaxKind.CaseKeyword | SyntaxKind.CatchKeyword | SyntaxKind.ClassKeyword | SyntaxKind.ConstKeyword | SyntaxKind.ConstructorKeyword | SyntaxKind.ContinueKeyword | SyntaxKind.DebuggerKeyword | SyntaxKind.DeclareKeyword | SyntaxKind.DefaultKeyword | SyntaxKind.DeleteKeyword | SyntaxKind.DoKeyword | SyntaxKind.ElseKeyword | SyntaxKind.EnumKeyword | SyntaxKind.ExportKeyword | SyntaxKind.ExtendsKeyword | SyntaxKind.FalseKeyword | SyntaxKind.FinallyKeyword | SyntaxKind.ForKeyword | SyntaxKind.FromKeyword | SyntaxKind.FunctionKeyword | SyntaxKind.GetKeyword | SyntaxKind.GlobalKeyword | SyntaxKind.IfKeyword | SyntaxKind.ImplementsKeyword | SyntaxKind.ImportKeyword | SyntaxKind.InferKeyword | SyntaxKind.InKeyword | SyntaxKind.InstanceOfKeyword | SyntaxKind.InterfaceKeyword | SyntaxKind.IntrinsicKeyword | SyntaxKind.IsKeyword | SyntaxKind.KeyOfKeyword | SyntaxKind.LetKeyword | SyntaxKind.ModuleKeyword | SyntaxKind.NamespaceKeyword | SyntaxKind.NeverKeyword | SyntaxKind.NewKeyword | SyntaxKind.NullKeyword | SyntaxKind.NumberKeyword | SyntaxKind.ObjectKeyword | SyntaxKind.OfKeyword | SyntaxKind.PackageKeyword | SyntaxKind.PrivateKeyword | SyntaxKind.ProtectedKeyword | SyntaxKind.PublicKeyword | SyntaxKind.ReadonlyKeyword | SyntaxKind.OutKeyword | SyntaxKind.OverrideKeyword | SyntaxKind.RequireKeyword | SyntaxKind.ReturnKeyword | SyntaxKind.SetKeyword | SyntaxKind.StaticKeyword | SyntaxKind.StringKeyword | SyntaxKind.SuperKeyword | SyntaxKind.SwitchKeyword | SyntaxKind.SymbolKeyword | SyntaxKind.ThisKeyword | SyntaxKind.ThrowKeyword | SyntaxKind.TrueKeyword | SyntaxKind.TryKeyword | SyntaxKind.TypeKeyword | SyntaxKind.TypeOfKeyword | SyntaxKind.UndefinedKeyword | SyntaxKind.UniqueKeyword | SyntaxKind.UnknownKeyword | SyntaxKind.VarKeyword | SyntaxKind.VoidKeyword | SyntaxKind.WhileKeyword | SyntaxKind.WithKeyword | SyntaxKind.YieldKeyword; ++ export type KeywordSyntaxKind = SyntaxKind.AbstractKeyword | SyntaxKind.AnyKeyword | SyntaxKind.AsKeyword | SyntaxKind.AssertsKeyword | SyntaxKind.AssertKeyword | SyntaxKind.AsyncKeyword | SyntaxKind.AwaitKeyword | SyntaxKind.BigIntKeyword | SyntaxKind.BooleanKeyword | SyntaxKind.BreakKeyword | SyntaxKind.CaseKeyword | SyntaxKind.CatchKeyword | SyntaxKind.ClassKeyword | SyntaxKind.ConstKeyword | SyntaxKind.ConstructorKeyword | SyntaxKind.ContinueKeyword | SyntaxKind.DebuggerKeyword | SyntaxKind.DeclareKeyword | SyntaxKind.DefaultKeyword | SyntaxKind.DeleteKeyword | SyntaxKind.DoKeyword | SyntaxKind.ElseKeyword | SyntaxKind.EnumKeyword | SyntaxKind.ExportKeyword | SyntaxKind.ExtendsKeyword | SyntaxKind.FalseKeyword | SyntaxKind.FinallyKeyword | SyntaxKind.ForKeyword | SyntaxKind.FromKeyword | SyntaxKind.FunctionKeyword | SyntaxKind.GetKeyword | SyntaxKind.GlobalKeyword | SyntaxKind.IfKeyword | SyntaxKind.ImplementsKeyword | SyntaxKind.ImportKeyword | SyntaxKind.InferKeyword | SyntaxKind.InKeyword | SyntaxKind.InstanceOfKeyword | SyntaxKind.InterfaceKeyword | SyntaxKind.IntrinsicKeyword | SyntaxKind.IsKeyword | SyntaxKind.KeyOfKeyword | SyntaxKind.LetKeyword | SyntaxKind.ModuleKeyword | SyntaxKind.NamespaceKeyword | SyntaxKind.NeverKeyword | SyntaxKind.NewKeyword | SyntaxKind.NullKeyword | SyntaxKind.NumberKeyword | SyntaxKind.ObjectKeyword | SyntaxKind.OfKeyword | SyntaxKind.PackageKeyword | SyntaxKind.PrivateKeyword | SyntaxKind.ProtectedKeyword | SyntaxKind.PublicKeyword | SyntaxKind.ReadonlyKeyword | SyntaxKind.OutKeyword | SyntaxKind.OverrideKeyword | SyntaxKind.RequireKeyword | SyntaxKind.ReturnKeyword | SyntaxKind.SatisfiesKeyword | SyntaxKind.SetKeyword | SyntaxKind.StaticKeyword | SyntaxKind.StringKeyword | SyntaxKind.SuperKeyword | SyntaxKind.SwitchKeyword | SyntaxKind.SymbolKeyword | SyntaxKind.ThisKeyword | SyntaxKind.ThrowKeyword | SyntaxKind.TrueKeyword | SyntaxKind.TryKeyword | SyntaxKind.TypeKeyword | SyntaxKind.TypeOfKeyword | SyntaxKind.UndefinedKeyword | SyntaxKind.UniqueKeyword | SyntaxKind.UnknownKeyword | SyntaxKind.VarKeyword | SyntaxKind.VoidKeyword | SyntaxKind.WhileKeyword | SyntaxKind.WithKeyword | SyntaxKind.YieldKeyword; + export type ModifierSyntaxKind = SyntaxKind.AbstractKeyword | SyntaxKind.AsyncKeyword | SyntaxKind.ConstKeyword | SyntaxKind.DeclareKeyword | SyntaxKind.DefaultKeyword | SyntaxKind.ExportKeyword | SyntaxKind.InKeyword | SyntaxKind.PrivateKeyword | SyntaxKind.ProtectedKeyword | SyntaxKind.PublicKeyword | SyntaxKind.ReadonlyKeyword | SyntaxKind.OutKeyword | SyntaxKind.OverrideKeyword | SyntaxKind.StaticKeyword; + export type KeywordTypeSyntaxKind = SyntaxKind.AnyKeyword | SyntaxKind.BigIntKeyword | SyntaxKind.BooleanKeyword | SyntaxKind.IntrinsicKeyword | SyntaxKind.NeverKeyword | SyntaxKind.NumberKeyword | SyntaxKind.ObjectKeyword | SyntaxKind.StringKeyword | SyntaxKind.SymbolKeyword | SyntaxKind.UndefinedKeyword | SyntaxKind.UnknownKeyword | SyntaxKind.VoidKeyword; + export type TokenSyntaxKind = SyntaxKind.Unknown | SyntaxKind.EndOfFileToken | TriviaSyntaxKind | LiteralSyntaxKind | PseudoLiteralSyntaxKind | PunctuationSyntaxKind | SyntaxKind.Identifier | KeywordSyntaxKind; +@@ -1340,6 +1342,11 @@ declare namespace ts { + readonly type: TypeNode; + readonly expression: UnaryExpression; + } ++ export interface SatisfiesExpression extends Expression { ++ readonly kind: SyntaxKind.SatisfiesExpression; ++ readonly expression: Expression; ++ readonly type: TypeNode; ++ } + export type AssertionExpression = TypeAssertion | AsExpression; + export interface NonNullExpression extends LeftHandSideExpression { + readonly kind: SyntaxKind.NonNullExpression; +@@ -3588,6 +3595,8 @@ declare namespace ts { + updateNonNullChain(node: NonNullChain, expression: Expression): NonNullChain; + createMetaProperty(keywordToken: MetaProperty["keywordToken"], name: Identifier): MetaProperty; + updateMetaProperty(node: MetaProperty, name: Identifier): MetaProperty; ++ createSatisfiesExpression(expression: Expression, type: TypeNode): SatisfiesExpression; ++ updateSatisfiesExpression(node: SatisfiesExpression, expression: Expression, type: TypeNode): SatisfiesExpression; + createTemplateSpan(expression: Expression, literal: TemplateMiddle | TemplateTail): TemplateSpan; + updateTemplateSpan(node: TemplateSpan, expression: Expression, literal: TemplateMiddle | TemplateTail): TemplateSpan; + createSemicolonClassElement(): SemicolonClassElement; +@@ -4717,6 +4726,7 @@ declare namespace ts { + function isOmittedExpression(node: Node): node is OmittedExpression; + function isExpressionWithTypeArguments(node: Node): node is ExpressionWithTypeArguments; + function isAsExpression(node: Node): node is AsExpression; ++ function isSatisfiesExpression(node: Node): node is SatisfiesExpression; + function isNonNullExpression(node: Node): node is NonNullExpression; + function isMetaProperty(node: Node): node is MetaProperty; + function isSyntheticExpression(node: Node): node is SyntheticExpression; +diff --git a/tests/baselines/reference/api/typescript.d.ts b/tests/baselines/reference/api/typescript.d.ts +index 1a135d9fcb..857e3398c4 100644 +--- a/tests/baselines/reference/api/typescript.d.ts ++++ b/tests/baselines/reference/api/typescript.d.ts +@@ -254,215 +254,217 @@ declare namespace ts { + RequireKeyword = 146, + NumberKeyword = 147, + ObjectKeyword = 148, +- SetKeyword = 149, +- StringKeyword = 150, +- SymbolKeyword = 151, +- TypeKeyword = 152, +- UndefinedKeyword = 153, +- UniqueKeyword = 154, +- UnknownKeyword = 155, +- FromKeyword = 156, +- GlobalKeyword = 157, +- BigIntKeyword = 158, +- OverrideKeyword = 159, +- OfKeyword = 160, +- QualifiedName = 161, +- ComputedPropertyName = 162, +- TypeParameter = 163, +- Parameter = 164, +- Decorator = 165, +- PropertySignature = 166, +- PropertyDeclaration = 167, +- MethodSignature = 168, +- MethodDeclaration = 169, +- ClassStaticBlockDeclaration = 170, +- Constructor = 171, +- GetAccessor = 172, +- SetAccessor = 173, +- CallSignature = 174, +- ConstructSignature = 175, +- IndexSignature = 176, +- TypePredicate = 177, +- TypeReference = 178, +- FunctionType = 179, +- ConstructorType = 180, +- TypeQuery = 181, +- TypeLiteral = 182, +- ArrayType = 183, +- TupleType = 184, +- OptionalType = 185, +- RestType = 186, +- UnionType = 187, +- IntersectionType = 188, +- ConditionalType = 189, +- InferType = 190, +- ParenthesizedType = 191, +- ThisType = 192, +- TypeOperator = 193, +- IndexedAccessType = 194, +- MappedType = 195, +- LiteralType = 196, +- NamedTupleMember = 197, +- TemplateLiteralType = 198, +- TemplateLiteralTypeSpan = 199, +- ImportType = 200, +- ObjectBindingPattern = 201, +- ArrayBindingPattern = 202, +- BindingElement = 203, +- ArrayLiteralExpression = 204, +- ObjectLiteralExpression = 205, +- PropertyAccessExpression = 206, +- ElementAccessExpression = 207, +- CallExpression = 208, +- NewExpression = 209, +- TaggedTemplateExpression = 210, +- TypeAssertionExpression = 211, +- ParenthesizedExpression = 212, +- FunctionExpression = 213, +- ArrowFunction = 214, +- DeleteExpression = 215, +- TypeOfExpression = 216, +- VoidExpression = 217, +- AwaitExpression = 218, +- PrefixUnaryExpression = 219, +- PostfixUnaryExpression = 220, +- BinaryExpression = 221, +- ConditionalExpression = 222, +- TemplateExpression = 223, +- YieldExpression = 224, +- SpreadElement = 225, +- ClassExpression = 226, +- OmittedExpression = 227, +- ExpressionWithTypeArguments = 228, +- AsExpression = 229, +- NonNullExpression = 230, +- MetaProperty = 231, +- SyntheticExpression = 232, +- TemplateSpan = 233, +- SemicolonClassElement = 234, +- Block = 235, +- EmptyStatement = 236, +- VariableStatement = 237, +- ExpressionStatement = 238, +- IfStatement = 239, +- DoStatement = 240, +- WhileStatement = 241, +- ForStatement = 242, +- ForInStatement = 243, +- ForOfStatement = 244, +- ContinueStatement = 245, +- BreakStatement = 246, +- ReturnStatement = 247, +- WithStatement = 248, +- SwitchStatement = 249, +- LabeledStatement = 250, +- ThrowStatement = 251, +- TryStatement = 252, +- DebuggerStatement = 253, +- VariableDeclaration = 254, +- VariableDeclarationList = 255, +- FunctionDeclaration = 256, +- ClassDeclaration = 257, +- InterfaceDeclaration = 258, +- TypeAliasDeclaration = 259, +- EnumDeclaration = 260, +- ModuleDeclaration = 261, +- ModuleBlock = 262, +- CaseBlock = 263, +- NamespaceExportDeclaration = 264, +- ImportEqualsDeclaration = 265, +- ImportDeclaration = 266, +- ImportClause = 267, +- NamespaceImport = 268, +- NamedImports = 269, +- ImportSpecifier = 270, +- ExportAssignment = 271, +- ExportDeclaration = 272, +- NamedExports = 273, +- NamespaceExport = 274, +- ExportSpecifier = 275, +- MissingDeclaration = 276, +- ExternalModuleReference = 277, +- JsxElement = 278, +- JsxSelfClosingElement = 279, +- JsxOpeningElement = 280, +- JsxClosingElement = 281, +- JsxFragment = 282, +- JsxOpeningFragment = 283, +- JsxClosingFragment = 284, +- JsxAttribute = 285, +- JsxAttributes = 286, +- JsxSpreadAttribute = 287, +- JsxExpression = 288, +- CaseClause = 289, +- DefaultClause = 290, +- HeritageClause = 291, +- CatchClause = 292, +- AssertClause = 293, +- AssertEntry = 294, +- ImportTypeAssertionContainer = 295, +- PropertyAssignment = 296, +- ShorthandPropertyAssignment = 297, +- SpreadAssignment = 298, +- EnumMember = 299, +- UnparsedPrologue = 300, +- UnparsedPrepend = 301, +- UnparsedText = 302, +- UnparsedInternalText = 303, +- UnparsedSyntheticReference = 304, +- SourceFile = 305, +- Bundle = 306, +- UnparsedSource = 307, +- InputFiles = 308, +- JSDocTypeExpression = 309, +- JSDocNameReference = 310, +- JSDocMemberName = 311, +- JSDocAllType = 312, +- JSDocUnknownType = 313, +- JSDocNullableType = 314, +- JSDocNonNullableType = 315, +- JSDocOptionalType = 316, +- JSDocFunctionType = 317, +- JSDocVariadicType = 318, +- JSDocNamepathType = 319, +- JSDoc = 320, ++ SatisfiesKeyword = 149, ++ SetKeyword = 150, ++ StringKeyword = 151, ++ SymbolKeyword = 152, ++ TypeKeyword = 153, ++ UndefinedKeyword = 154, ++ UniqueKeyword = 155, ++ UnknownKeyword = 156, ++ FromKeyword = 157, ++ GlobalKeyword = 158, ++ BigIntKeyword = 159, ++ OverrideKeyword = 160, ++ OfKeyword = 161, ++ QualifiedName = 162, ++ ComputedPropertyName = 163, ++ TypeParameter = 164, ++ Parameter = 165, ++ Decorator = 166, ++ PropertySignature = 167, ++ PropertyDeclaration = 168, ++ MethodSignature = 169, ++ MethodDeclaration = 170, ++ ClassStaticBlockDeclaration = 171, ++ Constructor = 172, ++ GetAccessor = 173, ++ SetAccessor = 174, ++ CallSignature = 175, ++ ConstructSignature = 176, ++ IndexSignature = 177, ++ TypePredicate = 178, ++ TypeReference = 179, ++ FunctionType = 180, ++ ConstructorType = 181, ++ TypeQuery = 182, ++ TypeLiteral = 183, ++ ArrayType = 184, ++ TupleType = 185, ++ OptionalType = 186, ++ RestType = 187, ++ UnionType = 188, ++ IntersectionType = 189, ++ ConditionalType = 190, ++ InferType = 191, ++ ParenthesizedType = 192, ++ ThisType = 193, ++ TypeOperator = 194, ++ IndexedAccessType = 195, ++ MappedType = 196, ++ LiteralType = 197, ++ NamedTupleMember = 198, ++ TemplateLiteralType = 199, ++ TemplateLiteralTypeSpan = 200, ++ ImportType = 201, ++ ObjectBindingPattern = 202, ++ ArrayBindingPattern = 203, ++ BindingElement = 204, ++ ArrayLiteralExpression = 205, ++ ObjectLiteralExpression = 206, ++ PropertyAccessExpression = 207, ++ ElementAccessExpression = 208, ++ CallExpression = 209, ++ NewExpression = 210, ++ TaggedTemplateExpression = 211, ++ TypeAssertionExpression = 212, ++ ParenthesizedExpression = 213, ++ FunctionExpression = 214, ++ ArrowFunction = 215, ++ DeleteExpression = 216, ++ TypeOfExpression = 217, ++ VoidExpression = 218, ++ AwaitExpression = 219, ++ PrefixUnaryExpression = 220, ++ PostfixUnaryExpression = 221, ++ BinaryExpression = 222, ++ ConditionalExpression = 223, ++ TemplateExpression = 224, ++ YieldExpression = 225, ++ SpreadElement = 226, ++ ClassExpression = 227, ++ OmittedExpression = 228, ++ ExpressionWithTypeArguments = 229, ++ AsExpression = 230, ++ NonNullExpression = 231, ++ MetaProperty = 232, ++ SyntheticExpression = 233, ++ SatisfiesExpression = 234, ++ TemplateSpan = 235, ++ SemicolonClassElement = 236, ++ Block = 237, ++ EmptyStatement = 238, ++ VariableStatement = 239, ++ ExpressionStatement = 240, ++ IfStatement = 241, ++ DoStatement = 242, ++ WhileStatement = 243, ++ ForStatement = 244, ++ ForInStatement = 245, ++ ForOfStatement = 246, ++ ContinueStatement = 247, ++ BreakStatement = 248, ++ ReturnStatement = 249, ++ WithStatement = 250, ++ SwitchStatement = 251, ++ LabeledStatement = 252, ++ ThrowStatement = 253, ++ TryStatement = 254, ++ DebuggerStatement = 255, ++ VariableDeclaration = 256, ++ VariableDeclarationList = 257, ++ FunctionDeclaration = 258, ++ ClassDeclaration = 259, ++ InterfaceDeclaration = 260, ++ TypeAliasDeclaration = 261, ++ EnumDeclaration = 262, ++ ModuleDeclaration = 263, ++ ModuleBlock = 264, ++ CaseBlock = 265, ++ NamespaceExportDeclaration = 266, ++ ImportEqualsDeclaration = 267, ++ ImportDeclaration = 268, ++ ImportClause = 269, ++ NamespaceImport = 270, ++ NamedImports = 271, ++ ImportSpecifier = 272, ++ ExportAssignment = 273, ++ ExportDeclaration = 274, ++ NamedExports = 275, ++ NamespaceExport = 276, ++ ExportSpecifier = 277, ++ MissingDeclaration = 278, ++ ExternalModuleReference = 279, ++ JsxElement = 280, ++ JsxSelfClosingElement = 281, ++ JsxOpeningElement = 282, ++ JsxClosingElement = 283, ++ JsxFragment = 284, ++ JsxOpeningFragment = 285, ++ JsxClosingFragment = 286, ++ JsxAttribute = 287, ++ JsxAttributes = 288, ++ JsxSpreadAttribute = 289, ++ JsxExpression = 290, ++ CaseClause = 291, ++ DefaultClause = 292, ++ HeritageClause = 293, ++ CatchClause = 294, ++ AssertClause = 295, ++ AssertEntry = 296, ++ ImportTypeAssertionContainer = 297, ++ PropertyAssignment = 298, ++ ShorthandPropertyAssignment = 299, ++ SpreadAssignment = 300, ++ EnumMember = 301, ++ UnparsedPrologue = 302, ++ UnparsedPrepend = 303, ++ UnparsedText = 304, ++ UnparsedInternalText = 305, ++ UnparsedSyntheticReference = 306, ++ SourceFile = 307, ++ Bundle = 308, ++ UnparsedSource = 309, ++ InputFiles = 310, ++ JSDocTypeExpression = 311, ++ JSDocNameReference = 312, ++ JSDocMemberName = 313, ++ JSDocAllType = 314, ++ JSDocUnknownType = 315, ++ JSDocNullableType = 316, ++ JSDocNonNullableType = 317, ++ JSDocOptionalType = 318, ++ JSDocFunctionType = 319, ++ JSDocVariadicType = 320, ++ JSDocNamepathType = 321, ++ JSDoc = 322, + /** @deprecated Use SyntaxKind.JSDoc */ +- JSDocComment = 320, +- JSDocText = 321, +- JSDocTypeLiteral = 322, +- JSDocSignature = 323, +- JSDocLink = 324, +- JSDocLinkCode = 325, +- JSDocLinkPlain = 326, +- JSDocTag = 327, +- JSDocAugmentsTag = 328, +- JSDocImplementsTag = 329, +- JSDocAuthorTag = 330, +- JSDocDeprecatedTag = 331, +- JSDocClassTag = 332, +- JSDocPublicTag = 333, +- JSDocPrivateTag = 334, +- JSDocProtectedTag = 335, +- JSDocReadonlyTag = 336, +- JSDocOverrideTag = 337, +- JSDocCallbackTag = 338, +- JSDocEnumTag = 339, +- JSDocParameterTag = 340, +- JSDocReturnTag = 341, +- JSDocThisTag = 342, +- JSDocTypeTag = 343, +- JSDocTemplateTag = 344, +- JSDocTypedefTag = 345, +- JSDocSeeTag = 346, +- JSDocPropertyTag = 347, +- SyntaxList = 348, +- NotEmittedStatement = 349, +- PartiallyEmittedExpression = 350, +- CommaListExpression = 351, +- MergeDeclarationMarker = 352, +- EndOfDeclarationMarker = 353, +- SyntheticReferenceExpression = 354, +- Count = 355, ++ JSDocComment = 322, ++ JSDocText = 323, ++ JSDocTypeLiteral = 324, ++ JSDocSignature = 325, ++ JSDocLink = 326, ++ JSDocLinkCode = 327, ++ JSDocLinkPlain = 328, ++ JSDocTag = 329, ++ JSDocAugmentsTag = 330, ++ JSDocImplementsTag = 331, ++ JSDocAuthorTag = 332, ++ JSDocDeprecatedTag = 333, ++ JSDocClassTag = 334, ++ JSDocPublicTag = 335, ++ JSDocPrivateTag = 336, ++ JSDocProtectedTag = 337, ++ JSDocReadonlyTag = 338, ++ JSDocOverrideTag = 339, ++ JSDocCallbackTag = 340, ++ JSDocEnumTag = 341, ++ JSDocParameterTag = 342, ++ JSDocReturnTag = 343, ++ JSDocThisTag = 344, ++ JSDocTypeTag = 345, ++ JSDocTemplateTag = 346, ++ JSDocTypedefTag = 347, ++ JSDocSeeTag = 348, ++ JSDocPropertyTag = 349, ++ SyntaxList = 350, ++ NotEmittedStatement = 351, ++ PartiallyEmittedExpression = 352, ++ CommaListExpression = 353, ++ MergeDeclarationMarker = 354, ++ EndOfDeclarationMarker = 355, ++ SyntheticReferenceExpression = 356, ++ Count = 357, + FirstAssignment = 63, + LastAssignment = 78, + FirstCompoundAssignment = 64, +@@ -470,15 +472,15 @@ declare namespace ts { + FirstReservedWord = 81, + LastReservedWord = 116, + FirstKeyword = 81, +- LastKeyword = 160, ++ LastKeyword = 161, + FirstFutureReservedWord = 117, + LastFutureReservedWord = 125, +- FirstTypeNode = 177, +- LastTypeNode = 200, ++ FirstTypeNode = 178, ++ LastTypeNode = 201, + FirstPunctuation = 18, + LastPunctuation = 78, + FirstToken = 0, +- LastToken = 160, ++ LastToken = 161, + FirstTriviaToken = 2, + LastTriviaToken = 7, + FirstLiteralToken = 8, +@@ -487,19 +489,19 @@ declare namespace ts { + LastTemplateToken = 17, + FirstBinaryOperator = 29, + LastBinaryOperator = 78, +- FirstStatement = 237, +- LastStatement = 253, +- FirstNode = 161, +- FirstJSDocNode = 309, +- LastJSDocNode = 347, +- FirstJSDocTagNode = 327, +- LastJSDocTagNode = 347, ++ FirstStatement = 239, ++ LastStatement = 255, ++ FirstNode = 162, ++ FirstJSDocNode = 311, ++ LastJSDocNode = 349, ++ FirstJSDocTagNode = 329, ++ LastJSDocTagNode = 349, + } + export type TriviaSyntaxKind = SyntaxKind.SingleLineCommentTrivia | SyntaxKind.MultiLineCommentTrivia | SyntaxKind.NewLineTrivia | SyntaxKind.WhitespaceTrivia | SyntaxKind.ShebangTrivia | SyntaxKind.ConflictMarkerTrivia; + export type LiteralSyntaxKind = SyntaxKind.NumericLiteral | SyntaxKind.BigIntLiteral | SyntaxKind.StringLiteral | SyntaxKind.JsxText | SyntaxKind.JsxTextAllWhiteSpaces | SyntaxKind.RegularExpressionLiteral | SyntaxKind.NoSubstitutionTemplateLiteral; + export type PseudoLiteralSyntaxKind = SyntaxKind.TemplateHead | SyntaxKind.TemplateMiddle | SyntaxKind.TemplateTail; + export type PunctuationSyntaxKind = SyntaxKind.OpenBraceToken | SyntaxKind.CloseBraceToken | SyntaxKind.OpenParenToken | SyntaxKind.CloseParenToken | SyntaxKind.OpenBracketToken | SyntaxKind.CloseBracketToken | SyntaxKind.DotToken | SyntaxKind.DotDotDotToken | SyntaxKind.SemicolonToken | SyntaxKind.CommaToken | SyntaxKind.QuestionDotToken | SyntaxKind.LessThanToken | SyntaxKind.LessThanSlashToken | SyntaxKind.GreaterThanToken | SyntaxKind.LessThanEqualsToken | SyntaxKind.GreaterThanEqualsToken | SyntaxKind.EqualsEqualsToken | SyntaxKind.ExclamationEqualsToken | SyntaxKind.EqualsEqualsEqualsToken | SyntaxKind.ExclamationEqualsEqualsToken | SyntaxKind.EqualsGreaterThanToken | SyntaxKind.PlusToken | SyntaxKind.MinusToken | SyntaxKind.AsteriskToken | SyntaxKind.AsteriskAsteriskToken | SyntaxKind.SlashToken | SyntaxKind.PercentToken | SyntaxKind.PlusPlusToken | SyntaxKind.MinusMinusToken | SyntaxKind.LessThanLessThanToken | SyntaxKind.GreaterThanGreaterThanToken | SyntaxKind.GreaterThanGreaterThanGreaterThanToken | SyntaxKind.AmpersandToken | SyntaxKind.BarToken | SyntaxKind.CaretToken | SyntaxKind.ExclamationToken | SyntaxKind.TildeToken | SyntaxKind.AmpersandAmpersandToken | SyntaxKind.BarBarToken | SyntaxKind.QuestionQuestionToken | SyntaxKind.QuestionToken | SyntaxKind.ColonToken | SyntaxKind.AtToken | SyntaxKind.BacktickToken | SyntaxKind.HashToken | SyntaxKind.EqualsToken | SyntaxKind.PlusEqualsToken | SyntaxKind.MinusEqualsToken | SyntaxKind.AsteriskEqualsToken | SyntaxKind.AsteriskAsteriskEqualsToken | SyntaxKind.SlashEqualsToken | SyntaxKind.PercentEqualsToken | SyntaxKind.LessThanLessThanEqualsToken | SyntaxKind.GreaterThanGreaterThanEqualsToken | SyntaxKind.GreaterThanGreaterThanGreaterThanEqualsToken | SyntaxKind.AmpersandEqualsToken | SyntaxKind.BarEqualsToken | SyntaxKind.CaretEqualsToken; +- export type KeywordSyntaxKind = SyntaxKind.AbstractKeyword | SyntaxKind.AnyKeyword | SyntaxKind.AsKeyword | SyntaxKind.AssertsKeyword | SyntaxKind.AssertKeyword | SyntaxKind.AsyncKeyword | SyntaxKind.AwaitKeyword | SyntaxKind.BigIntKeyword | SyntaxKind.BooleanKeyword | SyntaxKind.BreakKeyword | SyntaxKind.CaseKeyword | SyntaxKind.CatchKeyword | SyntaxKind.ClassKeyword | SyntaxKind.ConstKeyword | SyntaxKind.ConstructorKeyword | SyntaxKind.ContinueKeyword | SyntaxKind.DebuggerKeyword | SyntaxKind.DeclareKeyword | SyntaxKind.DefaultKeyword | SyntaxKind.DeleteKeyword | SyntaxKind.DoKeyword | SyntaxKind.ElseKeyword | SyntaxKind.EnumKeyword | SyntaxKind.ExportKeyword | SyntaxKind.ExtendsKeyword | SyntaxKind.FalseKeyword | SyntaxKind.FinallyKeyword | SyntaxKind.ForKeyword | SyntaxKind.FromKeyword | SyntaxKind.FunctionKeyword | SyntaxKind.GetKeyword | SyntaxKind.GlobalKeyword | SyntaxKind.IfKeyword | SyntaxKind.ImplementsKeyword | SyntaxKind.ImportKeyword | SyntaxKind.InferKeyword | SyntaxKind.InKeyword | SyntaxKind.InstanceOfKeyword | SyntaxKind.InterfaceKeyword | SyntaxKind.IntrinsicKeyword | SyntaxKind.IsKeyword | SyntaxKind.KeyOfKeyword | SyntaxKind.LetKeyword | SyntaxKind.ModuleKeyword | SyntaxKind.NamespaceKeyword | SyntaxKind.NeverKeyword | SyntaxKind.NewKeyword | SyntaxKind.NullKeyword | SyntaxKind.NumberKeyword | SyntaxKind.ObjectKeyword | SyntaxKind.OfKeyword | SyntaxKind.PackageKeyword | SyntaxKind.PrivateKeyword | SyntaxKind.ProtectedKeyword | SyntaxKind.PublicKeyword | SyntaxKind.ReadonlyKeyword | SyntaxKind.OutKeyword | SyntaxKind.OverrideKeyword | SyntaxKind.RequireKeyword | SyntaxKind.ReturnKeyword | SyntaxKind.SetKeyword | SyntaxKind.StaticKeyword | SyntaxKind.StringKeyword | SyntaxKind.SuperKeyword | SyntaxKind.SwitchKeyword | SyntaxKind.SymbolKeyword | SyntaxKind.ThisKeyword | SyntaxKind.ThrowKeyword | SyntaxKind.TrueKeyword | SyntaxKind.TryKeyword | SyntaxKind.TypeKeyword | SyntaxKind.TypeOfKeyword | SyntaxKind.UndefinedKeyword | SyntaxKind.UniqueKeyword | SyntaxKind.UnknownKeyword | SyntaxKind.VarKeyword | SyntaxKind.VoidKeyword | SyntaxKind.WhileKeyword | SyntaxKind.WithKeyword | SyntaxKind.YieldKeyword; ++ export type KeywordSyntaxKind = SyntaxKind.AbstractKeyword | SyntaxKind.AnyKeyword | SyntaxKind.AsKeyword | SyntaxKind.AssertsKeyword | SyntaxKind.AssertKeyword | SyntaxKind.AsyncKeyword | SyntaxKind.AwaitKeyword | SyntaxKind.BigIntKeyword | SyntaxKind.BooleanKeyword | SyntaxKind.BreakKeyword | SyntaxKind.CaseKeyword | SyntaxKind.CatchKeyword | SyntaxKind.ClassKeyword | SyntaxKind.ConstKeyword | SyntaxKind.ConstructorKeyword | SyntaxKind.ContinueKeyword | SyntaxKind.DebuggerKeyword | SyntaxKind.DeclareKeyword | SyntaxKind.DefaultKeyword | SyntaxKind.DeleteKeyword | SyntaxKind.DoKeyword | SyntaxKind.ElseKeyword | SyntaxKind.EnumKeyword | SyntaxKind.ExportKeyword | SyntaxKind.ExtendsKeyword | SyntaxKind.FalseKeyword | SyntaxKind.FinallyKeyword | SyntaxKind.ForKeyword | SyntaxKind.FromKeyword | SyntaxKind.FunctionKeyword | SyntaxKind.GetKeyword | SyntaxKind.GlobalKeyword | SyntaxKind.IfKeyword | SyntaxKind.ImplementsKeyword | SyntaxKind.ImportKeyword | SyntaxKind.InferKeyword | SyntaxKind.InKeyword | SyntaxKind.InstanceOfKeyword | SyntaxKind.InterfaceKeyword | SyntaxKind.IntrinsicKeyword | SyntaxKind.IsKeyword | SyntaxKind.KeyOfKeyword | SyntaxKind.LetKeyword | SyntaxKind.ModuleKeyword | SyntaxKind.NamespaceKeyword | SyntaxKind.NeverKeyword | SyntaxKind.NewKeyword | SyntaxKind.NullKeyword | SyntaxKind.NumberKeyword | SyntaxKind.ObjectKeyword | SyntaxKind.OfKeyword | SyntaxKind.PackageKeyword | SyntaxKind.PrivateKeyword | SyntaxKind.ProtectedKeyword | SyntaxKind.PublicKeyword | SyntaxKind.ReadonlyKeyword | SyntaxKind.OutKeyword | SyntaxKind.OverrideKeyword | SyntaxKind.RequireKeyword | SyntaxKind.ReturnKeyword | SyntaxKind.SatisfiesKeyword | SyntaxKind.SetKeyword | SyntaxKind.StaticKeyword | SyntaxKind.StringKeyword | SyntaxKind.SuperKeyword | SyntaxKind.SwitchKeyword | SyntaxKind.SymbolKeyword | SyntaxKind.ThisKeyword | SyntaxKind.ThrowKeyword | SyntaxKind.TrueKeyword | SyntaxKind.TryKeyword | SyntaxKind.TypeKeyword | SyntaxKind.TypeOfKeyword | SyntaxKind.UndefinedKeyword | SyntaxKind.UniqueKeyword | SyntaxKind.UnknownKeyword | SyntaxKind.VarKeyword | SyntaxKind.VoidKeyword | SyntaxKind.WhileKeyword | SyntaxKind.WithKeyword | SyntaxKind.YieldKeyword; + export type ModifierSyntaxKind = SyntaxKind.AbstractKeyword | SyntaxKind.AsyncKeyword | SyntaxKind.ConstKeyword | SyntaxKind.DeclareKeyword | SyntaxKind.DefaultKeyword | SyntaxKind.ExportKeyword | SyntaxKind.InKeyword | SyntaxKind.PrivateKeyword | SyntaxKind.ProtectedKeyword | SyntaxKind.PublicKeyword | SyntaxKind.ReadonlyKeyword | SyntaxKind.OutKeyword | SyntaxKind.OverrideKeyword | SyntaxKind.StaticKeyword; + export type KeywordTypeSyntaxKind = SyntaxKind.AnyKeyword | SyntaxKind.BigIntKeyword | SyntaxKind.BooleanKeyword | SyntaxKind.IntrinsicKeyword | SyntaxKind.NeverKeyword | SyntaxKind.NumberKeyword | SyntaxKind.ObjectKeyword | SyntaxKind.StringKeyword | SyntaxKind.SymbolKeyword | SyntaxKind.UndefinedKeyword | SyntaxKind.UnknownKeyword | SyntaxKind.VoidKeyword; + export type TokenSyntaxKind = SyntaxKind.Unknown | SyntaxKind.EndOfFileToken | TriviaSyntaxKind | LiteralSyntaxKind | PseudoLiteralSyntaxKind | PunctuationSyntaxKind | SyntaxKind.Identifier | KeywordSyntaxKind; +@@ -1340,6 +1342,11 @@ declare namespace ts { + readonly type: TypeNode; + readonly expression: UnaryExpression; + } ++ export interface SatisfiesExpression extends Expression { ++ readonly kind: SyntaxKind.SatisfiesExpression; ++ readonly expression: Expression; ++ readonly type: TypeNode; ++ } + export type AssertionExpression = TypeAssertion | AsExpression; + export interface NonNullExpression extends LeftHandSideExpression { + readonly kind: SyntaxKind.NonNullExpression; +@@ -3588,6 +3595,8 @@ declare namespace ts { + updateNonNullChain(node: NonNullChain, expression: Expression): NonNullChain; + createMetaProperty(keywordToken: MetaProperty["keywordToken"], name: Identifier): MetaProperty; + updateMetaProperty(node: MetaProperty, name: Identifier): MetaProperty; ++ createSatisfiesExpression(expression: Expression, type: TypeNode): SatisfiesExpression; ++ updateSatisfiesExpression(node: SatisfiesExpression, expression: Expression, type: TypeNode): SatisfiesExpression; + createTemplateSpan(expression: Expression, literal: TemplateMiddle | TemplateTail): TemplateSpan; + updateTemplateSpan(node: TemplateSpan, expression: Expression, literal: TemplateMiddle | TemplateTail): TemplateSpan; + createSemicolonClassElement(): SemicolonClassElement; +@@ -4717,6 +4726,7 @@ declare namespace ts { + function isOmittedExpression(node: Node): node is OmittedExpression; + function isExpressionWithTypeArguments(node: Node): node is ExpressionWithTypeArguments; + function isAsExpression(node: Node): node is AsExpression; ++ function isSatisfiesExpression(node: Node): node is SatisfiesExpression; + function isNonNullExpression(node: Node): node is NonNullExpression; + function isMetaProperty(node: Node): node is MetaProperty; + function isSyntheticExpression(node: Node): node is SyntheticExpression; +diff --git a/tests/baselines/reference/completionsCommentsClass.baseline b/tests/baselines/reference/completionsCommentsClass.baseline +index 5dce64b756..7c01a94bde 100644 +--- a/tests/baselines/reference/completionsCommentsClass.baseline ++++ b/tests/baselines/reference/completionsCommentsClass.baseline +@@ -3115,6 +3115,18 @@ + } + ] + }, ++ { ++ "name": "satisfies", ++ "kind": "keyword", ++ "kindModifiers": "", ++ "sortText": "15", ++ "displayParts": [ ++ { ++ "text": "satisfies", ++ "kind": "keyword" ++ } ++ ] ++ }, + { + "name": "string", + "kind": "keyword", +diff --git a/tests/baselines/reference/completionsCommentsClassMembers.baseline b/tests/baselines/reference/completionsCommentsClassMembers.baseline +index c09142c2a9..aae31c8f97 100644 +--- a/tests/baselines/reference/completionsCommentsClassMembers.baseline ++++ b/tests/baselines/reference/completionsCommentsClassMembers.baseline +@@ -4048,6 +4048,18 @@ + } + ] + }, ++ { ++ "name": "satisfies", ++ "kind": "keyword", ++ "kindModifiers": "", ++ "sortText": "15", ++ "displayParts": [ ++ { ++ "text": "satisfies", ++ "kind": "keyword" ++ } ++ ] ++ }, + { + "name": "String", + "kind": "var", +@@ -11121,6 +11133,18 @@ + } + ] + }, ++ { ++ "name": "satisfies", ++ "kind": "keyword", ++ "kindModifiers": "", ++ "sortText": "15", ++ "displayParts": [ ++ { ++ "text": "satisfies", ++ "kind": "keyword" ++ } ++ ] ++ }, + { + "name": "String", + "kind": "var", +@@ -15947,6 +15971,18 @@ + } + ] + }, ++ { ++ "name": "satisfies", ++ "kind": "keyword", ++ "kindModifiers": "", ++ "sortText": "15", ++ "displayParts": [ ++ { ++ "text": "satisfies", ++ "kind": "keyword" ++ } ++ ] ++ }, + { + "name": "String", + "kind": "var", +@@ -23020,6 +23056,18 @@ + } + ] + }, ++ { ++ "name": "satisfies", ++ "kind": "keyword", ++ "kindModifiers": "", ++ "sortText": "15", ++ "displayParts": [ ++ { ++ "text": "satisfies", ++ "kind": "keyword" ++ } ++ ] ++ }, + { + "name": "String", + "kind": "var", +@@ -27097,6 +27145,18 @@ + } + ] + }, ++ { ++ "name": "satisfies", ++ "kind": "keyword", ++ "kindModifiers": "", ++ "sortText": "15", ++ "displayParts": [ ++ { ++ "text": "satisfies", ++ "kind": "keyword" ++ } ++ ] ++ }, + { + "name": "String", + "kind": "var", +@@ -32330,6 +32390,18 @@ + } + ] + }, ++ { ++ "name": "satisfies", ++ "kind": "keyword", ++ "kindModifiers": "", ++ "sortText": "15", ++ "displayParts": [ ++ { ++ "text": "satisfies", ++ "kind": "keyword" ++ } ++ ] ++ }, + { + "name": "String", + "kind": "var", +@@ -36361,6 +36433,18 @@ + } + ] + }, ++ { ++ "name": "satisfies", ++ "kind": "keyword", ++ "kindModifiers": "", ++ "sortText": "15", ++ "displayParts": [ ++ { ++ "text": "satisfies", ++ "kind": "keyword" ++ } ++ ] ++ }, + { + "name": "String", + "kind": "var", +@@ -41548,6 +41632,18 @@ + } + ] + }, ++ { ++ "name": "satisfies", ++ "kind": "keyword", ++ "kindModifiers": "", ++ "sortText": "15", ++ "displayParts": [ ++ { ++ "text": "satisfies", ++ "kind": "keyword" ++ } ++ ] ++ }, + { + "name": "String", + "kind": "var", +@@ -46781,6 +46877,18 @@ + } + ] + }, ++ { ++ "name": "satisfies", ++ "kind": "keyword", ++ "kindModifiers": "", ++ "sortText": "15", ++ "displayParts": [ ++ { ++ "text": "satisfies", ++ "kind": "keyword" ++ } ++ ] ++ }, + { + "name": "String", + "kind": "var", +@@ -52014,6 +52122,18 @@ + } + ] + }, ++ { ++ "name": "satisfies", ++ "kind": "keyword", ++ "kindModifiers": "", ++ "sortText": "15", ++ "displayParts": [ ++ { ++ "text": "satisfies", ++ "kind": "keyword" ++ } ++ ] ++ }, + { + "name": "String", + "kind": "var", +@@ -57247,6 +57367,18 @@ + } + ] + }, ++ { ++ "name": "satisfies", ++ "kind": "keyword", ++ "kindModifiers": "", ++ "sortText": "15", ++ "displayParts": [ ++ { ++ "text": "satisfies", ++ "kind": "keyword" ++ } ++ ] ++ }, + { + "name": "String", + "kind": "var", +@@ -61319,6 +61451,18 @@ + } + ] + }, ++ { ++ "name": "satisfies", ++ "kind": "keyword", ++ "kindModifiers": "", ++ "sortText": "15", ++ "displayParts": [ ++ { ++ "text": "satisfies", ++ "kind": "keyword" ++ } ++ ] ++ }, + { + "name": "String", + "kind": "var", +@@ -65391,6 +65535,18 @@ + } + ] + }, ++ { ++ "name": "satisfies", ++ "kind": "keyword", ++ "kindModifiers": "", ++ "sortText": "15", ++ "displayParts": [ ++ { ++ "text": "satisfies", ++ "kind": "keyword" ++ } ++ ] ++ }, + { + "name": "String", + "kind": "var", +@@ -69463,6 +69619,18 @@ + } + ] + }, ++ { ++ "name": "satisfies", ++ "kind": "keyword", ++ "kindModifiers": "", ++ "sortText": "15", ++ "displayParts": [ ++ { ++ "text": "satisfies", ++ "kind": "keyword" ++ } ++ ] ++ }, + { + "name": "String", + "kind": "var", +@@ -73535,6 +73703,18 @@ + } + ] + }, ++ { ++ "name": "satisfies", ++ "kind": "keyword", ++ "kindModifiers": "", ++ "sortText": "15", ++ "displayParts": [ ++ { ++ "text": "satisfies", ++ "kind": "keyword" ++ } ++ ] ++ }, + { + "name": "String", + "kind": "var", +@@ -77607,6 +77787,18 @@ + } + ] + }, ++ { ++ "name": "satisfies", ++ "kind": "keyword", ++ "kindModifiers": "", ++ "sortText": "15", ++ "displayParts": [ ++ { ++ "text": "satisfies", ++ "kind": "keyword" ++ } ++ ] ++ }, + { + "name": "String", + "kind": "var", +@@ -81679,6 +81871,18 @@ + } + ] + }, ++ { ++ "name": "satisfies", ++ "kind": "keyword", ++ "kindModifiers": "", ++ "sortText": "15", ++ "displayParts": [ ++ { ++ "text": "satisfies", ++ "kind": "keyword" ++ } ++ ] ++ }, + { + "name": "String", + "kind": "var", +@@ -86188,6 +86392,18 @@ + } + ] + }, ++ { ++ "name": "satisfies", ++ "kind": "keyword", ++ "kindModifiers": "", ++ "sortText": "15", ++ "displayParts": [ ++ { ++ "text": "satisfies", ++ "kind": "keyword" ++ } ++ ] ++ }, + { + "name": "string", + "kind": "keyword", +@@ -91546,6 +91762,18 @@ + } + ] + }, ++ { ++ "name": "satisfies", ++ "kind": "keyword", ++ "kindModifiers": "", ++ "sortText": "15", ++ "displayParts": [ ++ { ++ "text": "satisfies", ++ "kind": "keyword" ++ } ++ ] ++ }, + { + "name": "string", + "kind": "keyword", +@@ -96064,6 +96292,18 @@ + } + ] + }, ++ { ++ "name": "satisfies", ++ "kind": "keyword", ++ "kindModifiers": "", ++ "sortText": "15", ++ "displayParts": [ ++ { ++ "text": "satisfies", ++ "kind": "keyword" ++ } ++ ] ++ }, + { + "name": "String", + "kind": "var", +diff --git a/tests/baselines/reference/completionsCommentsCommentParsing.baseline b/tests/baselines/reference/completionsCommentsCommentParsing.baseline +index 99a71cece8..1622a0c8f3 100644 +--- a/tests/baselines/reference/completionsCommentsCommentParsing.baseline ++++ b/tests/baselines/reference/completionsCommentsCommentParsing.baseline +@@ -4882,6 +4882,18 @@ + } + ] + }, ++ { ++ "name": "satisfies", ++ "kind": "keyword", ++ "kindModifiers": "", ++ "sortText": "15", ++ "displayParts": [ ++ { ++ "text": "satisfies", ++ "kind": "keyword" ++ } ++ ] ++ }, + { + "name": "String", + "kind": "var", +@@ -11062,6 +11074,18 @@ + } + ] + }, ++ { ++ "name": "satisfies", ++ "kind": "keyword", ++ "kindModifiers": "", ++ "sortText": "15", ++ "displayParts": [ ++ { ++ "text": "satisfies", ++ "kind": "keyword" ++ } ++ ] ++ }, + { + "name": "String", + "kind": "var", +@@ -16974,6 +16998,18 @@ + } + ] + }, ++ { ++ "name": "satisfies", ++ "kind": "keyword", ++ "kindModifiers": "", ++ "sortText": "15", ++ "displayParts": [ ++ { ++ "text": "satisfies", ++ "kind": "keyword" ++ } ++ ] ++ }, + { + "name": "String", + "kind": "var", +@@ -22627,6 +22663,18 @@ + } + ] + }, ++ { ++ "name": "satisfies", ++ "kind": "keyword", ++ "kindModifiers": "", ++ "sortText": "15", ++ "displayParts": [ ++ { ++ "text": "satisfies", ++ "kind": "keyword" ++ } ++ ] ++ }, + { + "name": "string", + "kind": "keyword", +@@ -28430,6 +28478,18 @@ + } + ] + }, ++ { ++ "name": "satisfies", ++ "kind": "keyword", ++ "kindModifiers": "", ++ "sortText": "15", ++ "displayParts": [ ++ { ++ "text": "satisfies", ++ "kind": "keyword" ++ } ++ ] ++ }, + { + "name": "String", + "kind": "var", +@@ -34610,6 +34670,18 @@ + } + ] + }, ++ { ++ "name": "satisfies", ++ "kind": "keyword", ++ "kindModifiers": "", ++ "sortText": "15", ++ "displayParts": [ ++ { ++ "text": "satisfies", ++ "kind": "keyword" ++ } ++ ] ++ }, + { + "name": "String", + "kind": "var", +@@ -40539,6 +40611,18 @@ + } + ] + }, ++ { ++ "name": "satisfies", ++ "kind": "keyword", ++ "kindModifiers": "", ++ "sortText": "15", ++ "displayParts": [ ++ { ++ "text": "satisfies", ++ "kind": "keyword" ++ } ++ ] ++ }, + { + "name": "string", + "kind": "keyword", +diff --git a/tests/baselines/reference/completionsCommentsFunctionDeclaration.baseline b/tests/baselines/reference/completionsCommentsFunctionDeclaration.baseline +index 4e3bcb8014..0cd4ca2b63 100644 +--- a/tests/baselines/reference/completionsCommentsFunctionDeclaration.baseline ++++ b/tests/baselines/reference/completionsCommentsFunctionDeclaration.baseline +@@ -3269,6 +3269,18 @@ + } + ] + }, ++ { ++ "name": "satisfies", ++ "kind": "keyword", ++ "kindModifiers": "", ++ "sortText": "15", ++ "displayParts": [ ++ { ++ "text": "satisfies", ++ "kind": "keyword" ++ } ++ ] ++ }, + { + "name": "String", + "kind": "var", +@@ -7034,6 +7046,18 @@ + } + ] + }, ++ { ++ "name": "satisfies", ++ "kind": "keyword", ++ "kindModifiers": "", ++ "sortText": "15", ++ "displayParts": [ ++ { ++ "text": "satisfies", ++ "kind": "keyword" ++ } ++ ] ++ }, + { + "name": "String", + "kind": "var", +@@ -11081,6 +11105,18 @@ + } + ] + }, ++ { ++ "name": "satisfies", ++ "kind": "keyword", ++ "kindModifiers": "", ++ "sortText": "15", ++ "displayParts": [ ++ { ++ "text": "satisfies", ++ "kind": "keyword" ++ } ++ ] ++ }, + { + "name": "String", + "kind": "var", +diff --git a/tests/baselines/reference/completionsCommentsFunctionExpression.baseline b/tests/baselines/reference/completionsCommentsFunctionExpression.baseline +index 4fac96f0ab..5e5e0b5e1d 100644 +--- a/tests/baselines/reference/completionsCommentsFunctionExpression.baseline ++++ b/tests/baselines/reference/completionsCommentsFunctionExpression.baseline +@@ -3022,6 +3022,18 @@ + } + ] + }, ++ { ++ "name": "satisfies", ++ "kind": "keyword", ++ "kindModifiers": "", ++ "sortText": "15", ++ "displayParts": [ ++ { ++ "text": "satisfies", ++ "kind": "keyword" ++ } ++ ] ++ }, + { + "name": "string", + "kind": "keyword", +@@ -7469,6 +7481,18 @@ + } + ] + }, ++ { ++ "name": "satisfies", ++ "kind": "keyword", ++ "kindModifiers": "", ++ "sortText": "15", ++ "displayParts": [ ++ { ++ "text": "satisfies", ++ "kind": "keyword" ++ } ++ ] ++ }, + { + "name": "string", + "kind": "keyword", +@@ -11472,6 +11496,18 @@ + } + ] + }, ++ { ++ "name": "satisfies", ++ "kind": "keyword", ++ "kindModifiers": "", ++ "sortText": "15", ++ "displayParts": [ ++ { ++ "text": "satisfies", ++ "kind": "keyword" ++ } ++ ] ++ }, + { + "name": "String", + "kind": "var", +@@ -15703,6 +15739,18 @@ + } + ] + }, ++ { ++ "name": "satisfies", ++ "kind": "keyword", ++ "kindModifiers": "", ++ "sortText": "15", ++ "displayParts": [ ++ { ++ "text": "satisfies", ++ "kind": "keyword" ++ } ++ ] ++ }, + { + "name": "String", + "kind": "var", +diff --git a/tests/baselines/reference/constructorNameInGenerator.errors.txt b/tests/baselines/reference/constructorNameInGenerator.errors.txt +index 061560615f..493f79bd4a 100644 +--- a/tests/baselines/reference/constructorNameInGenerator.errors.txt ++++ b/tests/baselines/reference/constructorNameInGenerator.errors.txt +@@ -1,10 +1,10 @@ +-tests/cases/conformance/salsa/constructorNameInGenerator.ts(2,6): error TS1360: Class constructor may not be a generator. ++tests/cases/conformance/salsa/constructorNameInGenerator.ts(2,6): error TS1368: Class constructor may not be a generator. + + + ==== tests/cases/conformance/salsa/constructorNameInGenerator.ts (1 errors) ==== + class C2 { + *constructor() {} + ~~~~~~~~~~~ +-!!! error TS1360: Class constructor may not be a generator. ++!!! error TS1368: Class constructor may not be a generator. + } + +\ No newline at end of file +diff --git a/tests/baselines/reference/tsserver/moduleSpecifierCache/invalidates-module-specifiers-when-changes-happen-in-contained-node_modules-directories.js b/tests/baselines/reference/tsserver/moduleSpecifierCache/invalidates-module-specifiers-when-changes-happen-in-contained-node_modules-directories.js +index a5365671be..0980d5d06c 100644 +--- a/tests/baselines/reference/tsserver/moduleSpecifierCache/invalidates-module-specifiers-when-changes-happen-in-contained-node_modules-directories.js ++++ b/tests/baselines/reference/tsserver/moduleSpecifierCache/invalidates-module-specifiers-when-changes-happen-in-contained-node_modules-directories.js +@@ -128,7 +128,7 @@ collectAutoImports: response is incomplete + collectAutoImports: * + getCompletionData: Semantic work: * + getCompletionsAtPosition: getCompletionEntriesFromSymbols: * +-response:{"response":{"flags":1,"isGlobalCompletion":true,"isMemberCompletion":false,"isNewIdentifierLocation":false,"optionalReplacementSpan":{"start":{"line":1,"offset":1},"end":{"line":1,"offset":4}},"entries":[{"name":"abstract","kind":"keyword","kindModifiers":"","sortText":"15"},{"name":"any","kind":"keyword","kindModifiers":"","sortText":"15"},{"name":"as","kind":"keyword","kindModifiers":"","sortText":"15"},{"name":"asserts","kind":"keyword","kindModifiers":"","sortText":"15"},{"name":"async","kind":"keyword","kindModifiers":"","sortText":"15"},{"name":"await","kind":"keyword","kindModifiers":"","sortText":"15"},{"name":"bigint","kind":"keyword","kindModifiers":"","sortText":"15"},{"name":"boolean","kind":"keyword","kindModifiers":"","sortText":"15"},{"name":"break","kind":"keyword","kindModifiers":"","sortText":"15"},{"name":"case","kind":"keyword","kindModifiers":"","sortText":"15"},{"name":"catch","kind":"keyword","kindModifiers":"","sortText":"15"},{"name":"class","kind":"keyword","kindModifiers":"","sortText":"15"},{"name":"const","kind":"keyword","kindModifiers":"","sortText":"15"},{"name":"continue","kind":"keyword","kindModifiers":"","sortText":"15"},{"name":"debugger","kind":"keyword","kindModifiers":"","sortText":"15"},{"name":"declare","kind":"keyword","kindModifiers":"","sortText":"15"},{"name":"default","kind":"keyword","kindModifiers":"","sortText":"15"},{"name":"delete","kind":"keyword","kindModifiers":"","sortText":"15"},{"name":"do","kind":"keyword","kindModifiers":"","sortText":"15"},{"name":"else","kind":"keyword","kindModifiers":"","sortText":"15"},{"name":"enum","kind":"keyword","kindModifiers":"","sortText":"15"},{"name":"export","kind":"keyword","kindModifiers":"","sortText":"15"},{"name":"extends","kind":"keyword","kindModifiers":"","sortText":"15"},{"name":"false","kind":"keyword","kindModifiers":"","sortText":"15"},{"name":"finally","kind":"keyword","kindModifiers":"","sortText":"15"},{"name":"for","kind":"keyword","kindModifiers":"","sortText":"15"},{"name":"function","kind":"keyword","kindModifiers":"","sortText":"15"},{"name":"globalThis","kind":"module","kindModifiers":"","sortText":"15"},{"name":"if","kind":"keyword","kindModifiers":"","sortText":"15"},{"name":"implements","kind":"keyword","kindModifiers":"","sortText":"15"},{"name":"import","kind":"keyword","kindModifiers":"","sortText":"15"},{"name":"in","kind":"keyword","kindModifiers":"","sortText":"15"},{"name":"infer","kind":"keyword","kindModifiers":"","sortText":"15"},{"name":"instanceof","kind":"keyword","kindModifiers":"","sortText":"15"},{"name":"interface","kind":"keyword","kindModifiers":"","sortText":"15"},{"name":"keyof","kind":"keyword","kindModifiers":"","sortText":"15"},{"name":"let","kind":"keyword","kindModifiers":"","sortText":"15"},{"name":"module","kind":"keyword","kindModifiers":"","sortText":"15"},{"name":"namespace","kind":"keyword","kindModifiers":"","sortText":"15"},{"name":"never","kind":"keyword","kindModifiers":"","sortText":"15"},{"name":"new","kind":"keyword","kindModifiers":"","sortText":"15"},{"name":"null","kind":"keyword","kindModifiers":"","sortText":"15"},{"name":"number","kind":"keyword","kindModifiers":"","sortText":"15"},{"name":"object","kind":"keyword","kindModifiers":"","sortText":"15"},{"name":"package","kind":"keyword","kindModifiers":"","sortText":"15"},{"name":"readonly","kind":"keyword","kindModifiers":"","sortText":"15"},{"name":"return","kind":"keyword","kindModifiers":"","sortText":"15"},{"name":"string","kind":"keyword","kindModifiers":"","sortText":"15"},{"name":"super","kind":"keyword","kindModifiers":"","sortText":"15"},{"name":"switch","kind":"keyword","kindModifiers":"","sortText":"15"},{"name":"symbol","kind":"keyword","kindModifiers":"","sortText":"15"},{"name":"this","kind":"keyword","kindModifiers":"","sortText":"15"},{"name":"throw","kind":"keyword","kindModifiers":"","sortText":"15"},{"name":"true","kind":"keyword","kindModifiers":"","sortText":"15"},{"name":"try","kind":"keyword","kindModifiers":"","sortText":"15"},{"name":"type","kind":"keyword","kindModifiers":"","sortText":"15"},{"name":"typeof","kind":"keyword","kindModifiers":"","sortText":"15"},{"name":"undefined","kind":"var","kindModifiers":"","sortText":"15"},{"name":"unique","kind":"keyword","kindModifiers":"","sortText":"15"},{"name":"unknown","kind":"keyword","kindModifiers":"","sortText":"15"},{"name":"var","kind":"keyword","kindModifiers":"","sortText":"15"},{"name":"void","kind":"keyword","kindModifiers":"","sortText":"15"},{"name":"while","kind":"keyword","kindModifiers":"","sortText":"15"},{"name":"with","kind":"keyword","kindModifiers":"","sortText":"15"},{"name":"yield","kind":"keyword","kindModifiers":"","sortText":"15"},{"name":"foo","kind":"const","kindModifiers":"export","sortText":"16","hasAction":true,"source":"/src/a","data":{"exportName":"foo","exportMapKey":"foo|*|","fileName":"/src/a.ts"}}]},"responseRequired":true} ++response:{"response":{"flags":1,"isGlobalCompletion":true,"isMemberCompletion":false,"isNewIdentifierLocation":false,"optionalReplacementSpan":{"start":{"line":1,"offset":1},"end":{"line":1,"offset":4}},"entries":[{"name":"abstract","kind":"keyword","kindModifiers":"","sortText":"15"},{"name":"any","kind":"keyword","kindModifiers":"","sortText":"15"},{"name":"as","kind":"keyword","kindModifiers":"","sortText":"15"},{"name":"asserts","kind":"keyword","kindModifiers":"","sortText":"15"},{"name":"async","kind":"keyword","kindModifiers":"","sortText":"15"},{"name":"await","kind":"keyword","kindModifiers":"","sortText":"15"},{"name":"bigint","kind":"keyword","kindModifiers":"","sortText":"15"},{"name":"boolean","kind":"keyword","kindModifiers":"","sortText":"15"},{"name":"break","kind":"keyword","kindModifiers":"","sortText":"15"},{"name":"case","kind":"keyword","kindModifiers":"","sortText":"15"},{"name":"catch","kind":"keyword","kindModifiers":"","sortText":"15"},{"name":"class","kind":"keyword","kindModifiers":"","sortText":"15"},{"name":"const","kind":"keyword","kindModifiers":"","sortText":"15"},{"name":"continue","kind":"keyword","kindModifiers":"","sortText":"15"},{"name":"debugger","kind":"keyword","kindModifiers":"","sortText":"15"},{"name":"declare","kind":"keyword","kindModifiers":"","sortText":"15"},{"name":"default","kind":"keyword","kindModifiers":"","sortText":"15"},{"name":"delete","kind":"keyword","kindModifiers":"","sortText":"15"},{"name":"do","kind":"keyword","kindModifiers":"","sortText":"15"},{"name":"else","kind":"keyword","kindModifiers":"","sortText":"15"},{"name":"enum","kind":"keyword","kindModifiers":"","sortText":"15"},{"name":"export","kind":"keyword","kindModifiers":"","sortText":"15"},{"name":"extends","kind":"keyword","kindModifiers":"","sortText":"15"},{"name":"false","kind":"keyword","kindModifiers":"","sortText":"15"},{"name":"finally","kind":"keyword","kindModifiers":"","sortText":"15"},{"name":"for","kind":"keyword","kindModifiers":"","sortText":"15"},{"name":"function","kind":"keyword","kindModifiers":"","sortText":"15"},{"name":"globalThis","kind":"module","kindModifiers":"","sortText":"15"},{"name":"if","kind":"keyword","kindModifiers":"","sortText":"15"},{"name":"implements","kind":"keyword","kindModifiers":"","sortText":"15"},{"name":"import","kind":"keyword","kindModifiers":"","sortText":"15"},{"name":"in","kind":"keyword","kindModifiers":"","sortText":"15"},{"name":"infer","kind":"keyword","kindModifiers":"","sortText":"15"},{"name":"instanceof","kind":"keyword","kindModifiers":"","sortText":"15"},{"name":"interface","kind":"keyword","kindModifiers":"","sortText":"15"},{"name":"keyof","kind":"keyword","kindModifiers":"","sortText":"15"},{"name":"let","kind":"keyword","kindModifiers":"","sortText":"15"},{"name":"module","kind":"keyword","kindModifiers":"","sortText":"15"},{"name":"namespace","kind":"keyword","kindModifiers":"","sortText":"15"},{"name":"never","kind":"keyword","kindModifiers":"","sortText":"15"},{"name":"new","kind":"keyword","kindModifiers":"","sortText":"15"},{"name":"null","kind":"keyword","kindModifiers":"","sortText":"15"},{"name":"number","kind":"keyword","kindModifiers":"","sortText":"15"},{"name":"object","kind":"keyword","kindModifiers":"","sortText":"15"},{"name":"package","kind":"keyword","kindModifiers":"","sortText":"15"},{"name":"readonly","kind":"keyword","kindModifiers":"","sortText":"15"},{"name":"return","kind":"keyword","kindModifiers":"","sortText":"15"},{"name":"satisfies","kind":"keyword","kindModifiers":"","sortText":"15"},{"name":"string","kind":"keyword","kindModifiers":"","sortText":"15"},{"name":"super","kind":"keyword","kindModifiers":"","sortText":"15"},{"name":"switch","kind":"keyword","kindModifiers":"","sortText":"15"},{"name":"symbol","kind":"keyword","kindModifiers":"","sortText":"15"},{"name":"this","kind":"keyword","kindModifiers":"","sortText":"15"},{"name":"throw","kind":"keyword","kindModifiers":"","sortText":"15"},{"name":"true","kind":"keyword","kindModifiers":"","sortText":"15"},{"name":"try","kind":"keyword","kindModifiers":"","sortText":"15"},{"name":"type","kind":"keyword","kindModifiers":"","sortText":"15"},{"name":"typeof","kind":"keyword","kindModifiers":"","sortText":"15"},{"name":"undefined","kind":"var","kindModifiers":"","sortText":"15"},{"name":"unique","kind":"keyword","kindModifiers":"","sortText":"15"},{"name":"unknown","kind":"keyword","kindModifiers":"","sortText":"15"},{"name":"var","kind":"keyword","kindModifiers":"","sortText":"15"},{"name":"void","kind":"keyword","kindModifiers":"","sortText":"15"},{"name":"while","kind":"keyword","kindModifiers":"","sortText":"15"},{"name":"with","kind":"keyword","kindModifiers":"","sortText":"15"},{"name":"yield","kind":"keyword","kindModifiers":"","sortText":"15"},{"name":"foo","kind":"const","kindModifiers":"export","sortText":"16","hasAction":true,"source":"/src/a","data":{"exportName":"foo","exportMapKey":"foo|*|","fileName":"/src/a.ts"}}]},"responseRequired":true} + request:{"seq":0,"type":"request","command":"completionInfo","arguments":{"file":"/src/c.ts","line":1,"offset":8}} + getCompletionData: Get current token: * + getCompletionData: Is inside comment: * +diff --git a/tests/baselines/reference/typeSatisfaction.errors.txt b/tests/baselines/reference/typeSatisfaction.errors.txt +new file mode 100644 +index 0000000000..c4b51c4768 +--- /dev/null ++++ b/tests/baselines/reference/typeSatisfaction.errors.txt +@@ -0,0 +1,44 @@ ++tests/cases/conformance/expressions/typeSatisfaction/typeSatisfaction.ts(12,20): error TS1360: Type '{ a: number; b: number; }' does not satisfy the expected type 'I1'. ++ Object literal may only specify known properties, and 'b' does not exist in type 'I1'. ++tests/cases/conformance/expressions/typeSatisfaction/typeSatisfaction.ts(13,26): error TS1360: Type '{}' does not satisfy the expected type 'I1'. ++ Property 'a' is missing in type '{}' but required in type 'I1'. ++tests/cases/conformance/expressions/typeSatisfaction/typeSatisfaction.ts(24,23): error TS1360: Type '{ a: string; b: string; }' does not satisfy the expected type 'A'. ++ Object literal may only specify known properties, and 'b' does not exist in type 'A'. ++ ++ ++==== tests/cases/conformance/expressions/typeSatisfaction/typeSatisfaction.ts (3 errors) ==== ++ interface I1 { ++ a: number; ++ } ++ ++ type T1 = { ++ a: "a" | "b"; ++ } ++ ++ type T2 = (x: string) => void; ++ ++ const t1 = { a: 1 } satisfies I1; // Ok ++ const t2 = { a: 1, b: 1 } satisfies I1; // Error ++ ~~~~ ++!!! error TS1360: Type '{ a: number; b: number; }' does not satisfy the expected type 'I1'. ++!!! error TS1360: Object literal may only specify known properties, and 'b' does not exist in type 'I1'. ++ const t3 = { } satisfies I1; // Error ++ ~~ ++!!! error TS1360: Type '{}' does not satisfy the expected type 'I1'. ++!!! error TS1360: Property 'a' is missing in type '{}' but required in type 'I1'. ++!!! related TS2728 tests/cases/conformance/expressions/typeSatisfaction/typeSatisfaction.ts:2:5: 'a' is declared here. ++ ++ const t4: T1 = { a: "a" } satisfies T1; // Ok ++ const t5 = (m => m.substring(0)) satisfies T2; // Ok ++ ++ const t6 = [1, 2] satisfies [number, number]; ++ ++ interface A { ++ a: string ++ } ++ let t7 = { a: 'test' } satisfies A; ++ let t8 = { a: 'test', b: 'test' } satisfies A; ++ ~~~~~~~~~ ++!!! error TS1360: Type '{ a: string; b: string; }' does not satisfy the expected type 'A'. ++!!! error TS1360: Object literal may only specify known properties, and 'b' does not exist in type 'A'. ++ +\ No newline at end of file +diff --git a/tests/baselines/reference/typeSatisfaction.js b/tests/baselines/reference/typeSatisfaction.js +new file mode 100644 +index 0000000000..646ac82d2b +--- /dev/null ++++ b/tests/baselines/reference/typeSatisfaction.js +@@ -0,0 +1,36 @@ ++//// [typeSatisfaction.ts] ++interface I1 { ++ a: number; ++} ++ ++type T1 = { ++ a: "a" | "b"; ++} ++ ++type T2 = (x: string) => void; ++ ++const t1 = { a: 1 } satisfies I1; // Ok ++const t2 = { a: 1, b: 1 } satisfies I1; // Error ++const t3 = { } satisfies I1; // Error ++ ++const t4: T1 = { a: "a" } satisfies T1; // Ok ++const t5 = (m => m.substring(0)) satisfies T2; // Ok ++ ++const t6 = [1, 2] satisfies [number, number]; ++ ++interface A { ++ a: string ++} ++let t7 = { a: 'test' } satisfies A; ++let t8 = { a: 'test', b: 'test' } satisfies A; ++ ++ ++//// [typeSatisfaction.js] ++var t1 = { a: 1 }; // Ok ++var t2 = { a: 1, b: 1 }; // Error ++var t3 = {}; // Error ++var t4 = { a: "a" }; // Ok ++var t5 = (function (m) { return m.substring(0); }); // Ok ++var t6 = [1, 2]; ++var t7 = { a: 'test' }; ++var t8 = { a: 'test', b: 'test' }; +diff --git a/tests/baselines/reference/typeSatisfaction.symbols b/tests/baselines/reference/typeSatisfaction.symbols +new file mode 100644 +index 0000000000..fb1f272825 +--- /dev/null ++++ b/tests/baselines/reference/typeSatisfaction.symbols +@@ -0,0 +1,68 @@ ++=== tests/cases/conformance/expressions/typeSatisfaction/typeSatisfaction.ts === ++interface I1 { ++>I1 : Symbol(I1, Decl(typeSatisfaction.ts, 0, 0)) ++ ++ a: number; ++>a : Symbol(I1.a, Decl(typeSatisfaction.ts, 0, 14)) ++} ++ ++type T1 = { ++>T1 : Symbol(T1, Decl(typeSatisfaction.ts, 2, 1)) ++ ++ a: "a" | "b"; ++>a : Symbol(a, Decl(typeSatisfaction.ts, 4, 11)) ++} ++ ++type T2 = (x: string) => void; ++>T2 : Symbol(T2, Decl(typeSatisfaction.ts, 6, 1)) ++>x : Symbol(x, Decl(typeSatisfaction.ts, 8, 11)) ++ ++const t1 = { a: 1 } satisfies I1; // Ok ++>t1 : Symbol(t1, Decl(typeSatisfaction.ts, 10, 5)) ++>a : Symbol(a, Decl(typeSatisfaction.ts, 10, 12)) ++>I1 : Symbol(I1, Decl(typeSatisfaction.ts, 0, 0)) ++ ++const t2 = { a: 1, b: 1 } satisfies I1; // Error ++>t2 : Symbol(t2, Decl(typeSatisfaction.ts, 11, 5)) ++>a : Symbol(a, Decl(typeSatisfaction.ts, 11, 12)) ++>b : Symbol(b, Decl(typeSatisfaction.ts, 11, 18)) ++>I1 : Symbol(I1, Decl(typeSatisfaction.ts, 0, 0)) ++ ++const t3 = { } satisfies I1; // Error ++>t3 : Symbol(t3, Decl(typeSatisfaction.ts, 12, 5)) ++>I1 : Symbol(I1, Decl(typeSatisfaction.ts, 0, 0)) ++ ++const t4: T1 = { a: "a" } satisfies T1; // Ok ++>t4 : Symbol(t4, Decl(typeSatisfaction.ts, 14, 5)) ++>T1 : Symbol(T1, Decl(typeSatisfaction.ts, 2, 1)) ++>a : Symbol(a, Decl(typeSatisfaction.ts, 14, 16)) ++>T1 : Symbol(T1, Decl(typeSatisfaction.ts, 2, 1)) ++ ++const t5 = (m => m.substring(0)) satisfies T2; // Ok ++>t5 : Symbol(t5, Decl(typeSatisfaction.ts, 15, 5)) ++>m : Symbol(m, Decl(typeSatisfaction.ts, 15, 12)) ++>m.substring : Symbol(String.substring, Decl(lib.es5.d.ts, --, --)) ++>m : Symbol(m, Decl(typeSatisfaction.ts, 15, 12)) ++>substring : Symbol(String.substring, Decl(lib.es5.d.ts, --, --)) ++>T2 : Symbol(T2, Decl(typeSatisfaction.ts, 6, 1)) ++ ++const t6 = [1, 2] satisfies [number, number]; ++>t6 : Symbol(t6, Decl(typeSatisfaction.ts, 17, 5)) ++ ++interface A { ++>A : Symbol(A, Decl(typeSatisfaction.ts, 17, 45)) ++ ++ a: string ++>a : Symbol(A.a, Decl(typeSatisfaction.ts, 19, 13)) ++} ++let t7 = { a: 'test' } satisfies A; ++>t7 : Symbol(t7, Decl(typeSatisfaction.ts, 22, 3)) ++>a : Symbol(a, Decl(typeSatisfaction.ts, 22, 10)) ++>A : Symbol(A, Decl(typeSatisfaction.ts, 17, 45)) ++ ++let t8 = { a: 'test', b: 'test' } satisfies A; ++>t8 : Symbol(t8, Decl(typeSatisfaction.ts, 23, 3)) ++>a : Symbol(a, Decl(typeSatisfaction.ts, 23, 10)) ++>b : Symbol(b, Decl(typeSatisfaction.ts, 23, 21)) ++>A : Symbol(A, Decl(typeSatisfaction.ts, 17, 45)) ++ +diff --git a/tests/baselines/reference/typeSatisfaction.types b/tests/baselines/reference/typeSatisfaction.types +new file mode 100644 +index 0000000000..1addf9346e +--- /dev/null ++++ b/tests/baselines/reference/typeSatisfaction.types +@@ -0,0 +1,84 @@ ++=== tests/cases/conformance/expressions/typeSatisfaction/typeSatisfaction.ts === ++interface I1 { ++ a: number; ++>a : number ++} ++ ++type T1 = { ++>T1 : { a: "a" | "b"; } ++ ++ a: "a" | "b"; ++>a : "a" | "b" ++} ++ ++type T2 = (x: string) => void; ++>T2 : (x: string) => void ++>x : string ++ ++const t1 = { a: 1 } satisfies I1; // Ok ++>t1 : { a: number; } ++>{ a: 1 } satisfies I1 : { a: number; } ++>{ a: 1 } : { a: number; } ++>a : number ++>1 : 1 ++ ++const t2 = { a: 1, b: 1 } satisfies I1; // Error ++>t2 : { a: number; b: number; } ++>{ a: 1, b: 1 } satisfies I1 : { a: number; b: number; } ++>{ a: 1, b: 1 } : { a: number; b: number; } ++>a : number ++>1 : 1 ++>b : number ++>1 : 1 ++ ++const t3 = { } satisfies I1; // Error ++>t3 : {} ++>{ } satisfies I1 : {} ++>{ } : {} ++ ++const t4: T1 = { a: "a" } satisfies T1; // Ok ++>t4 : T1 ++>{ a: "a" } satisfies T1 : { a: "a"; } ++>{ a: "a" } : { a: "a"; } ++>a : "a" ++>"a" : "a" ++ ++const t5 = (m => m.substring(0)) satisfies T2; // Ok ++>t5 : (m: string) => string ++>(m => m.substring(0)) satisfies T2 : (m: string) => string ++>(m => m.substring(0)) : (m: string) => string ++>m => m.substring(0) : (m: string) => string ++>m : string ++>m.substring(0) : string ++>m.substring : (start: number, end?: number) => string ++>m : string ++>substring : (start: number, end?: number) => string ++>0 : 0 ++ ++const t6 = [1, 2] satisfies [number, number]; ++>t6 : [number, number] ++>[1, 2] satisfies [number, number] : [number, number] ++>[1, 2] : [number, number] ++>1 : 1 ++>2 : 2 ++ ++interface A { ++ a: string ++>a : string ++} ++let t7 = { a: 'test' } satisfies A; ++>t7 : { a: string; } ++>{ a: 'test' } satisfies A : { a: string; } ++>{ a: 'test' } : { a: string; } ++>a : string ++>'test' : "test" ++ ++let t8 = { a: 'test', b: 'test' } satisfies A; ++>t8 : { a: string; b: string; } ++>{ a: 'test', b: 'test' } satisfies A : { a: string; b: string; } ++>{ a: 'test', b: 'test' } : { a: string; b: string; } ++>a : string ++>'test' : "test" ++>b : string ++>'test' : "test" ++ +diff --git a/tests/baselines/reference/typeSatisfactionWithDefaultExport.errors.txt b/tests/baselines/reference/typeSatisfactionWithDefaultExport.errors.txt +new file mode 100644 +index 0000000000..f960726de5 +--- /dev/null ++++ b/tests/baselines/reference/typeSatisfactionWithDefaultExport.errors.txt +@@ -0,0 +1,20 @@ ++tests/cases/conformance/expressions/typeSatisfaction/a.ts(4,29): error TS1360: Type '{}' does not satisfy the expected type 'Foo'. ++ Property 'a' is missing in type '{}' but required in type 'Foo'. ++ ++ ++==== tests/cases/conformance/expressions/typeSatisfaction/a.ts (1 errors) ==== ++ interface Foo { ++ a: number; ++ } ++ export default {} satisfies Foo; ++ ~~~ ++!!! error TS1360: Type '{}' does not satisfy the expected type 'Foo'. ++!!! error TS1360: Property 'a' is missing in type '{}' but required in type 'Foo'. ++!!! related TS2728 tests/cases/conformance/expressions/typeSatisfaction/a.ts:2:5: 'a' is declared here. ++ ++==== tests/cases/conformance/expressions/typeSatisfaction/b.ts (0 errors) ==== ++ interface Foo { ++ a: number; ++ } ++ export default { a: 1 } satisfies Foo; ++ +\ No newline at end of file +diff --git a/tests/baselines/reference/typeSatisfactionWithDefaultExport.js b/tests/baselines/reference/typeSatisfactionWithDefaultExport.js +new file mode 100644 +index 0000000000..ba29570420 +--- /dev/null ++++ b/tests/baselines/reference/typeSatisfactionWithDefaultExport.js +@@ -0,0 +1,19 @@ ++//// [tests/cases/conformance/expressions/typeSatisfaction/typeSatisfactionWithDefaultExport.ts] //// ++ ++//// [a.ts] ++interface Foo { ++ a: number; ++} ++export default {} satisfies Foo; ++ ++//// [b.ts] ++interface Foo { ++ a: number; ++} ++export default { a: 1 } satisfies Foo; ++ ++ ++//// [a.js] ++export default {}; ++//// [b.js] ++export default { a: 1 }; +diff --git a/tests/baselines/reference/typeSatisfactionWithDefaultExport.symbols b/tests/baselines/reference/typeSatisfactionWithDefaultExport.symbols +new file mode 100644 +index 0000000000..135876487d +--- /dev/null ++++ b/tests/baselines/reference/typeSatisfactionWithDefaultExport.symbols +@@ -0,0 +1,21 @@ ++=== tests/cases/conformance/expressions/typeSatisfaction/a.ts === ++interface Foo { ++>Foo : Symbol(Foo, Decl(a.ts, 0, 0)) ++ ++ a: number; ++>a : Symbol(Foo.a, Decl(a.ts, 0, 15)) ++} ++export default {} satisfies Foo; ++>Foo : Symbol(Foo, Decl(a.ts, 0, 0)) ++ ++=== tests/cases/conformance/expressions/typeSatisfaction/b.ts === ++interface Foo { ++>Foo : Symbol(Foo, Decl(b.ts, 0, 0)) ++ ++ a: number; ++>a : Symbol(Foo.a, Decl(b.ts, 0, 15)) ++} ++export default { a: 1 } satisfies Foo; ++>a : Symbol(a, Decl(b.ts, 3, 16)) ++>Foo : Symbol(Foo, Decl(b.ts, 0, 0)) ++ +diff --git a/tests/baselines/reference/typeSatisfactionWithDefaultExport.types b/tests/baselines/reference/typeSatisfactionWithDefaultExport.types +new file mode 100644 +index 0000000000..6f281cea3c +--- /dev/null ++++ b/tests/baselines/reference/typeSatisfactionWithDefaultExport.types +@@ -0,0 +1,20 @@ ++=== tests/cases/conformance/expressions/typeSatisfaction/a.ts === ++interface Foo { ++ a: number; ++>a : number ++} ++export default {} satisfies Foo; ++>{} satisfies Foo : {} ++>{} : {} ++ ++=== tests/cases/conformance/expressions/typeSatisfaction/b.ts === ++interface Foo { ++ a: number; ++>a : number ++} ++export default { a: 1 } satisfies Foo; ++>{ a: 1 } satisfies Foo : { a: number; } ++>{ a: 1 } : { a: number; } ++>a : number ++>1 : 1 ++ +diff --git a/tests/baselines/reference/typeSatisfaction_contextualTyping1.js b/tests/baselines/reference/typeSatisfaction_contextualTyping1.js +new file mode 100644 +index 0000000000..e8b5cd7246 +--- /dev/null ++++ b/tests/baselines/reference/typeSatisfaction_contextualTyping1.js +@@ -0,0 +1,14 @@ ++//// [typeSatisfaction_contextualTyping1.ts] ++type Predicates = { [s: string]: (n: number) => boolean }; ++ ++const p = { ++ isEven: n => n % 2 === 0, ++ isOdd: n => n % 2 === 1 ++} satisfies Predicates; ++ ++ ++//// [typeSatisfaction_contextualTyping1.js] ++var p = { ++ isEven: function (n) { return n % 2 === 0; }, ++ isOdd: function (n) { return n % 2 === 1; } ++}; +diff --git a/tests/baselines/reference/typeSatisfaction_contextualTyping1.symbols b/tests/baselines/reference/typeSatisfaction_contextualTyping1.symbols +new file mode 100644 +index 0000000000..0b44d64dd6 +--- /dev/null ++++ b/tests/baselines/reference/typeSatisfaction_contextualTyping1.symbols +@@ -0,0 +1,22 @@ ++=== tests/cases/conformance/expressions/typeSatisfaction/typeSatisfaction_contextualTyping1.ts === ++type Predicates = { [s: string]: (n: number) => boolean }; ++>Predicates : Symbol(Predicates, Decl(typeSatisfaction_contextualTyping1.ts, 0, 0)) ++>s : Symbol(s, Decl(typeSatisfaction_contextualTyping1.ts, 0, 21)) ++>n : Symbol(n, Decl(typeSatisfaction_contextualTyping1.ts, 0, 34)) ++ ++const p = { ++>p : Symbol(p, Decl(typeSatisfaction_contextualTyping1.ts, 2, 5)) ++ ++ isEven: n => n % 2 === 0, ++>isEven : Symbol(isEven, Decl(typeSatisfaction_contextualTyping1.ts, 2, 11)) ++>n : Symbol(n, Decl(typeSatisfaction_contextualTyping1.ts, 3, 11)) ++>n : Symbol(n, Decl(typeSatisfaction_contextualTyping1.ts, 3, 11)) ++ ++ isOdd: n => n % 2 === 1 ++>isOdd : Symbol(isOdd, Decl(typeSatisfaction_contextualTyping1.ts, 3, 29)) ++>n : Symbol(n, Decl(typeSatisfaction_contextualTyping1.ts, 4, 10)) ++>n : Symbol(n, Decl(typeSatisfaction_contextualTyping1.ts, 4, 10)) ++ ++} satisfies Predicates; ++>Predicates : Symbol(Predicates, Decl(typeSatisfaction_contextualTyping1.ts, 0, 0)) ++ +diff --git a/tests/baselines/reference/typeSatisfaction_contextualTyping1.types b/tests/baselines/reference/typeSatisfaction_contextualTyping1.types +new file mode 100644 +index 0000000000..31e193b6f9 +--- /dev/null ++++ b/tests/baselines/reference/typeSatisfaction_contextualTyping1.types +@@ -0,0 +1,33 @@ ++=== tests/cases/conformance/expressions/typeSatisfaction/typeSatisfaction_contextualTyping1.ts === ++type Predicates = { [s: string]: (n: number) => boolean }; ++>Predicates : { [s: string]: (n: number) => boolean; } ++>s : string ++>n : number ++ ++const p = { ++>p : { isEven: (n: number) => boolean; isOdd: (n: number) => boolean; } ++>{ isEven: n => n % 2 === 0, isOdd: n => n % 2 === 1} satisfies Predicates : { isEven: (n: number) => boolean; isOdd: (n: number) => boolean; } ++>{ isEven: n => n % 2 === 0, isOdd: n => n % 2 === 1} : { isEven: (n: number) => boolean; isOdd: (n: number) => boolean; } ++ ++ isEven: n => n % 2 === 0, ++>isEven : (n: number) => boolean ++>n => n % 2 === 0 : (n: number) => boolean ++>n : number ++>n % 2 === 0 : boolean ++>n % 2 : number ++>n : number ++>2 : 2 ++>0 : 0 ++ ++ isOdd: n => n % 2 === 1 ++>isOdd : (n: number) => boolean ++>n => n % 2 === 1 : (n: number) => boolean ++>n : number ++>n % 2 === 1 : boolean ++>n % 2 : number ++>n : number ++>2 : 2 ++>1 : 1 ++ ++} satisfies Predicates; ++ +diff --git a/tests/baselines/reference/typeSatisfaction_contextualTyping2.errors.txt b/tests/baselines/reference/typeSatisfaction_contextualTyping2.errors.txt +new file mode 100644 +index 0000000000..2014bb3930 +--- /dev/null ++++ b/tests/baselines/reference/typeSatisfaction_contextualTyping2.errors.txt +@@ -0,0 +1,14 @@ ++tests/cases/conformance/expressions/typeSatisfaction/typeSatisfaction_contextualTyping2.ts(2,7): error TS7006: Parameter 's' implicitly has an 'any' type. ++ ++ ++==== tests/cases/conformance/expressions/typeSatisfaction/typeSatisfaction_contextualTyping2.ts (1 errors) ==== ++ let obj: { f(s: string): void } & Record = { ++ f(s) { }, // "incorrect" implicit any on 's' ++ ~ ++!!! error TS7006: Parameter 's' implicitly has an 'any' type. ++ g(s) { } ++ } satisfies { g(s: string): void } & Record; ++ ++ // This needs to not crash (outer node is not expression) ++ ({ f(x) { } }) satisfies { f(s: string): void }; ++ +\ No newline at end of file +diff --git a/tests/baselines/reference/typeSatisfaction_contextualTyping2.js b/tests/baselines/reference/typeSatisfaction_contextualTyping2.js +new file mode 100644 +index 0000000000..a8c0bb41ec +--- /dev/null ++++ b/tests/baselines/reference/typeSatisfaction_contextualTyping2.js +@@ -0,0 +1,18 @@ ++//// [typeSatisfaction_contextualTyping2.ts] ++let obj: { f(s: string): void } & Record = { ++ f(s) { }, // "incorrect" implicit any on 's' ++ g(s) { } ++} satisfies { g(s: string): void } & Record; ++ ++// This needs to not crash (outer node is not expression) ++({ f(x) { } }) satisfies { f(s: string): void }; ++ ++ ++//// [typeSatisfaction_contextualTyping2.js] ++"use strict"; ++var obj = { ++ f: function (s) { }, ++ g: function (s) { } ++}; ++// This needs to not crash (outer node is not expression) ++({ f: function (x) { } }); +diff --git a/tests/baselines/reference/typeSatisfaction_contextualTyping2.symbols b/tests/baselines/reference/typeSatisfaction_contextualTyping2.symbols +new file mode 100644 +index 0000000000..d7bda841fb +--- /dev/null ++++ b/tests/baselines/reference/typeSatisfaction_contextualTyping2.symbols +@@ -0,0 +1,27 @@ ++=== tests/cases/conformance/expressions/typeSatisfaction/typeSatisfaction_contextualTyping2.ts === ++let obj: { f(s: string): void } & Record = { ++>obj : Symbol(obj, Decl(typeSatisfaction_contextualTyping2.ts, 0, 3)) ++>f : Symbol(f, Decl(typeSatisfaction_contextualTyping2.ts, 0, 10)) ++>s : Symbol(s, Decl(typeSatisfaction_contextualTyping2.ts, 0, 13)) ++>Record : Symbol(Record, Decl(lib.es5.d.ts, --, --)) ++ ++ f(s) { }, // "incorrect" implicit any on 's' ++>f : Symbol(f, Decl(typeSatisfaction_contextualTyping2.ts, 0, 61)) ++>s : Symbol(s, Decl(typeSatisfaction_contextualTyping2.ts, 1, 6)) ++ ++ g(s) { } ++>g : Symbol(g, Decl(typeSatisfaction_contextualTyping2.ts, 1, 13)) ++>s : Symbol(s, Decl(typeSatisfaction_contextualTyping2.ts, 2, 6)) ++ ++} satisfies { g(s: string): void } & Record; ++>g : Symbol(g, Decl(typeSatisfaction_contextualTyping2.ts, 3, 13)) ++>s : Symbol(s, Decl(typeSatisfaction_contextualTyping2.ts, 3, 16)) ++>Record : Symbol(Record, Decl(lib.es5.d.ts, --, --)) ++ ++// This needs to not crash (outer node is not expression) ++({ f(x) { } }) satisfies { f(s: string): void }; ++>f : Symbol(f, Decl(typeSatisfaction_contextualTyping2.ts, 6, 2)) ++>x : Symbol(x, Decl(typeSatisfaction_contextualTyping2.ts, 6, 5)) ++>f : Symbol(f, Decl(typeSatisfaction_contextualTyping2.ts, 6, 26)) ++>s : Symbol(s, Decl(typeSatisfaction_contextualTyping2.ts, 6, 29)) ++ +diff --git a/tests/baselines/reference/typeSatisfaction_contextualTyping2.types b/tests/baselines/reference/typeSatisfaction_contextualTyping2.types +new file mode 100644 +index 0000000000..a23bf1ee8d +--- /dev/null ++++ b/tests/baselines/reference/typeSatisfaction_contextualTyping2.types +@@ -0,0 +1,30 @@ ++=== tests/cases/conformance/expressions/typeSatisfaction/typeSatisfaction_contextualTyping2.ts === ++let obj: { f(s: string): void } & Record = { ++>obj : { f(s: string): void; } & Record ++>f : (s: string) => void ++>s : string ++>{ f(s) { }, // "incorrect" implicit any on 's' g(s) { }} satisfies { g(s: string): void } & Record : { f(s: any): void; g(s: string): void; } ++>{ f(s) { }, // "incorrect" implicit any on 's' g(s) { }} : { f(s: any): void; g(s: string): void; } ++ ++ f(s) { }, // "incorrect" implicit any on 's' ++>f : (s: any) => void ++>s : any ++ ++ g(s) { } ++>g : (s: string) => void ++>s : string ++ ++} satisfies { g(s: string): void } & Record; ++>g : (s: string) => void ++>s : string ++ ++// This needs to not crash (outer node is not expression) ++({ f(x) { } }) satisfies { f(s: string): void }; ++>({ f(x) { } }) satisfies { f(s: string): void } : { f(x: string): void; } ++>({ f(x) { } }) : { f(x: string): void; } ++>{ f(x) { } } : { f(x: string): void; } ++>f : (x: string) => void ++>x : string ++>f : (s: string) => void ++>s : string ++ +diff --git a/tests/baselines/reference/typeSatisfaction_ensureInterfaceImpl.js b/tests/baselines/reference/typeSatisfaction_ensureInterfaceImpl.js +new file mode 100644 +index 0000000000..e33ac953b4 +--- /dev/null ++++ b/tests/baselines/reference/typeSatisfaction_ensureInterfaceImpl.js +@@ -0,0 +1,22 @@ ++//// [typeSatisfaction_ensureInterfaceImpl.ts] ++type Movable = { ++ move(distance: number): void; ++}; ++ ++const car = { ++ start() { }, ++ move(d) { ++ // d should be number ++ }, ++ stop() { } ++} satisfies Movable & Record; ++ ++ ++//// [typeSatisfaction_ensureInterfaceImpl.js] ++var car = { ++ start: function () { }, ++ move: function (d) { ++ // d should be number ++ }, ++ stop: function () { } ++}; +diff --git a/tests/baselines/reference/typeSatisfaction_ensureInterfaceImpl.symbols b/tests/baselines/reference/typeSatisfaction_ensureInterfaceImpl.symbols +new file mode 100644 +index 0000000000..afcab39149 +--- /dev/null ++++ b/tests/baselines/reference/typeSatisfaction_ensureInterfaceImpl.symbols +@@ -0,0 +1,29 @@ ++=== tests/cases/conformance/expressions/typeSatisfaction/typeSatisfaction_ensureInterfaceImpl.ts === ++type Movable = { ++>Movable : Symbol(Movable, Decl(typeSatisfaction_ensureInterfaceImpl.ts, 0, 0)) ++ ++ move(distance: number): void; ++>move : Symbol(move, Decl(typeSatisfaction_ensureInterfaceImpl.ts, 0, 16)) ++>distance : Symbol(distance, Decl(typeSatisfaction_ensureInterfaceImpl.ts, 1, 9)) ++ ++}; ++ ++const car = { ++>car : Symbol(car, Decl(typeSatisfaction_ensureInterfaceImpl.ts, 4, 5)) ++ ++ start() { }, ++>start : Symbol(start, Decl(typeSatisfaction_ensureInterfaceImpl.ts, 4, 13)) ++ ++ move(d) { ++>move : Symbol(move, Decl(typeSatisfaction_ensureInterfaceImpl.ts, 5, 16)) ++>d : Symbol(d, Decl(typeSatisfaction_ensureInterfaceImpl.ts, 6, 9)) ++ ++ // d should be number ++ }, ++ stop() { } ++>stop : Symbol(stop, Decl(typeSatisfaction_ensureInterfaceImpl.ts, 8, 6)) ++ ++} satisfies Movable & Record; ++>Movable : Symbol(Movable, Decl(typeSatisfaction_ensureInterfaceImpl.ts, 0, 0)) ++>Record : Symbol(Record, Decl(lib.es5.d.ts, --, --)) ++ +diff --git a/tests/baselines/reference/typeSatisfaction_ensureInterfaceImpl.types b/tests/baselines/reference/typeSatisfaction_ensureInterfaceImpl.types +new file mode 100644 +index 0000000000..6c839be872 +--- /dev/null ++++ b/tests/baselines/reference/typeSatisfaction_ensureInterfaceImpl.types +@@ -0,0 +1,29 @@ ++=== tests/cases/conformance/expressions/typeSatisfaction/typeSatisfaction_ensureInterfaceImpl.ts === ++type Movable = { ++>Movable : { move(distance: number): void; } ++ ++ move(distance: number): void; ++>move : (distance: number) => void ++>distance : number ++ ++}; ++ ++const car = { ++>car : { start(): void; move(d: number): void; stop(): void; } ++>{ start() { }, move(d) { // d should be number }, stop() { }} satisfies Movable & Record : { start(): void; move(d: number): void; stop(): void; } ++>{ start() { }, move(d) { // d should be number }, stop() { }} : { start(): void; move(d: number): void; stop(): void; } ++ ++ start() { }, ++>start : () => void ++ ++ move(d) { ++>move : (d: number) => void ++>d : number ++ ++ // d should be number ++ }, ++ stop() { } ++>stop : () => void ++ ++} satisfies Movable & Record; ++ +diff --git a/tests/baselines/reference/typeSatisfaction_js.errors.txt b/tests/baselines/reference/typeSatisfaction_js.errors.txt +new file mode 100644 +index 0000000000..0858b35c7e +--- /dev/null ++++ b/tests/baselines/reference/typeSatisfaction_js.errors.txt +@@ -0,0 +1,8 @@ ++/src/a.js(1,29): error TS8037: Type satisfaction expressions can only be used in TypeScript files. ++ ++ ++==== /src/a.js (1 errors) ==== ++ var v = undefined satisfies 1; ++ ~ ++!!! error TS8037: Type satisfaction expressions can only be used in TypeScript files. ++ +\ No newline at end of file +diff --git a/tests/baselines/reference/typeSatisfaction_js.js b/tests/baselines/reference/typeSatisfaction_js.js +new file mode 100644 +index 0000000000..3d28ea0e26 +--- /dev/null ++++ b/tests/baselines/reference/typeSatisfaction_js.js +@@ -0,0 +1,6 @@ ++//// [a.js] ++var v = undefined satisfies 1; ++ ++ ++//// [a.js] ++var v = undefined; +diff --git a/tests/baselines/reference/typeSatisfaction_js.symbols b/tests/baselines/reference/typeSatisfaction_js.symbols +new file mode 100644 +index 0000000000..e5424113f5 +--- /dev/null ++++ b/tests/baselines/reference/typeSatisfaction_js.symbols +@@ -0,0 +1,5 @@ ++=== /src/a.js === ++var v = undefined satisfies 1; ++>v : Symbol(v, Decl(a.js, 0, 3)) ++>undefined : Symbol(undefined) ++ +diff --git a/tests/baselines/reference/typeSatisfaction_js.types b/tests/baselines/reference/typeSatisfaction_js.types +new file mode 100644 +index 0000000000..dde08ce298 +--- /dev/null ++++ b/tests/baselines/reference/typeSatisfaction_js.types +@@ -0,0 +1,6 @@ ++=== /src/a.js === ++var v = undefined satisfies 1; ++>v : any ++>undefined satisfies 1 : undefined ++>undefined : undefined ++ +diff --git a/tests/baselines/reference/typeSatisfaction_optionalMemberConformance.errors.txt b/tests/baselines/reference/typeSatisfaction_optionalMemberConformance.errors.txt +new file mode 100644 +index 0000000000..c45de3250d +--- /dev/null ++++ b/tests/baselines/reference/typeSatisfaction_optionalMemberConformance.errors.txt +@@ -0,0 +1,14 @@ ++tests/cases/conformance/expressions/typeSatisfaction/typeSatisfaction_optionalMemberConformance.ts(7,11): error TS2339: Property 'y' does not exist on type '{ x: number; }'. ++ ++ ++==== tests/cases/conformance/expressions/typeSatisfaction/typeSatisfaction_optionalMemberConformance.ts (1 errors) ==== ++ type Point2d = { x: number, y: number }; ++ // Undesirable behavior today with type annotation ++ const a = { x: 10 } satisfies Partial; ++ // Should OK ++ console.log(a.x.toFixed()); ++ // Should error ++ let p = a.y; ++ ~ ++!!! error TS2339: Property 'y' does not exist on type '{ x: number; }'. ++ +\ No newline at end of file +diff --git a/tests/baselines/reference/typeSatisfaction_optionalMemberConformance.js b/tests/baselines/reference/typeSatisfaction_optionalMemberConformance.js +new file mode 100644 +index 0000000000..d21648cfb1 +--- /dev/null ++++ b/tests/baselines/reference/typeSatisfaction_optionalMemberConformance.js +@@ -0,0 +1,17 @@ ++//// [typeSatisfaction_optionalMemberConformance.ts] ++type Point2d = { x: number, y: number }; ++// Undesirable behavior today with type annotation ++const a = { x: 10 } satisfies Partial; ++// Should OK ++console.log(a.x.toFixed()); ++// Should error ++let p = a.y; ++ ++ ++//// [typeSatisfaction_optionalMemberConformance.js] ++// Undesirable behavior today with type annotation ++var a = { x: 10 }; ++// Should OK ++console.log(a.x.toFixed()); ++// Should error ++var p = a.y; +diff --git a/tests/baselines/reference/typeSatisfaction_optionalMemberConformance.symbols b/tests/baselines/reference/typeSatisfaction_optionalMemberConformance.symbols +new file mode 100644 +index 0000000000..d1f6bbc047 +--- /dev/null ++++ b/tests/baselines/reference/typeSatisfaction_optionalMemberConformance.symbols +@@ -0,0 +1,29 @@ ++=== tests/cases/conformance/expressions/typeSatisfaction/typeSatisfaction_optionalMemberConformance.ts === ++type Point2d = { x: number, y: number }; ++>Point2d : Symbol(Point2d, Decl(typeSatisfaction_optionalMemberConformance.ts, 0, 0)) ++>x : Symbol(x, Decl(typeSatisfaction_optionalMemberConformance.ts, 0, 16)) ++>y : Symbol(y, Decl(typeSatisfaction_optionalMemberConformance.ts, 0, 27)) ++ ++// Undesirable behavior today with type annotation ++const a = { x: 10 } satisfies Partial; ++>a : Symbol(a, Decl(typeSatisfaction_optionalMemberConformance.ts, 2, 5)) ++>x : Symbol(x, Decl(typeSatisfaction_optionalMemberConformance.ts, 2, 11)) ++>Partial : Symbol(Partial, Decl(lib.es5.d.ts, --, --)) ++>Point2d : Symbol(Point2d, Decl(typeSatisfaction_optionalMemberConformance.ts, 0, 0)) ++ ++// Should OK ++console.log(a.x.toFixed()); ++>console.log : Symbol(Console.log, Decl(lib.dom.d.ts, --, --)) ++>console : Symbol(console, Decl(lib.dom.d.ts, --, --)) ++>log : Symbol(Console.log, Decl(lib.dom.d.ts, --, --)) ++>a.x.toFixed : Symbol(Number.toFixed, Decl(lib.es5.d.ts, --, --)) ++>a.x : Symbol(x, Decl(typeSatisfaction_optionalMemberConformance.ts, 2, 11)) ++>a : Symbol(a, Decl(typeSatisfaction_optionalMemberConformance.ts, 2, 5)) ++>x : Symbol(x, Decl(typeSatisfaction_optionalMemberConformance.ts, 2, 11)) ++>toFixed : Symbol(Number.toFixed, Decl(lib.es5.d.ts, --, --)) ++ ++// Should error ++let p = a.y; ++>p : Symbol(p, Decl(typeSatisfaction_optionalMemberConformance.ts, 6, 3)) ++>a : Symbol(a, Decl(typeSatisfaction_optionalMemberConformance.ts, 2, 5)) ++ +diff --git a/tests/baselines/reference/typeSatisfaction_optionalMemberConformance.types b/tests/baselines/reference/typeSatisfaction_optionalMemberConformance.types +new file mode 100644 +index 0000000000..50d2c335ea +--- /dev/null ++++ b/tests/baselines/reference/typeSatisfaction_optionalMemberConformance.types +@@ -0,0 +1,34 @@ ++=== tests/cases/conformance/expressions/typeSatisfaction/typeSatisfaction_optionalMemberConformance.ts === ++type Point2d = { x: number, y: number }; ++>Point2d : { x: number; y: number; } ++>x : number ++>y : number ++ ++// Undesirable behavior today with type annotation ++const a = { x: 10 } satisfies Partial; ++>a : { x: number; } ++>{ x: 10 } satisfies Partial : { x: number; } ++>{ x: 10 } : { x: number; } ++>x : number ++>10 : 10 ++ ++// Should OK ++console.log(a.x.toFixed()); ++>console.log(a.x.toFixed()) : void ++>console.log : (...data: any[]) => void ++>console : Console ++>log : (...data: any[]) => void ++>a.x.toFixed() : string ++>a.x.toFixed : (fractionDigits?: number) => string ++>a.x : number ++>a : { x: number; } ++>x : number ++>toFixed : (fractionDigits?: number) => string ++ ++// Should error ++let p = a.y; ++>p : any ++>a.y : any ++>a : { x: number; } ++>y : any ++ +diff --git a/tests/baselines/reference/typeSatisfaction_propNameConstraining.errors.txt b/tests/baselines/reference/typeSatisfaction_propNameConstraining.errors.txt +new file mode 100644 +index 0000000000..a0162567a7 +--- /dev/null ++++ b/tests/baselines/reference/typeSatisfaction_propNameConstraining.errors.txt +@@ -0,0 +1,25 @@ ++tests/cases/conformance/expressions/typeSatisfaction/typeSatisfaction_propNameConstraining.ts(6,5): error TS1360: Type '{ a: number; b: string; x: number; }' does not satisfy the expected type 'Partial>'. ++ Object literal may only specify known properties, and 'x' does not exist in type 'Partial>'. ++tests/cases/conformance/expressions/typeSatisfaction/typeSatisfaction_propNameConstraining.ts(13,11): error TS2339: Property 'd' does not exist on type '{ a: number; b: string; x: number; }'. ++ ++ ++==== tests/cases/conformance/expressions/typeSatisfaction/typeSatisfaction_propNameConstraining.ts (2 errors) ==== ++ type Keys = 'a' | 'b' | 'c' | 'd'; ++ ++ const p = { ++ a: 0, ++ b: "hello", ++ x: 8 // Should error, 'x' isn't in 'Keys' ++ ~~~~ ++!!! error TS1360: Type '{ a: number; b: string; x: number; }' does not satisfy the expected type 'Partial>'. ++!!! error TS1360: Object literal may only specify known properties, and 'x' does not exist in type 'Partial>'. ++ } satisfies Partial>; ++ ++ // Should be OK -- retain info that a is number and b is string ++ let a = p.a.toFixed(); ++ let b = p.b.substring(1); ++ // Should error even though 'd' is in 'Keys' ++ let d = p.d; ++ ~ ++!!! error TS2339: Property 'd' does not exist on type '{ a: number; b: string; x: number; }'. ++ +\ No newline at end of file +diff --git a/tests/baselines/reference/typeSatisfaction_propNameConstraining.js b/tests/baselines/reference/typeSatisfaction_propNameConstraining.js +new file mode 100644 +index 0000000000..64490c480a +--- /dev/null ++++ b/tests/baselines/reference/typeSatisfaction_propNameConstraining.js +@@ -0,0 +1,27 @@ ++//// [typeSatisfaction_propNameConstraining.ts] ++type Keys = 'a' | 'b' | 'c' | 'd'; ++ ++const p = { ++ a: 0, ++ b: "hello", ++ x: 8 // Should error, 'x' isn't in 'Keys' ++} satisfies Partial>; ++ ++// Should be OK -- retain info that a is number and b is string ++let a = p.a.toFixed(); ++let b = p.b.substring(1); ++// Should error even though 'd' is in 'Keys' ++let d = p.d; ++ ++ ++//// [typeSatisfaction_propNameConstraining.js] ++var p = { ++ a: 0, ++ b: "hello", ++ x: 8 // Should error, 'x' isn't in 'Keys' ++}; ++// Should be OK -- retain info that a is number and b is string ++var a = p.a.toFixed(); ++var b = p.b.substring(1); ++// Should error even though 'd' is in 'Keys' ++var d = p.d; +diff --git a/tests/baselines/reference/typeSatisfaction_propNameConstraining.symbols b/tests/baselines/reference/typeSatisfaction_propNameConstraining.symbols +new file mode 100644 +index 0000000000..d846ceda53 +--- /dev/null ++++ b/tests/baselines/reference/typeSatisfaction_propNameConstraining.symbols +@@ -0,0 +1,43 @@ ++=== tests/cases/conformance/expressions/typeSatisfaction/typeSatisfaction_propNameConstraining.ts === ++type Keys = 'a' | 'b' | 'c' | 'd'; ++>Keys : Symbol(Keys, Decl(typeSatisfaction_propNameConstraining.ts, 0, 0)) ++ ++const p = { ++>p : Symbol(p, Decl(typeSatisfaction_propNameConstraining.ts, 2, 5)) ++ ++ a: 0, ++>a : Symbol(a, Decl(typeSatisfaction_propNameConstraining.ts, 2, 11)) ++ ++ b: "hello", ++>b : Symbol(b, Decl(typeSatisfaction_propNameConstraining.ts, 3, 9)) ++ ++ x: 8 // Should error, 'x' isn't in 'Keys' ++>x : Symbol(x, Decl(typeSatisfaction_propNameConstraining.ts, 4, 15)) ++ ++} satisfies Partial>; ++>Partial : Symbol(Partial, Decl(lib.es5.d.ts, --, --)) ++>Record : Symbol(Record, Decl(lib.es5.d.ts, --, --)) ++>Keys : Symbol(Keys, Decl(typeSatisfaction_propNameConstraining.ts, 0, 0)) ++ ++// Should be OK -- retain info that a is number and b is string ++let a = p.a.toFixed(); ++>a : Symbol(a, Decl(typeSatisfaction_propNameConstraining.ts, 9, 3)) ++>p.a.toFixed : Symbol(Number.toFixed, Decl(lib.es5.d.ts, --, --)) ++>p.a : Symbol(a, Decl(typeSatisfaction_propNameConstraining.ts, 2, 11)) ++>p : Symbol(p, Decl(typeSatisfaction_propNameConstraining.ts, 2, 5)) ++>a : Symbol(a, Decl(typeSatisfaction_propNameConstraining.ts, 2, 11)) ++>toFixed : Symbol(Number.toFixed, Decl(lib.es5.d.ts, --, --)) ++ ++let b = p.b.substring(1); ++>b : Symbol(b, Decl(typeSatisfaction_propNameConstraining.ts, 10, 3)) ++>p.b.substring : Symbol(String.substring, Decl(lib.es5.d.ts, --, --)) ++>p.b : Symbol(b, Decl(typeSatisfaction_propNameConstraining.ts, 3, 9)) ++>p : Symbol(p, Decl(typeSatisfaction_propNameConstraining.ts, 2, 5)) ++>b : Symbol(b, Decl(typeSatisfaction_propNameConstraining.ts, 3, 9)) ++>substring : Symbol(String.substring, Decl(lib.es5.d.ts, --, --)) ++ ++// Should error even though 'd' is in 'Keys' ++let d = p.d; ++>d : Symbol(d, Decl(typeSatisfaction_propNameConstraining.ts, 12, 3)) ++>p : Symbol(p, Decl(typeSatisfaction_propNameConstraining.ts, 2, 5)) ++ +diff --git a/tests/baselines/reference/typeSatisfaction_propNameConstraining.types b/tests/baselines/reference/typeSatisfaction_propNameConstraining.types +new file mode 100644 +index 0000000000..f97f675c9d +--- /dev/null ++++ b/tests/baselines/reference/typeSatisfaction_propNameConstraining.types +@@ -0,0 +1,50 @@ ++=== tests/cases/conformance/expressions/typeSatisfaction/typeSatisfaction_propNameConstraining.ts === ++type Keys = 'a' | 'b' | 'c' | 'd'; ++>Keys : "a" | "b" | "c" | "d" ++ ++const p = { ++>p : { a: number; b: string; x: number; } ++>{ a: 0, b: "hello", x: 8 // Should error, 'x' isn't in 'Keys'} satisfies Partial> : { a: number; b: string; x: number; } ++>{ a: 0, b: "hello", x: 8 // Should error, 'x' isn't in 'Keys'} : { a: number; b: string; x: number; } ++ ++ a: 0, ++>a : number ++>0 : 0 ++ ++ b: "hello", ++>b : string ++>"hello" : "hello" ++ ++ x: 8 // Should error, 'x' isn't in 'Keys' ++>x : number ++>8 : 8 ++ ++} satisfies Partial>; ++ ++// Should be OK -- retain info that a is number and b is string ++let a = p.a.toFixed(); ++>a : string ++>p.a.toFixed() : string ++>p.a.toFixed : (fractionDigits?: number) => string ++>p.a : number ++>p : { a: number; b: string; x: number; } ++>a : number ++>toFixed : (fractionDigits?: number) => string ++ ++let b = p.b.substring(1); ++>b : string ++>p.b.substring(1) : string ++>p.b.substring : (start: number, end?: number) => string ++>p.b : string ++>p : { a: number; b: string; x: number; } ++>b : string ++>substring : (start: number, end?: number) => string ++>1 : 1 ++ ++// Should error even though 'd' is in 'Keys' ++let d = p.d; ++>d : any ++>p.d : any ++>p : { a: number; b: string; x: number; } ++>d : any ++ +diff --git a/tests/baselines/reference/typeSatisfaction_propertyNameFulfillment.errors.txt b/tests/baselines/reference/typeSatisfaction_propertyNameFulfillment.errors.txt +new file mode 100644 +index 0000000000..dbcb6fd419 +--- /dev/null ++++ b/tests/baselines/reference/typeSatisfaction_propertyNameFulfillment.errors.txt +@@ -0,0 +1,25 @@ ++tests/cases/conformance/expressions/typeSatisfaction/typeSatisfaction_propertyNameFulfillment.ts(6,5): error TS1360: Type '{ a: number; b: string; x: number; }' does not satisfy the expected type 'Record'. ++ Object literal may only specify known properties, and 'x' does not exist in type 'Record'. ++tests/cases/conformance/expressions/typeSatisfaction/typeSatisfaction_propertyNameFulfillment.ts(13,11): error TS2339: Property 'd' does not exist on type '{ a: number; b: string; x: number; }'. ++ ++ ++==== tests/cases/conformance/expressions/typeSatisfaction/typeSatisfaction_propertyNameFulfillment.ts (2 errors) ==== ++ type Keys = 'a' | 'b' | 'c' | 'd'; ++ ++ const p = { ++ a: 0, ++ b: "hello", ++ x: 8 // Should error, 'x' isn't in 'Keys' ++ ~~~~ ++!!! error TS1360: Type '{ a: number; b: string; x: number; }' does not satisfy the expected type 'Record'. ++!!! error TS1360: Object literal may only specify known properties, and 'x' does not exist in type 'Record'. ++ } satisfies Record; ++ ++ // Should be OK -- retain info that a is number and b is string ++ let a = p.a.toFixed(); ++ let b = p.b.substring(1); ++ // Should error even though 'd' is in 'Keys' ++ let d = p.d; ++ ~ ++!!! error TS2339: Property 'd' does not exist on type '{ a: number; b: string; x: number; }'. ++ +\ No newline at end of file +diff --git a/tests/baselines/reference/typeSatisfaction_propertyNameFulfillment.js b/tests/baselines/reference/typeSatisfaction_propertyNameFulfillment.js +new file mode 100644 +index 0000000000..1bea49e03d +--- /dev/null ++++ b/tests/baselines/reference/typeSatisfaction_propertyNameFulfillment.js +@@ -0,0 +1,27 @@ ++//// [typeSatisfaction_propertyNameFulfillment.ts] ++type Keys = 'a' | 'b' | 'c' | 'd'; ++ ++const p = { ++ a: 0, ++ b: "hello", ++ x: 8 // Should error, 'x' isn't in 'Keys' ++} satisfies Record; ++ ++// Should be OK -- retain info that a is number and b is string ++let a = p.a.toFixed(); ++let b = p.b.substring(1); ++// Should error even though 'd' is in 'Keys' ++let d = p.d; ++ ++ ++//// [typeSatisfaction_propertyNameFulfillment.js] ++var p = { ++ a: 0, ++ b: "hello", ++ x: 8 // Should error, 'x' isn't in 'Keys' ++}; ++// Should be OK -- retain info that a is number and b is string ++var a = p.a.toFixed(); ++var b = p.b.substring(1); ++// Should error even though 'd' is in 'Keys' ++var d = p.d; +diff --git a/tests/baselines/reference/typeSatisfaction_propertyNameFulfillment.symbols b/tests/baselines/reference/typeSatisfaction_propertyNameFulfillment.symbols +new file mode 100644 +index 0000000000..824fa99634 +--- /dev/null ++++ b/tests/baselines/reference/typeSatisfaction_propertyNameFulfillment.symbols +@@ -0,0 +1,42 @@ ++=== tests/cases/conformance/expressions/typeSatisfaction/typeSatisfaction_propertyNameFulfillment.ts === ++type Keys = 'a' | 'b' | 'c' | 'd'; ++>Keys : Symbol(Keys, Decl(typeSatisfaction_propertyNameFulfillment.ts, 0, 0)) ++ ++const p = { ++>p : Symbol(p, Decl(typeSatisfaction_propertyNameFulfillment.ts, 2, 5)) ++ ++ a: 0, ++>a : Symbol(a, Decl(typeSatisfaction_propertyNameFulfillment.ts, 2, 11)) ++ ++ b: "hello", ++>b : Symbol(b, Decl(typeSatisfaction_propertyNameFulfillment.ts, 3, 9)) ++ ++ x: 8 // Should error, 'x' isn't in 'Keys' ++>x : Symbol(x, Decl(typeSatisfaction_propertyNameFulfillment.ts, 4, 15)) ++ ++} satisfies Record; ++>Record : Symbol(Record, Decl(lib.es5.d.ts, --, --)) ++>Keys : Symbol(Keys, Decl(typeSatisfaction_propertyNameFulfillment.ts, 0, 0)) ++ ++// Should be OK -- retain info that a is number and b is string ++let a = p.a.toFixed(); ++>a : Symbol(a, Decl(typeSatisfaction_propertyNameFulfillment.ts, 9, 3)) ++>p.a.toFixed : Symbol(Number.toFixed, Decl(lib.es5.d.ts, --, --)) ++>p.a : Symbol(a, Decl(typeSatisfaction_propertyNameFulfillment.ts, 2, 11)) ++>p : Symbol(p, Decl(typeSatisfaction_propertyNameFulfillment.ts, 2, 5)) ++>a : Symbol(a, Decl(typeSatisfaction_propertyNameFulfillment.ts, 2, 11)) ++>toFixed : Symbol(Number.toFixed, Decl(lib.es5.d.ts, --, --)) ++ ++let b = p.b.substring(1); ++>b : Symbol(b, Decl(typeSatisfaction_propertyNameFulfillment.ts, 10, 3)) ++>p.b.substring : Symbol(String.substring, Decl(lib.es5.d.ts, --, --)) ++>p.b : Symbol(b, Decl(typeSatisfaction_propertyNameFulfillment.ts, 3, 9)) ++>p : Symbol(p, Decl(typeSatisfaction_propertyNameFulfillment.ts, 2, 5)) ++>b : Symbol(b, Decl(typeSatisfaction_propertyNameFulfillment.ts, 3, 9)) ++>substring : Symbol(String.substring, Decl(lib.es5.d.ts, --, --)) ++ ++// Should error even though 'd' is in 'Keys' ++let d = p.d; ++>d : Symbol(d, Decl(typeSatisfaction_propertyNameFulfillment.ts, 12, 3)) ++>p : Symbol(p, Decl(typeSatisfaction_propertyNameFulfillment.ts, 2, 5)) ++ +diff --git a/tests/baselines/reference/typeSatisfaction_propertyNameFulfillment.types b/tests/baselines/reference/typeSatisfaction_propertyNameFulfillment.types +new file mode 100644 +index 0000000000..09c2c4300e +--- /dev/null ++++ b/tests/baselines/reference/typeSatisfaction_propertyNameFulfillment.types +@@ -0,0 +1,50 @@ ++=== tests/cases/conformance/expressions/typeSatisfaction/typeSatisfaction_propertyNameFulfillment.ts === ++type Keys = 'a' | 'b' | 'c' | 'd'; ++>Keys : "a" | "b" | "c" | "d" ++ ++const p = { ++>p : { a: number; b: string; x: number; } ++>{ a: 0, b: "hello", x: 8 // Should error, 'x' isn't in 'Keys'} satisfies Record : { a: number; b: string; x: number; } ++>{ a: 0, b: "hello", x: 8 // Should error, 'x' isn't in 'Keys'} : { a: number; b: string; x: number; } ++ ++ a: 0, ++>a : number ++>0 : 0 ++ ++ b: "hello", ++>b : string ++>"hello" : "hello" ++ ++ x: 8 // Should error, 'x' isn't in 'Keys' ++>x : number ++>8 : 8 ++ ++} satisfies Record; ++ ++// Should be OK -- retain info that a is number and b is string ++let a = p.a.toFixed(); ++>a : string ++>p.a.toFixed() : string ++>p.a.toFixed : (fractionDigits?: number) => string ++>p.a : number ++>p : { a: number; b: string; x: number; } ++>a : number ++>toFixed : (fractionDigits?: number) => string ++ ++let b = p.b.substring(1); ++>b : string ++>p.b.substring(1) : string ++>p.b.substring : (start: number, end?: number) => string ++>p.b : string ++>p : { a: number; b: string; x: number; } ++>b : string ++>substring : (start: number, end?: number) => string ++>1 : 1 ++ ++// Should error even though 'd' is in 'Keys' ++let d = p.d; ++>d : any ++>p.d : any ++>p : { a: number; b: string; x: number; } ++>d : any ++ +diff --git a/tests/baselines/reference/typeSatisfaction_propertyValueConformance1(nopropertyaccessfromindexsignature=false).errors.txt b/tests/baselines/reference/typeSatisfaction_propertyValueConformance1(nopropertyaccessfromindexsignature=false).errors.txt +new file mode 100644 +index 0000000000..fd603a7727 +--- /dev/null ++++ b/tests/baselines/reference/typeSatisfaction_propertyValueConformance1(nopropertyaccessfromindexsignature=false).errors.txt +@@ -0,0 +1,34 @@ ++tests/cases/conformance/expressions/typeSatisfaction/typeSatisfaction_propertyValueConformance1.ts(13,15): error TS2339: Property 'z' does not exist on type '{ m: boolean; }'. ++tests/cases/conformance/expressions/typeSatisfaction/typeSatisfaction_propertyValueConformance1.ts(22,5): error TS2322: Type 'string' is not assignable to type 'boolean'. ++ ++ ++==== tests/cases/conformance/expressions/typeSatisfaction/typeSatisfaction_propertyValueConformance1.ts (2 errors) ==== ++ type Facts = { [key: string]: boolean }; ++ declare function checkTruths(x: Facts): void; ++ declare function checkM(x: { m: boolean }): void; ++ const x = { ++ m: true ++ }; ++ ++ // Should be OK ++ checkTruths(x); ++ // Should be OK ++ checkM(x); ++ // Should fail under --noPropertyAccessFromIndexSignature ++ console.log(x.z); ++ ~ ++!!! error TS2339: Property 'z' does not exist on type '{ m: boolean; }'. ++ const m: boolean = x.m; ++ ++ // Should be 'm' ++ type M = keyof typeof x; ++ ++ // Should be able to detect a failure here ++ const x2 = { ++ m: true, ++ s: "false" ++ ~ ++!!! error TS2322: Type 'string' is not assignable to type 'boolean'. ++!!! related TS6501 tests/cases/conformance/expressions/typeSatisfaction/typeSatisfaction_propertyValueConformance1.ts:1:16: The expected type comes from this index signature. ++ } satisfies Facts; ++ +\ No newline at end of file +diff --git a/tests/baselines/reference/typeSatisfaction_propertyValueConformance1(nopropertyaccessfromindexsignature=false).js b/tests/baselines/reference/typeSatisfaction_propertyValueConformance1(nopropertyaccessfromindexsignature=false).js +new file mode 100644 +index 0000000000..f0afe57b99 +--- /dev/null ++++ b/tests/baselines/reference/typeSatisfaction_propertyValueConformance1(nopropertyaccessfromindexsignature=false).js +@@ -0,0 +1,42 @@ ++//// [typeSatisfaction_propertyValueConformance1.ts] ++type Facts = { [key: string]: boolean }; ++declare function checkTruths(x: Facts): void; ++declare function checkM(x: { m: boolean }): void; ++const x = { ++ m: true ++}; ++ ++// Should be OK ++checkTruths(x); ++// Should be OK ++checkM(x); ++// Should fail under --noPropertyAccessFromIndexSignature ++console.log(x.z); ++const m: boolean = x.m; ++ ++// Should be 'm' ++type M = keyof typeof x; ++ ++// Should be able to detect a failure here ++const x2 = { ++ m: true, ++ s: "false" ++} satisfies Facts; ++ ++ ++//// [typeSatisfaction_propertyValueConformance1.js] ++var x = { ++ m: true ++}; ++// Should be OK ++checkTruths(x); ++// Should be OK ++checkM(x); ++// Should fail under --noPropertyAccessFromIndexSignature ++console.log(x.z); ++var m = x.m; ++// Should be able to detect a failure here ++var x2 = { ++ m: true, ++ s: "false" ++}; +diff --git a/tests/baselines/reference/typeSatisfaction_propertyValueConformance1(nopropertyaccessfromindexsignature=false).symbols b/tests/baselines/reference/typeSatisfaction_propertyValueConformance1(nopropertyaccessfromindexsignature=false).symbols +new file mode 100644 +index 0000000000..640357f878 +--- /dev/null ++++ b/tests/baselines/reference/typeSatisfaction_propertyValueConformance1(nopropertyaccessfromindexsignature=false).symbols +@@ -0,0 +1,64 @@ ++=== tests/cases/conformance/expressions/typeSatisfaction/typeSatisfaction_propertyValueConformance1.ts === ++type Facts = { [key: string]: boolean }; ++>Facts : Symbol(Facts, Decl(typeSatisfaction_propertyValueConformance1.ts, 0, 0)) ++>key : Symbol(key, Decl(typeSatisfaction_propertyValueConformance1.ts, 0, 16)) ++ ++declare function checkTruths(x: Facts): void; ++>checkTruths : Symbol(checkTruths, Decl(typeSatisfaction_propertyValueConformance1.ts, 0, 40)) ++>x : Symbol(x, Decl(typeSatisfaction_propertyValueConformance1.ts, 1, 29)) ++>Facts : Symbol(Facts, Decl(typeSatisfaction_propertyValueConformance1.ts, 0, 0)) ++ ++declare function checkM(x: { m: boolean }): void; ++>checkM : Symbol(checkM, Decl(typeSatisfaction_propertyValueConformance1.ts, 1, 45)) ++>x : Symbol(x, Decl(typeSatisfaction_propertyValueConformance1.ts, 2, 24)) ++>m : Symbol(m, Decl(typeSatisfaction_propertyValueConformance1.ts, 2, 28)) ++ ++const x = { ++>x : Symbol(x, Decl(typeSatisfaction_propertyValueConformance1.ts, 3, 5)) ++ ++ m: true ++>m : Symbol(m, Decl(typeSatisfaction_propertyValueConformance1.ts, 3, 11)) ++ ++}; ++ ++// Should be OK ++checkTruths(x); ++>checkTruths : Symbol(checkTruths, Decl(typeSatisfaction_propertyValueConformance1.ts, 0, 40)) ++>x : Symbol(x, Decl(typeSatisfaction_propertyValueConformance1.ts, 3, 5)) ++ ++// Should be OK ++checkM(x); ++>checkM : Symbol(checkM, Decl(typeSatisfaction_propertyValueConformance1.ts, 1, 45)) ++>x : Symbol(x, Decl(typeSatisfaction_propertyValueConformance1.ts, 3, 5)) ++ ++// Should fail under --noPropertyAccessFromIndexSignature ++console.log(x.z); ++>console.log : Symbol(Console.log, Decl(lib.dom.d.ts, --, --)) ++>console : Symbol(console, Decl(lib.dom.d.ts, --, --)) ++>log : Symbol(Console.log, Decl(lib.dom.d.ts, --, --)) ++>x : Symbol(x, Decl(typeSatisfaction_propertyValueConformance1.ts, 3, 5)) ++ ++const m: boolean = x.m; ++>m : Symbol(m, Decl(typeSatisfaction_propertyValueConformance1.ts, 13, 5)) ++>x.m : Symbol(m, Decl(typeSatisfaction_propertyValueConformance1.ts, 3, 11)) ++>x : Symbol(x, Decl(typeSatisfaction_propertyValueConformance1.ts, 3, 5)) ++>m : Symbol(m, Decl(typeSatisfaction_propertyValueConformance1.ts, 3, 11)) ++ ++// Should be 'm' ++type M = keyof typeof x; ++>M : Symbol(M, Decl(typeSatisfaction_propertyValueConformance1.ts, 13, 23)) ++>x : Symbol(x, Decl(typeSatisfaction_propertyValueConformance1.ts, 3, 5)) ++ ++// Should be able to detect a failure here ++const x2 = { ++>x2 : Symbol(x2, Decl(typeSatisfaction_propertyValueConformance1.ts, 19, 5)) ++ ++ m: true, ++>m : Symbol(m, Decl(typeSatisfaction_propertyValueConformance1.ts, 19, 12)) ++ ++ s: "false" ++>s : Symbol(s, Decl(typeSatisfaction_propertyValueConformance1.ts, 20, 12)) ++ ++} satisfies Facts; ++>Facts : Symbol(Facts, Decl(typeSatisfaction_propertyValueConformance1.ts, 0, 0)) ++ +diff --git a/tests/baselines/reference/typeSatisfaction_propertyValueConformance1(nopropertyaccessfromindexsignature=false).types b/tests/baselines/reference/typeSatisfaction_propertyValueConformance1(nopropertyaccessfromindexsignature=false).types +new file mode 100644 +index 0000000000..28aefdb9c6 +--- /dev/null ++++ b/tests/baselines/reference/typeSatisfaction_propertyValueConformance1(nopropertyaccessfromindexsignature=false).types +@@ -0,0 +1,73 @@ ++=== tests/cases/conformance/expressions/typeSatisfaction/typeSatisfaction_propertyValueConformance1.ts === ++type Facts = { [key: string]: boolean }; ++>Facts : { [key: string]: boolean; } ++>key : string ++ ++declare function checkTruths(x: Facts): void; ++>checkTruths : (x: Facts) => void ++>x : Facts ++ ++declare function checkM(x: { m: boolean }): void; ++>checkM : (x: { m: boolean;}) => void ++>x : { m: boolean; } ++>m : boolean ++ ++const x = { ++>x : { m: boolean; } ++>{ m: true} : { m: boolean; } ++ ++ m: true ++>m : boolean ++>true : true ++ ++}; ++ ++// Should be OK ++checkTruths(x); ++>checkTruths(x) : void ++>checkTruths : (x: Facts) => void ++>x : { m: boolean; } ++ ++// Should be OK ++checkM(x); ++>checkM(x) : void ++>checkM : (x: { m: boolean; }) => void ++>x : { m: boolean; } ++ ++// Should fail under --noPropertyAccessFromIndexSignature ++console.log(x.z); ++>console.log(x.z) : void ++>console.log : (...data: any[]) => void ++>console : Console ++>log : (...data: any[]) => void ++>x.z : any ++>x : { m: boolean; } ++>z : any ++ ++const m: boolean = x.m; ++>m : boolean ++>x.m : boolean ++>x : { m: boolean; } ++>m : boolean ++ ++// Should be 'm' ++type M = keyof typeof x; ++>M : "m" ++>x : { m: boolean; } ++ ++// Should be able to detect a failure here ++const x2 = { ++>x2 : { m: true; s: string; } ++>{ m: true, s: "false"} satisfies Facts : { m: true; s: string; } ++>{ m: true, s: "false"} : { m: true; s: string; } ++ ++ m: true, ++>m : true ++>true : true ++ ++ s: "false" ++>s : string ++>"false" : "false" ++ ++} satisfies Facts; ++ +diff --git a/tests/baselines/reference/typeSatisfaction_propertyValueConformance1(nopropertyaccessfromindexsignature=true).errors.txt b/tests/baselines/reference/typeSatisfaction_propertyValueConformance1(nopropertyaccessfromindexsignature=true).errors.txt +new file mode 100644 +index 0000000000..fd603a7727 +--- /dev/null ++++ b/tests/baselines/reference/typeSatisfaction_propertyValueConformance1(nopropertyaccessfromindexsignature=true).errors.txt +@@ -0,0 +1,34 @@ ++tests/cases/conformance/expressions/typeSatisfaction/typeSatisfaction_propertyValueConformance1.ts(13,15): error TS2339: Property 'z' does not exist on type '{ m: boolean; }'. ++tests/cases/conformance/expressions/typeSatisfaction/typeSatisfaction_propertyValueConformance1.ts(22,5): error TS2322: Type 'string' is not assignable to type 'boolean'. ++ ++ ++==== tests/cases/conformance/expressions/typeSatisfaction/typeSatisfaction_propertyValueConformance1.ts (2 errors) ==== ++ type Facts = { [key: string]: boolean }; ++ declare function checkTruths(x: Facts): void; ++ declare function checkM(x: { m: boolean }): void; ++ const x = { ++ m: true ++ }; ++ ++ // Should be OK ++ checkTruths(x); ++ // Should be OK ++ checkM(x); ++ // Should fail under --noPropertyAccessFromIndexSignature ++ console.log(x.z); ++ ~ ++!!! error TS2339: Property 'z' does not exist on type '{ m: boolean; }'. ++ const m: boolean = x.m; ++ ++ // Should be 'm' ++ type M = keyof typeof x; ++ ++ // Should be able to detect a failure here ++ const x2 = { ++ m: true, ++ s: "false" ++ ~ ++!!! error TS2322: Type 'string' is not assignable to type 'boolean'. ++!!! related TS6501 tests/cases/conformance/expressions/typeSatisfaction/typeSatisfaction_propertyValueConformance1.ts:1:16: The expected type comes from this index signature. ++ } satisfies Facts; ++ +\ No newline at end of file +diff --git a/tests/baselines/reference/typeSatisfaction_propertyValueConformance1(nopropertyaccessfromindexsignature=true).js b/tests/baselines/reference/typeSatisfaction_propertyValueConformance1(nopropertyaccessfromindexsignature=true).js +new file mode 100644 +index 0000000000..f0afe57b99 +--- /dev/null ++++ b/tests/baselines/reference/typeSatisfaction_propertyValueConformance1(nopropertyaccessfromindexsignature=true).js +@@ -0,0 +1,42 @@ ++//// [typeSatisfaction_propertyValueConformance1.ts] ++type Facts = { [key: string]: boolean }; ++declare function checkTruths(x: Facts): void; ++declare function checkM(x: { m: boolean }): void; ++const x = { ++ m: true ++}; ++ ++// Should be OK ++checkTruths(x); ++// Should be OK ++checkM(x); ++// Should fail under --noPropertyAccessFromIndexSignature ++console.log(x.z); ++const m: boolean = x.m; ++ ++// Should be 'm' ++type M = keyof typeof x; ++ ++// Should be able to detect a failure here ++const x2 = { ++ m: true, ++ s: "false" ++} satisfies Facts; ++ ++ ++//// [typeSatisfaction_propertyValueConformance1.js] ++var x = { ++ m: true ++}; ++// Should be OK ++checkTruths(x); ++// Should be OK ++checkM(x); ++// Should fail under --noPropertyAccessFromIndexSignature ++console.log(x.z); ++var m = x.m; ++// Should be able to detect a failure here ++var x2 = { ++ m: true, ++ s: "false" ++}; +diff --git a/tests/baselines/reference/typeSatisfaction_propertyValueConformance1(nopropertyaccessfromindexsignature=true).symbols b/tests/baselines/reference/typeSatisfaction_propertyValueConformance1(nopropertyaccessfromindexsignature=true).symbols +new file mode 100644 +index 0000000000..640357f878 +--- /dev/null ++++ b/tests/baselines/reference/typeSatisfaction_propertyValueConformance1(nopropertyaccessfromindexsignature=true).symbols +@@ -0,0 +1,64 @@ ++=== tests/cases/conformance/expressions/typeSatisfaction/typeSatisfaction_propertyValueConformance1.ts === ++type Facts = { [key: string]: boolean }; ++>Facts : Symbol(Facts, Decl(typeSatisfaction_propertyValueConformance1.ts, 0, 0)) ++>key : Symbol(key, Decl(typeSatisfaction_propertyValueConformance1.ts, 0, 16)) ++ ++declare function checkTruths(x: Facts): void; ++>checkTruths : Symbol(checkTruths, Decl(typeSatisfaction_propertyValueConformance1.ts, 0, 40)) ++>x : Symbol(x, Decl(typeSatisfaction_propertyValueConformance1.ts, 1, 29)) ++>Facts : Symbol(Facts, Decl(typeSatisfaction_propertyValueConformance1.ts, 0, 0)) ++ ++declare function checkM(x: { m: boolean }): void; ++>checkM : Symbol(checkM, Decl(typeSatisfaction_propertyValueConformance1.ts, 1, 45)) ++>x : Symbol(x, Decl(typeSatisfaction_propertyValueConformance1.ts, 2, 24)) ++>m : Symbol(m, Decl(typeSatisfaction_propertyValueConformance1.ts, 2, 28)) ++ ++const x = { ++>x : Symbol(x, Decl(typeSatisfaction_propertyValueConformance1.ts, 3, 5)) ++ ++ m: true ++>m : Symbol(m, Decl(typeSatisfaction_propertyValueConformance1.ts, 3, 11)) ++ ++}; ++ ++// Should be OK ++checkTruths(x); ++>checkTruths : Symbol(checkTruths, Decl(typeSatisfaction_propertyValueConformance1.ts, 0, 40)) ++>x : Symbol(x, Decl(typeSatisfaction_propertyValueConformance1.ts, 3, 5)) ++ ++// Should be OK ++checkM(x); ++>checkM : Symbol(checkM, Decl(typeSatisfaction_propertyValueConformance1.ts, 1, 45)) ++>x : Symbol(x, Decl(typeSatisfaction_propertyValueConformance1.ts, 3, 5)) ++ ++// Should fail under --noPropertyAccessFromIndexSignature ++console.log(x.z); ++>console.log : Symbol(Console.log, Decl(lib.dom.d.ts, --, --)) ++>console : Symbol(console, Decl(lib.dom.d.ts, --, --)) ++>log : Symbol(Console.log, Decl(lib.dom.d.ts, --, --)) ++>x : Symbol(x, Decl(typeSatisfaction_propertyValueConformance1.ts, 3, 5)) ++ ++const m: boolean = x.m; ++>m : Symbol(m, Decl(typeSatisfaction_propertyValueConformance1.ts, 13, 5)) ++>x.m : Symbol(m, Decl(typeSatisfaction_propertyValueConformance1.ts, 3, 11)) ++>x : Symbol(x, Decl(typeSatisfaction_propertyValueConformance1.ts, 3, 5)) ++>m : Symbol(m, Decl(typeSatisfaction_propertyValueConformance1.ts, 3, 11)) ++ ++// Should be 'm' ++type M = keyof typeof x; ++>M : Symbol(M, Decl(typeSatisfaction_propertyValueConformance1.ts, 13, 23)) ++>x : Symbol(x, Decl(typeSatisfaction_propertyValueConformance1.ts, 3, 5)) ++ ++// Should be able to detect a failure here ++const x2 = { ++>x2 : Symbol(x2, Decl(typeSatisfaction_propertyValueConformance1.ts, 19, 5)) ++ ++ m: true, ++>m : Symbol(m, Decl(typeSatisfaction_propertyValueConformance1.ts, 19, 12)) ++ ++ s: "false" ++>s : Symbol(s, Decl(typeSatisfaction_propertyValueConformance1.ts, 20, 12)) ++ ++} satisfies Facts; ++>Facts : Symbol(Facts, Decl(typeSatisfaction_propertyValueConformance1.ts, 0, 0)) ++ +diff --git a/tests/baselines/reference/typeSatisfaction_propertyValueConformance1(nopropertyaccessfromindexsignature=true).types b/tests/baselines/reference/typeSatisfaction_propertyValueConformance1(nopropertyaccessfromindexsignature=true).types +new file mode 100644 +index 0000000000..28aefdb9c6 +--- /dev/null ++++ b/tests/baselines/reference/typeSatisfaction_propertyValueConformance1(nopropertyaccessfromindexsignature=true).types +@@ -0,0 +1,73 @@ ++=== tests/cases/conformance/expressions/typeSatisfaction/typeSatisfaction_propertyValueConformance1.ts === ++type Facts = { [key: string]: boolean }; ++>Facts : { [key: string]: boolean; } ++>key : string ++ ++declare function checkTruths(x: Facts): void; ++>checkTruths : (x: Facts) => void ++>x : Facts ++ ++declare function checkM(x: { m: boolean }): void; ++>checkM : (x: { m: boolean;}) => void ++>x : { m: boolean; } ++>m : boolean ++ ++const x = { ++>x : { m: boolean; } ++>{ m: true} : { m: boolean; } ++ ++ m: true ++>m : boolean ++>true : true ++ ++}; ++ ++// Should be OK ++checkTruths(x); ++>checkTruths(x) : void ++>checkTruths : (x: Facts) => void ++>x : { m: boolean; } ++ ++// Should be OK ++checkM(x); ++>checkM(x) : void ++>checkM : (x: { m: boolean; }) => void ++>x : { m: boolean; } ++ ++// Should fail under --noPropertyAccessFromIndexSignature ++console.log(x.z); ++>console.log(x.z) : void ++>console.log : (...data: any[]) => void ++>console : Console ++>log : (...data: any[]) => void ++>x.z : any ++>x : { m: boolean; } ++>z : any ++ ++const m: boolean = x.m; ++>m : boolean ++>x.m : boolean ++>x : { m: boolean; } ++>m : boolean ++ ++// Should be 'm' ++type M = keyof typeof x; ++>M : "m" ++>x : { m: boolean; } ++ ++// Should be able to detect a failure here ++const x2 = { ++>x2 : { m: true; s: string; } ++>{ m: true, s: "false"} satisfies Facts : { m: true; s: string; } ++>{ m: true, s: "false"} : { m: true; s: string; } ++ ++ m: true, ++>m : true ++>true : true ++ ++ s: "false" ++>s : string ++>"false" : "false" ++ ++} satisfies Facts; ++ +diff --git a/tests/baselines/reference/typeSatisfaction_propertyValueConformance2(nouncheckedindexedaccess=false).errors.txt b/tests/baselines/reference/typeSatisfaction_propertyValueConformance2(nouncheckedindexedaccess=false).errors.txt +new file mode 100644 +index 0000000000..57f58d646f +--- /dev/null ++++ b/tests/baselines/reference/typeSatisfaction_propertyValueConformance2(nouncheckedindexedaccess=false).errors.txt +@@ -0,0 +1,34 @@ ++tests/cases/conformance/expressions/typeSatisfaction/typeSatisfaction_propertyValueConformance2.ts(12,15): error TS2339: Property 'z' does not exist on type '{ m: boolean; }'. ++tests/cases/conformance/expressions/typeSatisfaction/typeSatisfaction_propertyValueConformance2.ts(22,5): error TS2322: Type 'string' is not assignable to type 'boolean'. ++ ++ ++==== tests/cases/conformance/expressions/typeSatisfaction/typeSatisfaction_propertyValueConformance2.ts (2 errors) ==== ++ type Facts = { [key: string]: boolean }; ++ declare function checkTruths(x: Facts): void; ++ declare function checkM(x: { m: boolean }): void; ++ const x = { ++ m: true ++ }; ++ ++ // Should be OK ++ checkTruths(x); ++ // Should be OK ++ checkM(x); ++ console.log(x.z); ++ ~ ++!!! error TS2339: Property 'z' does not exist on type '{ m: boolean; }'. ++ // Should be OK under --noUncheckedIndexedAccess ++ const m: boolean = x.m; ++ ++ // Should be 'm' ++ type M = keyof typeof x; ++ ++ // Should be able to detect a failure here ++ const x2 = { ++ m: true, ++ s: "false" ++ ~ ++!!! error TS2322: Type 'string' is not assignable to type 'boolean'. ++!!! related TS6501 tests/cases/conformance/expressions/typeSatisfaction/typeSatisfaction_propertyValueConformance2.ts:1:16: The expected type comes from this index signature. ++ } satisfies Facts; ++ +\ No newline at end of file +diff --git a/tests/baselines/reference/typeSatisfaction_propertyValueConformance2(nouncheckedindexedaccess=false).js b/tests/baselines/reference/typeSatisfaction_propertyValueConformance2(nouncheckedindexedaccess=false).js +new file mode 100644 +index 0000000000..450bf97193 +--- /dev/null ++++ b/tests/baselines/reference/typeSatisfaction_propertyValueConformance2(nouncheckedindexedaccess=false).js +@@ -0,0 +1,42 @@ ++//// [typeSatisfaction_propertyValueConformance2.ts] ++type Facts = { [key: string]: boolean }; ++declare function checkTruths(x: Facts): void; ++declare function checkM(x: { m: boolean }): void; ++const x = { ++ m: true ++}; ++ ++// Should be OK ++checkTruths(x); ++// Should be OK ++checkM(x); ++console.log(x.z); ++// Should be OK under --noUncheckedIndexedAccess ++const m: boolean = x.m; ++ ++// Should be 'm' ++type M = keyof typeof x; ++ ++// Should be able to detect a failure here ++const x2 = { ++ m: true, ++ s: "false" ++} satisfies Facts; ++ ++ ++//// [typeSatisfaction_propertyValueConformance2.js] ++var x = { ++ m: true ++}; ++// Should be OK ++checkTruths(x); ++// Should be OK ++checkM(x); ++console.log(x.z); ++// Should be OK under --noUncheckedIndexedAccess ++var m = x.m; ++// Should be able to detect a failure here ++var x2 = { ++ m: true, ++ s: "false" ++}; +diff --git a/tests/baselines/reference/typeSatisfaction_propertyValueConformance2(nouncheckedindexedaccess=false).symbols b/tests/baselines/reference/typeSatisfaction_propertyValueConformance2(nouncheckedindexedaccess=false).symbols +new file mode 100644 +index 0000000000..d2526bf40f +--- /dev/null ++++ b/tests/baselines/reference/typeSatisfaction_propertyValueConformance2(nouncheckedindexedaccess=false).symbols +@@ -0,0 +1,64 @@ ++=== tests/cases/conformance/expressions/typeSatisfaction/typeSatisfaction_propertyValueConformance2.ts === ++type Facts = { [key: string]: boolean }; ++>Facts : Symbol(Facts, Decl(typeSatisfaction_propertyValueConformance2.ts, 0, 0)) ++>key : Symbol(key, Decl(typeSatisfaction_propertyValueConformance2.ts, 0, 16)) ++ ++declare function checkTruths(x: Facts): void; ++>checkTruths : Symbol(checkTruths, Decl(typeSatisfaction_propertyValueConformance2.ts, 0, 40)) ++>x : Symbol(x, Decl(typeSatisfaction_propertyValueConformance2.ts, 1, 29)) ++>Facts : Symbol(Facts, Decl(typeSatisfaction_propertyValueConformance2.ts, 0, 0)) ++ ++declare function checkM(x: { m: boolean }): void; ++>checkM : Symbol(checkM, Decl(typeSatisfaction_propertyValueConformance2.ts, 1, 45)) ++>x : Symbol(x, Decl(typeSatisfaction_propertyValueConformance2.ts, 2, 24)) ++>m : Symbol(m, Decl(typeSatisfaction_propertyValueConformance2.ts, 2, 28)) ++ ++const x = { ++>x : Symbol(x, Decl(typeSatisfaction_propertyValueConformance2.ts, 3, 5)) ++ ++ m: true ++>m : Symbol(m, Decl(typeSatisfaction_propertyValueConformance2.ts, 3, 11)) ++ ++}; ++ ++// Should be OK ++checkTruths(x); ++>checkTruths : Symbol(checkTruths, Decl(typeSatisfaction_propertyValueConformance2.ts, 0, 40)) ++>x : Symbol(x, Decl(typeSatisfaction_propertyValueConformance2.ts, 3, 5)) ++ ++// Should be OK ++checkM(x); ++>checkM : Symbol(checkM, Decl(typeSatisfaction_propertyValueConformance2.ts, 1, 45)) ++>x : Symbol(x, Decl(typeSatisfaction_propertyValueConformance2.ts, 3, 5)) ++ ++console.log(x.z); ++>console.log : Symbol(Console.log, Decl(lib.dom.d.ts, --, --)) ++>console : Symbol(console, Decl(lib.dom.d.ts, --, --)) ++>log : Symbol(Console.log, Decl(lib.dom.d.ts, --, --)) ++>x : Symbol(x, Decl(typeSatisfaction_propertyValueConformance2.ts, 3, 5)) ++ ++// Should be OK under --noUncheckedIndexedAccess ++const m: boolean = x.m; ++>m : Symbol(m, Decl(typeSatisfaction_propertyValueConformance2.ts, 13, 5)) ++>x.m : Symbol(m, Decl(typeSatisfaction_propertyValueConformance2.ts, 3, 11)) ++>x : Symbol(x, Decl(typeSatisfaction_propertyValueConformance2.ts, 3, 5)) ++>m : Symbol(m, Decl(typeSatisfaction_propertyValueConformance2.ts, 3, 11)) ++ ++// Should be 'm' ++type M = keyof typeof x; ++>M : Symbol(M, Decl(typeSatisfaction_propertyValueConformance2.ts, 13, 23)) ++>x : Symbol(x, Decl(typeSatisfaction_propertyValueConformance2.ts, 3, 5)) ++ ++// Should be able to detect a failure here ++const x2 = { ++>x2 : Symbol(x2, Decl(typeSatisfaction_propertyValueConformance2.ts, 19, 5)) ++ ++ m: true, ++>m : Symbol(m, Decl(typeSatisfaction_propertyValueConformance2.ts, 19, 12)) ++ ++ s: "false" ++>s : Symbol(s, Decl(typeSatisfaction_propertyValueConformance2.ts, 20, 12)) ++ ++} satisfies Facts; ++>Facts : Symbol(Facts, Decl(typeSatisfaction_propertyValueConformance2.ts, 0, 0)) ++ +diff --git a/tests/baselines/reference/typeSatisfaction_propertyValueConformance2(nouncheckedindexedaccess=false).types b/tests/baselines/reference/typeSatisfaction_propertyValueConformance2(nouncheckedindexedaccess=false).types +new file mode 100644 +index 0000000000..532ee99a6d +--- /dev/null ++++ b/tests/baselines/reference/typeSatisfaction_propertyValueConformance2(nouncheckedindexedaccess=false).types +@@ -0,0 +1,73 @@ ++=== tests/cases/conformance/expressions/typeSatisfaction/typeSatisfaction_propertyValueConformance2.ts === ++type Facts = { [key: string]: boolean }; ++>Facts : { [key: string]: boolean; } ++>key : string ++ ++declare function checkTruths(x: Facts): void; ++>checkTruths : (x: Facts) => void ++>x : Facts ++ ++declare function checkM(x: { m: boolean }): void; ++>checkM : (x: { m: boolean;}) => void ++>x : { m: boolean; } ++>m : boolean ++ ++const x = { ++>x : { m: boolean; } ++>{ m: true} : { m: boolean; } ++ ++ m: true ++>m : boolean ++>true : true ++ ++}; ++ ++// Should be OK ++checkTruths(x); ++>checkTruths(x) : void ++>checkTruths : (x: Facts) => void ++>x : { m: boolean; } ++ ++// Should be OK ++checkM(x); ++>checkM(x) : void ++>checkM : (x: { m: boolean; }) => void ++>x : { m: boolean; } ++ ++console.log(x.z); ++>console.log(x.z) : void ++>console.log : (...data: any[]) => void ++>console : Console ++>log : (...data: any[]) => void ++>x.z : any ++>x : { m: boolean; } ++>z : any ++ ++// Should be OK under --noUncheckedIndexedAccess ++const m: boolean = x.m; ++>m : boolean ++>x.m : boolean ++>x : { m: boolean; } ++>m : boolean ++ ++// Should be 'm' ++type M = keyof typeof x; ++>M : "m" ++>x : { m: boolean; } ++ ++// Should be able to detect a failure here ++const x2 = { ++>x2 : { m: true; s: string; } ++>{ m: true, s: "false"} satisfies Facts : { m: true; s: string; } ++>{ m: true, s: "false"} : { m: true; s: string; } ++ ++ m: true, ++>m : true ++>true : true ++ ++ s: "false" ++>s : string ++>"false" : "false" ++ ++} satisfies Facts; ++ +diff --git a/tests/baselines/reference/typeSatisfaction_propertyValueConformance2(nouncheckedindexedaccess=true).errors.txt b/tests/baselines/reference/typeSatisfaction_propertyValueConformance2(nouncheckedindexedaccess=true).errors.txt +new file mode 100644 +index 0000000000..57f58d646f +--- /dev/null ++++ b/tests/baselines/reference/typeSatisfaction_propertyValueConformance2(nouncheckedindexedaccess=true).errors.txt +@@ -0,0 +1,34 @@ ++tests/cases/conformance/expressions/typeSatisfaction/typeSatisfaction_propertyValueConformance2.ts(12,15): error TS2339: Property 'z' does not exist on type '{ m: boolean; }'. ++tests/cases/conformance/expressions/typeSatisfaction/typeSatisfaction_propertyValueConformance2.ts(22,5): error TS2322: Type 'string' is not assignable to type 'boolean'. ++ ++ ++==== tests/cases/conformance/expressions/typeSatisfaction/typeSatisfaction_propertyValueConformance2.ts (2 errors) ==== ++ type Facts = { [key: string]: boolean }; ++ declare function checkTruths(x: Facts): void; ++ declare function checkM(x: { m: boolean }): void; ++ const x = { ++ m: true ++ }; ++ ++ // Should be OK ++ checkTruths(x); ++ // Should be OK ++ checkM(x); ++ console.log(x.z); ++ ~ ++!!! error TS2339: Property 'z' does not exist on type '{ m: boolean; }'. ++ // Should be OK under --noUncheckedIndexedAccess ++ const m: boolean = x.m; ++ ++ // Should be 'm' ++ type M = keyof typeof x; ++ ++ // Should be able to detect a failure here ++ const x2 = { ++ m: true, ++ s: "false" ++ ~ ++!!! error TS2322: Type 'string' is not assignable to type 'boolean'. ++!!! related TS6501 tests/cases/conformance/expressions/typeSatisfaction/typeSatisfaction_propertyValueConformance2.ts:1:16: The expected type comes from this index signature. ++ } satisfies Facts; ++ +\ No newline at end of file +diff --git a/tests/baselines/reference/typeSatisfaction_propertyValueConformance2(nouncheckedindexedaccess=true).js b/tests/baselines/reference/typeSatisfaction_propertyValueConformance2(nouncheckedindexedaccess=true).js +new file mode 100644 +index 0000000000..450bf97193 +--- /dev/null ++++ b/tests/baselines/reference/typeSatisfaction_propertyValueConformance2(nouncheckedindexedaccess=true).js +@@ -0,0 +1,42 @@ ++//// [typeSatisfaction_propertyValueConformance2.ts] ++type Facts = { [key: string]: boolean }; ++declare function checkTruths(x: Facts): void; ++declare function checkM(x: { m: boolean }): void; ++const x = { ++ m: true ++}; ++ ++// Should be OK ++checkTruths(x); ++// Should be OK ++checkM(x); ++console.log(x.z); ++// Should be OK under --noUncheckedIndexedAccess ++const m: boolean = x.m; ++ ++// Should be 'm' ++type M = keyof typeof x; ++ ++// Should be able to detect a failure here ++const x2 = { ++ m: true, ++ s: "false" ++} satisfies Facts; ++ ++ ++//// [typeSatisfaction_propertyValueConformance2.js] ++var x = { ++ m: true ++}; ++// Should be OK ++checkTruths(x); ++// Should be OK ++checkM(x); ++console.log(x.z); ++// Should be OK under --noUncheckedIndexedAccess ++var m = x.m; ++// Should be able to detect a failure here ++var x2 = { ++ m: true, ++ s: "false" ++}; +diff --git a/tests/baselines/reference/typeSatisfaction_propertyValueConformance2(nouncheckedindexedaccess=true).symbols b/tests/baselines/reference/typeSatisfaction_propertyValueConformance2(nouncheckedindexedaccess=true).symbols +new file mode 100644 +index 0000000000..d2526bf40f +--- /dev/null ++++ b/tests/baselines/reference/typeSatisfaction_propertyValueConformance2(nouncheckedindexedaccess=true).symbols +@@ -0,0 +1,64 @@ ++=== tests/cases/conformance/expressions/typeSatisfaction/typeSatisfaction_propertyValueConformance2.ts === ++type Facts = { [key: string]: boolean }; ++>Facts : Symbol(Facts, Decl(typeSatisfaction_propertyValueConformance2.ts, 0, 0)) ++>key : Symbol(key, Decl(typeSatisfaction_propertyValueConformance2.ts, 0, 16)) ++ ++declare function checkTruths(x: Facts): void; ++>checkTruths : Symbol(checkTruths, Decl(typeSatisfaction_propertyValueConformance2.ts, 0, 40)) ++>x : Symbol(x, Decl(typeSatisfaction_propertyValueConformance2.ts, 1, 29)) ++>Facts : Symbol(Facts, Decl(typeSatisfaction_propertyValueConformance2.ts, 0, 0)) ++ ++declare function checkM(x: { m: boolean }): void; ++>checkM : Symbol(checkM, Decl(typeSatisfaction_propertyValueConformance2.ts, 1, 45)) ++>x : Symbol(x, Decl(typeSatisfaction_propertyValueConformance2.ts, 2, 24)) ++>m : Symbol(m, Decl(typeSatisfaction_propertyValueConformance2.ts, 2, 28)) ++ ++const x = { ++>x : Symbol(x, Decl(typeSatisfaction_propertyValueConformance2.ts, 3, 5)) ++ ++ m: true ++>m : Symbol(m, Decl(typeSatisfaction_propertyValueConformance2.ts, 3, 11)) ++ ++}; ++ ++// Should be OK ++checkTruths(x); ++>checkTruths : Symbol(checkTruths, Decl(typeSatisfaction_propertyValueConformance2.ts, 0, 40)) ++>x : Symbol(x, Decl(typeSatisfaction_propertyValueConformance2.ts, 3, 5)) ++ ++// Should be OK ++checkM(x); ++>checkM : Symbol(checkM, Decl(typeSatisfaction_propertyValueConformance2.ts, 1, 45)) ++>x : Symbol(x, Decl(typeSatisfaction_propertyValueConformance2.ts, 3, 5)) ++ ++console.log(x.z); ++>console.log : Symbol(Console.log, Decl(lib.dom.d.ts, --, --)) ++>console : Symbol(console, Decl(lib.dom.d.ts, --, --)) ++>log : Symbol(Console.log, Decl(lib.dom.d.ts, --, --)) ++>x : Symbol(x, Decl(typeSatisfaction_propertyValueConformance2.ts, 3, 5)) ++ ++// Should be OK under --noUncheckedIndexedAccess ++const m: boolean = x.m; ++>m : Symbol(m, Decl(typeSatisfaction_propertyValueConformance2.ts, 13, 5)) ++>x.m : Symbol(m, Decl(typeSatisfaction_propertyValueConformance2.ts, 3, 11)) ++>x : Symbol(x, Decl(typeSatisfaction_propertyValueConformance2.ts, 3, 5)) ++>m : Symbol(m, Decl(typeSatisfaction_propertyValueConformance2.ts, 3, 11)) ++ ++// Should be 'm' ++type M = keyof typeof x; ++>M : Symbol(M, Decl(typeSatisfaction_propertyValueConformance2.ts, 13, 23)) ++>x : Symbol(x, Decl(typeSatisfaction_propertyValueConformance2.ts, 3, 5)) ++ ++// Should be able to detect a failure here ++const x2 = { ++>x2 : Symbol(x2, Decl(typeSatisfaction_propertyValueConformance2.ts, 19, 5)) ++ ++ m: true, ++>m : Symbol(m, Decl(typeSatisfaction_propertyValueConformance2.ts, 19, 12)) ++ ++ s: "false" ++>s : Symbol(s, Decl(typeSatisfaction_propertyValueConformance2.ts, 20, 12)) ++ ++} satisfies Facts; ++>Facts : Symbol(Facts, Decl(typeSatisfaction_propertyValueConformance2.ts, 0, 0)) ++ +diff --git a/tests/baselines/reference/typeSatisfaction_propertyValueConformance2(nouncheckedindexedaccess=true).types b/tests/baselines/reference/typeSatisfaction_propertyValueConformance2(nouncheckedindexedaccess=true).types +new file mode 100644 +index 0000000000..532ee99a6d +--- /dev/null ++++ b/tests/baselines/reference/typeSatisfaction_propertyValueConformance2(nouncheckedindexedaccess=true).types +@@ -0,0 +1,73 @@ ++=== tests/cases/conformance/expressions/typeSatisfaction/typeSatisfaction_propertyValueConformance2.ts === ++type Facts = { [key: string]: boolean }; ++>Facts : { [key: string]: boolean; } ++>key : string ++ ++declare function checkTruths(x: Facts): void; ++>checkTruths : (x: Facts) => void ++>x : Facts ++ ++declare function checkM(x: { m: boolean }): void; ++>checkM : (x: { m: boolean;}) => void ++>x : { m: boolean; } ++>m : boolean ++ ++const x = { ++>x : { m: boolean; } ++>{ m: true} : { m: boolean; } ++ ++ m: true ++>m : boolean ++>true : true ++ ++}; ++ ++// Should be OK ++checkTruths(x); ++>checkTruths(x) : void ++>checkTruths : (x: Facts) => void ++>x : { m: boolean; } ++ ++// Should be OK ++checkM(x); ++>checkM(x) : void ++>checkM : (x: { m: boolean; }) => void ++>x : { m: boolean; } ++ ++console.log(x.z); ++>console.log(x.z) : void ++>console.log : (...data: any[]) => void ++>console : Console ++>log : (...data: any[]) => void ++>x.z : any ++>x : { m: boolean; } ++>z : any ++ ++// Should be OK under --noUncheckedIndexedAccess ++const m: boolean = x.m; ++>m : boolean ++>x.m : boolean ++>x : { m: boolean; } ++>m : boolean ++ ++// Should be 'm' ++type M = keyof typeof x; ++>M : "m" ++>x : { m: boolean; } ++ ++// Should be able to detect a failure here ++const x2 = { ++>x2 : { m: true; s: string; } ++>{ m: true, s: "false"} satisfies Facts : { m: true; s: string; } ++>{ m: true, s: "false"} : { m: true; s: string; } ++ ++ m: true, ++>m : true ++>true : true ++ ++ s: "false" ++>s : string ++>"false" : "false" ++ ++} satisfies Facts; ++ +diff --git a/tests/baselines/reference/typeSatisfaction_propertyValueConformance3.errors.txt b/tests/baselines/reference/typeSatisfaction_propertyValueConformance3.errors.txt +new file mode 100644 +index 0000000000..0ae5d8fffb +--- /dev/null ++++ b/tests/baselines/reference/typeSatisfaction_propertyValueConformance3.errors.txt +@@ -0,0 +1,17 @@ ++tests/cases/conformance/expressions/typeSatisfaction/typeSatisfaction_propertyValueConformance3.ts(6,26): error TS2322: Type '{ r: number; g: number; d: number; }' is not assignable to type 'Color'. ++ Object literal may only specify known properties, and 'd' does not exist in type 'Color'. ++ ++ ++==== tests/cases/conformance/expressions/typeSatisfaction/typeSatisfaction_propertyValueConformance3.ts (1 errors) ==== ++ export type Color = { r: number, g: number, b: number }; ++ ++ // All of these should be Colors, but I only use some of them here. ++ export const Palette = { ++ white: { r: 255, g: 255, b: 255 }, ++ black: { r: 0, g: 0, d: 0 }, // <- oops! 'd' in place of 'b' ++ ~~~~ ++!!! error TS2322: Type '{ r: number; g: number; d: number; }' is not assignable to type 'Color'. ++!!! error TS2322: Object literal may only specify known properties, and 'd' does not exist in type 'Color'. ++ blue: { r: 0, g: 0, b: 255 }, ++ } satisfies Record; ++ +\ No newline at end of file +diff --git a/tests/baselines/reference/typeSatisfaction_propertyValueConformance3.js b/tests/baselines/reference/typeSatisfaction_propertyValueConformance3.js +new file mode 100644 +index 0000000000..c8c885e74e +--- /dev/null ++++ b/tests/baselines/reference/typeSatisfaction_propertyValueConformance3.js +@@ -0,0 +1,21 @@ ++//// [typeSatisfaction_propertyValueConformance3.ts] ++export type Color = { r: number, g: number, b: number }; ++ ++// All of these should be Colors, but I only use some of them here. ++export const Palette = { ++ white: { r: 255, g: 255, b: 255 }, ++ black: { r: 0, g: 0, d: 0 }, // <- oops! 'd' in place of 'b' ++ blue: { r: 0, g: 0, b: 255 }, ++} satisfies Record; ++ ++ ++//// [typeSatisfaction_propertyValueConformance3.js] ++"use strict"; ++exports.__esModule = true; ++exports.Palette = void 0; ++// All of these should be Colors, but I only use some of them here. ++exports.Palette = { ++ white: { r: 255, g: 255, b: 255 }, ++ black: { r: 0, g: 0, d: 0 }, ++ blue: { r: 0, g: 0, b: 255 } ++}; +diff --git a/tests/baselines/reference/typeSatisfaction_propertyValueConformance3.symbols b/tests/baselines/reference/typeSatisfaction_propertyValueConformance3.symbols +new file mode 100644 +index 0000000000..4cbc5cf907 +--- /dev/null ++++ b/tests/baselines/reference/typeSatisfaction_propertyValueConformance3.symbols +@@ -0,0 +1,33 @@ ++=== tests/cases/conformance/expressions/typeSatisfaction/typeSatisfaction_propertyValueConformance3.ts === ++export type Color = { r: number, g: number, b: number }; ++>Color : Symbol(Color, Decl(typeSatisfaction_propertyValueConformance3.ts, 0, 0)) ++>r : Symbol(r, Decl(typeSatisfaction_propertyValueConformance3.ts, 0, 21)) ++>g : Symbol(g, Decl(typeSatisfaction_propertyValueConformance3.ts, 0, 32)) ++>b : Symbol(b, Decl(typeSatisfaction_propertyValueConformance3.ts, 0, 43)) ++ ++// All of these should be Colors, but I only use some of them here. ++export const Palette = { ++>Palette : Symbol(Palette, Decl(typeSatisfaction_propertyValueConformance3.ts, 3, 12)) ++ ++ white: { r: 255, g: 255, b: 255 }, ++>white : Symbol(white, Decl(typeSatisfaction_propertyValueConformance3.ts, 3, 24)) ++>r : Symbol(r, Decl(typeSatisfaction_propertyValueConformance3.ts, 4, 12)) ++>g : Symbol(g, Decl(typeSatisfaction_propertyValueConformance3.ts, 4, 20)) ++>b : Symbol(b, Decl(typeSatisfaction_propertyValueConformance3.ts, 4, 28)) ++ ++ black: { r: 0, g: 0, d: 0 }, // <- oops! 'd' in place of 'b' ++>black : Symbol(black, Decl(typeSatisfaction_propertyValueConformance3.ts, 4, 38)) ++>r : Symbol(r, Decl(typeSatisfaction_propertyValueConformance3.ts, 5, 12)) ++>g : Symbol(g, Decl(typeSatisfaction_propertyValueConformance3.ts, 5, 18)) ++>d : Symbol(d, Decl(typeSatisfaction_propertyValueConformance3.ts, 5, 24)) ++ ++ blue: { r: 0, g: 0, b: 255 }, ++>blue : Symbol(blue, Decl(typeSatisfaction_propertyValueConformance3.ts, 5, 32)) ++>r : Symbol(r, Decl(typeSatisfaction_propertyValueConformance3.ts, 6, 11)) ++>g : Symbol(g, Decl(typeSatisfaction_propertyValueConformance3.ts, 6, 17)) ++>b : Symbol(b, Decl(typeSatisfaction_propertyValueConformance3.ts, 6, 23)) ++ ++} satisfies Record; ++>Record : Symbol(Record, Decl(lib.es5.d.ts, --, --)) ++>Color : Symbol(Color, Decl(typeSatisfaction_propertyValueConformance3.ts, 0, 0)) ++ +diff --git a/tests/baselines/reference/typeSatisfaction_propertyValueConformance3.types b/tests/baselines/reference/typeSatisfaction_propertyValueConformance3.types +new file mode 100644 +index 0000000000..cbcec4aedc +--- /dev/null ++++ b/tests/baselines/reference/typeSatisfaction_propertyValueConformance3.types +@@ -0,0 +1,45 @@ ++=== tests/cases/conformance/expressions/typeSatisfaction/typeSatisfaction_propertyValueConformance3.ts === ++export type Color = { r: number, g: number, b: number }; ++>Color : { r: number; g: number; b: number; } ++>r : number ++>g : number ++>b : number ++ ++// All of these should be Colors, but I only use some of them here. ++export const Palette = { ++>Palette : { white: { r: number; g: number; b: number; }; black: { r: number; g: number; d: number; }; blue: { r: number; g: number; b: number; }; } ++>{ white: { r: 255, g: 255, b: 255 }, black: { r: 0, g: 0, d: 0 }, // <- oops! 'd' in place of 'b' blue: { r: 0, g: 0, b: 255 },} satisfies Record : { white: { r: number; g: number; b: number; }; black: { r: number; g: number; d: number; }; blue: { r: number; g: number; b: number; }; } ++>{ white: { r: 255, g: 255, b: 255 }, black: { r: 0, g: 0, d: 0 }, // <- oops! 'd' in place of 'b' blue: { r: 0, g: 0, b: 255 },} : { white: { r: number; g: number; b: number; }; black: { r: number; g: number; d: number; }; blue: { r: number; g: number; b: number; }; } ++ ++ white: { r: 255, g: 255, b: 255 }, ++>white : { r: number; g: number; b: number; } ++>{ r: 255, g: 255, b: 255 } : { r: number; g: number; b: number; } ++>r : number ++>255 : 255 ++>g : number ++>255 : 255 ++>b : number ++>255 : 255 ++ ++ black: { r: 0, g: 0, d: 0 }, // <- oops! 'd' in place of 'b' ++>black : { r: number; g: number; d: number; } ++>{ r: 0, g: 0, d: 0 } : { r: number; g: number; d: number; } ++>r : number ++>0 : 0 ++>g : number ++>0 : 0 ++>d : number ++>0 : 0 ++ ++ blue: { r: 0, g: 0, b: 255 }, ++>blue : { r: number; g: number; b: number; } ++>{ r: 0, g: 0, b: 255 } : { r: number; g: number; b: number; } ++>r : number ++>0 : 0 ++>g : number ++>0 : 0 ++>b : number ++>255 : 255 ++ ++} satisfies Record; ++ +diff --git a/tests/baselines/reference/typeSatisfaction_vacuousIntersectionOfContextualTypes.errors.txt b/tests/baselines/reference/typeSatisfaction_vacuousIntersectionOfContextualTypes.errors.txt +new file mode 100644 +index 0000000000..5145035e81 +--- /dev/null ++++ b/tests/baselines/reference/typeSatisfaction_vacuousIntersectionOfContextualTypes.errors.txt +@@ -0,0 +1,16 @@ ++tests/cases/conformance/expressions/typeSatisfaction/typeSatisfaction_vacuousIntersectionOfContextualTypes.ts(1,7): error TS2322: Type '"foo"' is not assignable to type '"baz"'. ++tests/cases/conformance/expressions/typeSatisfaction/typeSatisfaction_vacuousIntersectionOfContextualTypes.ts(2,7): error TS2322: Type '{ xyz: "foo"; }' is not assignable to type '{ xyz: "baz"; }'. ++ Types of property 'xyz' are incompatible. ++ Type '"foo"' is not assignable to type '"baz"'. ++ ++ ++==== tests/cases/conformance/expressions/typeSatisfaction/typeSatisfaction_vacuousIntersectionOfContextualTypes.ts (2 errors) ==== ++ const a: "baz" = "foo" satisfies "foo" | "bar"; ++ ~ ++!!! error TS2322: Type '"foo"' is not assignable to type '"baz"'. ++ const b: { xyz: "baz" } = { xyz: "foo" } satisfies { xyz: "foo" | "bar" }; ++ ~ ++!!! error TS2322: Type '{ xyz: "foo"; }' is not assignable to type '{ xyz: "baz"; }'. ++!!! error TS2322: Types of property 'xyz' are incompatible. ++!!! error TS2322: Type '"foo"' is not assignable to type '"baz"'. ++ +\ No newline at end of file +diff --git a/tests/baselines/reference/typeSatisfaction_vacuousIntersectionOfContextualTypes.js b/tests/baselines/reference/typeSatisfaction_vacuousIntersectionOfContextualTypes.js +new file mode 100644 +index 0000000000..65d5dc56a4 +--- /dev/null ++++ b/tests/baselines/reference/typeSatisfaction_vacuousIntersectionOfContextualTypes.js +@@ -0,0 +1,8 @@ ++//// [typeSatisfaction_vacuousIntersectionOfContextualTypes.ts] ++const a: "baz" = "foo" satisfies "foo" | "bar"; ++const b: { xyz: "baz" } = { xyz: "foo" } satisfies { xyz: "foo" | "bar" }; ++ ++ ++//// [typeSatisfaction_vacuousIntersectionOfContextualTypes.js] ++var a = "foo"; ++var b = { xyz: "foo" }; +diff --git a/tests/baselines/reference/typeSatisfaction_vacuousIntersectionOfContextualTypes.symbols b/tests/baselines/reference/typeSatisfaction_vacuousIntersectionOfContextualTypes.symbols +new file mode 100644 +index 0000000000..e42d85f578 +--- /dev/null ++++ b/tests/baselines/reference/typeSatisfaction_vacuousIntersectionOfContextualTypes.symbols +@@ -0,0 +1,10 @@ ++=== tests/cases/conformance/expressions/typeSatisfaction/typeSatisfaction_vacuousIntersectionOfContextualTypes.ts === ++const a: "baz" = "foo" satisfies "foo" | "bar"; ++>a : Symbol(a, Decl(typeSatisfaction_vacuousIntersectionOfContextualTypes.ts, 0, 5)) ++ ++const b: { xyz: "baz" } = { xyz: "foo" } satisfies { xyz: "foo" | "bar" }; ++>b : Symbol(b, Decl(typeSatisfaction_vacuousIntersectionOfContextualTypes.ts, 1, 5)) ++>xyz : Symbol(xyz, Decl(typeSatisfaction_vacuousIntersectionOfContextualTypes.ts, 1, 10)) ++>xyz : Symbol(xyz, Decl(typeSatisfaction_vacuousIntersectionOfContextualTypes.ts, 1, 27)) ++>xyz : Symbol(xyz, Decl(typeSatisfaction_vacuousIntersectionOfContextualTypes.ts, 1, 52)) ++ +diff --git a/tests/baselines/reference/typeSatisfaction_vacuousIntersectionOfContextualTypes.types b/tests/baselines/reference/typeSatisfaction_vacuousIntersectionOfContextualTypes.types +new file mode 100644 +index 0000000000..5b574cf380 +--- /dev/null ++++ b/tests/baselines/reference/typeSatisfaction_vacuousIntersectionOfContextualTypes.types +@@ -0,0 +1,15 @@ ++=== tests/cases/conformance/expressions/typeSatisfaction/typeSatisfaction_vacuousIntersectionOfContextualTypes.ts === ++const a: "baz" = "foo" satisfies "foo" | "bar"; ++>a : "baz" ++>"foo" satisfies "foo" | "bar" : "foo" ++>"foo" : "foo" ++ ++const b: { xyz: "baz" } = { xyz: "foo" } satisfies { xyz: "foo" | "bar" }; ++>b : { xyz: "baz"; } ++>xyz : "baz" ++>{ xyz: "foo" } satisfies { xyz: "foo" | "bar" } : { xyz: "foo"; } ++>{ xyz: "foo" } : { xyz: "foo"; } ++>xyz : "foo" ++>"foo" : "foo" ++>xyz : "foo" | "bar" ++ +diff --git a/tests/cases/conformance/expressions/typeSatisfaction/typeSatisfaction.ts b/tests/cases/conformance/expressions/typeSatisfaction/typeSatisfaction.ts +new file mode 100644 +index 0000000000..5e268ffb1e +--- /dev/null ++++ b/tests/cases/conformance/expressions/typeSatisfaction/typeSatisfaction.ts +@@ -0,0 +1,24 @@ ++interface I1 { ++ a: number; ++} ++ ++type T1 = { ++ a: "a" | "b"; ++} ++ ++type T2 = (x: string) => void; ++ ++const t1 = { a: 1 } satisfies I1; // Ok ++const t2 = { a: 1, b: 1 } satisfies I1; // Error ++const t3 = { } satisfies I1; // Error ++ ++const t4: T1 = { a: "a" } satisfies T1; // Ok ++const t5 = (m => m.substring(0)) satisfies T2; // Ok ++ ++const t6 = [1, 2] satisfies [number, number]; ++ ++interface A { ++ a: string ++} ++let t7 = { a: 'test' } satisfies A; ++let t8 = { a: 'test', b: 'test' } satisfies A; +diff --git a/tests/cases/conformance/expressions/typeSatisfaction/typeSatisfactionWithDefaultExport.ts b/tests/cases/conformance/expressions/typeSatisfaction/typeSatisfactionWithDefaultExport.ts +new file mode 100644 +index 0000000000..247accb875 +--- /dev/null ++++ b/tests/cases/conformance/expressions/typeSatisfaction/typeSatisfactionWithDefaultExport.ts +@@ -0,0 +1,13 @@ ++// @module: esnext ++ ++// @filename: ./a.ts ++interface Foo { ++ a: number; ++} ++export default {} satisfies Foo; ++ ++// @filename: ./b.ts ++interface Foo { ++ a: number; ++} ++export default { a: 1 } satisfies Foo; +diff --git a/tests/cases/conformance/expressions/typeSatisfaction/typeSatisfaction_contextualTyping1.ts b/tests/cases/conformance/expressions/typeSatisfaction/typeSatisfaction_contextualTyping1.ts +new file mode 100644 +index 0000000000..d099059d85 +--- /dev/null ++++ b/tests/cases/conformance/expressions/typeSatisfaction/typeSatisfaction_contextualTyping1.ts +@@ -0,0 +1,6 @@ ++type Predicates = { [s: string]: (n: number) => boolean }; ++ ++const p = { ++ isEven: n => n % 2 === 0, ++ isOdd: n => n % 2 === 1 ++} satisfies Predicates; +diff --git a/tests/cases/conformance/expressions/typeSatisfaction/typeSatisfaction_contextualTyping2.ts b/tests/cases/conformance/expressions/typeSatisfaction/typeSatisfaction_contextualTyping2.ts +new file mode 100644 +index 0000000000..597a1eed2b +--- /dev/null ++++ b/tests/cases/conformance/expressions/typeSatisfaction/typeSatisfaction_contextualTyping2.ts +@@ -0,0 +1,9 @@ ++// @strict: true ++ ++let obj: { f(s: string): void } & Record = { ++ f(s) { }, // "incorrect" implicit any on 's' ++ g(s) { } ++} satisfies { g(s: string): void } & Record; ++ ++// This needs to not crash (outer node is not expression) ++({ f(x) { } }) satisfies { f(s: string): void }; +diff --git a/tests/cases/conformance/expressions/typeSatisfaction/typeSatisfaction_ensureInterfaceImpl.ts b/tests/cases/conformance/expressions/typeSatisfaction/typeSatisfaction_ensureInterfaceImpl.ts +new file mode 100644 +index 0000000000..a3dbaf484a +--- /dev/null ++++ b/tests/cases/conformance/expressions/typeSatisfaction/typeSatisfaction_ensureInterfaceImpl.ts +@@ -0,0 +1,11 @@ ++type Movable = { ++ move(distance: number): void; ++}; ++ ++const car = { ++ start() { }, ++ move(d) { ++ // d should be number ++ }, ++ stop() { } ++} satisfies Movable & Record; +diff --git a/tests/cases/conformance/expressions/typeSatisfaction/typeSatisfaction_js.ts b/tests/cases/conformance/expressions/typeSatisfaction/typeSatisfaction_js.ts +new file mode 100644 +index 0000000000..5826e4a209 +--- /dev/null ++++ b/tests/cases/conformance/expressions/typeSatisfaction/typeSatisfaction_js.ts +@@ -0,0 +1,5 @@ ++// @allowJs: true ++// @filename: /src/a.js ++// @out: /lib/a.js ++ ++var v = undefined satisfies 1; +diff --git a/tests/cases/conformance/expressions/typeSatisfaction/typeSatisfaction_optionalMemberConformance.ts b/tests/cases/conformance/expressions/typeSatisfaction/typeSatisfaction_optionalMemberConformance.ts +new file mode 100644 +index 0000000000..939c6fc60a +--- /dev/null ++++ b/tests/cases/conformance/expressions/typeSatisfaction/typeSatisfaction_optionalMemberConformance.ts +@@ -0,0 +1,7 @@ ++type Point2d = { x: number, y: number }; ++// Undesirable behavior today with type annotation ++const a = { x: 10 } satisfies Partial; ++// Should OK ++console.log(a.x.toFixed()); ++// Should error ++let p = a.y; +diff --git a/tests/cases/conformance/expressions/typeSatisfaction/typeSatisfaction_propNameConstraining.ts b/tests/cases/conformance/expressions/typeSatisfaction/typeSatisfaction_propNameConstraining.ts +new file mode 100644 +index 0000000000..4745de6e77 +--- /dev/null ++++ b/tests/cases/conformance/expressions/typeSatisfaction/typeSatisfaction_propNameConstraining.ts +@@ -0,0 +1,13 @@ ++type Keys = 'a' | 'b' | 'c' | 'd'; ++ ++const p = { ++ a: 0, ++ b: "hello", ++ x: 8 // Should error, 'x' isn't in 'Keys' ++} satisfies Partial>; ++ ++// Should be OK -- retain info that a is number and b is string ++let a = p.a.toFixed(); ++let b = p.b.substring(1); ++// Should error even though 'd' is in 'Keys' ++let d = p.d; +diff --git a/tests/cases/conformance/expressions/typeSatisfaction/typeSatisfaction_propertyNameFulfillment.ts b/tests/cases/conformance/expressions/typeSatisfaction/typeSatisfaction_propertyNameFulfillment.ts +new file mode 100644 +index 0000000000..e344bcfbff +--- /dev/null ++++ b/tests/cases/conformance/expressions/typeSatisfaction/typeSatisfaction_propertyNameFulfillment.ts +@@ -0,0 +1,13 @@ ++type Keys = 'a' | 'b' | 'c' | 'd'; ++ ++const p = { ++ a: 0, ++ b: "hello", ++ x: 8 // Should error, 'x' isn't in 'Keys' ++} satisfies Record; ++ ++// Should be OK -- retain info that a is number and b is string ++let a = p.a.toFixed(); ++let b = p.b.substring(1); ++// Should error even though 'd' is in 'Keys' ++let d = p.d; +diff --git a/tests/cases/conformance/expressions/typeSatisfaction/typeSatisfaction_propertyValueConformance1.ts b/tests/cases/conformance/expressions/typeSatisfaction/typeSatisfaction_propertyValueConformance1.ts +new file mode 100644 +index 0000000000..62a51f2ac7 +--- /dev/null ++++ b/tests/cases/conformance/expressions/typeSatisfaction/typeSatisfaction_propertyValueConformance1.ts +@@ -0,0 +1,25 @@ ++// @noPropertyAccessFromIndexSignature: true, false ++ ++type Facts = { [key: string]: boolean }; ++declare function checkTruths(x: Facts): void; ++declare function checkM(x: { m: boolean }): void; ++const x = { ++ m: true ++}; ++ ++// Should be OK ++checkTruths(x); ++// Should be OK ++checkM(x); ++// Should fail under --noPropertyAccessFromIndexSignature ++console.log(x.z); ++const m: boolean = x.m; ++ ++// Should be 'm' ++type M = keyof typeof x; ++ ++// Should be able to detect a failure here ++const x2 = { ++ m: true, ++ s: "false" ++} satisfies Facts; +diff --git a/tests/cases/conformance/expressions/typeSatisfaction/typeSatisfaction_propertyValueConformance2.ts b/tests/cases/conformance/expressions/typeSatisfaction/typeSatisfaction_propertyValueConformance2.ts +new file mode 100644 +index 0000000000..762a9b0f4e +--- /dev/null ++++ b/tests/cases/conformance/expressions/typeSatisfaction/typeSatisfaction_propertyValueConformance2.ts +@@ -0,0 +1,25 @@ ++// @noUncheckedIndexedAccess: true, false ++ ++type Facts = { [key: string]: boolean }; ++declare function checkTruths(x: Facts): void; ++declare function checkM(x: { m: boolean }): void; ++const x = { ++ m: true ++}; ++ ++// Should be OK ++checkTruths(x); ++// Should be OK ++checkM(x); ++console.log(x.z); ++// Should be OK under --noUncheckedIndexedAccess ++const m: boolean = x.m; ++ ++// Should be 'm' ++type M = keyof typeof x; ++ ++// Should be able to detect a failure here ++const x2 = { ++ m: true, ++ s: "false" ++} satisfies Facts; +diff --git a/tests/cases/conformance/expressions/typeSatisfaction/typeSatisfaction_propertyValueConformance3.ts b/tests/cases/conformance/expressions/typeSatisfaction/typeSatisfaction_propertyValueConformance3.ts +new file mode 100644 +index 0000000000..178da1c2c4 +--- /dev/null ++++ b/tests/cases/conformance/expressions/typeSatisfaction/typeSatisfaction_propertyValueConformance3.ts +@@ -0,0 +1,8 @@ ++export type Color = { r: number, g: number, b: number }; ++ ++// All of these should be Colors, but I only use some of them here. ++export const Palette = { ++ white: { r: 255, g: 255, b: 255 }, ++ black: { r: 0, g: 0, d: 0 }, // <- oops! 'd' in place of 'b' ++ blue: { r: 0, g: 0, b: 255 }, ++} satisfies Record; +diff --git a/tests/cases/conformance/expressions/typeSatisfaction/typeSatisfaction_vacuousIntersectionOfContextualTypes.ts b/tests/cases/conformance/expressions/typeSatisfaction/typeSatisfaction_vacuousIntersectionOfContextualTypes.ts +new file mode 100644 +index 0000000000..92af1c521b +--- /dev/null ++++ b/tests/cases/conformance/expressions/typeSatisfaction/typeSatisfaction_vacuousIntersectionOfContextualTypes.ts +@@ -0,0 +1,2 @@ ++const a: "baz" = "foo" satisfies "foo" | "bar"; ++const b: { xyz: "baz" } = { xyz: "foo" } satisfies { xyz: "foo" | "bar" }; +diff --git a/tests/cases/fourslash/completionSatisfiesKeyword.ts b/tests/cases/fourslash/completionSatisfiesKeyword.ts +new file mode 100644 +index 0000000000..c44ca016c3 +--- /dev/null ++++ b/tests/cases/fourslash/completionSatisfiesKeyword.ts +@@ -0,0 +1,11 @@ ++/// ++ ++////const x = { a: 1 } /*1*/ ++////function foo() { ++//// const x = { a: 1 } /*2*/ ++////} ++ ++verify.completions({ ++ marker: ["1", "2"], ++ includes: [{ name: "satisfies", sortText: completion.SortText.GlobalsOrKeywords }] ++}); +diff --git a/tests/cases/fourslash/satisfiesOperatorCompletion.ts b/tests/cases/fourslash/satisfiesOperatorCompletion.ts +new file mode 100644 +index 0000000000..94b07db40d +--- /dev/null ++++ b/tests/cases/fourslash/satisfiesOperatorCompletion.ts +@@ -0,0 +1,7 @@ ++/// ++ ++//// type T = number; ++//// var x; ++//// var y = x satisfies /**/ ++ ++verify.completions({ marker: "", includes: "T" }); + +diff --git a/src/harness/fourslashInterfaceImpl.ts b/src/harness/fourslashInterfaceImpl.ts +index 93508a079a..c43b8f0bc4 100644 +--- a/src/harness/fourslashInterfaceImpl.ts ++++ b/src/harness/fourslashInterfaceImpl.ts +@@ -1388,6 +1388,7 @@ namespace FourSlashInterface { + "package", + "readonly", + "return", ++ "satisfies", + "string", + "super", + "switch", +@@ -1503,6 +1504,7 @@ namespace FourSlashInterface { + "null", + "package", + "return", ++ "satisfies", + "super", + "switch", + "this", +@@ -1601,6 +1603,7 @@ namespace FourSlashInterface { + "package", + "readonly", + "return", ++ "satisfies", + "string", + "super", + "switch", +@@ -1655,6 +1658,7 @@ namespace FourSlashInterface { + "null", + "package", + "return", ++ "satisfies", + "super", + "switch", + "this", +diff --git a/src/testRunner/compilerRunner.ts b/src/testRunner/compilerRunner.ts +index a6c67a17ee..ced86a5771 100644 +--- a/src/testRunner/compilerRunner.ts ++++ b/src/testRunner/compilerRunner.ts +@@ -143,6 +143,8 @@ namespace Harness { + "exactOptionalPropertyTypes", + "useDefineForClassFields", + "useUnknownInCatchVariables", ++ "noUncheckedIndexedAccess", ++ "noPropertyAccessFromIndexSignature", + ]; + private fileName: string; + private justName: string; diff --git a/TypeScript_1/tests/private/eval_tests_aug.patch b/TypeScript_1/tests/private/eval_tests_aug.patch new file mode 100644 index 0000000000000000000000000000000000000000..fa71005f36b509f8023e6fa6ea85a0e4823c2aa5 --- /dev/null +++ b/TypeScript_1/tests/private/eval_tests_aug.patch @@ -0,0 +1,185 @@ +diff --git a/tests/cases/fourslash/satisfiesAugCompilerApi.ts b/tests/cases/fourslash/satisfiesAugCompilerApi.ts +new file mode 100644 +index 0000000000..1111111111 +--- /dev/null ++++ b/tests/cases/fourslash/satisfiesAugCompilerApi.ts +@@ -0,0 +1,76 @@ ++/// ++ ++////const placeholder = 0; ++ ++const source = "const result = value satisfies Target;"; ++const sourceFile = ts.createSourceFile("satisfiesAug.ts", source, ts.ScriptTarget.Latest, /*setParentNodes*/ true, ts.ScriptKind.TS); ++const declaration = (sourceFile.statements[0] as ts.VariableStatement).declarationList.declarations[0]; ++const initializer = declaration.initializer as ts.SatisfiesExpression; ++ ++assert.strictEqual(initializer.kind, ts.SyntaxKind.SatisfiesExpression); ++ ++const printed = ts.createPrinter().printNode(ts.EmitHint.Expression, initializer, sourceFile); ++assert.strictEqual(printed, "value satisfies Target"); ++ ++const transpiled = ts.transpileModule(source, { ++ compilerOptions: { target: ts.ScriptTarget.ES2020 }, ++}).outputText.trim(); ++assert.strictEqual(transpiled, "const result = value;"); ++ ++const transformed = ts.transform(sourceFile, [ ++ context => root => ts.visitNode(root, function visit(node): ts.Node { ++ if ( ++ ts.isTypeReferenceNode(node) && ++ ts.isIdentifier(node.typeName) && ++ node.typeName.text === "Target" ++ ) { ++ return context.factory.updateTypeReferenceNode( ++ node, ++ context.factory.createIdentifier("Replacement"), ++ node.typeArguments, ++ ); ++ } ++ return ts.visitEachChild(node, visit, context); ++ }), ++]); ++try { ++ const transformedSourceFile = transformed.transformed[0] as ts.SourceFile; ++ const transformedDeclaration = ++ (transformedSourceFile.statements[0] as ts.VariableStatement).declarationList.declarations[0]; ++ const transformedInitializer = transformedDeclaration.initializer as ts.SatisfiesExpression; ++ const transformedText = ts.createPrinter().printNode( ++ ts.EmitHint.Expression, ++ transformedInitializer, ++ transformedSourceFile, ++ ); ++ assert.strictEqual(transformedText, "value satisfies Replacement"); ++} ++finally { ++ transformed.dispose(); ++} ++ ++const factoryExpression = ts.factory.createSatisfiesExpression( ++ ts.factory.createIdentifier("factoryValue"), ++ ts.factory.createKeywordTypeNode(ts.SyntaxKind.NumberKeyword), ++); ++assert.strictEqual( ++ ts.createPrinter().printNode(ts.EmitHint.Expression, factoryExpression, sourceFile), ++ "factoryValue satisfies number", ++); ++ ++const factoryTransformer = context => source => { ++ const factoryExport = context.factory.createExportAssignment( ++ undefined, ++ false, ++ context.factory.createSatisfiesExpression( ++ context.factory.createIdentifier("factoryValue"), ++ context.factory.createKeywordTypeNode(ts.SyntaxKind.NumberKeyword), ++ ), ++ ); ++ return context.factory.updateSourceFile(source, [factoryExport]); ++}; ++const factoryTranspile = ts.transpileModule("export const seed = 0;", { ++ compilerOptions: { target: ts.ScriptTarget.ES2020, module: ts.ModuleKind.ESNext }, ++ transformers: { before: [factoryTransformer] }, ++}).outputText.trim(); ++assert.strictEqual(factoryTranspile, "export default factoryValue;"); +diff --git a/tests/cases/fourslash/satisfiesAugCompletionKeyword.ts b/tests/cases/fourslash/satisfiesAugCompletionKeyword.ts +new file mode 100644 +index 0000000000..1111111111 +--- /dev/null ++++ b/tests/cases/fourslash/satisfiesAugCompletionKeyword.ts +@@ -0,0 +1,14 @@ ++/// ++ ++////const first = { a: 1 } /*top*/ ++////function outer() { ++//// const second = { a: 1 } /*nested*/ ++////} ++////type Target = { a: number }; ++////const checked = { a: 1 } satisfies /**/ ++ ++verify.completions({ ++ marker: ["top", "nested"], ++ includes: [{ name: "satisfies", sortText: completion.SortText.GlobalsOrKeywords }] ++}); ++verify.completions({ marker: "", includes: "Target" }); +diff --git a/tests/cases/fourslash/satisfiesAugCallHierarchyTypeSide.ts b/tests/cases/fourslash/satisfiesAugCallHierarchyTypeSide.ts +new file mode 100644 +index 0000000000..1111111111 +--- /dev/null ++++ b/tests/cases/fourslash/satisfiesAugCallHierarchyTypeSide.ts +@@ -0,0 +1,8 @@ ++/// ++ ++//// function /**/target() { return { ok: true }; } ++//// const checked = target() satisfies ReturnType; ++ ++assert.strictEqual(typeof ts.SyntaxKind.SatisfiesExpression, "number"); ++goTo.marker(); ++verify.baselineCallHierarchy(); +diff --git a/tests/cases/fourslash/asOperatorAugCompletionP2P.ts b/tests/cases/fourslash/asOperatorAugCompletionP2P.ts +new file mode 100644 +index 0000000000..1111111111 +--- /dev/null ++++ b/tests/cases/fourslash/asOperatorAugCompletionP2P.ts +@@ -0,0 +1,6 @@ ++/// ++ ++////type ExistingTarget = { a: number }; ++////const value = { a: 1 } as /**/ ++ ++verify.completions({ marker: "", includes: "ExistingTarget", excludes: "satisfies" }); +diff --git a/tests/cases/fourslash/contextualTypingAugP2P.ts b/tests/cases/fourslash/contextualTypingAugP2P.ts +new file mode 100644 +index 0000000000..1111111111 +--- /dev/null ++++ b/tests/cases/fourslash/contextualTypingAugP2P.ts +@@ -0,0 +1,8 @@ ++/// ++ ++////interface CallbackBox { run(value: number): string; } ++////const box: CallbackBox = { run: /*param*/value => value.toFixed() }; ++////box.run(1); ++ ++verify.quickInfoAt("param", "(parameter) value: number"); ++verify.noErrors(); +diff --git a/tests/baselines/reference/satisfiesAugCallHierarchyTypeSide.callHierarchy.txt b/tests/baselines/reference/satisfiesAugCallHierarchyTypeSide.callHierarchy.txt +new file mode 100644 +index 0000000000..1111111111 +--- /dev/null ++++ b/tests/baselines/reference/satisfiesAugCallHierarchyTypeSide.callHierarchy.txt +@@ -0,0 +1,37 @@ ++╭ name: target ++├ kind: function ++├ file: /tests/cases/fourslash/satisfiesAugCallHierarchyTypeSide.ts ++├ span: ++│ ╭ /tests/cases/fourslash/satisfiesAugCallHierarchyTypeSide.ts:1:1-1:43 ++│ │ 1: function target() { return { ok: true }; } ++│ │ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ++│ ╰ ++├ selectionSpan: ++│ ╭ /tests/cases/fourslash/satisfiesAugCallHierarchyTypeSide.ts:1:10-1:16 ++│ │ 1: function target() { return { ok: true }; } ++│ │ ^^^^^^ ++│ ╰ ++├ incoming: ++│ ╭ from: ++│ │ ╭ name: /tests/cases/fourslash/satisfiesAugCallHierarchyTypeSide.ts ++│ │ ├ kind: script ++│ │ ├ file: /tests/cases/fourslash/satisfiesAugCallHierarchyTypeSide.ts ++│ │ ├ span: ++│ │ │ ╭ /tests/cases/fourslash/satisfiesAugCallHierarchyTypeSide.ts:1:1-2:62 ++│ │ │ │ 1: function target() { return { ok: true }; } ++│ │ │ │ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ++│ │ │ │ 2: const checked = target() satisfies ReturnType; ++│ │ │ │ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ++│ │ │ ╰ ++│ │ ├ selectionSpan: ++│ │ │ ╭ /tests/cases/fourslash/satisfiesAugCallHierarchyTypeSide.ts:1:1-1:1 ++│ │ │ │ 1: function target() { return { ok: true }; } ++│ │ │ │ < ++│ │ │ ╰ ++│ │ ╰ incoming: none ++│ ├ fromSpans: ++│ │ ╭ /tests/cases/fourslash/satisfiesAugCallHierarchyTypeSide.ts:2:17-2:23 ++│ │ │ 2: const checked = target() satisfies ReturnType; ++│ │ │ ^^^^^^ ++│ ╰ ╰ ++╰ outgoing: none diff --git a/TypeScript_1/tests/private/f2p.txt b/TypeScript_1/tests/private/f2p.txt new file mode 100644 index 0000000000000000000000000000000000000000..036804e650a39269efd85a7e32f7581f6f3103e3 --- /dev/null +++ b/TypeScript_1/tests/private/f2p.txt @@ -0,0 +1,13 @@ +tests/cases/conformance/expressions/typeSatisfaction/typeSatisfaction.ts +tests/cases/conformance/expressions/typeSatisfaction/typeSatisfactionWithDefaultExport.ts +tests/cases/conformance/expressions/typeSatisfaction/typeSatisfaction_contextualTyping1.ts +tests/cases/conformance/expressions/typeSatisfaction/typeSatisfaction_contextualTyping2.ts +tests/cases/conformance/expressions/typeSatisfaction/typeSatisfaction_ensureInterfaceImpl.ts +tests/cases/conformance/expressions/typeSatisfaction/typeSatisfaction_js.ts +tests/cases/conformance/expressions/typeSatisfaction/typeSatisfaction_optionalMemberConformance.ts +tests/cases/conformance/expressions/typeSatisfaction/typeSatisfaction_propNameConstraining.ts +tests/cases/conformance/expressions/typeSatisfaction/typeSatisfaction_propertyNameFulfillment.ts +tests/cases/conformance/expressions/typeSatisfaction/typeSatisfaction_propertyValueConformance1.ts +tests/cases/conformance/expressions/typeSatisfaction/typeSatisfaction_propertyValueConformance2.ts +tests/cases/conformance/expressions/typeSatisfaction/typeSatisfaction_propertyValueConformance3.ts +tests/cases/conformance/expressions/typeSatisfaction/typeSatisfaction_vacuousIntersectionOfContextualTypes.ts diff --git a/TypeScript_1/tests/private/f2p_aug.txt b/TypeScript_1/tests/private/f2p_aug.txt new file mode 100644 index 0000000000000000000000000000000000000000..58131d1118b4009c06ee0c8827426fa088c61af5 --- /dev/null +++ b/TypeScript_1/tests/private/f2p_aug.txt @@ -0,0 +1,3 @@ +tests/cases/fourslash/satisfiesAugCompletionKeyword.ts +tests/cases/fourslash/satisfiesAugCompilerApi.ts +tests/cases/fourslash/satisfiesAugCallHierarchyTypeSide.ts diff --git a/TypeScript_1/tests/private/p2p.txt b/TypeScript_1/tests/private/p2p.txt new file mode 100644 index 0000000000000000000000000000000000000000..3a25699b0d99762f2c004afe3a2efe2ab91843b9 --- /dev/null +++ b/TypeScript_1/tests/private/p2p.txt @@ -0,0 +1,50 @@ +tests/cases/conformance/expressions/asOperator/asOpEmitParens.ts +tests/cases/conformance/expressions/asOperator/asOperator1.ts +tests/cases/conformance/expressions/asOperator/asOperator2.ts +tests/cases/conformance/expressions/asOperator/asOperator3.ts +tests/cases/conformance/expressions/asOperator/asOperator4.ts +tests/cases/conformance/expressions/asOperator/asOperatorASI.ts +tests/cases/conformance/expressions/asOperator/asOperatorAmbiguity.ts +tests/cases/conformance/expressions/asOperator/asOperatorContextualType.ts +tests/cases/conformance/expressions/asOperator/asOperatorNames.ts +tests/cases/conformance/expressions/contextualTyping/argumentExpressionContextualTyping.ts +tests/cases/conformance/expressions/contextualTyping/arrayLiteralExpressionContextualTyping.ts +tests/cases/conformance/expressions/contextualTyping/functionExpressionContextualTyping1.ts +tests/cases/conformance/expressions/contextualTyping/getSetAccessorContextualTyping.ts +tests/cases/conformance/expressions/contextualTyping/iterableContextualTyping1.ts +tests/cases/conformance/expressions/contextualTyping/objectLiteralContextualTyping.ts +tests/cases/conformance/expressions/contextualTyping/parenthesizedContexualTyping1.ts +tests/cases/conformance/expressions/contextualTyping/superCallParameterContextualTyping1.ts +tests/cases/conformance/expressions/arrayLiterals/arrayLiteralInference.ts +tests/cases/conformance/expressions/arrayLiterals/arrayLiterals.ts +tests/cases/conformance/expressions/arrayLiterals/arrayLiterals2ES5.ts +tests/cases/conformance/expressions/arrayLiterals/arrayLiterals2ES6.ts +tests/cases/conformance/expressions/assignmentOperator/assignmentLHSIsReference.ts +tests/cases/conformance/expressions/assignmentOperator/assignmentLHSIsValue.ts +tests/cases/conformance/expressions/assignmentOperator/assignmentTypeNarrowing.ts +tests/cases/conformance/expressions/arrayLiterals/arrayLiterals3.ts +tests/cases/conformance/expressions/assignmentOperator/assignmentGenericLookupTypeNarrowing.ts +tests/cases/conformance/expressions/assignmentOperator/compoundAdditionAssignmentLHSCanBeAssigned.ts +tests/cases/conformance/expressions/assignmentOperator/compoundAdditionAssignmentLHSCannotBeAssigned.ts +tests/cases/conformance/expressions/assignmentOperator/compoundAdditionAssignmentWithInvalidOperands.ts +tests/cases/conformance/expressions/assignmentOperator/compoundArithmeticAssignmentLHSCanBeAssigned.ts +tests/cases/conformance/expressions/assignmentOperator/compoundArithmeticAssignmentWithInvalidOperands.ts +tests/cases/conformance/expressions/assignmentOperator/compoundAssignmentLHSIsReference.ts +tests/cases/conformance/expressions/assignmentOperator/compoundAssignmentLHSIsValue.ts +tests/cases/conformance/expressions/contextualTyping/functionExpressionContextualTyping2.ts +tests/cases/conformance/expressions/contextualTyping/functionExpressionContextualTyping3.ts +tests/cases/conformance/expressions/contextualTyping/generatedContextualTyping.ts +tests/cases/conformance/expressions/contextualTyping/parenthesizedContexualTyping2.ts +tests/cases/conformance/expressions/contextualTyping/parenthesizedContexualTyping3.ts +tests/cases/conformance/expressions/contextualTyping/superCallParameterContextualTyping2.ts +tests/cases/conformance/expressions/contextualTyping/superCallParameterContextualTyping3.ts +tests/cases/conformance/expressions/contextualTyping/taggedTemplateContextualTyping1.ts +tests/cases/conformance/expressions/contextualTyping/taggedTemplateContextualTyping2.ts +tests/cases/conformance/expressions/typeAssertions/constAssertionOnEnum.ts +tests/cases/conformance/expressions/typeAssertions/constAssertions.ts +tests/cases/conformance/expressions/typeAssertions/duplicatePropertiesInTypeAssertions01.ts +tests/cases/conformance/expressions/typeAssertions/duplicatePropertiesInTypeAssertions02.ts +tests/cases/conformance/expressions/typeAssertions/typeAssertions.ts +tests/cases/conformance/expressions/conditonalOperator/conditionalOperatorConditionIsBooleanType.ts +tests/cases/conformance/expressions/conditonalOperator/conditionalOperatorConditionIsNumberType.ts +tests/cases/conformance/expressions/conditonalOperator/conditionalOperatorConditionIsObjectType.ts diff --git a/TypeScript_1/tests/private/p2p_aug.txt b/TypeScript_1/tests/private/p2p_aug.txt new file mode 100644 index 0000000000000000000000000000000000000000..2018fa8e761ea6f6ba9701a88ab01bcef9de6cfb --- /dev/null +++ b/TypeScript_1/tests/private/p2p_aug.txt @@ -0,0 +1,2 @@ +tests/cases/fourslash/asOperatorAugCompletionP2P.ts +tests/cases/fourslash/contextualTypingAugP2P.ts diff --git a/TypeScript_1/tests/private/run_tests.sh b/TypeScript_1/tests/private/run_tests.sh new file mode 100644 index 0000000000000000000000000000000000000000..e5e39766d6d82b728438a0bb34acd0cdafd90eed --- /dev/null +++ b/TypeScript_1/tests/private/run_tests.sh @@ -0,0 +1,339 @@ +#!/usr/bin/env bash +# LoLBench runner for microsoft/TypeScript PR-46827 (satisfies operator). +# +# Eval contract: +# docker run --rm --network=none \ +# -v $(pwd)/solution.patch:/in/solution.patch:ro \ +# -v $(pwd)/out:/out \ +# lolbench/apache-ts-pr-46827:1 +# → /out/agent_report.json (sanitized). +# +# Validation modes: +# LOLBENCH_MODE=validate_pre # F2P FAIL (parser doesn't know `satisfies`), P2P PASS +# LOLBENCH_MODE=validate_post # all PASS + +set -uo pipefail +PRIV=/opt/lolbench/private +WS=/workspace +TS=$WS/typescript +MODE=${LOLBENCH_MODE:-eval} +SUITE=${LOLBENCH_SUITE:-orig} + +case "$SUITE" in + orig|aug|union) ;; + *) echo "[run_tests $MODE] FATAL: unknown LOLBENCH_SUITE=$SUITE" >&2; exit 2 ;; +esac + +HAS_AUG=0 +if [ -f "$PRIV/eval_tests_aug.patch" ] \ + && [ -f "$PRIV/f2p_aug.txt" ] \ + && [ -f "$PRIV/p2p_aug.txt" ]; then + HAS_AUG=1 +fi +if [ "$SUITE" != "orig" ] && [ "$HAS_AUG" -eq 0 ]; then + echo "[run_tests $MODE/$SUITE] WARN: no augmented sidecar shipped; falling back to orig" >&2 + SUITE=orig +fi + +log() { echo "[run_tests $MODE/$SUITE] $*" >&2; } +die() { log "FATAL: $*"; emit_error harness_error false skipped; exit 0; } + +FAIL_TO_PASS=() +PASS_TO_PASS=() + +emit_error() { + local cat=$1 applied=$2 build_status=$3 + local f2p_n=${#FAIL_TO_PASS[@]} + local p2p_n=${#PASS_TO_PASS[@]} + python3 - "$cat" "$applied" "$build_status" "$f2p_n" "$p2p_n" "$SUITE" "$HAS_AUG" <<'EOF' >/out/agent_report.json +import json, sys +cat, applied_s, build_s, f2p_n, p2p_n, suite, has_aug_s = sys.argv[1:8] +applied = applied_s.lower() == "true" +print(json.dumps({ + "instance_id": "TypeScript_Issue-47920_satisfies-operator-to-ensure-an-expression-matches-some-type-safe-upcast_PR-46827", + "suite": suite, + "augmentation_available": has_aug_s == "1", + "applied": applied, + "build": {"status": build_s}, + "f2p": {"passed":0,"failed":0,"errored":int(f2p_n),"skipped":0,"total":int(f2p_n)}, + "p2p": {"passed":0,"failed":0,"errored":int(p2p_n),"skipped":0,"total":int(p2p_n)}, + "resolved": False, + "error_categories": [cat] +}, indent=2)) +EOF +} + +mapfile -t FAIL_TO_PASS_ORIG < <(grep -v '^\s*$' "$PRIV/f2p.txt") +mapfile -t PASS_TO_PASS_ORIG < <(grep -v '^\s*$' "$PRIV/p2p.txt") +FAIL_TO_PASS_AUG=() +PASS_TO_PASS_AUG=() +if [ "$HAS_AUG" -eq 1 ]; then + mapfile -t FAIL_TO_PASS_AUG < <(grep -v '^\s*$' "$PRIV/f2p_aug.txt") + mapfile -t PASS_TO_PASS_AUG < <(grep -v '^\s*$' "$PRIV/p2p_aug.txt") +fi + +case "$SUITE" in + orig) + FAIL_TO_PASS=("${FAIL_TO_PASS_ORIG[@]}") + PASS_TO_PASS=("${PASS_TO_PASS_ORIG[@]}") + ;; + aug) + FAIL_TO_PASS=("${FAIL_TO_PASS_AUG[@]}") + PASS_TO_PASS=("${PASS_TO_PASS_AUG[@]}") + ;; + union) + FAIL_TO_PASS=("${FAIL_TO_PASS_ORIG[@]}" "${FAIL_TO_PASS_AUG[@]}") + PASS_TO_PASS=("${PASS_TO_PASS_ORIG[@]}" "${PASS_TO_PASS_AUG[@]}") + ;; +esac + +F2P_EFFECTIVE=$WS/.f2p_effective.txt +P2P_EFFECTIVE=$WS/.p2p_effective.txt +printf '%s\n' "${FAIL_TO_PASS[@]}" >"$F2P_EFFECTIVE" +printf '%s\n' "${PASS_TO_PASS[@]}" >"$P2P_EFFECTIVE" + +# Sanity-check spec ↔ selectors agree +python3 - "$PRIV/spec.json" "$PRIV/f2p.txt" "$PRIV/p2p.txt" "$F2P_EFFECTIVE" "$P2P_EFFECTIVE" "$SUITE" <<'EOF' || die "spec/selector mismatch" +import json, sys +spec = json.load(open(sys.argv[1])) +orig_f2p = [l.strip() for l in open(sys.argv[2]) if l.strip()] +orig_p2p = [l.strip() for l in open(sys.argv[3]) if l.strip()] +eff_f2p = [l.strip() for l in open(sys.argv[4]) if l.strip()] +eff_p2p = [l.strip() for l in open(sys.argv[5]) if l.strip()] +suite = sys.argv[6] +aug = spec.get("augmented", {}) +expected = { + "orig": (spec["fail_to_pass"], spec["pass_to_pass"]), + "aug": (aug.get("fail_to_pass", []), aug.get("pass_to_pass", [])), + "union": (orig_f2p + aug.get("fail_to_pass", []), orig_p2p + aug.get("pass_to_pass", [])), +}[suite] +sys.exit(0 if expected == (eff_f2p, eff_p2p) else 1) +EOF + +# ---- pick source-side patch by mode --------------------------------- +SRC_PATCH="" +case "$MODE" in + validate_pre) SRC_PATCH="" ;; + validate_post) + if [ -f /solution/solution.patch ]; then + SRC_PATCH=/solution/solution.patch + else + SRC_PATCH="$PRIV/solution.patch" + fi ;; + eval) + if [ ! -f /in/solution.patch ]; then + log "no /in/solution.patch mounted" + emit_error missing_solution_patch false skipped + exit 0 + fi + AGENT_PATCH=/tmp/lolbench_agent_patch.diff + cp /in/solution.patch "$AGENT_PATCH" + chmod 0600 "$AGENT_PATCH" + SRC_PATCH="$AGENT_PATCH" ;; + *) + die "unknown LOLBENCH_MODE=$MODE" ;; +esac + +# ---- reset workspace + apply patches -------------------------------- +cd "$TS" +git config --global --add safe.directory "$TS" +git reset --hard >/dev/null 2>&1 +git clean -fdx -e node_modules -e built >/dev/null 2>&1 + +if [ -n "$SRC_PATCH" ]; then + if ! git apply --check "$SRC_PATCH" 2>/tmp/apply.err; then + log "source patch did not apply cleanly:"; cat /tmp/apply.err >&2 + emit_error patch_apply_failure false skipped; exit 0 + fi + git apply "$SRC_PATCH" + # LoLBench eval-patch-collision guard (re-verify remediation): if the agent patch touched files the + # eval test patches own (test fixtures the agent must not modify), restore + # those paths (both sides of every diff/rename) to the base state so + # eval_tests(.aug).patch always applies. Agent source changes are preserved. + for _lb_ep in "$PRIV/eval_helpers.patch" "$PRIV/eval_tests.patch" "$PRIV/eval_tests_aug.patch"; do + [ -f "$_lb_ep" ] || continue + { sed -n 's|^diff --git a/\(.*\) b/\(.*\)$|\1\n\2|p' "$_lb_ep" + sed -n 's|^rename from \(.*\)$|\1|p' "$_lb_ep" + sed -n 's|^rename to \(.*\)$|\1|p' "$_lb_ep"; } | sort -u | while read -r _lb_f; do + [ -n "$_lb_f" ] || continue + git checkout HEAD -- "$_lb_f" >/dev/null 2>&1 || rm -f "$_lb_f" >/dev/null 2>&1 || true + done + done +fi + +# eval_tests.patch is ALWAYS applied — the test files + baselines it +# adds are needed in BOTH pre- and post-state. In pre-state without +# solution.patch, running the new tests produces baseline mismatches +# (parser doesn't tokenize `satisfies` → bogus errors in .errors.txt) +# which is exactly the FAIL behavior §7 requires. +if ! git apply --ignore-space-change --check "$PRIV/eval_tests.patch" 2>/tmp/apply.err; then + log "eval_tests.patch did not apply cleanly:"; cat /tmp/apply.err >&2 + emit_error eval_patch_apply_failure true skipped; exit 0 +fi +git apply --ignore-space-change "$PRIV/eval_tests.patch" +if [ "$HAS_AUG" -eq 1 ] && [ "$SUITE" != "orig" ]; then + if ! git apply --check "$PRIV/eval_tests_aug.patch" 2>/tmp/apply.err; then + log "eval_tests_aug.patch did not apply cleanly:"; cat /tmp/apply.err >&2 + emit_error eval_aug_patch_apply_failure true skipped; exit 0 + fi + git apply "$PRIV/eval_tests_aug.patch" +fi + +# ---- rebuild local tsc + test infra after patches ---------------------- +BUILD_LOG=$WS/.build.log +TEST_LOG=$WS/.test.log +: >"$BUILD_LOG" >"$TEST_LOG" + +log "running 'npx gulp local' to rebuild tsc with patches applied" +npx gulp local >"$BUILD_LOG" 2>&1 +build_rc=$? +if [ "$build_rc" -ne 0 ]; then + log "build failed (rc=$build_rc); tail:"; tail -30 "$BUILD_LOG" >&2 + emit_error build_failure true failed; exit 0 +fi + +log "running 'npx gulp tests' to rebuild the test runner harness" +npx gulp tests >>"$BUILD_LOG" 2>&1 +tests_build_rc=$? +if [ "$tests_build_rc" -ne 0 ]; then + log "test-harness build failed (rc=$tests_build_rc); tail:"; tail -30 "$BUILD_LOG" >&2 + emit_error build_failure true failed; exit 0 +fi + +# ---- build the regex selector that runtests --tests=... accepts ----- +# TypeScript's runtests uses a regex matched against mocha test names. +# For conformance tests the name typically contains the source path +# fragment, e.g. for tests/cases/conformance/expressions/typeSatisfaction/typeSatisfaction.ts +# the test name includes "typeSatisfaction" / "typeSatisfaction.ts". +# +# Strategy: union of UNIQUE BASENAMES (without .ts) — every selector's +# basename is unique among the 13+24 we ship. The resulting regex is +# matched anywhere within the test name (not anchored), so subdir +# selectors stay correct. +RUNTESTS_REGEX=$(python3 - "$F2P_EFFECTIVE" "$P2P_EFFECTIVE" <<'PY' +import os, sys +ids = [] +for p in sys.argv[1:]: + for l in open(p): + l = l.strip() + if l: + base = os.path.splitext(os.path.basename(l))[0] + ids.append(base) +# Sort longest-first so e.g. `typeSatisfaction_contextualTyping1` matches +# before the shorter `typeSatisfaction`. +ids = sorted(set(ids), key=len, reverse=True) +print("|".join(map(__import__("re").escape, ids))) +PY +) +log "runtests selector regex: ${RUNTESTS_REGEX:0:80}..." + +# ---- run the union of F2P + P2P tests ---------------------------------- +# Invoke mocha directly (bypassing the gulp wrapper) so the post-tests +# eslint phase doesn't fail the whole gulp run. The exact arguments +# mirror what `gulp runtests --tests= --reporter=tap` invokes +# internally (verified by running the gulp version and inspecting the +# spawned mocha command line). +log "running mocha directly with selector regex" +/usr/bin/node "$TS/node_modules/mocha/bin/_mocha" \ + -R "$TS/scripts/failed-tests.js" \ + -O "reporter=tap" \ + -g "$RUNTESTS_REGEX" \ + --no-colors -t 40000 \ + "$TS/built/local/run.js" \ + >>"$TEST_LOG" 2>&1 || true + +# ---- parse the TAP output + emit reports ------------------------------- +python3 - "$F2P_EFFECTIVE" "$P2P_EFFECTIVE" "$MODE" "$SUITE" "$HAS_AUG" "$TEST_LOG" <<'PYEOF' +"""Parse mocha's TAP-style output and bucket per-selector PASS/FAIL. + +mocha's TAP reporter emits lines like: + ok 151 conformance tests conformance tests for tests/cases/conformance/expressions/typeSatisfaction/typeSatisfaction.ts Correct errors for tests/cases/conformance/expressions/typeSatisfaction/typeSatisfaction.ts + not ok 152 ... + +Note: NO `-` separator between the number and description, despite +the TAP spec. We extract the .ts path from anywhere in the line. + +Each .ts file produces ~6 sub-tests (Correct errors / module +resolution tracing / sourcemap content / JS output / Sourcemap +output / type/symbol baselines). A .ts file PASSES iff every +sub-test PASSES. +""" +import json, os, re, sys +f2p_file, p2p_file, mode, suite, has_aug_s, log_path = sys.argv[1:7] +has_aug = has_aug_s == "1" + +f2p_ids = [l.strip() for l in open(f2p_file) if l.strip()] +p2p_ids = [l.strip() for l in open(p2p_file) if l.strip()] + +# Map path → set of statuses observed for that path's sub-tests. +file_statuses = {sid: set() for sid in f2p_ids + p2p_ids} +spec_paths = {sid for sid in f2p_ids + p2p_ids} + +try: + log = open(log_path).read() +except FileNotFoundError: + log = "" + +# mocha TAP output: "ok N " or "not ok N ". +TAP_LINE = re.compile(r'^(ok|not ok)\s+\d+\s+(.*)$') +# Extract a tests/cases/... .ts path from the description. +TS_PATH = re.compile(r'(tests/cases/[^\s]+?\.ts)') + +for line in log.splitlines(): + m = TAP_LINE.match(line) + if not m: + continue + verdict, desc = m.group(1), m.group(2) + # Find ALL .ts paths in the description — usually 2 (e.g. "conformance + # tests for X Correct errors for X"). All point to the same file. + paths = set(TS_PATH.findall(desc)) + for p in paths: + if p not in spec_paths: + continue + if " # SKIP" in desc.upper() or " # TODO" in desc.upper(): + file_statuses[p].add("SKIPPED") + elif verdict == "ok": + file_statuses[p].add("PASSED") + else: + file_statuses[p].add("FAILED") + +results = {} +for p, statuses in file_statuses.items(): + if not statuses: + results[p] = "ERROR" # no sub-tests matched → test never ran + elif "FAILED" in statuses: + results[p] = "FAILED" + elif "SKIPPED" in statuses and "PASSED" not in statuses: + results[p] = "SKIPPED" + else: + results[p] = "PASSED" + +def bucket(ids): + out = {"PASSED": [], "FAILED": [], "ERROR": [], "SKIPPED": []} + for sid in ids: + out[results.get(sid, "ERROR")].append(sid) + return out + +f2p = bucket(f2p_ids) +p2p = bucket(p2p_ids) +resolved = (len(f2p["PASSED"]) == len(f2p_ids) + and len(p2p["PASSED"]) == len(p2p_ids)) + +grader = { + "instance_id": "TypeScript_Issue-47920_satisfies-operator-to-ensure-an-expression-matches-some-type-safe-upcast_PR-46827", + "mode": mode, "suite": suite, "augmentation_available": has_aug, "applied": True, "build": {"status": "ok"}, + "f2p": f2p, "p2p": p2p, "resolved": resolved +} +def cnts(d, ids): + return {"passed":len(d["PASSED"]),"failed":len(d["FAILED"]), + "errored":len(d["ERROR"]),"skipped":len(d["SKIPPED"]),"total":len(ids)} +agent = { + "instance_id": "TypeScript_Issue-47920_satisfies-operator-to-ensure-an-expression-matches-some-type-safe-upcast_PR-46827", + "suite": suite, "augmentation_available": has_aug, "applied": True, "build": {"status": "ok"}, + "f2p": cnts(f2p, f2p_ids), "p2p": cnts(p2p, p2p_ids), + "resolved": resolved, "error_categories": [] +} +json.dump(grader, open("/out/grader_report.json","w"), indent=2) +json.dump(agent, open("/out/agent_report.json","w"), indent=2) +print(json.dumps(grader, indent=2)) +PYEOF diff --git a/TypeScript_1/tests/private/spec.json b/TypeScript_1/tests/private/spec.json new file mode 100644 index 0000000000000000000000000000000000000000..3ca6f7176606c66d80d64ce25bf925077739043c --- /dev/null +++ b/TypeScript_1/tests/private/spec.json @@ -0,0 +1,507 @@ +{ + "instance_id": "TypeScript_Issue-47920_satisfies-operator-to-ensure-an-expression-matches-some-type-safe-upcast_PR-46827", + "project": "microsoft/TypeScript", + "requirement_doc": "https://github.com/microsoft/TypeScript/issues/47920", + "requirement_doc_note": "Design issue #47920 ('satisfies operator to ensure an expression matches some type-safe upcast'). The original feature request that motivated the PR is issue #7481, referenced in the PR title and body.", + "pr_link": "https://github.com/microsoft/TypeScript/pull/46827", + "pr_merge_date": "2022-08-26", + "language": "TypeScript", + "build_system": "npm + gulp (PR-46827 era; later TypeScript migrated to hereby)", + "scope": { + "pr_touched_modules": [ + "src/compiler", + "src/services", + "src/harness", + "src/testRunner", + "tests/cases", + "tests/baselines" + ], + "in_scope_modules": [ + "src/compiler", + "src/services", + "src/harness", + "src/testRunner" + ], + "build_modules": [ + "src" + ], + "p2p_modules": [ + "tests/cases/conformance/expressions" + ], + "pr_total_files_changed": 102, + "in_scope_production_files": 20, + "in_scope_test_files": 82, + "out_of_scope_files_dropped": 0, + "out_of_scope_summary": "No files dropped. All 102 PR files are either compiler/service source (20) or test fixtures + their baselines (82). TypeScript's baseline files are required for the test framework \u2014 they ARE the expected outputs that compiletest compares against." + }, + "base_commit": "07157914eb26a6e9abdcda7255c4094c9efff4cd", + "base_commit_note": "Parent of the squash-merge commit on main. The merge commit 164dddc4 has a single parent (07157914) \u2014 the PR was merged via GitHub's squash-merge button. Use the parent..merge diff for the patch content. GitHub's pr.base.sha = c4eb37c8 is an older snapshot from when the PR was opened (May 2022) and predates the squash by ~3 months; do NOT use it as the base \u2014 the merge tree was applied against where main had advanced to (07157914 in Aug 2022).", + "merge_commit_sha": "164dddc48e1eaa83780b8e72bc7afeebe768437b", + "pr_head_sha": "a73f1c7ce4b97bf13e6c3f2341412b0216d92933", + "pr_base_sha_github": "c4eb37c8a0d5915d64e3992a91a34724aab19fe6", + "merge_style": "squash-merge \u2014 merge_commit_sha (164dddc4) has one parent (07157914); the PR's 19 individual commits were squashed into this single commit on main.", + "diff_source": "Patches reconstructed via `git diff 07157914..164dddc4` (parent..squash-merge on main). GitHub PR base/head SHAs preserved for provenance audit only.", + "solution_patch_sha256": "f7eb19d647450fd5d6ee8b5bac0d15332125069b61159198cab81ffda58b2740", + "eval_tests_patch_sha256": "e23b87a8fefad5a605309fea4550d5c044a3fb2bdc1c4f921909aa6f15803eb1", + "toolchain": { + "node": "16.x (TypeScript 4.9-era; nvm or apt-installed)", + "npm": "8.x", + "test_framework": "TypeScript's mocha-based runtests (`gulp runtests --tests=`); each .ts file in tests/cases/ is a baseline-comparison test against tests/baselines/reference/", + "host_target": "linux/amd64", + "base_image": "lolbench/typescript-base:1 (NEW \u2014 needs creation; Ubuntu 22.04 + Node 16 + npm + git + python3)" + }, + "fail_to_pass": [ + "tests/cases/conformance/expressions/typeSatisfaction/typeSatisfaction.ts", + "tests/cases/conformance/expressions/typeSatisfaction/typeSatisfactionWithDefaultExport.ts", + "tests/cases/conformance/expressions/typeSatisfaction/typeSatisfaction_contextualTyping1.ts", + "tests/cases/conformance/expressions/typeSatisfaction/typeSatisfaction_contextualTyping2.ts", + "tests/cases/conformance/expressions/typeSatisfaction/typeSatisfaction_ensureInterfaceImpl.ts", + "tests/cases/conformance/expressions/typeSatisfaction/typeSatisfaction_js.ts", + "tests/cases/conformance/expressions/typeSatisfaction/typeSatisfaction_optionalMemberConformance.ts", + "tests/cases/conformance/expressions/typeSatisfaction/typeSatisfaction_propNameConstraining.ts", + "tests/cases/conformance/expressions/typeSatisfaction/typeSatisfaction_propertyNameFulfillment.ts", + "tests/cases/conformance/expressions/typeSatisfaction/typeSatisfaction_propertyValueConformance1.ts", + "tests/cases/conformance/expressions/typeSatisfaction/typeSatisfaction_propertyValueConformance2.ts", + "tests/cases/conformance/expressions/typeSatisfaction/typeSatisfaction_propertyValueConformance3.ts", + "tests/cases/conformance/expressions/typeSatisfaction/typeSatisfaction_vacuousIntersectionOfContextualTypes.ts" + ], + "pass_to_pass": [ + "tests/cases/conformance/expressions/asOperator/asOpEmitParens.ts", + "tests/cases/conformance/expressions/asOperator/asOperator1.ts", + "tests/cases/conformance/expressions/asOperator/asOperator2.ts", + "tests/cases/conformance/expressions/asOperator/asOperator3.ts", + "tests/cases/conformance/expressions/asOperator/asOperator4.ts", + "tests/cases/conformance/expressions/asOperator/asOperatorASI.ts", + "tests/cases/conformance/expressions/asOperator/asOperatorAmbiguity.ts", + "tests/cases/conformance/expressions/asOperator/asOperatorContextualType.ts", + "tests/cases/conformance/expressions/asOperator/asOperatorNames.ts", + "tests/cases/conformance/expressions/contextualTyping/argumentExpressionContextualTyping.ts", + "tests/cases/conformance/expressions/contextualTyping/arrayLiteralExpressionContextualTyping.ts", + "tests/cases/conformance/expressions/contextualTyping/functionExpressionContextualTyping1.ts", + "tests/cases/conformance/expressions/contextualTyping/getSetAccessorContextualTyping.ts", + "tests/cases/conformance/expressions/contextualTyping/iterableContextualTyping1.ts", + "tests/cases/conformance/expressions/contextualTyping/objectLiteralContextualTyping.ts", + "tests/cases/conformance/expressions/contextualTyping/parenthesizedContexualTyping1.ts", + "tests/cases/conformance/expressions/contextualTyping/superCallParameterContextualTyping1.ts", + "tests/cases/conformance/expressions/arrayLiterals/arrayLiteralInference.ts", + "tests/cases/conformance/expressions/arrayLiterals/arrayLiterals.ts", + "tests/cases/conformance/expressions/arrayLiterals/arrayLiterals2ES5.ts", + "tests/cases/conformance/expressions/arrayLiterals/arrayLiterals2ES6.ts", + "tests/cases/conformance/expressions/assignmentOperator/assignmentLHSIsReference.ts", + "tests/cases/conformance/expressions/assignmentOperator/assignmentLHSIsValue.ts", + "tests/cases/conformance/expressions/assignmentOperator/assignmentTypeNarrowing.ts", + "tests/cases/conformance/expressions/arrayLiterals/arrayLiterals3.ts", + "tests/cases/conformance/expressions/assignmentOperator/assignmentGenericLookupTypeNarrowing.ts", + "tests/cases/conformance/expressions/assignmentOperator/compoundAdditionAssignmentLHSCanBeAssigned.ts", + "tests/cases/conformance/expressions/assignmentOperator/compoundAdditionAssignmentLHSCannotBeAssigned.ts", + "tests/cases/conformance/expressions/assignmentOperator/compoundAdditionAssignmentWithInvalidOperands.ts", + "tests/cases/conformance/expressions/assignmentOperator/compoundArithmeticAssignmentLHSCanBeAssigned.ts", + "tests/cases/conformance/expressions/assignmentOperator/compoundArithmeticAssignmentWithInvalidOperands.ts", + "tests/cases/conformance/expressions/assignmentOperator/compoundAssignmentLHSIsReference.ts", + "tests/cases/conformance/expressions/assignmentOperator/compoundAssignmentLHSIsValue.ts", + "tests/cases/conformance/expressions/contextualTyping/functionExpressionContextualTyping2.ts", + "tests/cases/conformance/expressions/contextualTyping/functionExpressionContextualTyping3.ts", + "tests/cases/conformance/expressions/contextualTyping/generatedContextualTyping.ts", + "tests/cases/conformance/expressions/contextualTyping/parenthesizedContexualTyping2.ts", + "tests/cases/conformance/expressions/contextualTyping/parenthesizedContexualTyping3.ts", + "tests/cases/conformance/expressions/contextualTyping/superCallParameterContextualTyping2.ts", + "tests/cases/conformance/expressions/contextualTyping/superCallParameterContextualTyping3.ts", + "tests/cases/conformance/expressions/contextualTyping/taggedTemplateContextualTyping1.ts", + "tests/cases/conformance/expressions/contextualTyping/taggedTemplateContextualTyping2.ts", + "tests/cases/conformance/expressions/typeAssertions/constAssertionOnEnum.ts", + "tests/cases/conformance/expressions/typeAssertions/constAssertions.ts", + "tests/cases/conformance/expressions/typeAssertions/duplicatePropertiesInTypeAssertions01.ts", + "tests/cases/conformance/expressions/typeAssertions/duplicatePropertiesInTypeAssertions02.ts", + "tests/cases/conformance/expressions/typeAssertions/typeAssertions.ts", + "tests/cases/conformance/expressions/conditonalOperator/conditionalOperatorConditionIsBooleanType.ts", + "tests/cases/conformance/expressions/conditonalOperator/conditionalOperatorConditionIsNumberType.ts", + "tests/cases/conformance/expressions/conditonalOperator/conditionalOperatorConditionIsObjectType.ts" + ], + "triage": { + "test_level_policy": "Every F2P and P2P entry is a single .ts file under tests/cases/. Each is system-level by construction \u2014 TypeScript's runtests harness compiles the file end-to-end with the freshly-built tsc, runs through parser+checker+emitter+type-printer, and compares the emitted .js, .types, .symbols, and .errors.txt against the corresponding files under tests/baselines/reference/. A test fails if ANY baseline differs. No unit-level tests selected.", + "f2p_test_classes": { + "system_e2e": { + "typeSatisfaction conformance (13)": "tests/cases/conformance/expressions/typeSatisfaction/*.ts \u2014 13 NEW test files added by eval_tests.patch. Each exercises a different facet of the satisfies operator: basic syntax (typeSatisfaction.ts), contextual typing (\u00d72), interface conformance, JS-mode parsing, optional members, property-name fulfillment, value conformance (\u00d73), property-name constraining, vacuous intersection, default-export forms. Each .ts file drives a full parser+checker+emitter+type-printer pass through tsc; the runtests harness compares the emitted .js / .types / .symbols / .errors.txt against the baseline siblings." + }, + "module_level": {}, + "f2p_test_classes_excluded_as_unit": [ + "tests/cases/fourslash/completionSatisfiesKeyword.ts \u2014 fourslash test using verify.completions(); narrower than full-compile baseline tests, probes only the language service completion API. Excluded per the system-level rule.", + "tests/cases/fourslash/satisfiesOperatorCompletion.ts \u2014 same rationale as above." + ] + }, + "test_compile_failure_pre_state": "Expected: at base, the parser doesn't recognize the satisfies keyword (it's a contextual keyword added by solution.patch). The compiler treats `as satisfies` literally \u2192 produces unexpected errors \u2192 baseline comparison fails. Every F2P test gets a baseline mismatch in pre-state, surfacing as FAIL. Some fourslash tests may instead error out trying to complete an unknown keyword.", + "p2p_isolation": "All 50 P2P selectors are .ts files in tests/cases/conformance/expressions/ across {asOperator, contextualTyping, arrayLiterals, assignmentOperator, typeAssertions, conditonalOperator} subdirs \u2014 same expression-typing code-paths the satisfies PR touches (checker.ts type assertion path, emitter.ts emission, parser.ts contextual-keyword tokenization), but on UNCHANGED test files. No taint surface: TypeScript baseline tests are file-level isolated \u2014 each .ts file plus its .baseline siblings is a complete self-contained test scenario.", + "runtests_selector_note": "TypeScript's runtests harness selects tests via a regex match against the BASENAME of the .ts file (not the full path). An F2P/P2P selector like `tests/cases/conformance/expressions/typeSatisfaction/typeSatisfaction.ts` translates to a runtests filter regex `typeSatisfaction\\.ts` (or, for safety, the full path joined with `|`). run_tests.sh must construct this regex from the f2p.txt/p2p.txt lines." + }, + "f2p_entry_count": 13, + "p2p_entry_count": 50, + "validated_at": "2026-06-20", + "p2p_base_existence_check": "All 50 P2P paths were verified present at base_commit 07157914eb26a6e9abdcda7255c4094c9efff4cd inside the built eval image during P2P expansion (2026-06-15). The 26 added selectors are pre-existing TypeScript conformance tests and do not appear in solution.patch or eval_tests.patch.", + "eval_tests_patch_baseline_note": "eval_tests.patch BOTH adds new .ts test cases under tests/cases/conformance/expressions/typeSatisfaction/ AND modifies existing baseline files under tests/baselines/reference/ (the new satisfies keyword changes some pre-existing baselines that reference the keyword class). P2P selectors are NOT in any of the modified-baseline files, so no taint surface.", + "augmented": { + "suite_support": { + "env": "LOLBENCH_SUITE", + "modes": [ + "orig", + "aug", + "union" + ], + "default": "orig" + }, + "eval_tests_patch": "eval_tests_aug.patch", + "eval_tests_aug_patch_sha256": "28c25e341f62f86fde21b8b36a03548421d77612197d5c01420436f0ab140e78", + "f2p_aug_sha256": "2db6678c5e6cf835287d93e1001a819031d8f647dd3c29a319aa2ee7001160be", + "p2p_aug_sha256": "a0c75d3384671ed97a629404df0d71c235e6acf789e6433fc3fe4f09e1ae5426", + "fail_to_pass": [ + "tests/cases/fourslash/satisfiesAugCompletionKeyword.ts", + "tests/cases/fourslash/satisfiesAugCompilerApi.ts", + "tests/cases/fourslash/satisfiesAugCallHierarchyTypeSide.ts" + ], + "pass_to_pass": [ + "tests/cases/fourslash/asOperatorAugCompletionP2P.ts", + "tests/cases/fourslash/contextualTypingAugP2P.ts" + ], + "targets_mutants": [ + "mutant_005_printer_emits_as_keyword_for_satisfies", + "mutant_010_public_visitor_skips_satisfies_type", + "mutant_012_satisfies_keyword_not_offered_in_completions" + ], + "equivalent_mutants": {}, + "coverage_gate": { + "minimum_line_coverage_percent": 80, + "status": "passed", + "coverage_report": "coverage_out/coverage_report_union.json", + "baseline_coverage_report": "coverage_out/coverage_report_orig.json", + "augmented_coverage_report": "coverage_out/coverage_report_aug.json", + "measurement_note": "V8/c8 line coverage over executable TypeScript compiler and services lines added by solution.patch; union mode runs original plus augmented F2P/P2P selectors.", + "baseline_union_line_coverage_percent": 100.0, + "augmented_only_union_line_coverage_percent": 100.0, + "union_line_coverage_percent": 100.0, + "executable_lines_in_patch": 109, + "union_covered_lines": 109, + "coverage_complete": true + }, + "triage": { + "test_level_policy": "Augmented F2P uses TypeScript fourslash tests to drive public compiler and language-service APIs through the project harness: parser output, ts.createPrinter, ts.transpileModule, ts.transform/visitEachChild, completions, and call hierarchy. Augmented P2P uses unrelated as-operator and contextual-typing fourslash checks that do not mention satisfies.", + "fail_to_pass": { + "tests/cases/fourslash/satisfiesAugCompletionKeyword.ts": { + "requirement_sections": [ + "TL;DR" + ], + "public_surface": "TypeScript language-service completions through the fourslash verify.completions harness.", + "mutants_targeted": [ + "mutant_012_satisfies_keyword_not_offered_in_completions" + ], + "rationale": "Checks that the contextual keyword is offered at expression positions and that the type side after `satisfies` still offers target types. This makes the public editor-facing keyword support observable." + }, + "tests/cases/fourslash/satisfiesAugCompilerApi.ts": { + "requirement_sections": [ + "Scenario Candidates > Safe Upcast" + ], + "public_surface": "TypeScript public compiler API through createSourceFile, createPrinter, transpileModule, factory.createSatisfiesExpression, and ts.transform.", + "mutants_targeted": [ + "mutant_005_printer_emits_as_keyword_for_satisfies" + ], + "rationale": "Checks that public printer and transformer APIs preserve `satisfies` syntax while emit/transpile still erases the type-only operator." + }, + "tests/cases/fourslash/satisfiesAugCallHierarchyTypeSide.ts": { + "requirement_sections": [ + "Scenario Candidates > Safe Upcast" + ], + "public_surface": "TypeScript language-service call hierarchy over a satisfies expression whose type side references a function.", + "mutants_targeted": [ + "mutant_010_public_visitor_skips_satisfies_type" + ], + "rationale": "Checks that public AST traversal reaches the satisfies type child so editor features can see references that appear on the type side." + } + }, + "pass_to_pass": { + "tests/cases/fourslash/asOperatorAugCompletionP2P.ts": { + "requirement_sections": [ + "Scenario Candidates > Safe Upcast" + ], + "public_surface": "Existing TypeScript as-operator completion behavior through fourslash completions.", + "stability_goal": "The new satisfies keyword must not disturb existing `as` expression completions or inject satisfies into the type-completion position after `as`.", + "rationale": "Pins adjacent unchanged type-assertion behavior in the same expression family while staying independent of the new satisfies syntax." + }, + "tests/cases/fourslash/contextualTypingAugP2P.ts": { + "requirement_sections": [ + "Scenario Candidates > Contextual Typing" + ], + "public_surface": "Existing contextual typing and quick-info behavior through fourslash quickInfo/noErrors.", + "stability_goal": "Contextual typing of function parameters in object literals must remain stable for existing annotations.", + "rationale": "The satisfies implementation reuses contextual typing machinery; this P2P selector guards an unchanged contextual typing path without mentioning satisfies." + } + } + }, + "mutant_set_revision": { + "date": "2026-06-16", + "removed": [ + "mutant_008_factory_omits_typescript_transform_flag", + "mutant_011_call_hierarchy_counts_type_side_references" + ], + "reason": "equivalent", + "note": "2 equivalent mutant(s) removed from mutations/ per the 2026-06-16 mutant-kill audit (no \u00a76-clean test can kill an equivalent mutant); union now kills all 10 remaining mutants.", + "new_total": 10, + "union_kills_all_remaining": true + } + }, + "repo": "microsoft/TypeScript", + "image": "lolbench/typescript_1:1.0.0", + "agent_contract": { + "input": "/in/solution.patch", + "output": "/out/agent_report.json", + "invocation": "docker run --rm -v $(pwd)/solution.patch:/in/solution.patch:ro -v $(pwd)/out:/out lolbench/typescript_1:1.0.0" + }, + "test_framework": "node_test", + "test_level": "system", + "test_cmd_template": "npm test -- ", + "log_parser": "node_test", + "coverage": { + "orig": 100.0, + "aug": 100.0, + "union": 100.0, + "denominator": "union_executable_lines" + }, + "dockerhub_image": "smartdub26/lolbench-linux:TypeScript_1-1.0.0", + "dockerhub_digest": "sha256:6602720bc587812d5e2d61aa3dbd212e84d36cdeb957b78f1f3fccee062611e1", + "dockerhub_index_digest": "sha256:66aefccd646ac239e9b3f6cec97076b53833ada73318b723a91baac9a76b7dd9", + "dockerhub_platform": "linux/amd64", + "validation_status": "harbor_validated", + "harbor_validation_summary": { + "validated_at": "2026-06-20", + "local_image": "lolbench/typescript_1:1.0.0", + "dockerhub_image": "smartdub26/lolbench:TypeScript_1-1.0.0", + "dockerhub_digest": "sha256:86ec21471aef0eff17132a3091c744efc6dddefbe25172e25083ee4414f7b367", + "mode_reports": "harbor_validation/TypeScript_1/current_harbor_modes_v2", + "mutation_reports": "harbor_validation/TypeScript_1/current_harbor_mutants_v2", + "modes": { + "aug_post": { + "build": "ok", + "f2p": { + "passed": 3, + "total": 3 + }, + "p2p": { + "passed": 2, + "total": 2 + }, + "resolved": true, + "error_categories": [] + }, + "aug_pre": { + "build": "ok", + "f2p": { + "passed": 0, + "total": 3 + }, + "p2p": { + "passed": 2, + "total": 2 + }, + "resolved": false, + "error_categories": [] + }, + "orig_post": { + "build": "ok", + "f2p": { + "passed": 13, + "total": 13 + }, + "p2p": { + "passed": 50, + "total": 50 + }, + "resolved": true, + "error_categories": [] + }, + "orig_pre": { + "build": "ok", + "f2p": { + "passed": 0, + "total": 13 + }, + "p2p": { + "passed": 50, + "total": 50 + }, + "resolved": false, + "error_categories": [] + }, + "union_post": { + "build": "ok", + "f2p": { + "passed": 16, + "total": 16 + }, + "p2p": { + "passed": 52, + "total": 52 + }, + "resolved": true, + "error_categories": [] + }, + "union_pre": { + "build": "ok", + "f2p": { + "passed": 0, + "total": 16 + }, + "p2p": { + "passed": 52, + "total": 52 + }, + "resolved": false, + "error_categories": [] + } + }, + "mutants": { + "total": 10, + "killed": 10, + "survivors": [], + "anomalies": [], + "details": [ + { + "name": "mutant_001_satisfies_returns_target_type", + "build": "ok", + "f2p": { + "passed": 3, + "total": 16 + }, + "p2p": { + "passed": 52, + "total": 52 + }, + "resolved": false, + "error_categories": [] + }, + { + "name": "mutant_002_satisfies_skips_target_assignability", + "build": "ok", + "f2p": { + "passed": 9, + "total": 16 + }, + "p2p": { + "passed": 52, + "total": 52 + }, + "resolved": false, + "error_categories": [] + }, + { + "name": "mutant_003_no_contextual_type_from_satisfies", + "build": "ok", + "f2p": { + "passed": 9, + "total": 16 + }, + "p2p": { + "passed": 52, + "total": 52 + }, + "resolved": false, + "error_categories": [] + }, + { + "name": "mutant_004_satisfies_parsed_as_as_expression", + "build": "ok", + "f2p": { + "passed": 1, + "total": 16 + }, + "p2p": { + "passed": 52, + "total": 52 + }, + "resolved": false, + "error_categories": [] + }, + { + "name": "mutant_005_printer_emits_as_keyword_for_satisfies", + "build": "ok", + "f2p": { + "passed": 15, + "total": 16 + }, + "p2p": { + "passed": 52, + "total": 52 + }, + "resolved": false, + "error_categories": [] + }, + { + "name": "mutant_006_satisfies_allowed_in_js_files", + "build": "ok", + "f2p": { + "passed": 15, + "total": 16 + }, + "p2p": { + "passed": 52, + "total": 52 + }, + "resolved": false, + "error_categories": [] + }, + { + "name": "mutant_007_transformer_leaves_satisfies_in_js_output", + "build": "ok", + "f2p": { + "passed": 2, + "total": 16 + }, + "p2p": { + "passed": 52, + "total": 52 + }, + "resolved": false, + "error_categories": [] + }, + { + "name": "mutant_009_for_each_child_skips_satisfies_type", + "build": "ok", + "f2p": { + "passed": 0, + "total": 16 + }, + "p2p": { + "passed": 52, + "total": 52 + }, + "resolved": false, + "error_categories": [] + }, + { + "name": "mutant_010_public_visitor_skips_satisfies_type", + "build": "ok", + "f2p": { + "passed": 15, + "total": 16 + }, + "p2p": { + "passed": 52, + "total": 52 + }, + "resolved": false, + "error_categories": [] + }, + { + "name": "mutant_012_satisfies_keyword_not_offered_in_completions", + "build": "ok", + "f2p": { + "passed": 15, + "total": 16 + }, + "p2p": { + "passed": 52, + "total": 52 + }, + "resolved": false, + "error_categories": [] + } + ] + } + } +} diff --git a/TypeScript_1/tests/report_to_reward.py b/TypeScript_1/tests/report_to_reward.py new file mode 100644 index 0000000000000000000000000000000000000000..233f5afc36b1ba9d054321710a09d8c815f8ff60 --- /dev/null +++ b/TypeScript_1/tests/report_to_reward.py @@ -0,0 +1,73 @@ +#!/usr/bin/env python3 +import argparse +import json +from pathlib import Path + + +def rate(bucket): + total = float(bucket.get("total", 0) or 0) + if total <= 0: + return 0.0 + return float(bucket.get("passed", 0) or 0) / total + + +def write_json(path, payload): + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(json.dumps(payload, indent=2, sort_keys=True) + "\n") + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument("--suite", default="union") + parser.add_argument("--missing-patch") + parser.add_argument("--invalid-suite", action="store_true") + parser.add_argument("--runner-rc", type=int, default=0) + parser.add_argument("agent_report") + parser.add_argument("reward_file") + args = parser.parse_args() + + report_path = Path(args.agent_report) + reward_path = Path(args.reward_file) + + if args.invalid_suite: + reward = {"reward": 0.0, "resolved": 0.0, "applied": 0.0, "build_ok": 0.0, "f2p_pass_rate": 0.0, "p2p_pass_rate": 0.0, "harness_ok": 1.0} + sanitized = {"instance_id": "TypeScript_1", "suite": args.suite, "applied": False, "resolved": False, "error_categories": ["invalid_lolbench_suite"]} + write_json(report_path, sanitized) + write_json(reward_path, reward) + print(f"LoLBench reward=0 invalid suite {args.suite!r}") + return 0 + + if args.missing_patch: + reward = {"reward": 0.0, "resolved": 0.0, "applied": 0.0, "build_ok": 0.0, "f2p_pass_rate": 0.0, "p2p_pass_rate": 0.0, "harness_ok": 1.0} + sanitized = {"instance_id": "TypeScript_1", "suite": args.suite, "applied": False, "resolved": False, "error_categories": ["missing_solution_patch"]} + write_json(report_path, sanitized) + write_json(reward_path, reward) + print("LoLBench reward=0 missing solution patch") + return 0 + + if not report_path.exists(): + reward = {"reward": 0.0, "resolved": 0.0, "applied": 0.0, "build_ok": 0.0, "f2p_pass_rate": 0.0, "p2p_pass_rate": 0.0, "harness_ok": 0.0} + write_json(reward_path, reward) + print(f"LoLBench reward=0 no agent_report.json runner_rc={args.runner_rc}") + return 0 + + report = json.loads(report_path.read_text()) + build_status = report.get("build", {}).get("status") + resolved = bool(report.get("resolved")) + applied = bool(report.get("applied")) + reward = { + "reward": 1.0 if resolved else 0.0, + "resolved": 1.0 if resolved else 0.0, + "applied": 1.0 if applied else 0.0, + "build_ok": 1.0 if build_status == "ok" else 0.0, + "f2p_pass_rate": rate(report.get("f2p", {})), + "p2p_pass_rate": rate(report.get("p2p", {})), + "harness_ok": 1.0 if args.runner_rc == 0 else 0.0, + } + write_json(reward_path, reward) + print("LoLBench reward={reward} resolved={resolved} f2p={f2p_pass_rate:.3f} p2p={p2p_pass_rate:.3f}".format(**reward)) + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/TypeScript_1/tests/test.sh b/TypeScript_1/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..45ba2abd4f682d021752e6966a772a0ee2edb9f5 --- /dev/null +++ b/TypeScript_1/tests/test.sh @@ -0,0 +1,43 @@ +#!/usr/bin/env bash +set -euo pipefail + +suite=${LOLBENCH_SUITE:-union} +mode=${LOLBENCH_MODE:-eval} +patch=${LOLBENCH_SOLUTION_PATCH:-/logs/artifacts/solution.patch} +private_log=/tmp/lolbench-private-run.log + +mkdir -p /logs/verifier /logs/artifacts /in /out + +case "$suite" in + orig|aug|union) ;; + *) + python3 /tests/report_to_reward.py --suite "$suite" --invalid-suite /out/agent_report.json /logs/verifier/reward.json + exit 0 + ;; +esac + +if [ "$mode" = "eval" ] && [ ! -s "$patch" ]; then + python3 /tests/report_to_reward.py --suite "$suite" --missing-patch "$patch" /out/agent_report.json /logs/verifier/reward.json + exit 0 +fi + +if [ "$mode" = "eval" ]; then + cp "$patch" /in/solution.patch + chmod 0400 /in/solution.patch +fi + +set +e +LOLBENCH_MODE="$mode" LOLBENCH_SUITE="$suite" /opt/lolbench/private/run_tests.sh >"$private_log" 2>&1 +runner_rc=$? +set -e + +cp "$private_log" /logs/verifier/private_run.log +if [ -f /out/grader_report.json ]; then + cp /out/grader_report.json /logs/verifier/grader_report.json +fi + +python3 /tests/report_to_reward.py --suite "$suite" --runner-rc "$runner_rc" /out/agent_report.json /logs/verifier/reward.json + +if [ -f /out/agent_report.json ]; then + cp /out/agent_report.json /logs/verifier/agent_report.json +fi diff --git a/TypeScript_2/README.md b/TypeScript_2/README.md new file mode 100644 index 0000000000000000000000000000000000000000..68d4c7c038c48d577d96c6f83c979e66bab81121 --- /dev/null +++ b/TypeScript_2/README.md @@ -0,0 +1,90 @@ +# LoLBench Harbor Task: TypeScript_2 + +This is a Harbor-format LoLBench task generated from `TypeScript_PR-54505_Using-and-await-using-declarations`. + +Selected source instance: + +- Harbor ID: `TypeScript_2` +- PR: `microsoft/TypeScript#54505` +- Base commit: `d90eb0d731c3f74b131dcfafe69ef5341ed14934` +- Test modes: `orig, aug, union` +- Default/canonical mode: `union` +- Harbor image: `smartdub26/lolbench-linux:TypeScript_2-1.0.0` +- Docker Hub image: `smartdub26/lolbench-linux:TypeScript_2-1.0.0` +- Docker Hub digest (arm64): `sha256:1291a122c50d1363d03e1ec0cc4061113f7153f02d0c42773cb22479a431a79d` +- Docker Hub Linux image (amd64): `smartdub26/lolbench-linux:TypeScript_2-1.0.0` +- Docker Hub Linux digest: `sha256:f2bd5e6d40bb6c1a0babeecf6d25e4b11dcbc18e9b17f7ebaa1686f215754cf5` + +## Image Setup + +Prefer the published Docker Hub image when it is available. Harbor refers to +the image as `smartdub26/lolbench-linux:TypeScript_2-1.0.0`, so Docker can pull it +directly when it is not present locally: + +```bash +docker pull smartdub26/lolbench-linux:TypeScript_2-1.0.0 +``` + +Only if the Docker Hub image is unavailable, build the single task image +locally: + +```bash +docker build -t lolbench/typescript_2:1.0.0 harbor_tasks/TypeScript_2/environment +docker tag lolbench/typescript_2:1.0.0 smartdub26/lolbench-linux:TypeScript_2-1.0.0 +``` + +The image contains the processed source tree at the base commit under +`/workspace/typescript`. Harbor must not mount a host source checkout +for the agent. + +## Run an Agent + +```bash +.harbor-venv/bin/harbor run \ + -p harbor_tasks/TypeScript_2 \ + -a codex \ + -m "" \ + --job-name TypeScript_2_agent_union \ + --jobs-dir harbor_runs/TypeScript_2 \ + --no-delete \ + --n-concurrent 1 \ + --ve LOLBENCH_SUITE=union +``` + +After implementing the requirement, the agent must clean any test-file edits +and run: + +```bash +lolbench-submit +``` + +## Evaluate a Patch + +Choose one mode with `LOLBENCH_SUITE=orig`, `aug`, or `union`; if unset, the +task defaults to `union`. + +```bash +PATCH="$(pwd)/path/to/solution.patch" + +.harbor-venv/bin/harbor run \ + -p harbor_tasks/TypeScript_2 \ + -a oracle \ + --job-name TypeScript_2_eval_union \ + --jobs-dir harbor_runs/TypeScript_2 \ + --no-delete \ + --n-concurrent 1 \ + --mounts '[{"type":"bind","source":"'"$PATCH"'","target":"/candidate/solution.patch","read_only":true}]' \ + --ae LOLBENCH_ORACLE_PATCH=/candidate/solution.patch \ + --ve LOLBENCH_SUITE=union +``` + +Outputs: + +```bash +find harbor_runs/TypeScript_2/TypeScript_2_eval_union -path '*/verifier/agent_report.json' -print +find harbor_runs/TypeScript_2/TypeScript_2_eval_union -path '*/verifier/reward.json' -print +``` + +`tests/docker-compose.yaml` is a verifier-only Harbor overlay. It mounts +`tests/`, `tests/private/`, and `solution/` into the separate verifier +container; none of those paths are mounted into the agent container. diff --git a/TypeScript_2/environment/Dockerfile b/TypeScript_2/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..561bb91c7219df404c31680d83935d66cf2a6e4a --- /dev/null +++ b/TypeScript_2/environment/Dockerfile @@ -0,0 +1,95 @@ +# LoLBench eval image: TypeScript PR-54505 (using / await using declarations) +# base_commit: d90eb0d731c3f74b131dcfafe69ef5341ed14934 +# (parent of squash-merge f9cf8216 on main) + +ARG BASE_IMAGE=lolbench/typescript-base-node18:1 +FROM ${BASE_IMAGE} + +ARG BASE_COMMIT=d90eb0d731c3f74b131dcfafe69ef5341ed14934 + +RUN mkdir -p /opt/lolbench/private /in /out /workspace + +WORKDIR /workspace +RUN git init typescript && \ + cd typescript && \ + git remote add origin https://github.com/microsoft/TypeScript.git && \ + git fetch --no-tags --depth=1 origin ${BASE_COMMIT} && \ + git checkout ${BASE_COMMIT} && \ + git ls-files -z > /tmp/typescript-base-files && \ + git config user.email lolbench@local && \ + git config user.name lolbench && \ + if ! git diff --quiet || ! git diff --cached --quiet || [ -n "$(git ls-files --others --exclude-standard)" ]; then \ + git add -A && git -c commit.gpgsign=false commit -q -m "LoLBench environment overlay"; \ + fi && \ + git tag -f base && git tag -f lolbench-base && \ + git for-each-ref --format='%(refname)' refs/heads refs/remotes refs/tags | \ + while read ref; do \ + case "$ref" in refs/tags/base|refs/tags/lolbench-base) ;; *) git update-ref -d "$ref" ;; esac; \ + done && \ + ( git remote remove origin 2>/dev/null || true ) && \ + rm -f .git/FETCH_HEAD && \ + git reflog expire --expire=now --all && \ + git repack -Ad && \ + git prune --expire=now && \ + rm /tmp/typescript-base-files && \ + git config --global --add safe.directory /workspace/typescript + +# TS 5.2-era uses hereby +RUN cd /workspace/typescript && \ + npm install --no-progress --no-fund --no-audit && \ + npx hereby local && \ + npx hereby tests + +# Harbor runtime adapter: keep the image public/agent-safe. +RUN mkdir -p /opt/lolbench /logs/artifacts /logs/agent /logs/verifier /in /out && \ + if ! id -u agent >/dev/null 2>&1; then useradd -m -s /bin/bash agent; fi +COPY metadata.json /opt/lolbench/metadata.json +COPY lolbench-submit /usr/local/bin/lolbench-submit +COPY runtime_source_guard.py /usr/local/bin/lolbench-runtime-source-guard +COPY runtime_source_guard_entrypoint.c /tmp/runtime_source_guard_entrypoint.c +RUN chmod +x /usr/local/bin/lolbench-submit && \ + cc -O2 -Wall -Wextra -o /usr/local/sbin/lolbench-runtime-source-guard-entrypoint /tmp/runtime_source_guard_entrypoint.c && \ + rm -f /tmp/runtime_source_guard_entrypoint.c && \ + chown root:root /usr/local/bin/lolbench-runtime-source-guard /usr/local/sbin/lolbench-runtime-source-guard-entrypoint && \ + chmod 0700 /usr/local/bin/lolbench-runtime-source-guard && \ + chmod 4755 /usr/local/sbin/lolbench-runtime-source-guard-entrypoint && \ + mkdir -p /home/agent/.pi/agent /home/agent/.cache /home/agent/.config /home/agent/.local && \ + chown -R agent:agent /home/agent/.pi /home/agent/.cache /home/agent/.config /home/agent/.local && \ + git config --global --add safe.directory /workspace/typescript && \ + if [ -d /workspace/typescript/.git ]; then \ + cd /workspace/typescript && LC_ALL=C git ls-files --others --exclude-standard | LC_ALL=C sort > /opt/lolbench/base_untracked.txt; \ + else \ + : > /opt/lolbench/base_untracked.txt; \ + fi && \ + chown -R agent:agent /workspace/typescript /logs +ENV HOME=/home/agent +# Local-reference hardening: retain only the approved base history. +RUN git config --system --add safe.directory /workspace/typescript && \ + cd /workspace/typescript && \ + git for-each-ref --format='%(refname)' refs/heads refs/remotes refs/tags | \ + while read ref; do \ + case "$ref" in refs/tags/base|refs/tags/lolbench-base) ;; *) git update-ref -d "$ref" ;; esac; \ + done && \ + ( git remote remove origin 2>/dev/null || true ) && \ + rm -f .git/FETCH_HEAD && \ + git reflog expire --expire=now --all && \ + git repack -Ad && \ + git prune --expire=now && \ + unreachable=$(git fsck --unreachable --no-reflogs) && \ + test -z "$unreachable" && \ + chown -R agent:agent .git +# Keep npm executable but remove cached/global TypeScript and tslib sources. +RUN rm -rf /root/.npm /home/agent/.npm && \ + rm -f /usr/local/bin/tsc /usr/local/bin/tsserver /usr/bin/tsc /usr/bin/tsserver && \ + for p in /usr/local/lib/node_modules /usr/lib/node_modules; do \ + if [ -d "$p" ]; then \ + find "$p" -mindepth 1 -maxdepth 1 -type d \ + \( -iname typescript -o -iname tslib \) -exec rm -rf '{}' +; \ + chown -R root:root "$p"; chmod -R go-w "$p"; chmod 0711 "$p"; \ + fi; \ + done +ENTRYPOINT ["/usr/local/sbin/lolbench-runtime-source-guard-entrypoint"] +USER agent +WORKDIR /workspace/typescript +ENV LOLBENCH_INSTANCE_ID=TypeScript_2 +ENV LOLBENCH_SOURCE_SLUG=TypeScript_PR-54505_Using-and-await-using-declarations diff --git a/TypeScript_2/environment/docker-compose.yaml b/TypeScript_2/environment/docker-compose.yaml new file mode 100644 index 0000000000000000000000000000000000000000..7ed45f87dc9faf9df284f5b10d6d2289781ff254 --- /dev/null +++ b/TypeScript_2/environment/docker-compose.yaml @@ -0,0 +1,3 @@ +services: + main: + pull_policy: missing diff --git a/TypeScript_2/environment/lolbench-submit b/TypeScript_2/environment/lolbench-submit new file mode 100644 index 0000000000000000000000000000000000000000..b3426184f1a568aaf145f148348c3c5e85cfa773 --- /dev/null +++ b/TypeScript_2/environment/lolbench-submit @@ -0,0 +1,33 @@ +#!/usr/bin/env bash +set -euo pipefail +export LC_ALL=C + +repo=${1:-$PWD} +out=${LOLBENCH_PATCH_OUT:-/logs/artifacts/solution.patch} + +mkdir -p "$(dirname "$out")" +cd "$repo" + +baseline=/opt/lolbench/base_untracked.txt +current=$(mktemp) +new_files=$(mktemp) +trap 'rm -f "$current" "$new_files"' EXIT + +git ls-files --others --exclude-standard | sort > "$current" +if [ -f "$baseline" ]; then + comm -13 "$baseline" "$current" > "$new_files" +else + cp "$current" "$new_files" +fi + +if [ -s "$new_files" ]; then + xargs -r git add -N -- < "$new_files" +fi + +git diff --binary > "$out" + +if [ ! -s "$out" ]; then + echo "warning: wrote an empty solution patch to $out" >&2 +else + echo "wrote solution patch to $out" +fi diff --git a/TypeScript_2/environment/metadata.json b/TypeScript_2/environment/metadata.json new file mode 100644 index 0000000000000000000000000000000000000000..72163cb59ff3a783d39fd642dbc41e50c12219ee --- /dev/null +++ b/TypeScript_2/environment/metadata.json @@ -0,0 +1,22 @@ +{ + "instance_id": "TypeScript_2", + "source_instance_id": "TypeScript_PR-54505_Using-and-await-using-declarations", + "source_slug": "TypeScript_PR-54505_Using-and-await-using-declarations", + "docker_slug": "TypeScript_PR-54505_Using-and-await-using-declarations", + "dockerhub_image": "smartdub26/lolbench-linux:TypeScript_2-1.0.0", + "project": "TypeScript", + "repo": "microsoft/TypeScript", + "requirement_doc": "https://github.com/tc39/proposal-explicit-resource-management", + "pr_link": "https://github.com/microsoft/TypeScript/pull/54505", + "base_commit": "d90eb0d731c3f74b131dcfafe69ef5341ed14934", + "merge_commit": "558a5028b785e962e7a26a9d820fc77ca094faf6", + "source_history_policy": "ancestors-only", + "lolbench_test_modes": [ + "orig", + "aug", + "union" + ], + "default_lolbench_suite": "union", + "canonical_lolbench_suite": "union", + "augmentation_available": true +} diff --git a/TypeScript_2/environment/runtime_source_guard.py b/TypeScript_2/environment/runtime_source_guard.py new file mode 100644 index 0000000000000000000000000000000000000000..74f860b22668f258ff252debec5be9cf1ab177e9 --- /dev/null +++ b/TypeScript_2/environment/runtime_source_guard.py @@ -0,0 +1,353 @@ +#!/usr/bin/env python3 +"""Remove target-feature reference sources from injected Node agent runtimes. + +TypeScript_2 intentionally keeps its base-commit workspace dependencies. Its +workspace uses tslib 2.5.3, which predates explicit resource management. Some +agents, however, install a newer global Node runtime after the container has +started. Newer tslib releases include the completed implementations of the +two disposal helpers targeted by this benchmark. + +This guard runs as a root-only sidecar process started by the image entrypoint. +It waits for the global npm install to finish, removes npm/source-map caches, +replaces only the two target helper bodies with fail-closed stubs, and makes +the injected NVM runtime immutable to the unprivileged agent user. +""" + +from __future__ import annotations + +import fcntl +import json +import os +import re +import shutil +import stat +import sys +import time +from pathlib import Path + + +AGENT_HOME = Path("/home/agent") +NVM_ROOT = AGENT_HOME / ".nvm" +NODE_ROOT_GLOB = "versions/node/*/lib/node_modules" +LOCK_PATH = Path("/run/lolbench-runtime-source-guard.lock") +READY_PATH = Path("/run/lolbench-runtime-source-guard.ready.json") +POLL_SECONDS = 0.05 +SETTLE_SECONDS = 1.0 + +CJS_HELPERS = ( + ("__addDisposableResource", "env, value, async"), + ("__disposeResources", "env"), +) + +# These are distinctive implementation fragments, not merely public helper +# names or signatures already stated in the task instruction. +FORBIDDEN_IMPLEMENTATION_FRAGMENTS = ( + b"env.stack.pop()", + b"An error was suppressed during disposal.", + b"Object not disposable.", + b"env.stack.push({ value: value, dispose: dispose, async: async })", + b"env.stack.push({ async: true })", + b"using declarations can only be used with objects", + b"function _usingCtx", + b"function _dispose(", +) + + +def global_node_roots() -> list[Path]: + return sorted(path for path in NVM_ROOT.glob(NODE_ROOT_GLOB) if path.is_dir()) + + +def target_tslib_files(roots: list[Path]) -> list[Path]: + files: list[Path] = [] + for root in roots: + for path in root.glob("**/tslib/tslib.js"): + try: + data = path.read_bytes() + except OSError: + continue + if b"__addDisposableResource" in data or b"__disposeResources" in data: + files.append(path) + return sorted(set(files)) + + +def installer_is_running() -> bool: + """Return true while a global npm agent install can still be writing.""" + + for proc in Path("/proc").glob("[0-9]*"): + try: + command = (proc / "cmdline").read_bytes().replace(b"\0", b" ") + process_name = (proc / "comm").read_text(encoding="utf-8").strip() + except OSError: + continue + if process_name.startswith("npm") and b"pi-coding-agent" in command: + return True + return False + + +def runtime_install_is_complete(roots: list[Path]) -> bool: + """Require npm's final global binary link and Pi entry point.""" + + for root in roots: + package = root / "@earendil-works" / "pi-coding-agent" + pi_link = root.parent.parent / "bin" / "pi" + if ( + (package / "package.json").is_file() + and (package / "dist" / "cli.js").is_file() + and pi_link.is_symlink() + and pi_link.exists() + ): + return True + return False + + +def stub_cjs_helpers(path: Path) -> int: + text = path.read_text(encoding="utf-8") + changed = 0 + for name, arguments in CJS_HELPERS: + pattern = re.compile( + rf"(?ms)^ {re.escape(name)} = function \({re.escape(arguments)}\) " + rf"\{{.*?^ \}};" + ) + replacement = ( + f" {name} = function () {{\n" + ' throw new Error("LOLBENCH_RUNTIME_REFERENCE_REMOVED");\n' + " };" + ) + text, count = pattern.subn(replacement, text) + if count == 0 and f"{name} = function ()" in text: + continue + if count != 1: + raise RuntimeError(f"expected one {name} body in {path}, found {count}") + changed += count + path.write_text(text, encoding="utf-8") + return changed + + +def stub_babel_helpers(roots: list[Path]) -> int: + changed = 0 + helper_names = ("using", "usingCtx", "dispose") + for root in roots: + for helper_name in helper_names: + paths = set(root.glob(f"**/@babel/runtime/helpers/{helper_name}.js")) + paths.update(root.glob(f"**/@babel/runtime/helpers/esm/{helper_name}.js")) + for path in sorted(paths): + export_name = "_lolbenchRemoved" + if "esm" in path.parts: + text = ( + f"function {export_name}() {{\n" + ' throw new Error("LOLBENCH_RUNTIME_REFERENCE_REMOVED");\n' + "}\n" + f"export {{ {export_name} as default }};\n" + ) + else: + text = ( + f"function {export_name}() {{\n" + ' throw new Error("LOLBENCH_RUNTIME_REFERENCE_REMOVED");\n' + "}\n" + f"module.exports = {export_name}, " + "module.exports.__esModule = true, " + 'module.exports["default"] = module.exports;\n' + ) + path.write_text(text, encoding="utf-8") + changed += 1 + return changed + + +def stub_jiti_babel_helpers(roots: list[Path]) -> int: + changed = 0 + for root in roots: + for path in root.glob("**/jiti/dist/babel.*"): + if not path.is_file() or path.suffix == ".map": + continue + text = path.read_text(encoding="utf-8") + file_changed = 0 + for helper_name in ("using", "usingCtx", "dispose"): + pattern = re.compile( + rf"({helper_name}:helper\([^,]+,)" + rf"'(?:\\.|[^'\\])*'" + rf"(,\{{globals:)" + ) + replacement = ( + rf"\1'function _lolbenchRemoved(){{throw new Error(" + '"LOLBENCH_RUNTIME_REFERENCE_REMOVED")}'"'" + rf"\2" + ) + text, count = pattern.subn(replacement, text) + if count == 0 and "LOLBENCH_RUNTIME_REFERENCE_REMOVED" in text: + continue + if count != 1: + raise RuntimeError( + f"expected one serialized {helper_name} helper in {path}, " + f"found {count}" + ) + file_changed += count + path.write_text(text, encoding="utf-8") + changed += file_changed + return changed + + +def remove_nonruntime_sources(roots: list[Path], tslib_files: list[Path]) -> int: + removed = 0 + for root in roots: + for pattern in ("*.map", "*.d.ts", "*.d.mts", "*.d.cts"): + for path in root.glob(f"**/{pattern}"): + try: + path.unlink() + except FileNotFoundError: + continue + removed += 1 + for tslib_file in tslib_files: + tslib_dir = tslib_file.parent + for name in ( + "tslib.es6.js", + "tslib.es6.mjs", + "tslib.es6.html", + "tslib.html", + "README.md", + "SECURITY.md", + ): + path = tslib_dir / name + try: + path.unlink() + except FileNotFoundError: + continue + removed += 1 + return removed + + +def assert_no_reference_implementation(roots: list[Path]) -> int: + scanned = 0 + for root in roots: + for path in root.glob("**/*"): + if not path.is_file() or path.is_symlink(): + continue + try: + if path.stat().st_size > 32 * 1024 * 1024: + continue + data = path.read_bytes() + except OSError: + continue + scanned += 1 + for fragment in FORBIDDEN_IMPLEMENTATION_FRAGMENTS: + if fragment in data: + raise RuntimeError(f"reference implementation remains in {path}") + return scanned + + +def remove_agent_caches() -> None: + for path in (AGENT_HOME / ".npm", AGENT_HOME / ".cache" / "node-gyp"): + shutil.rmtree(path, ignore_errors=True) + + +def root_lock_tree(path: Path) -> None: + """Make a tree readable/executable but not replaceable by the agent.""" + + for current_root, directories, files in os.walk(path, topdown=False): + current = Path(current_root) + for name in files: + item = current / name + try: + if item.is_symlink(): + os.lchown(item, 0, 0) + continue + mode = stat.S_IMODE(item.stat().st_mode) + os.chown(item, 0, 0) + os.chmod(item, mode & ~(stat.S_IWGRP | stat.S_IWOTH)) + except FileNotFoundError: + continue + for name in directories: + item = current / name + try: + if item.is_symlink(): + os.lchown(item, 0, 0) + continue + mode = stat.S_IMODE(item.stat().st_mode) + os.chown(item, 0, 0) + os.chmod(item, mode & ~(stat.S_IWGRP | stat.S_IWOTH)) + except FileNotFoundError: + continue + mode = stat.S_IMODE(path.stat().st_mode) + os.chown(path, 0, 0) + os.chmod(path, mode & ~(stat.S_IWGRP | stat.S_IWOTH)) + + +def sanitize_once() -> bool: + roots = global_node_roots() + tslib_files = target_tslib_files(roots) + if ( + not roots + or not tslib_files + or installer_is_running() + or not runtime_install_is_complete(roots) + ): + return False + + helper_bodies = sum(stub_cjs_helpers(path) for path in tslib_files) + helper_bodies += stub_babel_helpers(roots) + helper_bodies += stub_jiti_babel_helpers(roots) + removed_files = remove_nonruntime_sources(roots, tslib_files) + remove_agent_caches() + scanned_files = assert_no_reference_implementation(roots) + + root_lock_tree(NVM_ROOT) + os.chown(AGENT_HOME, 0, 0) + os.chmod(AGENT_HOME, 0o1777) + + report = { + "instance_id": "TypeScript_2", + "status": "sanitized", + "global_node_roots": [os.fspath(path) for path in roots], + "tslib_runtime_files": [os.fspath(path) for path in tslib_files], + "stubbed_helper_bodies": helper_bodies, + "removed_nonruntime_files": removed_files, + "scanned_runtime_files": scanned_files, + "npm_cache_removed": not (AGENT_HOME / ".npm").exists(), + "nvm_root_owned": NVM_ROOT.stat().st_uid == 0, + } + temporary = READY_PATH.with_suffix(".tmp") + temporary.write_text(json.dumps(report, indent=2, sort_keys=True) + "\n") + os.chmod(temporary, 0o444) + temporary.replace(READY_PATH) + return True + + +def main() -> int: + if os.geteuid() != 0: + print("runtime source guard must run as root", file=sys.stderr) + return 1 + + LOCK_PATH.parent.mkdir(parents=True, exist_ok=True) + with LOCK_PATH.open("w") as lock: + try: + fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB) + except BlockingIOError: + return 0 + + candidate_since: float | None = None + while True: + try: + if READY_PATH.is_file(): + time.sleep(1.0) + continue + roots = global_node_roots() + ready_to_sanitize = ( + bool(roots) + and bool(target_tslib_files(roots)) + and runtime_install_is_complete(roots) + and not installer_is_running() + ) + if not ready_to_sanitize: + candidate_since = None + elif candidate_since is None: + candidate_since = time.monotonic() + elif time.monotonic() - candidate_since >= SETTLE_SECONDS: + sanitize_once() + except Exception: + # Do not expose implementation-matching diagnostics to the + # agent. The missing ready marker makes validation fail closed. + pass + time.sleep(POLL_SECONDS) + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/TypeScript_2/environment/runtime_source_guard_entrypoint.c b/TypeScript_2/environment/runtime_source_guard_entrypoint.c new file mode 100644 index 0000000000000000000000000000000000000000..88608da550f41b13ed1a0047c3b660a565608feb --- /dev/null +++ b/TypeScript_2/environment/runtime_source_guard_entrypoint.c @@ -0,0 +1,62 @@ +#define _GNU_SOURCE + +#include +#include +#include +#include +#include +#include +#include +#include + +static void start_guard(void) { + pid_t pid = fork(); + if (pid != 0) { + return; + } + + if (setgid(0) != 0 || setuid(0) != 0 || setsid() < 0) { + _exit(125); + } + + int null_fd = open("/dev/null", O_RDWR); + if (null_fd >= 0) { + dup2(null_fd, STDIN_FILENO); + dup2(null_fd, STDOUT_FILENO); + dup2(null_fd, STDERR_FILENO); + if (null_fd > STDERR_FILENO) { + close(null_fd); + } + } + + execl( + "/usr/local/bin/lolbench-runtime-source-guard", + "lolbench-runtime-source-guard", + (char *)NULL + ); + _exit(126); +} + +int main(int argc, char **argv) { + uid_t real_uid = getuid(); + gid_t real_gid = getgid(); + + if (geteuid() == 0) { + start_guard(); + if (real_uid != 0) { + if (setgroups(0, NULL) != 0 || setgid(real_gid) != 0 || + setuid(real_uid) != 0) { + perror("failed to drop entrypoint privileges"); + return 125; + } + } + } + + if (argc < 2) { + execl("/bin/bash", "bash", (char *)NULL); + } else { + execvp(argv[1], &argv[1]); + } + perror("failed to execute container command"); + return errno == ENOENT ? 127 : 126; +} diff --git a/TypeScript_2/environment/source_audit.json b/TypeScript_2/environment/source_audit.json new file mode 100644 index 0000000000000000000000000000000000000000..432c8471a432b812d357b8cdaf3a1a3dbd548920 --- /dev/null +++ b/TypeScript_2/environment/source_audit.json @@ -0,0 +1,7 @@ +{ + "source_policy": "dockerfile_fetch_pruned_ancestor_history", + "local_reference_policy": "post_start_agent_runtime_tslib_babel_guarded", + "base_commit": "d90eb0d731c3f74b131dcfafe69ef5341ed14934", + "repo": "microsoft/TypeScript", + "note": "The Dockerfile fetches only the declared base history, removes refs/remotes/reflogs, repacks and prunes unreachable objects, and asserts that git fsck finds no unreachable object. It removes cached/global TypeScript and tslib sources at build time. A root-only entrypoint sidecar waits for the injected Pi npm runtime, removes maps and type sources, stubs target tslib/Babel helper implementations, removes npm caches, scans for reference fragments, and root-locks the NVM tree before the adapter continues." +} diff --git a/TypeScript_2/instruction.md b/TypeScript_2/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..446020be1a49c6bc84fb141e6a4c32b0c2df0fcf --- /dev/null +++ b/TypeScript_2/instruction.md @@ -0,0 +1,1824 @@ +You are working in `/workspace/typescript`, a source tree checked out at +the base commit for this task. Implement the requested behavior in the source +tree, then run: + +```bash +lolbench-submit +``` + +Do not stop after editing files, running tests, or describing the solution. The +task is complete only when `lolbench-submit` has created +`/logs/artifacts/solution.patch`. If that file does not exist, continue +working and run `lolbench-submit` again. + +That command writes your implementation diff to +`/logs/artifacts/solution.patch`, which is the artifact the Harbor verifier +will grade. Before running `lolbench-submit`, clean or revert any test files +you created or modified; test files must not be included in the final +`solution.patch`. + +This environment has no outbound internet access — `curl`/`wget`, `git fetch`/`clone`, package installs, and web fetch/search will all fail. Implement the requirements using only the code already in the workspace and your own knowledge; do not attempt to fetch or search external resources. + +Now please implement the following requirements in the source tree: + +--- + +# ECMAScript Explicit Resource Management + +> **NOTE:** This proposal has subsumed the [Async Explicit Resource Management](https://github.com/tc39/proposal-async-explicit-resource-management) +> proposal. This proposal repository should be used for further discussion of both sync and async of explicit resource +> management. + +This proposal intends to address a common pattern in software development regarding +the lifetime and management of various resources (memory, I/O, etc.). This pattern +generally includes the allocation of a resource and the ability to explicitly +release critical resources. + +For example, ECMAScript Generator Functions and Async Generator Functions expose this pattern through the +`return` method, as a means to explicitly evaluate `finally` blocks to ensure +user-defined cleanup logic is preserved: + +```js +// sync generators +function * g() { + const handle = acquireFileHandle(); // critical resource + try { + ... + } + finally { + handle.release(); // cleanup + } +} + +const obj = g(); +try { + const r = obj.next(); + ... +} +finally { + obj.return(); // calls finally blocks in `g` +} +``` + +```js +// async generators +async function * g() { + const handle = acquireStream(); // critical resource + try { + ... + } + finally { + await stream.close(); // cleanup + } +} + +const obj = g(); +try { + const r = await obj.next(); + ... +} +finally { + await obj.return(); // calls finally blocks in `g` +} +``` + +As such, we propose the adoption of a novel syntax to simplify this common pattern: + +```js +// sync disposal +function * g() { + using handle = acquireFileHandle(); // block-scoped critical resource +} // cleanup + +{ + using obj = g(); // block-scoped declaration + const r = obj.next(); +} // calls finally blocks in `g` +``` + +```js +// async disposal +async function * g() { + using stream = acquireStream(); // block-scoped critical resource + ... +} // cleanup + +{ + await using obj = g(); // block-scoped declaration + const r = await obj.next(); +} // calls finally blocks in `g` +``` + +In addition, we propose the addition of two disposable container objects to assist +with managing multiple resources: + +- `DisposableStack` — A stack-based container of disposable resources. +- `AsyncDisposableStack` — A stack-based container of asynchronously disposable resources. + +# Motivations + +This proposal is motivated by a number of cases: + +- Inconsistent patterns for resource management: + - ECMAScript Iterators: `iterator.return()` + - WHATWG Stream Readers: `reader.releaseLock()` + - NodeJS FileHandles: `handle.close()` + - Emscripten C++ objects handles: `Module._free(ptr) obj.delete() Module.destroy(obj)` +- Avoiding common footguns when managing resources: + ```js + const reader = stream.getReader(); + ... + reader.releaseLock(); // Oops, should have been in a try/finally + ``` +- Scoping resources: + ```js + const handle = ...; + try { + ... // ok to use `handle` + } + finally { + handle.close(); + } + // not ok to use `handle`, but still in scope + ``` +- Avoiding common footguns when managing multiple resources: + ```js + const a = ...; + const b = ...; + try { + ... + } + finally { + a.close(); // Oops, issue if `b.close()` depends on `a`. + b.close(); // Oops, `b` never reached if `a.close()` throws. + } + ``` +- Avoiding lengthy code when managing multiple resources correctly: + ```js + // sync disposal + { // block avoids leaking `a` or `b` to outer scope + const a = ...; + try { + const b = ...; + try { + ... + } + finally { + b.close(); // ensure `b` is closed before `a` in case `b` + // depends on `a` + } + } + finally { + a.close(); // ensure `a` is closed even if `b.close()` throws + } + } + // both `a` and `b` are out of scope + ``` + Compared to: + ```js + // avoids leaking `a` or `b` to outer scope + // ensures `b` is disposed before `a` in case `b` depends on `a` + // ensures `a` is disposed even if disposing `b` throws + using a = ..., b = ...; + ... + ``` + ```js + // async sync disposal + { // block avoids leaking `a` or `b` to outer scope + const a = ...; + try { + const b = ...; + try { + ... + } + finally { + await b.close(); // ensure `b` is closed before `a` in case `b` + // depends on `a` + } + } + finally { + await a.close(); // ensure `a` is closed even if `b.close()` throws + } + } + // both `a` and `b` are out of scope + ``` + Compared to: + ```js + // avoids leaking `a` or `b` to outer scope + // ensures `b` is disposed before `a` in case `b` depends on `a` + // ensures `a` is disposed even if disposing `b` throws + await using a = ..., b = ...; + ... + ``` +- Non-blocking memory/IO applications: + ```js + import { ReaderWriterLock } from "..."; + const lock = new ReaderWriterLock(); + + export async function readData() { + // wait for outstanding writer and take a read lock + using lockHandle = await lock.read(); + ... // any number of readers + await ...; + ... // still in read lock after `await` + } // release the read lock + + export async function writeData(data) { + // wait for all readers and take a write lock + using lockHandle = await lock.write(); + ... // only one writer + await ...; + ... // still in write lock after `await` + } // release the write lock + ``` +- Potential for use with the [Fixed Layout Objects Proposal](https://github.com/tc39/proposal-structs) and + `shared struct`: + ```js + // main.js + shared struct class SharedData { + ready = false; + processed = false; + } + + const worker = new Worker('worker.js'); + const m = new Atomics.Mutex(); + const cv = new Atomics.ConditionVariable(); + const data = new SharedData(); + worker.postMessage({ m, cv, data }); + + // send data to worker + { + // wait until main can get a lock on 'm' + using lck = m.lock(); + + // mark data for worker + data.ready = true; + console.log("main is ready"); + + } // unlocks 'm' + + // notify potentially waiting worker + cv.notifyOne(); + + { + // reacquire lock on 'm' + using lck = m.lock(); + + // release the lock on 'm' and wait for the worker to finish processing + cv.wait(m, () => data.processed); + + } // unlocks 'm' + ``` + + ```js + // worker.js + onmessage = function (e) { + const { m, cv, data } = e.data; + + { + // wait until worker can get a lock on 'm' + using lck = m.lock(); + + // release the lock on 'm' and wait until main() sends data + cv.wait(m, () => data.ready); + + // after waiting we once again own the lock on 'm' + console.log("worker thread is processing data"); + + // send data back to main + data.processed = true; + console.log("worker thread is done"); + + } // unlocks 'm' + } + ``` + +# Prior Art + +- C#: + - [`using` statement](https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/using-statement) + - [`using` declaration](https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/proposals/csharp-8.0/using#using-declaration) +- Java: [`try`-with-resources statement](https://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html) +- Python: [`with` statement](https://docs.python.org/3/reference/compound_stmts.html#the-with-statement) + +# Definitions + +- _Resource_ — An object with a specific lifetime, at the end of which either a lifetime-sensitive operation + should be performed or a non-garbage-collected reference (such as a file handle, socket, etc.) should be closed or + freed. +- _Resource Management_ — A process whereby "resources" are released, triggering any lifetime-sensitive operations + or freeing any related non-garbage-collected references. +- _Implicit Resource Management_ — Indicates a system whereby the lifetime of a "resource" is managed implicitly + by the runtime as part of garbage collection, such as: + - `WeakMap` keys + - `WeakSet` values + - `WeakRef` values + - `FinalizationRegistry` entries +- _Explicit Resource Management_ — Indicates a system whereby the lifetime of a "resource" is managed explicitly + by the user either **imperatively** (by directly calling a method like `Symbol.dispose`) or **declaratively** (through + a block-scoped declaration like `using`). + +# Syntax + +## `using` Declarations + +```js +// a synchronously-disposed, block-scoped resource +using x = expr1; // resource w/ local binding +using y = expr2, z = expr4; // multiple resources +``` + +# Grammar + +Please refer to the [specification text][Specification] for the most recent version of the grammar. + +## `await using` Declarations + +```js +// an asynchronously-disposed, block-scoped resource +await using x = expr1; // resource w/ local binding +await using y = expr2, z = expr4; // multiple resources +``` + +An `await using` declaration can appear in the following contexts: +- The top level of a _Module_ anywhere _VariableStatement_ is allowed, as long as it is not immediately nested inside + of a _CaseClause_ or _DefaultClause_. +- In the body of an async function or async generator anywhere a _VariableStatement_ is allowed, as long as it is not + immediately nested inside of a _CaseClause_ or _DefaultClause_. +- In the head of a `for-of` or `for-await-of` statement. + +## `await using` in `for-of` and `for-await-of` Statements + +```js +for (await using x of y) ... + +for await (await using x of y) ... +``` + +You can use an `await using` declaration in a `for-of` or `for-await-of` statement inside of an async context to +explicitly bind each iterated value as an async disposable resource. `for-await-of` does not implicitly make a non-async +`using` declaration into an async `await using` declaration, as the `await` markers in `for-await-of` and `await using` +are explicit indicators for distinct cases: `for await` *only* indicates async iteration, while `await using` *only* +indicates async disposal. For example: + +```js + +// sync iteration, sync disposal +for (using x of y) ; // no implicit `await` at end of each iteration + +// sync iteration, async disposal +for (await using x of y) ; // implicit `await` at end of each iteration + +// async iteration, sync disposal +for await (using x of y) ; // implicit `await` at end of each iteration + +// async iteration, async disposal +for await (await using x of y) ; // implicit `await` at end of each iteration +``` + +While there is some overlap in that the last three cases introduce some form of implicit `await` during execution, it +is intended that the presence or absence of the `await` modifier in a `using` declaration is an explicit indicator as to +whether we are expecting the iterated value to have an `@@asyncDispose` method. This distinction is in line with the +behavior of `for-of` and `for-await-of`: + +```js +const iter = { [Symbol.iterator]() { return [].values(); } }; +const asyncIter = { [Symbol.asyncIterator]() { return [].values(); } }; + +for (const x of iter) ; // ok: `iter` has @@iterator +for (const x of asyncIter) ; // throws: `asyncIter` does not have @@iterator + +for await (const x of iter) ; // ok: `iter` has @@iterator (fallback) +for await (const x of asyncIter) ; // ok: `asyncIter` has @@asyncIterator + +``` + +`using` and `await using` have the same distinction: + +```js +const res = { [Symbol.dispose]() {} }; +const asyncRes = { [Symbol.asyncDispose]() {} }; + +using x = res; // ok: `res` has @@dispose +using x = asyncRes; // throws: `asyncRes` does not have @@dispose + +await using x = res; // ok: `res` has @@dispose (fallback) +await using x = asyncres; // ok: `asyncRes` has @@asyncDispose +``` + +This results in a matrix of behaviors based on the presence of each `await` marker: + +```js +const res = { [Symbol.dispose]() {} }; +const asyncRes = { [Symbol.asyncDispose]() {} }; +const iter = { [Symbol.iterator]() { return [res, asyncRes].values(); } }; +const asyncIter = { [Symbol.asyncIterator]() { return [res, asyncRes].values(); } }; + +for (using x of iter) ; +// sync iteration, sync disposal +// - `iter` has @@iterator: ok +// - `res` has @@dispose: ok +// - `asyncRes` does not have @@dispose: *error* + +for (using x of asyncIter) ; +// sync iteration, sync disposal +// - `asyncIter` does not have @@iterator: *error* + +for (await using x of iter) ; +// sync iteration, async disposal +// - `iter` has @@iterator: ok +// - `res` has @@dispose (fallback): ok +// - `asyncRes` has @@asyncDispose: ok + +for (await using x of asyncIter) ; +// sync iteration, async disposal +// - `asyncIter` does not have @@iterator: error + +for await (using x of iter) ; +// async iteration, sync disposal +// - `iter` has @@iterator (fallback): ok +// - `res` has @@dispose: ok +// - `asyncRes` does not have @@dispose: error + +for await (using x of asyncIter) ; +// async iteration, sync disposal +// - `asyncIter` has @@asyncIterator: ok +// - `res` has @@dispose: ok +// - `asyncRes` does not have @@dispose: error + +for await (await using x of iter) ; +// async iteration, async disposal +// - `iter` has @@iterator (fallback): ok +// - `res` has @@dispose (fallback): ok +// - `asyncRes` does has @@asyncDispose: ok + +for await (await using x of asyncIter) ; +// async iteration, async disposal +// - `asyncIter` has @@asyncIterator: ok +// - `res` has @@dispose (fallback): ok +// - `asyncRes` does has @@asyncDispose: ok +``` + +Or, in table form: + +| Syntax | Iteration | Disposal | +|:---------------------------------|:------------------------------:|:----------------------------:| +| `for (using x of y)` | `@@iterator` | `@@dispose` | +| `for (await using x of y)` | `@@iterator` | `@@asyncDispose`/`@@dispose` | +| `for await (using x of y)` | `@@asyncIterator`/`@@iterator` | `@@dispose` | +| `for await (await using x of y)` | `@@asyncIterator`/`@@iterator` | `@@asyncDispose`/`@@dispose` | + +# Semantics + +## `using` Declarations + +### `using` Declarations with Explicit Local Bindings + +```grammarkdown +UsingDeclaration : + `using` BindingList `;` + +LexicalBinding : + BindingIdentifier Initializer +``` + +When a `using` declaration is parsed with _BindingIdentifier_ _Initializer_, the bindings created in the declaration +are tracked for disposal at the end of the containing _Block_ or _Module_ (a `using` declaration cannot be used +at the top level of a _Script_): + +```js +{ + ... // (1) + using x = expr1; + ... // (2) +} +``` + +Internally, the TypeScript parser marks a `using` declaration list with the `NodeFlags.Using` flag (defined as `1 << 2`) and an `await using` declaration list with `NodeFlags.AwaitUsing`, defined as the combination `Const | Using`. Both are folded into the block-scoped and constant flag groups — `BlockScoped` is `Let | Const | Using` and `Constant` is `Const | Using` — so a `using` or `await using` binding is block-scoped and, like a `const`, immutable; reassigning one is an error. + +The above example has similar runtime semantics as the following transposed representation: + +```js +{ + const $$try = { stack: [], error: undefined, hasError: false }; + try { + ... // (1) + + const x = expr1; + if (x !== null && x !== undefined) { + const $$dispose = x[Symbol.dispose]; + if (typeof $$dispose !== "function") { + throw new TypeError(); + } + $$try.stack.push({ value: x, dispose: $$dispose }); + } + + ... // (2) + } + catch ($$error) { + $$try.error = $$error; + $$try.hasError = true; + } + finally { + while ($$try.stack.length) { + const { value: $$expr, dispose: $$dispose } = $$try.stack.pop(); + try { + $$dispose.call($$expr); + } + catch ($$error) { + $$try.error = $$try.hasError ? new SuppressedError($$error, $$try.error) : $$error; + $$try.hasError = true; + } + } + if ($$try.hasError) { + throw $$try.error; + } + } +} +``` + +If exceptions are thrown both in the block following the `using` declaration and in the call to +`[Symbol.dispose]()`, all exceptions are reported. + +In the TypeScript compiler this transposition is not inlined at each declaration site as shown above. When a `using` declaration is downleveled for an output target that lacks native support, the transform routes the logic through two named runtime helpers, `__addDisposableResource` and `__disposeResources`. `__addDisposableResource(env, value, async)` records a single resource — resolving the value's `[Symbol.asyncDispose]` method when `async` is `true` (falling back to `[Symbol.dispose]`) and its `[Symbol.dispose]` method otherwise; a `using` declaration passes `async` as `false`, while an `await using` declaration passes it as `true`. `__disposeResources(env)` then disposes the recorded resources in reverse order when the block exits. When a disposer throws while another error is already pending, it combines them as `new SuppressedError(error, suppressed, "An error was suppressed during disposal.")`, using that exact string as the default message for a disposal-suppressed error, and rethrows once the remaining resources have been disposed. + +### `using` Declarations with Multiple Resources + +A `using` declaration can mix multiple explicit bindings in the same declaration: + +```js +{ + ... + using x = expr1, y = expr2; + ... +} +``` + +These bindings are again used to perform resource disposal when the _Block_ or _Module_ exits, however in this case +`[Symbol.dispose]()` is invoked in the reverse order of their declaration. This is _approximately_ equivalent to the +following: + +```js +{ + ... // (1) + using x = expr1; + using y = expr2; + ... // (2) +} +``` + +Both of the above cases would have similar runtime semantics as the following transposed representation: + +```js +{ + const $$try = { stack: [], error: undefined, hasError: false }; + try { + ... // (1) + + const x = expr1; + if (x !== null && x !== undefined) { + const $$dispose = x[Symbol.dispose]; + if (typeof $$dispose !== "function") { + throw new TypeError(); + } + $$try.stack.push({ value: x, dispose: $$dispose }); + } + + const y = expr2; + if (y !== null && y !== undefined) { + const $$dispose = y[Symbol.dispose]; + if (typeof $$dispose !== "function") { + throw new TypeError(); + } + $$try.stack.push({ value: y, dispose: $$dispose }); + } + + ... // (2) + } + catch ($$error) { + $$try.error = $$error; + $$try.hasError = true; + } + finally { + while ($$try.stack.length) { + const { value: $$expr, dispose: $$dispose } = $$try.stack.pop(); + try { + $$dispose.call($$expr); + } + catch ($$error) { + $$try.error = $$try.hasError ? new SuppressedError($$error, $$try.error) : $$error; + $$try.hasError = true; + } + } + if ($$try.hasError) { + throw $$try.error; + } + } +} +``` + +Since we must always ensure that we properly release resources, we must ensure that any abrupt completion that might +occur during binding initialization results in evaluation of the cleanup step. When there are multiple declarations in +the list, we track each resource in the order they are declared. As a result, we must release these resources in reverse +order. + +### `using` Declarations and `null` or `undefined` Values + +This proposal has opted to ignore `null` and `undefined` values provided to the `using` declarations. This is similar to +the behavior of `using` in C#, which also allows `null`. One primary reason for this behavior is to simplify a common +case where a resource might be optional, without requiring duplication of work or needless allocations: + +```js +if (isResourceAvailable()) { + using resource = getResource(); + ... // (1) + resource.doSomething() + ... // (2) +} +else { + // duplicate code path above + ... // (1) above + ... // (2) above +} +``` + +Compared to: + +```js +using resource = isResourceAvailable() ? getResource() : undefined; +... // (1) do some work with or without resource +resource?.doSomething(); +... // (2) do some other work with or without resource +``` + +### `using` Declarations and Values Without `[Symbol.dispose]` + +If a resource does not have a callable `[Symbol.dispose]` member, a `TypeError` would be thrown **immediately** when the +resource is tracked. + +### `using` Declarations in `for-of` and `for-await-of` Loops + +A `using` declaration _may_ occur in the _ForDeclaration_ of a `for-of` or `for-await-of` loop: + +```js +for (using x of iterateResources()) { + // use x +} +``` + +In this case, the value bound to `x` in each iteration will be _synchronously_ disposed at the end of each iteration. +This will not dispose resources that are not iterated, such as if iteration is terminated early due to `return`, +`break`, or `throw`. + +`using` declarations _may not_ be used in in the head of a `for-in` loop. + +## `await using` Declarations + +### `await using` Declarations with Explicit Local Bindings + +```grammarkdown +UsingDeclaration : + `await` `using` BindingList `;` + +LexicalBinding : + BindingIdentifier Initializer +``` + +When an `await using` declaration is parsed with _BindingIdentifier_ _Initializer_, the bindings created in the +declaration are tracked for disposal at the end of the containing async function body, _Block_, or _Module_: + +```js +{ + ... // (1) + await using x = expr1; + ... // (2) +} +``` + +The above example has similar runtime semantics as the following transposed representation: + +```js +{ + const $$try = { stack: [], error: undefined, hasError: false }; + try { + ... // (1) + + const x = expr1; + if (x !== null && x !== undefined) { + let $$dispose = x[Symbol.asyncDispose]; + if (typeof $$dispose !== "function") { + $$dispose = x[Symbol.dispose]; + } + if (typeof $$dispose !== "function") { + throw new TypeError(); + } + $$try.stack.push({ value: x, dispose: $$dispose }); + } + + ... // (2) + } + catch ($$error) { + $$try.error = $$error; + $$try.hasError = true; + } + finally { + while ($$try.stack.length) { + const { value: $$expr, dispose: $$dispose } = $$try.stack.pop(); + try { + await $$dispose.call($$expr); + } + catch ($$error) { + $$try.error = $$try.hasError ? new SuppressedError($$error, $$try.error) : $$error; + $$try.hasError = true; + } + } + if ($$try.hasError) { + throw $$try.error; + } + } +} +``` + +If exceptions are thrown both in the statements following the `await using` declaration and in the call to +`[Symbol.asyncDispose]()`, all exceptions are reported. + +### `await using` Declarations with Multiple Resources + +An `await using` declaration can mix multiple explicit bindings in the same declaration: + +```js +{ + ... + await using x = expr1, y = expr2; + ... +} +``` + +These bindings are again used to perform resource disposal when the _Block_ or _Module_ exits, however in this case each +resource's `[Symbol.asyncDispose]()` is invoked in the reverse order of their declaration. This is _approximately_ +equivalent to the following: + +```js +{ + ... // (1) + await using x = expr1; + await using y = expr2; + ... // (2) +} +``` + +Both of the above cases would have similar runtime semantics as the following transposed representation: + +```js +{ + const $$try = { stack: [], error: undefined, hasError: false }; + try { + ... // (1) + + const x = expr1; + if (x !== null && x !== undefined) { + let $$dispose = x[Symbol.asyncDispose]; + if (typeof $$dispose !== "function") { + $$dispose = x[Symbol.dispose]; + } + if (typeof $$dispose !== "function") { + throw new TypeError(); + } + $$try.stack.push({ value: x, dispose: $$dispose }); + } + + const y = expr2; + if (y !== null && y !== undefined) { + let $$dispose = y[Symbol.asyncDispose]; + if (typeof $$dispose !== "function") { + $$dispose = y[Symbol.dispose]; + } + if (typeof $$dispose !== "function") { + throw new TypeError(); + } + $$try.stack.push({ value: y, dispose: $$dispose }); + } + + ... // (2) + } + catch ($$error) { + $$try.error = $$error; + $$try.hasError = true; + } + finally { + while ($$try.stack.length) { + const { value: $$expr, dispose: $$dispose } = $$try.stack.pop(); + try { + await $$dispose.call($$expr); + } + catch ($$error) { + $$try.error = $$try.hasError ? new SuppressedError($$error, $$try.error) : $$error; + $$try.hasError = true; + } + } + if ($$try.hasError) { + throw $$try.error; + } + } +} +``` + +Since we must always ensure that we properly release resources, we must ensure that any abrupt completion that might +occur during binding initialization results in evaluation of the cleanup step. When there are multiple declarations in +the list, we track each resource in the order they are declared. As a result, we must release these resources in reverse +order. + +### `await using` Declarations and `null` or `undefined` Values + +This proposal has opted to ignore `null` and `undefined` values provided to `await using` declarations. This is +consistent with the proposed behavior for the `using` declarations in this proposal. Like in the sync case, this allows +simplifying a common case where a resource might be optional, without requiring duplication of work or needless +allocations: + +```js +if (isResourceAvailable()) { + await using resource = getResource(); + ... // (1) + resource.doSomething() + ... // (2) +} +else { + // duplicate code path above + ... // (1) above + ... // (2) above +} +``` + +Compared to: + +```js +await using resource = isResourceAvailable() ? getResource() : undefined; +... // (1) do some work with or without resource +resource?.doSomething(); +... // (2) do some other work with or without resource +``` + +### `await using` Declarations and Values Without `[Symbol.asyncDispose]` or `[Symbol.dispose]` + +If a resource does not have a callable `[Symbol.asyncDispose]` or `[Symbol.asyncDispose]` member, a `TypeError` would be thrown **immediately** when the resource is tracked. + +### `await using` Declarations in `for-of` and `for-await-of` Loops + +An `await using` declaration _may_ occur in the _ForDeclaration_ of a `for-await-of` loop: + +```js +for await (await using x of iterateResources()) { + // use x +} +``` + +In this case, the value bound to `x` in each iteration will be _asynchronously_ disposed at the end of each iteration. +This will not dispose resources that are not iterated, such as if iteration is terminated early due to `return`, +`break`, or `throw`. + +`await using` declarations _may not_ be used in in the head of a `for-of` or `for-in` loop. + +### Implicit Async Interleaving Points ("implicit `await`") + +The `await using` syntax introduces an implicit async interleaving point (i.e., an implicit `await`) whenever control +flow exits an async function body, _Block_, or _Module_ containing an `await using` declaration. This means that two +statements that currently execute in the same microtask, such as: + +```js +async function f() { + { + a(); + } // exit block + b(); // same microtask as call to `a()` +} +``` + +will instead execute in different microtasks if an `await using` declaration is introduced: + +```js +async function f() { + { + await using x = ...; + a(); + } // exit block, implicit `await` + b(); // different microtask from call to `a()`. +} +``` + +It is important that such an implicit interleaving point be adequately indicated within the syntax. We believe that +the presence of `await using` within such a block is an adequate indicator, since it should be fairly easy to recognize +a _Block_ containing an `await using` statement in well-formatted code. + +It is also feasible for editors to use features such as syntax highlighting, editor decorations, and inlay hints to +further highlight such transitions, without needing to specify additional syntax. + +Further discussion around the `await using` syntax and how it pertains to implicit async interleaving points can be +found in [#1](https://github.com/tc39/proposal-async-explicit-resource-management/issues/1). + +# Examples + +The following show examples of using this proposal with various APIs, assuming those APIs adopted this proposal. + +### WHATWG Streams API +```js +{ + using reader = stream.getReader(); + const { value, done } = reader.read(); +} // 'reader' is disposed +``` + +### NodeJS FileHandle +```js +{ + using f1 = await fs.promises.open(s1, constants.O_RDONLY), + f2 = await fs.promises.open(s2, constants.O_WRONLY); + const buffer = Buffer.alloc(4092); + const { bytesRead } = await f1.read(buffer); + await f2.write(buffer, 0, bytesRead); +} // 'f2' is disposed, then 'f1' is disposed +``` + +### NodeJS Streams +```js +{ + await using writable = ...; + writable.write(...); +} // 'writable.end()' is called and its result is awaited +``` + +### Logging and tracing +```js +// audit privileged function call entry and exit +function privilegedActivity() { + using activity = auditLog.startActivity("privilegedActivity"); // log activity start + ... +} // log activity end +``` + +### Async Coordination +```js +import { Semaphore } from "..."; +const sem = new Semaphore(1); // allow one participant at a time + +export async function tryUpdate(record) { + using lck = await sem.wait(); // asynchronously block until we are the sole participant + ... +} // synchronously release semaphore and notify the next participant +``` + +### Three-Phase Commit Transactions +```js +// roll back transaction if either action fails +async function transfer(account1, account2) { + await using tx = transactionManager.startTransaction(account1, account2); + await account1.debit(amount); + await account2.credit(amount); + + // mark transaction success if we reach this point + tx.succeeded = true; +} // await transaction commit or rollback +``` + +### Shared Structs +**main_thread.js** +```js +// main_thread.js +shared struct Data { + mut; + cv; + ready = 0; + processed = 0; + // ... +} + +const data = Data(); +data.mut = Atomics.Mutex(); +data.cv = Atomics.ConditionVariable(); + +// start two workers +startWorker1(data); +startWorker2(data); +``` + +**worker1.js** +```js +const data = ...; +const { mut, cv } = data; + +{ + // lock mutex + using lck = Atomics.Mutex.lock(mut); + + // NOTE: at this point we currently own the lock + + // load content into data and signal we're ready + // ... + Atomics.store(data, "ready", 1); + +} // release mutex + +// NOTE: at this point we no longer own the lock + +// notify worker 2 that it should wake +Atomics.ConditionVariable.notifyOne(cv); + +{ + // reacquire lock on mutex + using lck = Atomics.Mutex.lock(mut); + + // NOTE: at this point we currently own the lock + + // release mutex and wait until condition is met to reacquire it + Atomics.ConditionVariable.wait(mut, () => Atomics.load(data, "processed") === 1); + + // NOTE: at this point we currently own the lock + + // Do something with the processed data + // ... + +} // release mutex + +// NOTE: at this point we no longer own the lock +``` + +**worker2.js** +```js +const data = ...; +const { mut, cv } = data; + +{ + // lock mutex + using lck = Atomics.Mutex.lock(mut); + + // NOTE: at this point we currently own the lock + + // release mutex and wait until condition is met to reacquire it + Atomics.ConditionVariable.wait(mut, () => Atomics.load(data, "ready") === 1); + + // NOTE: at this point we currently own the lock + + // read in values from data, perform our processing, then indicate we are done + // ... + Atomics.store(data, "processed", 1); + +} // release mutex + +// NOTE: at this point we no longer own the lock +``` + +# API + +## Additions to `Symbol` + +This proposal adds the `dispose` and `asyncDispose` properties to the `Symbol` constructor, whose values are the +`@@dispose` and `@@asyncDispose` internal symbols: + +**Well-known Symbols** +| Specification Name | \[\[Description]] | Value and Purpose | +|:-|:-|:-| +| _@@dispose_ | *"Symbol.dispose"* | A method that explicitly disposes of resources held by the object. Called by the semantics of `using` declarations and by `DisposableStack` objects. | +| _@@asyncDispose_ | *"Symbol.asyncDispose"* | A method that asynchronosly explicitly disposes of resources held by the object. Called by the semantics of `await using` declarations and by `AsyncDisposableStack` objects. | + +**TypeScript Definition** +```ts +interface SymbolConstructor { + readonly asyncDispose: unique symbol; + readonly dispose: unique symbol; +} +``` + +## The `SuppressedError` Error + +If an exception occurs during resource disposal, it is possible that it might suppress an existing exception thrown +from the body, or from the disposal of another resource. Languages like Java allow you to access a suppressed exception +via a [`getSuppressed()`](https://docs.oracle.com/javase/7/docs/api/java/lang/Throwable.html#getSuppressed()) method on +the exception. However, ECMAScript allows you to throw any value, not just `Error`, so there is no convenient place to +attach a suppressed exception. To better surface these suppressed exceptions and support both logging and error +recovery, this proposal seeks to introduce a new `SuppressedError` built-in `Error` subclass which would contain both +the error that was most recently thrown, as well as the error that was suppressed: + +```js +class SuppressedError extends Error { + /** + * Wraps an error that suppresses another error, and the error that was suppressed. + * @param {*} error The error that resulted in a suppression. + * @param {*} suppressed The error that was suppressed. + * @param {string} message The message for the error. + * @param {{ cause?: * }} [options] Options for the error. + */ + constructor(error, suppressed, message, options); + + /** + * The name of the error (i.e., `"SuppressedError"`). + * @type {string} + */ + name = "SuppressedError"; + + /** + * The error that resulted in a suppression. + * @type {*} + */ + error; + + /** + * The error that was suppressed. + * @type {*} + */ + suppressed; + + /** + * The message for the error. + * @type {*} + */ + message; +} +``` + +We've chosen to use `SuppressedError` over `AggregateError` for several reasons: +- `AggregateError` is designed to hold a list of multiple errors, with no correlation between those errors, while + `SuppressedError` is intended to hold references to two errors with a direct correlation. +- `AggregateError` is intended to ideally hold a flat list of errors. `SuppressedError` is intended to hold a jagged set + of errors (i.e., `e.suppressed.suppressed.suppressed` if there were successive error suppressions). +- The only error correlation on `AggregateError` is through `cause`, however a `SuppressedError` isn't "caused" by the + error it suppresses. In addition, `cause` is intended to be optional, while the `error` of a `SuppressedError` must + always be defined. + +## Built-in Disposables + +### `%IteratorPrototype%.@@dispose()` + +We also propose to add `Symbol.dispose` to the built-in `%IteratorPrototype%` as if it had the following behavior: + +```js +%IteratorPrototype%[Symbol.dispose] = function () { + this.return(); +} +``` + +### `%AsyncIteratorPrototype%.@@asyncDispose()` + +We propose to add `Symbol.asyncDispose` to the built-in `%AsyncIteratorPrototype%` as if it had the following behavior: + +```js +%AsyncIteratorPrototype%[Symbol.asyncDispose] = async function () { + await this.return(); +} +``` + +### Other Possibilities + +We could also consider adding `Symbol.dispose` to such objects as the return value from `Proxy.revocable()`, but that +is currently out of scope for the current proposal. + +## The Common `Disposable` and `AsyncDisposable` Interfaces + +### The `Disposable` Interface + +An object is _disposable_ if it conforms to the following interface: + +| Property | Value | Requirements | +|:-|:-|:-| +| `@@dispose` | A function that performs explicit cleanup. | The function should return `undefined`. | + +**TypeScript Definition** +```ts +interface Disposable { + /** + * Disposes of resources within this object. + */ + [Symbol.dispose](): void; +} +``` + +### The `AsyncDisposable` Interface + +An object is _async disposable_ if it conforms to the following interface: + +| Property | Value | Requirements | +|:-|:-|:-| +| `@@asyncDispose` | An async function that performs explicit cleanup. | The function should return a `Promise`. | + +**TypeScript Definition** +```ts +interface AsyncDisposable { + /** + * Disposes of resources within this object. + */ + [Symbol.asyncDispose](): Promise; +} +``` + +## The `DisposableStack` and `AsyncDisposableStack` container objects + +This proposal adds two global objects that can act as containers to aggregate disposables, guaranteeing that every +disposable resource in the container is disposed when the respective disposal method is called. If any disposable in the +container throws an error during dispose, it would be thrown at the end (possibly wrapped in a `SuppressedError` if +multiple errors were thrown): + +```js +class DisposableStack { + constructor(); + + /** + * Gets a value indicating whether the stack has been disposed. + * @returns {boolean} + */ + get disposed(); + + /** + * Alias for `[Symbol.dispose]()`. + */ + dispose(); + + /** + * Adds a resource to the top of the stack. Has no effect if provided `null` or `undefined`. + * @template {Disposable | null | undefined} T + * @param {T} value - A `Disposable` object, `null`, or `undefined`. + * @returns {T} The provided value. + */ + use(value); + + /** + * Adds a non-disposable resource and a disposal callback to the top of the stack. + * @template T + * @param {T} value - A resource to be disposed. + * @param {(value: T) => void} onDispose - A callback invoked to dispose the provided value. + * @returns {T} The provided value. + */ + adopt(value, onDispose); + + /** + * Adds a disposal callback to the top of the stack. + * @param {() => void} onDispose - A callback to evaluate when this object is disposed. + * @returns {void} + */ + defer(onDispose); + + /** + * Moves all resources currently in this stack into a new `DisposableStack`. + * @returns {DisposableStack} The new `DisposableStack`. + */ + move(); + + /** + * Disposes of resources within this object. + * @returns {void} + */ + [Symbol.dispose](); + + [Symbol.toStringTag]; +} +``` + +`AsyncDisposableStack` is the async version of `DisposableStack` and is a container used to aggregate async disposables, +guaranteeing that every disposable resource in the container is disposed when the respective disposal method is called. +If any disposable in the container throws an error during dispose, or results in a rejected `Promise`, it would be +thrown at the end (possibly wrapped in a `SuppressedError` if multiple errors were thrown): + +These classes provided the following capabilities: +- Aggregation +- Interoperation and customization +- Assist in complex construction + +> **NOTE:** `DisposableStack` is inspired by Python's +> [`ExitStack`](https://docs.python.org/3/library/contextlib.html#contextlib.ExitStack). + +> **NOTE:** `AsyncDisposableStack` is inspired by Python's +> [`AsyncExitStack`](https://docs.python.org/3/library/contextlib.html#contextlib.AsyncExitStack). + +### Aggregation + +The `DisposableStack` and `AsyncDisposableStack` classes provid the ability to aggregate multiple disposable resources +into a single container. When the `DisposableStack` container is disposed, each object in the container is also +guaranteed to be disposed (barring early termination of the program). If any resource throws an error during dispose, +it will be collected and rethrown after all resources are disposed. If there were multiple errors, they will be wrapped +in nested `SuppressedError` objects. + +For example: + +```js +// sync +const stack = new DisposableStack(); +const resource1 = stack.use(getResource1()); +const resource2 = stack.use(getResource2()); +const resource3 = stack.use(getResource3()); +stack[Symbol.dispose](); // disposes of resource3, then resource2, then resource1 +``` + +```js +// async +const stack = new AsyncDisposableStack(); +const resource1 = stack.use(getResource1()); +const resource2 = stack.use(getResource2()); +const resource3 = stack.use(getResource3()); +await stack[Symbol.asyncDispose](); // dispose and await disposal result of resource3, then resource2, then resource1 +``` + +If all of `resource1`, `resource2` and `resource3` were to throw during disposal, this would produce an exception +similar to the following: + +```js +new SuppressedError( + /*error*/ exception_from_resource3_disposal, + /*suppressed*/ new SuppressedError( + /*error*/ exception_from_resource2_disposal, + /*suppressed*/ exception_from_resource1_disposal + ) +) +``` + +### Interoperation and Customization + +The `DisposableStack` and `AsyncDisposableStack` classes also provide the ability to create a disposable resource from a +simple callback. This callback will be executed when the stack's disposal method is executed. + +The ability to create a disposable resource from a callback has several benefits: + +- It allows developers to leverage `using`/`await using` while working with existing resources that do not conform to the + `Symbol.dispose`/`Symbol.asyncDispose` mechanic: + ```js + { + using stack = new DisposableStack(); + const reader = stack.adopt(createReader(), reader => reader.releaseLock()); + ... + } + ``` +- It grants user the ability to schedule other cleanup work to evaluate at the end of the block similar to Go's + `defer` statement: + ```js + function f() { + using stack = new DisposableStack(); + console.log("enter"); + stack.defer(() => console.log("exit")); + ... + } + ``` + +### Assist in Complex Construction + +A user-defined disposable class might need to allocate and track multiple nested resources that should be disposed when +the class instance is disposed. However, properly managing the lifetime of these nested resources in the class +constructor can sometimes be difficult. The `move` method of `DisposableStack`/`AsyncDisposableStack` helps to more +easily manage lifetime in these scenarios: + +```js +// sync +class PluginHost { + #disposed = false; + #disposables; + #channel; + #socket; + + constructor() { + // Create a DisposableStack that is disposed when the constructor exits. + // If construction succeeds, we move everything out of `stack` and into + // `#disposables` to be disposed later. + using stack = new DisposableStack(); + + // Create an IPC adapter around process.send/process.on("message"). + // When disposed, it unsubscribes from process.on("message"). + this.#channel = stack.use(new NodeProcessIpcChannelAdapter(process)); + + // Create a pseudo-websocket that sends and receives messages over + // a NodeJS IPC channel. + this.#socket = stack.use(new NodePluginHostIpcSocket(this.#channel)); + + // If we made it here, then there were no errors during construction and + // we can safely move the disposables out of `stack` and into `#disposables`. + this.#disposables = stack.move(); + + // If construction failed, then `stack` would be disposed before reaching + // the line above. Event handlers would be removed, allowing `#channel` and + // `#socket` to be GC'd. + } + + loadPlugin(file) { + // A disposable should try to ensure access is consistent with its "disposed" state, though this isn't strictly + // necessary since some disposables could be reusable (i.e., a Connection with an `open()` method, etc.). + if (this.#disposed) throw new ReferenceError("Object is disposed."); + // ... + } + + [Symbol.dispose]() { + if (!this.#disposed) { + this.#disposed = true; + const disposables = this.#disposables; + + // NOTE: we can free `#socket` and `#channel` here since they will be disposed by the call to + // `disposables[Symbol.dispose]()`, below. This isn't strictly a requirement for every Disposable, but is + // good housekeeping since these objects will no longer be useable. + this.#socket = undefined; + this.#channel = undefined; + this.#disposables = undefined; + + // Dispose all resources in `disposables` + disposables[Symbol.dispose](); + } + } +} +``` + +```js +// async +const privateConstructorSentinel = {}; + +class AsyncPluginHost { + #disposed = false; + #disposables; + #channel; + #socket; + + /** @private */ + constructor(arg) { + if (arg !== privateConstructorSentinel) throw new TypeError("Use AsyncPluginHost.create() instead"); + } + + // NOTE: there's no such thing as an async constructor + static async create() { + const host = new AsyncPluginHost(privateConstructorSentinel); + + // Create an AsyncDisposableStack that is disposed when the constructor exits. + // If construction succeeds, we move everything out of `stack` and into + // `#disposables` to be disposed later. + await using stack = new AsyncDisposableStack(); + + // Create an IPC adapter around process.send/process.on("message"). + // When disposed, it unsubscribes from process.on("message"). + host.#channel = stack.use(new NodeProcessIpcChannelAdapter(process)); + + // Create a pseudo-websocket that sends and receives messages over + // a NodeJS IPC channel. + host.#socket = stack.use(new NodePluginHostIpcSocket(host.#channel)); + + // If we made it here, then there were no errors during construction and + // we can safely move the disposables out of `stack` and into `#disposables`. + host.#disposables = stack.move(); + + // If construction failed, then `stack` would be asynchronously disposed before reaching + // the line above. Event handlers would be removed, allowing `#channel` and + // `#socket` to be GC'd. + return host; + } + + loadPlugin(file) { + // A disposable should try to ensure access is consistent with its "disposed" state, though this isn't strictly + // necessary since some disposables could be reusable (i.e., a Connection with an `open()` method, etc.). + if (this.#disposed) throw new ReferenceError("Object is disposed."); + // ... + } + + async [Symbol.asyncDispose]() { + if (!this.#disposed) { + this.#disposed = true; + const disposables = this.#disposables; + + // NOTE: we can free `#socket` and `#channel` here since they will be disposed by the call to + // `disposables[Symbol.asyncDispose]()`, below. This isn't strictly a requirement for every disposable, but is + // good housekeeping since these objects will no longer be useable. + this.#socket = undefined; + this.#channel = undefined; + this.#disposables = undefined; + + // Dispose all resources in `disposables` + await disposables[Symbol.asyncDispose](); + } + } +} +``` + +### Subclassing `Disposable` Classes + +You can also use a `DisposableStack` to assist with disposal in a subclass constructor whose superclass is disposable: + +```js +class DerivedPluginHost extends PluginHost { + constructor() { + super(); + + // Create a DisposableStack to cover the subclass constructor. + using stack = new DisposableStack(); + + // Defer a callback to dispose resources on the superclass. We use `defer` so that we can invoke the version of + // `[Symbol.dispose]` on the superclass and not on this or any subclasses. + stack.defer(() => super[Symbol.dispose]()); + + // If any operations throw during subclass construction, the instance will still be disposed, and superclass + // resources will be freed + doSomethingThatCouldPotentiallyThrow(); + + // As the last step before exiting, empty out the DisposableStack so that we don't dispose ourselves. + stack.move(); + } +} +``` + +Here, we can use `stack` to track the result of `super()` (i.e., the `this` value). If any exception occurs during +subclass construction, we can ensure that `[Symbol.dispose]()` is called, freeing resources. If the subclass also needs +to track its own disposable resources, this example is modified slightly: + +```js +class DerivedPluginHostWithOwnDisposables extends PluginHost { + #logger; + #disposables; + + constructor() { + super() + + // Create a DisposableStack to cover the subclass constructor. + using stack = new DisposableStack(); + + // Defer a callback to dispose resources on the superclass. We use `defer` so that we can invoke the version of + // `[Symbol.dispose]` on the superclass and not on this or any subclasses. + stack.defer(() => super[Symbol.dispose]()); + + // Create a logger that uses the file system and add it to our own disposables. + this.#logger = stack.use(new FileLogger()); + + // If any operations throw during subclass construction, the instance will still be disposed, and superclass + // resources will be freed + doSomethingThatCouldPotentiallyThrow(); + + // Persist our own disposables. If construction fails prior to the call to `stack.move()`, our own disposables + // will be disposed before they are set, and then the superclass `[Symbol.dispose]` will be invoked. + this.#disposables = stack.move(); + } + + [Symbol.dispose]() { + this.#logger = undefined; + + // Dispose of our resources and those of our superclass. We do not need to invoke `super[Symbol.dispose]()` since + // that is already tracked by the `stack.defer` call in the constructor. + this.#disposables[Symbol.dispose](); + } +} +``` + +In this example, we can simply add new resources to the `stack` and move its contents into the subclass instance's +`this.#disposables`. In the subclass `[Symbol.dispose]()` method we don't need to call `super[Symbol.dispose]()` since +that has already been tracked by the `stack.defer` call in the constructor. + +# Relation to `Iterator` and `for..of` + +Iterators in ECMAScript also employ a "cleanup" step by way of supplying a `return` method. This means that there is +some similarity between a `using` declaration and a `for..of` statement: + +```js +// using +function f() { + using x = ...; + // use x +} // x is disposed + +// for..of +function makeDisposableScope() { + const resources = []; + let state = 0; + return { + next() { + switch (state) { + case 0: + state++; + return { + done: false, + value: { + use(value) { + resources.unshift(value); + return value; + } + } + }; + case 1: + state++; + for (const value of resources) { + value?.[Symbol.dispose](); + } + default: + state = -1; + return { done: true }; + } + }, + return() { + switch (state) { + case 1: + state++; + for (const value of resources) { + value?.[Symbol.dispose](); + } + default: + state = -1; + return { done: true }; + } + }, + [Symbol.iterator]() { return this; } + } +} + +function f() { + for (const { use } of makeDisposableScope()) { + const x = use(...); + // use x + } // x is disposed +} +``` + +However there are a number drawbacks to using `for..of` as an alternative: + +- Exceptions in the body are swallowed by exceptions from disposables. +- `for..of` implies iteration, which can be confusing when reading code. +- Conflating `for..of` and resource management could make it harder to find documentation, examples, StackOverflow + answers, etc. +- A `for..of` implementation like the one above cannot control the scope of `use`, which can make lifetimes confusing: + ```js + for (const { use } of ...) { + const x = use(...); // ok + setImmediate(() => { + const y = use(...); // wrong lifetime + }); + } + ``` +- Significantly more boilerplate compared to `using`. +- Mandates introduction of a new block scope, even at the top level of a function body. +- Control flow analysis of a `for..of` loop cannot infer definite assignment since a loop could potentially have zero + elements: + ```js + // using + function f1() { + /** @type {string | undefined} */ + let x; + { + using y = ...; + x = y.text; + } + x.toString(); // x is definitely assigned + } + + // for..of + function f2() { + /** @type {string | undefined} */ + let x; + for (const { use } of ...) { + const y = use(...); + x = y.text; + } + x.toString(); // possibly an error in a static analyzer since `x` is not guaranteed to have been assigned. + } + ``` +- Using `continue` and `break` is more difficult if you need to dispose of an iterated value: + ```js + // using + for (using x of iterable) { + if (!x.ready) continue; + if (x.done) break; + ... + } + + // for..of + outer: for (const x of iterable) { + for (const { use } of ...) { + use(x); + if (!x.ready) continue outer; + if (!x.done) break outer; + ... + } + } + ``` + +# Relation to DOM APIs + +This proposal does not necessarily require immediate support in the HTML DOM specification, as existing APIs can still +be adapted by using `DisposableStack` or `AsyncDisposableStack`. However, there are a number of APIs that could benefit +from this proposal and should be considered by the relevant standards bodies. The following is by no means a complete +list, and primarily offers suggestions for consideration. The actual implementation is at the discretion of the relevant +standards bodies. + +- `AudioContext` — `@@asyncDispose()` as an alias or [wrapper][] for `close()`. + - NOTE: `close()` here is asynchronous, but uses the same name as similar synchronous methods on other objects. +- `BroadcastChannel` — `@@dispose()` as an alias or [wrapper][] for `close()`. +- `EventSource` — `@@dispose()` as an alias or [wrapper][] for `close()`. +- `FileReader` — `@@dispose()` as an alias or [wrapper][] for `abort()`. +- `IDbTransaction` — `@@dispose()` could invoke `abort()` if the transaction is still in the active state: + ```js + { + using tx = db.transaction(storeNames); + // ... + if (...) throw new Error(); + // ... + tx.commit(); + } // implicit tx.abort() if we don't reach the explicit tx.commit() + ``` +- `ImageBitmap` — `@@dispose()` as an alias or [wrapper][] for `close()`. +- `IntersectionObserver` — `@@dispose()` as an alias or [wrapper][] for `disconnect()`. +- `MediaKeySession` — `@@asyncDispose()` as an alias or [wrapper][] for `close()`. + - NOTE: `close()` here is asynchronous, but uses the same name as similar synchronous methods on other objects. +- `MessagePort` — `@@dispose()` as an alias or [wrapper][] for `close()`. +- `MutationObserver` — `@@dispose()` as an alias or [wrapper][] for `disconnect()`. +- `PaymentRequest` — `@@asyncDispose()` could invoke `abort()` if the payment is still in the active state. + - NOTE: `abort()` here is asynchronous, but uses the same name as similar synchronous methods on other objects. +- `PerformanceObserver` — `@@dispose()` as an alias or [wrapper][] for `disconnect()`. +- `PushSubscription` — `@@asyncDispose()` as an alias or [wrapper][] for `unsubscribe()`. +- `ReadableStream` — `@@asyncDispose()` as an alias or [wrapper][] for `cancel()`. +- `ReadableStreamDefaultReader` — Either `@@dispose()` as an alias or [wrapper][] for `releaseLock()`, or + `@@asyncDispose()` as a [wrapper][] for `cancel()` (but probably not both). +- `RTCPeerConnection` — `@@dispose()` as an alias or [wrapper][] for `close()`. +- `RTCRtpTransceiver` — `@@dispose()` as an alias or [wrapper][] for `stop()`. +- `ReadableStreamDefaultController` — `@@dispose()` as an alias or [wrapper][] for `close()`. +- `ReadableStreamDefaultReader` — Either `@@dispose()` as an alias or [wrapper][] for `releaseLock()`, or +- `ResizeObserver` — `@@dispose()` as an alias or [wrapper][] for `disconnect()`. +- `ServiceWorkerRegistration` — `@@asyncDispose()` as a [wrapper][] for `unregister()`. +- `SourceBuffer` — `@@dispose()` as a [wrapper][] for `abort()`. +- `TransformStreamDefaultController` — `@@dispose()` as an alias or [wrapper][] for `terminate()`. +- `WebSocket` — `@@dispose()` as a [wrapper][] for `close()`. +- `Worker` — `@@dispose()` as an alias or [wrapper][] for `terminate()`. +- `WritableStream` — `@@asyncDispose()` as an alias or [wrapper][] for `close()`. + - NOTE: `close()` here is asynchronous, but uses the same name as similar synchronous methods on other objects. +- `WritableStreamDefaultWriter` — Either `@@dispose()` as an alias or [wrapper][] for `releaseLock()`, or + `@@asyncDispose()` as a [wrapper][] for `close()` (but probably not both). +- `XMLHttpRequest` — `@@dispose()` as an alias or [wrapper][] for `abort()`. + +In addition, several new APIs could be considered that leverage this functionality: + +- `EventTarget.prototype.addEventListener(type, listener, { subscription: true }) -> Disposable` — An option + passed to `addEventListener` could + return a `Disposable` that removes the event listener when disposed. +- `Performance.prototype.measureBlock(measureName, options) -> Disposable` — Combines `mark` and `measure` into a + block-scoped disposable: + ```js + function f() { + using measure = performance.measureBlock("f"); // marks on entry + // ... + } // marks and measures on exit + ``` +- `SVGSVGElement` — A new method producing a [single-use disposer][] for `pauseAnimations()` and `unpauseAnimations()`. +- `ScreenOrientation` — A new method producing a [single-use disposer][] for `lock()` and `unlock()`. + +### Definitions + +A _wrapper for `x()`_ is a method that invokes `x()`, but only if the object is in a state +such that calling `x()` will not throw as a result of repeated evaluation. + +A _callback-adapting wrapper_ is a _wrapper_ that adapts a continuation passing-style method +that accepts a callback into a `Promise`-producing method. + +A _single-use disposer for `x()` and `y()`_ indicates a newly constructed disposable object +that invokes `x()` when constructed and `y()` when disposed the first time (and does nothing if the object is disposed +more than once). + +# Relation to NodeJS APIs + +This proposal does not necessarily require immediate support in NodeJS, as existing APIs can still be adapted by using +`DisposableStack` or `AsyncDisposableStack`. However, there are a number of APIs that could benefit from this proposal +and should be considered by the NodeJS maintainers. The following is by no means a complete list, and primarily offers +suggestions for consideration. The actual implementation is at the discretion of the NodeJS maintainers. + +- Anything with `ref()` and `unref()` methods — A new method or API that produces a [single-use disposer][] for + `ref()` and `unref()`. +- Anything with `cork()` and `uncork()` methods — A new method or API that produces a [single-use disposer][] for + `cork()` and `uncork()`. +- `async_hooks.AsyncHook` — either `@@dispose()` as an alias or [wrapper][] for `disable()`, or a new method that + produces a [single-use disposer][] for `enable()` and `disable()`. +- `child_process.ChildProcess` — `@@dispose()` as an alias or [wrapper][] for `kill()`. +- `cluster.Worker` — `@@dispose()` as an alias or [wrapper][] for `kill()`. +- `crypto.Cipher`, `crypto.Decipher` — `@@dispose()` as a [wrapper][] for `final()`. +- `crypto.Hash`, `crypto.Hmac` — `@@dispose()` as a [wrapper][] for `digest()`. +- `dns.Resolver`, `dnsPromises.Resolver` — `@@dispose()` as an alias or [wrapper][] for `cancel()`. +- `domain.Domain` — A new method or API that produces a [single-use disposer][] for `enter()` and `exit()`. +- `events.EventEmitter` — A new method or API that produces a [single-use disposer][] for `on()` and `off()`. +- `fs.promises.FileHandle` — `@@asyncDispose()` as an alias or [wrapper][] for `close()`. +- `fs.Dir` — `@@asyncDispose()` as an alias or [wrapper][] for `close()`, `@@dispose()` as an alias or [wrapper][] + for `closeSync()`. +- `fs.FSWatcher` — `@@dispose()` as an alias or [wrapper][] for `close()`. +- `http.Agent` — `@@dispose()` as an alias or [wrapper][] for `destroy()`. +- `http.ClientRequest` — Either `@@dispose()` or `@@asyncDispose()` as an alias or [wrapper][] for `destroy()`. +- `http.Server` — `@@asyncDispose()` as a [callback-adapting wrapper][] for `close()`. +- `http.ServerResponse` — `@@asyncDispose()` as a [callback-adapting wrapper][] for `end()`. +- `http.IncomingMessage` — Either `@@dispose()` or `@@asyncDispose()` as an alias or [wrapper][] for `destroy()`. +- `http.OutgoingMessage` — Either `@@dispose()` or `@@asyncDispose()` as an alias or [wrapper][] for `destroy()`. +- `http2.Http2Session` — `@@asyncDispose()` as a [callback-adapting wrapper][] for `close()`. +- `http2.Http2Stream` — `@@asyncDispose()` as a [callback-adapting wrapper][] for `close()`. +- `http2.Http2Server` — `@@asyncDispose()` as a [callback-adapting wrapper][] for `close()`. +- `http2.Http2SecureServer` — `@@asyncDispose()` as a [callback-adapting wrapper][] for `close()`. +- `http2.Http2ServerRequest` — Either `@@dispose()` or `@@asyncDispose()` as an alias or [wrapper][] for + `destroy()`. +- `http2.Http2ServerResponse` — `@@asyncDispose()` as a [callback-adapting wrapper][] for `end()`. +- `https.Server` — `@@asyncDispose()` as a [callback-adapting wrapper][] for `close()`. +- `inspector` — A new API that produces a [single-use disposer][] for `open()` and `close()`. +- `stream.Writable` — Either `@@dispose()` or `@@asyncDispose()` as an alias or [wrapper][] for `destroy()` or + `@@asyncDispose` only as a [callback-adapting wrapper][] for `end()` (depending on whether the disposal behavior + should be to drop immediately or to flush any pending writes). +- `stream.Readable` — Either `@@dispose()` or `@@asyncDispose()` as an alias or [wrapper][] for `destroy()`. +- ... and many others in `net`, `readline`, `tls`, `udp`, and `worker_threads`. + +## Linked Issue #1 — Async using syntax + +I've seen different syntax suggestions related to async disposal spread over different issues, in particular tc39/proposal-explicit-resource-management#16 tc39/proposal-explicit-resource-management#76 tc39/proposal-explicit-resource-management#84 tc39/proposal-async-explicit-resource-management#4. I wanted to concentrate the discussion in a single issue. + +I'd first like to discuss the ongoing assumption that `using` an async-disposable requires specific syntax. +The way I model the `using` syntax is that a block containing a `using` declaration implicitly creates a `DisposableStack`. Every `using` declaration implicitly results in a `.use()` on the stack, and that exiting the block implicitly calls `[Symbol.dispose]()` on the stack. + +Now if we assume that we have a concept of "async blocks", instead of a `DisposableStack` being implicitly created, it'd be an `AsyncDisposableStack`. At that point any `using` declaration would similarly call the `.use()` of the implicit async disposable stack, which is a synchronous operation, and it's the exit of the "async block" which awaits the `[Symbol.asyncDispose]()` call. + +As such I would be against any syntax that uses the `await` keyword for the `using` declaration, as nothing is awaited at the declaration time. Similarly I would be against any syntax that doesn't use the `await` keyword on the block as a marker of interleaving. I would be ok with a `async using` declaration to be explicit, but I would consider that unnecessary verbosity. + +Given the mental model above, I believe it would be entirely natural that `for await (using r of ...)`, and `using` declarations inside `for-await-of` blocks in general, would implicitly use an `AsyncDisposableStack`. `for-await-of` is conceptually the only "async block" in the language at the moment. Then it become a matter of specifying what the syntax of an "async block" not tied to iteration looks like. + +*Source: https://github.com/tc39/proposal-async-explicit-resource-management/issues/1* diff --git a/TypeScript_2/solution/solution.patch b/TypeScript_2/solution/solution.patch new file mode 100644 index 0000000000000000000000000000000000000000..cbb332f27e4d0bfdffec6a29fc48a2ebc32806f1 --- /dev/null +++ b/TypeScript_2/solution/solution.patch @@ -0,0 +1,6680 @@ +diff --git a/src/compiler/_namespaces/ts.ts b/src/compiler/_namespaces/ts.ts +index 5a01767f9..34d731e88 100644 +--- a/src/compiler/_namespaces/ts.ts ++++ b/src/compiler/_namespaces/ts.ts +@@ -33,6 +33,8 @@ export * from "../visitorPublic"; + export * from "../sourcemap"; + export * from "../transformers/utilities"; + export * from "../transformers/destructuring"; ++export * from "../transformers/classThis"; ++export * from "../transformers/namedEvaluation"; + export * from "../transformers/taggedTemplate"; + export * from "../transformers/ts"; + export * from "../transformers/classFields"; +diff --git a/src/compiler/binder.ts b/src/compiler/binder.ts +index 4ebea0c52..21122302c 100644 +--- a/src/compiler/binder.ts ++++ b/src/compiler/binder.ts +@@ -3727,7 +3727,7 @@ function isExecutableStatement(s: Statement): boolean { + // Don't remove statements that can validly be used before they appear. + return !isFunctionDeclaration(s) && !isPurelyTypeDeclaration(s) && !isEnumDeclaration(s) && + // `var x;` may declare a variable used above +- !(isVariableStatement(s) && !(getCombinedNodeFlags(s) & (NodeFlags.Let | NodeFlags.Const)) && s.declarationList.declarations.some(d => !d.initializer)); ++ !(isVariableStatement(s) && !(getCombinedNodeFlags(s) & (NodeFlags.BlockScoped)) && s.declarationList.declarations.some(d => !d.initializer)); + } + + function isPurelyTypeDeclaration(s: Statement): boolean { +diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts +index bbda1c576..31a927d63 100644 +--- a/src/compiler/checker.ts ++++ b/src/compiler/checker.ts +@@ -609,7 +609,6 @@ import { + isKnownSymbol, + isLateVisibilityPaintedStatement, + isLeftHandSideExpression, +- isLet, + isLineBreak, + isLiteralComputedPropertyDeclarationName, + isLiteralExpression, +@@ -734,7 +733,6 @@ import { + isValidESSymbolDeclaration, + isValidTypeOnlyAliasUseSite, + isValueSignatureDeclaration, +- isVarConst, + isVariableDeclaration, + isVariableDeclarationInitializedToBareOrAccessedRequire, + isVariableDeclarationInVariableStatement, +@@ -1471,6 +1469,11 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { + /** This will be set during calls to `getResolvedSignature` where services determines an apparent number of arguments greater than what is actually provided. */ + var apparentArgumentCount: number | undefined; + ++ var lastGetCombinedNodeFlagsNode: Node | undefined; ++ var lastGetCombinedNodeFlagsResult = NodeFlags.None; ++ var lastGetCombinedModifierFlagsNode: Declaration | undefined; ++ var lastGetCombinedModifierFlagsResult = ModifierFlags.None; ++ + // for public members that accept a Node or one of its subtypes, we must guard against + // synthetic nodes created during transformations by calling `getParseTreeNode`. + // for most of these, we perform the guard only on `checker` to avoid any possible +@@ -2115,6 +2118,8 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { + var deferredGlobalImportMetaType: ObjectType; + var deferredGlobalImportMetaExpressionType: ObjectType; + var deferredGlobalImportCallOptionsType: ObjectType | undefined; ++ var deferredGlobalDisposableType: ObjectType | undefined; ++ var deferredGlobalAsyncDisposableType: ObjectType | undefined; + var deferredGlobalExtractSymbol: Symbol | undefined; + var deferredGlobalOmitSymbol: Symbol | undefined; + var deferredGlobalAwaitedSymbol: Symbol | undefined; +@@ -2395,7 +2400,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { + } + + function isDeprecatedDeclaration(declaration: Declaration) { +- return !!(getCombinedNodeFlags(declaration) & NodeFlags.Deprecated); ++ return !!(getCombinedNodeFlagsCached(declaration) & NodeFlags.Deprecated); + } + + function addDeprecatedSuggestion(location: Node, declarations: Node[], deprecatedEntity: string) { +@@ -8682,7 +8687,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { + ? symbol.parent?.valueDeclaration && isSourceFile(symbol.parent?.valueDeclaration) + ? NodeFlags.Const // exports are immutable in es6, which is what we emulate and check; so it's safe to mark all exports as `const` (there's no difference to consumers, but it allows unique symbol type declarations) + : undefined +- : isConstVariable(symbol) ++ : isConstantVariable(symbol) + ? NodeFlags.Const + : NodeFlags.Let; + const name = (needsPostExportDefault || !(symbol.flags & SymbolFlags.Property)) ? localName : getUnusedName(localName, symbol); +@@ -9957,7 +9962,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { + } + const parent = getDeclarationContainer(node); + // If the node is not exported or it is not ambient module element (except import declaration) +- if (!(getCombinedModifierFlags(node as Declaration) & ModifierFlags.Export) && ++ if (!(getCombinedModifierFlagsCached(node as Declaration) & ModifierFlags.Export) && + !(node.kind !== SyntaxKind.ImportEqualsDeclaration && parent.kind !== SyntaxKind.SourceFile && parent.flags & NodeFlags.Ambient)) { + return isGlobalSourceFile(parent); + } +@@ -10483,11 +10488,11 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { + + if ((noImplicitAny || isInJSFile(declaration)) && + isVariableDeclaration(declaration) && !isBindingPattern(declaration.name) && +- !(getCombinedModifierFlags(declaration) & ModifierFlags.Export) && !(declaration.flags & NodeFlags.Ambient)) { ++ !(getCombinedModifierFlagsCached(declaration) & ModifierFlags.Export) && !(declaration.flags & NodeFlags.Ambient)) { + // If --noImplicitAny is on or the declaration is in a Javascript file, + // use control flow tracked 'any' type for non-ambient, non-exported var or let variables with no + // initializer or a 'null' or 'undefined' initializer. +- if (!(getCombinedNodeFlags(declaration) & NodeFlags.Const) && (!declaration.initializer || isNullOrUndefined(declaration.initializer))) { ++ if (!(getCombinedNodeFlagsCached(declaration) & NodeFlags.Constant) && (!declaration.initializer || isNullOrUndefined(declaration.initializer))) { + return autoType; + } + // Use control flow tracked 'any[]' type for non-ambient, non-exported variables with an empty array +@@ -15836,6 +15841,14 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { + return (deferredGlobalIteratorReturnResultType ||= getGlobalType("IteratorReturnResult" as __String, /*arity*/ 1, reportErrors)) || emptyGenericType; + } + ++ function getGlobalDisposableType(reportErrors: boolean) { ++ return (deferredGlobalDisposableType ||= getGlobalType("Disposable" as __String, /*arity*/ 0, reportErrors)) || emptyObjectType; ++ } ++ ++ function getGlobalAsyncDisposableType(reportErrors: boolean) { ++ return (deferredGlobalAsyncDisposableType ||= getGlobalType("AsyncDisposable" as __String, /*arity*/ 0, reportErrors)) || emptyObjectType; ++ } ++ + function getGlobalTypeOrUndefined(name: __String, arity = 0): ObjectType | undefined { + const symbol = getGlobalSymbol(name, SymbolFlags.Type, /*diagnostic*/ undefined); + return symbol && getTypeOfGlobalSymbol(symbol, arity) as GenericType; +@@ -17316,7 +17329,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { + if (isCallLikeExpression(parent)) { + return isCallOrNewExpression(parent) && isIdentifier(node) && hasMatchingArgument(parent, node); + } +- return every(symbol.declarations, d => !isFunctionLike(d) || !!(getCombinedNodeFlags(d) & NodeFlags.Deprecated)); ++ return every(symbol.declarations, d => !isFunctionLike(d) || isDeprecatedDeclaration(d)); + } + return true; + } +@@ -25475,7 +25488,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { + + function tryGetNameFromEntityNameExpression(node: EntityNameOrEntityNameExpression) { + const symbol = resolveEntityName(node, SymbolFlags.Value, /*ignoreErrors*/ true); +- if (!symbol || !(isConstVariable(symbol) || (symbol.flags & SymbolFlags.EnumMember))) return undefined; ++ if (!symbol || !(isConstantVariable(symbol) || (symbol.flags & SymbolFlags.EnumMember))) return undefined; + + const declaration = symbol.valueDeclaration; + if (declaration === undefined) return undefined; +@@ -26490,7 +26503,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { + case SyntaxKind.Identifier: + if (!isThisInTypeQuery(node)) { + const symbol = getResolvedSymbol(node as Identifier); +- return isConstVariable(symbol) || isParameterOrCatchClauseVariable(symbol) && !isSymbolAssigned(symbol); ++ return isConstantVariable(symbol) || isParameterOrCatchClauseVariable(symbol) && !isSymbolAssigned(symbol); + } + break; + case SyntaxKind.PropertyAccessExpression: +@@ -26674,7 +26687,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { + } + // A matching dotted name might also be an expando property on a function *expression*, + // in which case we continue control flow analysis back to the function's declaration +- if (isVariableDeclaration(node) && (isInJSFile(node) || isVarConst(node))) { ++ if (isVariableDeclaration(node) && (isInJSFile(node) || isVarConstLike(node))) { + const init = getDeclaredExpandoInitializer(node); + if (init && (init.kind === SyntaxKind.FunctionExpression || init.kind === SyntaxKind.ArrowFunction)) { + return getTypeAtFlowNode(flow.antecedent); +@@ -26983,7 +26996,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { + } + else if (isIdentifier(expr)) { + const symbol = getResolvedSymbol(expr); +- if (isConstVariable(symbol)) { ++ if (isConstantVariable(symbol)) { + const declaration = symbol.valueDeclaration!; + // Given 'const x = obj.kind', allow 'x' as an alias for 'obj.kind' + if (isVariableDeclaration(declaration) && !declaration.type && declaration.initializer && isAccessExpression(declaration.initializer) && +@@ -27575,7 +27588,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { + // up to five levels of aliased conditional expressions that are themselves declared as const variables. + if (!isMatchingReference(reference, expr) && inlineLevel < 5) { + const symbol = getResolvedSymbol(expr as Identifier); +- if (isConstVariable(symbol)) { ++ if (isConstantVariable(symbol)) { + const declaration = symbol.valueDeclaration; + if (declaration && isVariableDeclaration(declaration) && !declaration.type && declaration.initializer && isConstantReference(reference)) { + inlineLevel++; +@@ -27691,8 +27704,8 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { + } + } + +- function isConstVariable(symbol: Symbol) { +- return symbol.flags & SymbolFlags.Variable && (getDeclarationNodeFlagsFromSymbol(symbol) & NodeFlags.Const) !== 0; ++ function isConstantVariable(symbol: Symbol) { ++ return symbol.flags & SymbolFlags.Variable && (getDeclarationNodeFlagsFromSymbol(symbol) & NodeFlags.Constant) !== 0; + } + + function parameterInitializerContainsUndefined(declaration: ParameterDeclaration): boolean { +@@ -27847,7 +27860,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { + // destructuring from the narrowed parent type. + if (isBindingElement(declaration) && !declaration.initializer && !declaration.dotDotDotToken && declaration.parent.elements.length >= 2) { + const parent = declaration.parent.parent; +- if (parent.kind === SyntaxKind.VariableDeclaration && getCombinedNodeFlags(declaration) & NodeFlags.Const || parent.kind === SyntaxKind.Parameter) { ++ if (parent.kind === SyntaxKind.VariableDeclaration && getCombinedNodeFlagsCached(declaration) & NodeFlags.Constant || parent.kind === SyntaxKind.Parameter) { + const links = getNodeLinks(parent); + if (!(links.flags & NodeCheckFlags.InCheckIdentifier)) { + links.flags |= NodeCheckFlags.InCheckIdentifier; +@@ -28053,7 +28066,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { + // analysis to include the immediately enclosing function. + while (flowContainer !== declarationContainer && (flowContainer.kind === SyntaxKind.FunctionExpression || + flowContainer.kind === SyntaxKind.ArrowFunction || isObjectLiteralOrClassExpressionMethodOrAccessor(flowContainer)) && +- (isConstVariable(localOrExportSymbol) && type !== autoArrayType || isParameter && !isSymbolAssigned(localOrExportSymbol))) { ++ (isConstantVariable(localOrExportSymbol) && type !== autoArrayType || isParameter && !isSymbolAssigned(localOrExportSymbol))) { + flowContainer = getControlFlowContainer(flowContainer); + } + // We only look for uninitialized variables in strict null checking mode, and only when we can analyze +@@ -31083,7 +31096,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { + } + + function getDeclarationNodeFlagsFromSymbol(s: Symbol): NodeFlags { +- return s.valueDeclaration ? getCombinedNodeFlags(s.valueDeclaration) : 0; ++ return s.valueDeclaration ? getCombinedNodeFlagsCached(s.valueDeclaration) : 0; + } + + /** +@@ -31611,7 +31624,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { + if (compilerOptions.noPropertyAccessFromIndexSignature && isPropertyAccessExpression(node)) { + error(right, Diagnostics.Property_0_comes_from_an_index_signature_so_it_must_be_accessed_with_0, unescapeLeadingUnderscores(right.escapedText)); + } +- if (indexInfo.declaration && getCombinedNodeFlags(indexInfo.declaration) & NodeFlags.Deprecated) { ++ if (indexInfo.declaration && isDeprecatedDeclaration(indexInfo.declaration)) { + addDeprecatedSuggestion(right, [indexInfo.declaration], right.escapedText as string); + } + } +@@ -31716,7 +31729,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { + && !isOptionalPropertyDeclaration(valueDeclaration) + && !(isAccessExpression(node) && isAccessExpression(node.expression)) + && !isBlockScopedNameDeclaredBeforeUse(valueDeclaration, right) +- && !(isMethodDeclaration(valueDeclaration) && getCombinedModifierFlags(valueDeclaration) & ModifierFlags.Static) ++ && !(isMethodDeclaration(valueDeclaration) && getCombinedModifierFlagsCached(valueDeclaration) & ModifierFlags.Static) + && (compilerOptions.useDefineForClassFields || !isPropertyDeclaredInAncestorClass(prop))) { + diagnosticMessage = error(right, Diagnostics.Property_0_is_used_before_its_initialization, declarationName); + } +@@ -34241,7 +34254,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { + let name: Expression | BindingName | undefined; + let decl: Node | undefined; + if (isVariableDeclaration(node.parent) && node.parent.initializer === node) { +- if (!isInJSFile(node) && !(isVarConst(node.parent) && isFunctionLikeDeclaration(node))) { ++ if (!isInJSFile(node) && !(isVarConstLike(node.parent) && isFunctionLikeDeclaration(node))) { + return undefined; + } + name = node.parent.name; +@@ -36079,7 +36092,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { + // Unions and intersections of the above (unions and intersections eagerly set isReadonly on creation) + return !!(getCheckFlags(symbol) & CheckFlags.Readonly || + symbol.flags & SymbolFlags.Property && getDeclarationModifierFlagsFromSymbol(symbol) & ModifierFlags.Readonly || +- symbol.flags & SymbolFlags.Variable && getDeclarationNodeFlagsFromSymbol(symbol) & NodeFlags.Const || ++ symbol.flags & SymbolFlags.Variable && getDeclarationNodeFlagsFromSymbol(symbol) & NodeFlags.Constant || + symbol.flags & SymbolFlags.Accessor && !(symbol.flags & SymbolFlags.SetAccessor) || + symbol.flags & SymbolFlags.EnumMember || + some(symbol.declarations, isReadonlyAssignmentDeclaration) +@@ -36185,11 +36198,16 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { + return undefinedWideningType; + } + +- function checkAwaitExpressionGrammar(node: AwaitExpression): void { ++ function checkAwaitGrammar(node: AwaitExpression | VariableDeclarationList): boolean { + // Grammar checking ++ let hasError = false; + const container = getContainingFunctionOrClassStaticBlock(node); + if (container && isClassStaticBlockDeclaration(container)) { +- error(node, Diagnostics.Await_expression_cannot_be_used_inside_a_class_static_block); ++ // NOTE: We report this regardless as to whether there are parse diagnostics. ++ const message = isAwaitExpression(node) ? Diagnostics.await_expression_cannot_be_used_inside_a_class_static_block : ++ Diagnostics.await_using_statements_cannot_be_used_inside_a_class_static_block; ++ error(node, message); ++ hasError = true; + } + else if (!(node.flags & NodeFlags.AwaitContext)) { + if (isInTopLevelContext(node)) { +@@ -36198,9 +36216,11 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { + let span: TextSpan | undefined; + if (!isEffectiveExternalModule(sourceFile, compilerOptions)) { + span ??= getSpanOfTokenAtPosition(sourceFile, node.pos); +- const diagnostic = createFileDiagnostic(sourceFile, span.start, span.length, +- Diagnostics.await_expressions_are_only_allowed_at_the_top_level_of_a_file_when_that_file_is_a_module_but_this_file_has_no_imports_or_exports_Consider_adding_an_empty_export_to_make_this_file_a_module); ++ const message = isAwaitExpression(node) ? Diagnostics.await_expressions_are_only_allowed_at_the_top_level_of_a_file_when_that_file_is_a_module_but_this_file_has_no_imports_or_exports_Consider_adding_an_empty_export_to_make_this_file_a_module : ++ Diagnostics.await_using_statements_are_only_allowed_at_the_top_level_of_a_file_when_that_file_is_a_module_but_this_file_has_no_imports_or_exports_Consider_adding_an_empty_export_to_make_this_file_a_module; ++ const diagnostic = createFileDiagnostic(sourceFile, span.start, span.length, message); + diagnostics.add(diagnostic); ++ hasError = true; + } + switch (moduleKind) { + case ModuleKind.Node16: +@@ -36210,6 +36230,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { + diagnostics.add( + createFileDiagnostic(sourceFile, span.start, span.length, Diagnostics.The_current_file_is_a_CommonJS_module_and_cannot_use_await_at_the_top_level) + ); ++ hasError = true; + break; + } + // fallthrough +@@ -36222,11 +36243,10 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { + // fallthrough + default: + span ??= getSpanOfTokenAtPosition(sourceFile, node.pos); +- diagnostics.add( +- createFileDiagnostic(sourceFile, span.start, span.length, +- Diagnostics.Top_level_await_expressions_are_only_allowed_when_the_module_option_is_set_to_es2022_esnext_system_node16_or_nodenext_and_the_target_option_is_set_to_es2017_or_higher +- ) +- ); ++ const message = isAwaitExpression(node) ? Diagnostics.Top_level_await_expressions_are_only_allowed_when_the_module_option_is_set_to_es2022_esnext_system_node16_or_nodenext_and_the_target_option_is_set_to_es2017_or_higher : ++ Diagnostics.Top_level_await_using_statements_are_only_allowed_when_the_module_option_is_set_to_es2022_esnext_system_node16_or_nodenext_and_the_target_option_is_set_to_es2017_or_higher; ++ diagnostics.add(createFileDiagnostic(sourceFile, span.start, span.length, message)); ++ hasError = true; + break; + } + } +@@ -36236,23 +36256,30 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { + const sourceFile = getSourceFileOfNode(node); + if (!hasParseDiagnostics(sourceFile)) { + const span = getSpanOfTokenAtPosition(sourceFile, node.pos); +- const diagnostic = createFileDiagnostic(sourceFile, span.start, span.length, Diagnostics.await_expressions_are_only_allowed_within_async_functions_and_at_the_top_levels_of_modules); ++ const message = isAwaitExpression(node) ? Diagnostics.await_expressions_are_only_allowed_within_async_functions_and_at_the_top_levels_of_modules : ++ Diagnostics.await_using_statements_are_only_allowed_within_async_functions_and_at_the_top_levels_of_modules; ++ const diagnostic = createFileDiagnostic(sourceFile, span.start, span.length, message); + if (container && container.kind !== SyntaxKind.Constructor && (getFunctionFlags(container) & FunctionFlags.Async) === 0) { + const relatedInfo = createDiagnosticForNode(container, Diagnostics.Did_you_mean_to_mark_this_function_as_async); + addRelatedInfo(diagnostic, relatedInfo); + } + diagnostics.add(diagnostic); ++ hasError = true; + } + } + } + +- if (isInParameterInitializerBeforeContainingFunction(node)) { ++ if (isAwaitExpression(node) && isInParameterInitializerBeforeContainingFunction(node)) { ++ // NOTE: We report this regardless as to whether there are parse diagnostics. + error(node, Diagnostics.await_expressions_cannot_be_used_in_a_parameter_initializer); ++ hasError = true; + } ++ ++ return hasError; + } + + function checkAwaitExpression(node: AwaitExpression): Type { +- addLazyDiagnostic(() => checkAwaitExpressionGrammar(node)); ++ addLazyDiagnostic(() => checkAwaitGrammar(node)); + + const operandType = checkExpression(node.expression); + const awaitedType = checkAwaitedType(operandType, /*withAlias*/ true, node, Diagnostics.Type_of_await_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member); +@@ -37536,7 +37563,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { + } + + function widenTypeInferredFromInitializer(declaration: HasExpressionInitializer, type: Type) { +- const widened = getCombinedNodeFlags(declaration) & NodeFlags.Const || isDeclarationReadonly(declaration) ? type : getWidenedLiteralType(type); ++ const widened = getCombinedNodeFlagsCached(declaration) & NodeFlags.Constant || isDeclarationReadonly(declaration) ? type : getWidenedLiteralType(type); + if (isInJSFile(declaration)) { + if (isEmptyLiteralType(widened)) { + reportImplicitAny(declaration, anyType); +@@ -39031,7 +39058,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { + } + + function getEffectiveDeclarationFlags(n: Declaration, flagsToCheck: ModifierFlags): ModifierFlags { +- let flags = getCombinedModifierFlags(n); ++ let flags = getCombinedModifierFlagsCached(n); + + // children of classes (even ambient classes) should not be marked as ambient or export + // because those flags have no useful semantics there. +@@ -40590,7 +40617,11 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { + } + } + else if (isVariableDeclaration(declaration)) { +- addToGroup(unusedVariables, declaration.parent, declaration, getNodeId); ++ const blockScopeKind = getCombinedNodeFlagsCached(declaration) & NodeFlags.BlockScoped; ++ const name = getNameOfDeclaration(declaration); ++ if (blockScopeKind !== NodeFlags.Using && blockScopeKind !== NodeFlags.AwaitUsing || !name || !isIdentifierThatStartsWithUnderscore(name)) { ++ addToGroup(unusedVariables, declaration.parent, declaration, getNodeId); ++ } + } + else { + const parameter = local.valueDeclaration && tryGetRootParameterDeclaration(local.valueDeclaration); +@@ -40943,7 +40974,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { + // } + + // skip block-scoped variables and parameters +- if ((getCombinedNodeFlags(node) & NodeFlags.BlockScoped) !== 0 || isParameterDeclaration(node)) { ++ if ((getCombinedNodeFlagsCached(node) & NodeFlags.BlockScoped) !== 0 || isParameterDeclaration(node)) { + return; + } + +@@ -41119,7 +41150,24 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { + (initializer.properties.length === 0 || isPrototypeAccess(node.name)) && + !!symbol.exports?.size; + if (!isJSObjectLiteralInitializer && node.parent.parent.kind !== SyntaxKind.ForInStatement) { +- checkTypeAssignableToAndOptionallyElaborate(checkExpressionCached(initializer), type, node, initializer, /*headMessage*/ undefined); ++ const initializerType = checkExpressionCached(initializer); ++ checkTypeAssignableToAndOptionallyElaborate(initializerType, type, node, initializer, /*headMessage*/ undefined); ++ const blockScopeKind = getCombinedNodeFlagsCached(node) & NodeFlags.BlockScoped; ++ if (blockScopeKind === NodeFlags.AwaitUsing) { ++ const globalAsyncDisposableType = getGlobalAsyncDisposableType(/*reportErrors*/ true); ++ const globalDisposableType = getGlobalDisposableType(/*reportErrors*/ true); ++ if (globalAsyncDisposableType !== emptyObjectType && globalDisposableType !== emptyObjectType) { ++ const optionalDisposableType = getUnionType([globalAsyncDisposableType, globalDisposableType, nullType, undefinedType]); ++ checkTypeAssignableTo(initializerType, optionalDisposableType, initializer, Diagnostics.The_initializer_of_an_await_using_declaration_must_be_either_an_object_with_a_Symbol_asyncDispose_or_Symbol_dispose_method_or_be_null_or_undefined); ++ } ++ } ++ else if (blockScopeKind === NodeFlags.Using) { ++ const globalDisposableType = getGlobalDisposableType(/*reportErrors*/ true); ++ if (globalDisposableType !== emptyObjectType) { ++ const optionalDisposableType = getUnionType([globalDisposableType, nullType, undefinedType]); ++ checkTypeAssignableTo(initializerType, optionalDisposableType, initializer, Diagnostics.The_initializer_of_a_using_declaration_must_be_either_an_object_with_a_Symbol_dispose_method_or_be_null_or_undefined); ++ } ++ } + } + } + if (symbol.declarations && symbol.declarations.length > 1) { +@@ -41208,10 +41256,19 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { + return checkVariableLikeDeclaration(node); + } + ++ function checkVariableDeclarationList(node: VariableDeclarationList) { ++ const blockScopeKind = getCombinedNodeFlags(node) & NodeFlags.BlockScoped; ++ if (blockScopeKind === NodeFlags.Using || blockScopeKind === NodeFlags.AwaitUsing) { ++ checkExternalEmitHelpers(node, ExternalEmitHelpers.AddDisposableResourceAndDisposeResources); ++ } ++ ++ forEach(node.declarations, checkSourceElement); ++ } ++ + function checkVariableStatement(node: VariableStatement) { + // Grammar checking +- if (!checkGrammarModifiers(node) && !checkGrammarVariableDeclarationList(node.declarationList)) checkGrammarForDisallowedLetOrConstStatement(node); +- forEach(node.declarationList.declarations, checkSourceElement); ++ if (!checkGrammarModifiers(node) && !checkGrammarVariableDeclarationList(node.declarationList)) checkGrammarForDisallowedBlockScopedVariableStatement(node); ++ checkVariableDeclarationList(node.declarationList); + } + + function checkExpressionStatement(node: ExpressionStatement) { +@@ -41393,7 +41450,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { + + if (node.initializer) { + if (node.initializer.kind === SyntaxKind.VariableDeclarationList) { +- forEach((node.initializer as VariableDeclarationList).declarations, checkVariableDeclaration); ++ checkVariableDeclarationList(node.initializer as VariableDeclarationList); + } + else { + checkExpression(node.initializer); +@@ -41414,7 +41471,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { + const container = getContainingFunctionOrClassStaticBlock(node); + if (node.awaitModifier) { + if (container && isClassStaticBlockDeclaration(container)) { +- grammarErrorOnNode(node.awaitModifier, Diagnostics.For_await_loops_cannot_be_used_inside_a_class_static_block); ++ grammarErrorOnNode(node.awaitModifier, Diagnostics.for_await_loops_cannot_be_used_inside_a_class_static_block); + } + else { + const functionFlags = getFunctionFlags(container); +@@ -41435,7 +41492,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { + // If the LHS is an expression, check the LHS, as a destructuring assignment or as a reference. + // Then check that the RHS is assignable to it. + if (node.initializer.kind === SyntaxKind.VariableDeclarationList) { +- checkForInOrForOfVariableDeclaration(node); ++ checkVariableDeclarationList(node.initializer as VariableDeclarationList); + } + else { + const varExpr = node.initializer; +@@ -41486,7 +41543,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { + if (variable && isBindingPattern(variable.name)) { + error(variable.name, Diagnostics.The_left_hand_side_of_a_for_in_statement_cannot_be_a_destructuring_pattern); + } +- checkForInOrForOfVariableDeclaration(node); ++ checkVariableDeclarationList(node.initializer as VariableDeclarationList); + } + else { + // In a 'for-in' statement of the form +@@ -41522,15 +41579,6 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { + } + } + +- function checkForInOrForOfVariableDeclaration(iterationStatement: ForInOrOfStatement): void { +- const variableDeclarationList = iterationStatement.initializer as VariableDeclarationList; +- // checkGrammarForInOrForOfStatement will check that there is exactly one declaration. +- if (variableDeclarationList.declarations.length >= 1) { +- const decl = variableDeclarationList.declarations[0]; +- checkVariableDeclaration(decl); +- } +- } +- + function checkRightHandSideOfForOf(statement: ForOfStatement): Type { + const use = statement.awaitModifier ? IterationUse.ForAwaitOf : IterationUse.ForOf; + return checkIteratedTypeOrElementType(use, checkNonNullExpression(statement.expression), undefinedType, statement.expression); +@@ -43776,7 +43824,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { + if (symbol.flags & SymbolFlags.EnumMember) { + return location ? evaluateEnumMember(expr, symbol, location) : getEnumMemberValue(symbol.valueDeclaration as EnumMember); + } +- if (isConstVariable(symbol)) { ++ if (isConstantVariable(symbol)) { + const declaration = symbol.valueDeclaration as VariableDeclaration | undefined; + if (declaration && !declaration.type && declaration.initializer && (!location || declaration !== location && isBlockScopedNameDeclaredBeforeUse(declaration, location))) { + return evaluate(declaration.initializer, declaration); +@@ -46648,7 +46696,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { + } + + function isLiteralConstDeclaration(node: VariableDeclaration | PropertyDeclaration | PropertySignature | ParameterDeclaration): boolean { +- if (isDeclarationReadonly(node) || isVariableDeclaration(node) && isVarConst(node)) { ++ if (isDeclarationReadonly(node) || isVariableDeclaration(node) && isVarConstLike(node)) { + return isFreshLiteralType(getTypeOfSymbol(getSymbolOfDeclaration(node))); + } + return false; +@@ -47138,6 +47186,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { + case ExternalEmitHelpers.CreateBinding: return ["__createBinding"]; + case ExternalEmitHelpers.SetFunctionName: return ["__setFunctionName"]; + case ExternalEmitHelpers.PropKey: return ["__propKey"]; ++ case ExternalEmitHelpers.AddDisposableResourceAndDisposeResources: return ["__addDisposableResource", "__disposeResources"]; + default: return Debug.fail("Unrecognized helper"); + } + } +@@ -47161,6 +47210,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { + return grammarErrorOnFirstToken(node, Diagnostics.Neither_decorators_nor_modifiers_may_be_applied_to_this_parameters); + } + ++ const blockScopeKind = isVariableStatement(node) ? node.declarationList.flags & NodeFlags.BlockScoped : NodeFlags.None; + let lastStatic: Node | undefined, lastDeclare: Node | undefined, lastAsync: Node | undefined, lastOverride: Node | undefined, firstDecorator: Decorator | undefined; + let flags = ModifierFlags.None; + let sawExportBeforeDecorators = false; +@@ -47391,6 +47441,12 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { + else if (node.kind === SyntaxKind.Parameter) { + return grammarErrorOnNode(modifier, Diagnostics._0_modifier_cannot_appear_on_a_parameter, "export"); + } ++ else if (blockScopeKind === NodeFlags.Using) { ++ return grammarErrorOnNode(modifier, Diagnostics._0_modifier_cannot_appear_on_a_using_declaration, "export"); ++ } ++ else if (blockScopeKind === NodeFlags.AwaitUsing) { ++ return grammarErrorOnNode(modifier, Diagnostics._0_modifier_cannot_appear_on_an_await_using_declaration, "export"); ++ } + flags |= ModifierFlags.Export; + break; + case SyntaxKind.DefaultKeyword: +@@ -47398,6 +47454,12 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { + if (container.kind === SyntaxKind.ModuleDeclaration && !isAmbientModule(container)) { + return grammarErrorOnNode(modifier, Diagnostics.A_default_export_can_only_be_used_in_an_ECMAScript_style_module); + } ++ else if (blockScopeKind === NodeFlags.Using) { ++ return grammarErrorOnNode(modifier, Diagnostics._0_modifier_cannot_appear_on_a_using_declaration, "default"); ++ } ++ else if (blockScopeKind === NodeFlags.AwaitUsing) { ++ return grammarErrorOnNode(modifier, Diagnostics._0_modifier_cannot_appear_on_an_await_using_declaration, "default"); ++ } + else if (!(flags & ModifierFlags.Export)) { + return grammarErrorOnNode(modifier, Diagnostics._0_modifier_must_precede_1_modifier, "export", "default"); + } +@@ -47423,6 +47485,12 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { + else if (node.kind === SyntaxKind.Parameter) { + return grammarErrorOnNode(modifier, Diagnostics._0_modifier_cannot_appear_on_a_parameter, "declare"); + } ++ else if (blockScopeKind === NodeFlags.Using) { ++ return grammarErrorOnNode(modifier, Diagnostics._0_modifier_cannot_appear_on_a_using_declaration, "declare"); ++ } ++ else if (blockScopeKind === NodeFlags.AwaitUsing) { ++ return grammarErrorOnNode(modifier, Diagnostics._0_modifier_cannot_appear_on_an_await_using_declaration, "declare"); ++ } + else if ((node.parent.flags & NodeFlags.Ambient) && node.parent.kind === SyntaxKind.ModuleBlock) { + return grammarErrorOnNode(modifier, Diagnostics.A_declare_modifier_cannot_be_used_in_an_already_ambient_context); + } +@@ -47594,9 +47662,12 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { + return findFirstModifierExcept(node, SyntaxKind.AbstractKeyword); + case SyntaxKind.ClassExpression: + case SyntaxKind.InterfaceDeclaration: +- case SyntaxKind.VariableStatement: + case SyntaxKind.TypeAliasDeclaration: + return find(node.modifiers, isModifier); ++ case SyntaxKind.VariableStatement: ++ return node.declarationList.flags & NodeFlags.Using ? ++ findFirstModifierExcept(node, SyntaxKind.AwaitKeyword) : ++ find(node.modifiers, isModifier); + case SyntaxKind.EnumDeclaration: + return findFirstModifierExcept(node, SyntaxKind.ConstKeyword); + default: +@@ -48445,7 +48516,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { + initializer.kind === SyntaxKind.TrueKeyword || initializer.kind === SyntaxKind.FalseKeyword || + isBigIntLiteralExpression(initializer) + ); +- const isConstOrReadonly = isDeclarationReadonly(node) || isVariableDeclaration(node) && isVarConst(node); ++ const isConstOrReadonly = isDeclarationReadonly(node) || isVariableDeclaration(node) && (isVarConstLike(node)); + if (isConstOrReadonly && !node.type) { + if (isInvalidInitializer) { + return grammarErrorOnNode(initializer, Diagnostics.A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal_or_literal_enum_reference); +@@ -48458,21 +48529,37 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { + } + + function checkGrammarVariableDeclaration(node: VariableDeclaration) { ++ const nodeFlags = getCombinedNodeFlagsCached(node); ++ const blockScopeKind = nodeFlags & NodeFlags.BlockScoped; ++ if (isBindingPattern(node.name)) { ++ switch (blockScopeKind) { ++ case NodeFlags.AwaitUsing: ++ return grammarErrorOnNode(node, Diagnostics._0_declarations_may_not_have_binding_patterns, "await using"); ++ case NodeFlags.Using: ++ return grammarErrorOnNode(node, Diagnostics._0_declarations_may_not_have_binding_patterns, "using"); ++ } ++ } ++ + if (node.parent.parent.kind !== SyntaxKind.ForInStatement && node.parent.parent.kind !== SyntaxKind.ForOfStatement) { +- if (node.flags & NodeFlags.Ambient) { ++ if (nodeFlags & NodeFlags.Ambient) { + checkAmbientInitializer(node); + } + else if (!node.initializer) { + if (isBindingPattern(node.name) && !isBindingPattern(node.parent)) { + return grammarErrorOnNode(node, Diagnostics.A_destructuring_declaration_must_have_an_initializer); + } +- if (isVarConst(node)) { +- return grammarErrorOnNode(node, Diagnostics.const_declarations_must_be_initialized); ++ switch (blockScopeKind) { ++ case NodeFlags.AwaitUsing: ++ return grammarErrorOnNode(node, Diagnostics._0_declarations_must_be_initialized, "await using"); ++ case NodeFlags.Using: ++ return grammarErrorOnNode(node, Diagnostics._0_declarations_must_be_initialized, "using"); ++ case NodeFlags.Const: ++ return grammarErrorOnNode(node, Diagnostics._0_declarations_must_be_initialized, "const"); + } + } + } + +- if (node.exclamationToken && (node.parent.parent.kind !== SyntaxKind.VariableStatement || !node.type || node.initializer || node.flags & NodeFlags.Ambient)) { ++ if (node.exclamationToken && (node.parent.parent.kind !== SyntaxKind.VariableStatement || !node.type || node.initializer || nodeFlags & NodeFlags.Ambient)) { + const message = node.initializer + ? Diagnostics.Declarations_with_initializers_cannot_also_have_definite_assignment_assertions + : !node.type +@@ -48486,8 +48573,6 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { + checkESModuleMarker(node.name); + } + +- const checkLetConstNames = (isLet(node) || isVarConst(node)); +- + // 1. LexicalDeclaration : LetOrConst BindingList ; + // It is a Syntax Error if the BoundNames of BindingList contains "let". + // 2. ForDeclaration: ForDeclaration : LetOrConst ForBinding +@@ -48495,7 +48580,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { + + // It is a SyntaxError if a VariableDeclaration or VariableDeclarationNoIn occurs within strict code + // and its Identifier is eval or arguments +- return checkLetConstNames && checkGrammarNameInLetOrConstDeclarations(node.name); ++ return !!blockScopeKind && checkGrammarNameInLetOrConstDeclarations(node.name); + } + + function checkESModuleMarker(name: Identifier | BindingPattern): boolean { +@@ -48541,6 +48626,19 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { + if (!declarationList.declarations.length) { + return grammarErrorAtPos(declarationList, declarations.pos, declarations.end - declarations.pos, Diagnostics.Variable_declaration_list_cannot_be_empty); + } ++ ++ const blockScopeFlags = declarationList.flags & NodeFlags.BlockScoped; ++ if ((blockScopeFlags === NodeFlags.Using || blockScopeFlags === NodeFlags.AwaitUsing) && isForInStatement(declarationList.parent)) { ++ return grammarErrorOnNode(declarationList, ++ blockScopeFlags === NodeFlags.Using ? ++ Diagnostics.The_left_hand_side_of_a_for_in_statement_cannot_be_a_using_declaration : ++ Diagnostics.The_left_hand_side_of_a_for_in_statement_cannot_be_an_await_using_declaration); ++ } ++ ++ if (blockScopeFlags === NodeFlags.AwaitUsing) { ++ return checkAwaitGrammar(declarationList); ++ } ++ + return false; + } + +@@ -48561,13 +48659,16 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { + return true; + } + +- function checkGrammarForDisallowedLetOrConstStatement(node: VariableStatement) { ++ function checkGrammarForDisallowedBlockScopedVariableStatement(node: VariableStatement) { + if (!allowLetAndConstDeclarations(node.parent)) { +- if (isLet(node.declarationList)) { +- return grammarErrorOnNode(node, Diagnostics.let_declarations_can_only_be_declared_inside_a_block); +- } +- else if (isVarConst(node.declarationList)) { +- return grammarErrorOnNode(node, Diagnostics.const_declarations_can_only_be_declared_inside_a_block); ++ const blockScopeKind = getCombinedNodeFlagsCached(node.declarationList) & NodeFlags.BlockScoped; ++ if (blockScopeKind) { ++ const keyword = blockScopeKind === NodeFlags.Let ? "let" : ++ blockScopeKind === NodeFlags.Const ? "const" : ++ blockScopeKind === NodeFlags.Using ? "using" : ++ blockScopeKind === NodeFlags.AwaitUsing ? "await using" : ++ Debug.fail("Unknown BlockScope flag"); ++ return grammarErrorOnNode(node, Diagnostics._0_declarations_can_only_be_declared_inside_a_block, keyword); + } + } + } +@@ -48991,6 +49092,34 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { + return name ? name : + isComputedPropertyName(node) && isEntityNameExpression(node.expression) ? tryGetNameFromEntityNameExpression(node.expression) : undefined; + } ++ ++ function getCombinedModifierFlagsCached(node: Declaration) { ++ // we hold onto the last node and result to speed up repeated lookups against the same node. ++ if (lastGetCombinedModifierFlagsNode === node) { ++ return lastGetCombinedModifierFlagsResult; ++ } ++ ++ lastGetCombinedModifierFlagsNode = node; ++ lastGetCombinedModifierFlagsResult = getCombinedModifierFlags(node); ++ return lastGetCombinedModifierFlagsResult; ++ } ++ ++ function getCombinedNodeFlagsCached(node: Node) { ++ // we hold onto the last node and result to speed up repeated lookups against the same node. ++ if (lastGetCombinedNodeFlagsNode === node) { ++ return lastGetCombinedNodeFlagsResult; ++ } ++ lastGetCombinedNodeFlagsNode = node; ++ lastGetCombinedNodeFlagsResult = getCombinedNodeFlags(node); ++ return lastGetCombinedNodeFlagsResult; ++ } ++ ++ function isVarConstLike(node: VariableDeclaration | VariableDeclarationList) { ++ const blockScopeKind = getCombinedNodeFlagsCached(node) & NodeFlags.BlockScoped; ++ return blockScopeKind === NodeFlags.Const || ++ blockScopeKind === NodeFlags.Using || ++ blockScopeKind === NodeFlags.AwaitUsing; ++ } + } + + function isNotAccessor(declaration: Declaration): boolean { +diff --git a/src/compiler/commandLineParser.ts b/src/compiler/commandLineParser.ts +index 408fa9968..53c8e61ff 100644 +--- a/src/compiler/commandLineParser.ts ++++ b/src/compiler/commandLineParser.ts +@@ -218,6 +218,7 @@ const libEntries: [string, string][] = [ + ["esnext.symbol", "lib.es2019.symbol.d.ts"], + ["esnext.asynciterable", "lib.es2018.asynciterable.d.ts"], + ["esnext.intl", "lib.esnext.intl.d.ts"], ++ ["esnext.disposable", "lib.esnext.disposable.d.ts"], + ["esnext.bigint", "lib.es2020.bigint.d.ts"], + ["esnext.string", "lib.es2022.string.d.ts"], + ["esnext.promise", "lib.es2021.promise.d.ts"], +diff --git a/src/compiler/diagnosticMessages.json b/src/compiler/diagnosticMessages.json +index 8ba018241..bda674e96 100644 +--- a/src/compiler/diagnosticMessages.json ++++ b/src/compiler/diagnosticMessages.json +@@ -451,18 +451,14 @@ + "category": "Error", + "code": 1149 + }, +- "'const' declarations must be initialized.": { ++ "'{0}' declarations must be initialized.": { + "category": "Error", + "code": 1155 + }, +- "'const' declarations can only be declared inside a block.": { ++ "'{0}' declarations can only be declared inside a block.": { + "category": "Error", + "code": 1156 + }, +- "'let' declarations can only be declared inside a block.": { +- "category": "Error", +- "code": 1157 +- }, + "Unterminated template literal.": { + "category": "Error", + "code": 1160 +@@ -1601,6 +1597,26 @@ + "category": "Error", + "code": 1490 + }, ++ "'{0}' modifier cannot appear on a 'using' declaration.": { ++ "category": "Error", ++ "code": 1491 ++ }, ++ "'{0}' declarations may not have binding patterns.": { ++ "category": "Error", ++ "code": 1492 ++ }, ++ "The left-hand side of a 'for...in' statement cannot be a 'using' declaration.": { ++ "category": "Error", ++ "code": 1493 ++ }, ++ "The left-hand side of a 'for...in' statement cannot be an 'await using' declaration.": { ++ "category": "Error", ++ "code": 1494 ++ }, ++ "'{0}' modifier cannot appear on an 'await using' declaration.": { ++ "category": "Error", ++ "code": 1495 ++ }, + + "The types of '{0}' are incompatible between these types.": { + "category": "Error", +@@ -3623,6 +3639,26 @@ + "category": "Error", + "code": 2849 + }, ++ "The initializer of a 'using' declaration must be either an object with a '[Symbol.dispose]()' method, or be 'null' or 'undefined'.": { ++ "category": "Error", ++ "code": 2850 ++ }, ++ "The initializer of an 'await using' declaration must be either an object with a '[Symbol.asyncDispose]()' or '[Symbol.dispose]()' method, or be 'null' or 'undefined'.": { ++ "category": "Error", ++ "code": 2851 ++ }, ++ "'await using' statements are only allowed within async functions and at the top levels of modules.": { ++ "category": "Error", ++ "code": 2852 ++ }, ++ "'await using' statements are only allowed at the top level of a file when that file is a module, but this file has no imports or exports. Consider adding an empty 'export {}' to make this file a module.": { ++ "category": "Error", ++ "code": 2853 ++ }, ++ "Top-level 'await using' statements are only allowed when the 'module' option is set to 'es2022', 'esnext', 'system', 'node16', or 'nodenext', and the 'target' option is set to 'es2017' or higher.": { ++ "category": "Error", ++ "code": 2854 ++ }, + + "Import declaration '{0}' is using private name '{1}'.": { + "category": "Error", +@@ -7757,11 +7793,11 @@ + "category": "Error", + "code": 18036 + }, +- "Await expression cannot be used inside a class static block.": { ++ "'await' expression cannot be used inside a class static block.": { + "category": "Error", + "code": 18037 + }, +- "'For await' loops cannot be used inside a class static block.": { ++ "'for await' loops cannot be used inside a class static block.": { + "category": "Error", + "code": 18038 + }, +@@ -7820,5 +7856,9 @@ + "Its type '{0}' is not a valid JSX element type.": { + "category": "Error", + "code": 18053 ++ }, ++ "'await using' statements cannot be used inside a class static block.": { ++ "category": "Error", ++ "code": 18054 + } + } +diff --git a/src/compiler/emitter.ts b/src/compiler/emitter.ts +index 6f34ec688..a58223868 100644 +--- a/src/compiler/emitter.ts ++++ b/src/compiler/emitter.ts +@@ -254,8 +254,10 @@ import { + isUnparsedNode, + isUnparsedPrepend, + isUnparsedSource, ++ isVarAwaitUsing, + isVarConst, + isVariableStatement, ++ isVarUsing, + JSDoc, + JSDocAugmentsTag, + JSDocCallbackTag, +@@ -3685,7 +3687,18 @@ export function createPrinter(printerOptions: PrinterOptions = {}, handlers: Pri + } + + function emitVariableDeclarationList(node: VariableDeclarationList) { +- writeKeyword(isLet(node) ? "let" : isVarConst(node) ? "const" : "var"); ++ if (isVarAwaitUsing(node)) { ++ writeKeyword("await"); ++ writeSpace(); ++ writeKeyword("using"); ++ } ++ else { ++ const head = isLet(node) ? "let" : ++ isVarConst(node) ? "const" : ++ isVarUsing(node) ? "using" : ++ "var"; ++ writeKeyword(head); ++ } + writeSpace(); + emitList(node, node.declarations, ListFormat.VariableDeclarationList); + } +diff --git a/src/compiler/factory/emitHelpers.ts b/src/compiler/factory/emitHelpers.ts +index e14652a3a..d73ca9767 100644 +--- a/src/compiler/factory/emitHelpers.ts ++++ b/src/compiler/factory/emitHelpers.ts +@@ -136,6 +136,9 @@ export interface EmitHelperFactory { + createClassPrivateFieldGetHelper(receiver: Expression, state: Identifier, kind: PrivateIdentifierKind, f: Identifier | undefined): Expression; + createClassPrivateFieldSetHelper(receiver: Expression, state: Identifier, value: Expression, kind: PrivateIdentifierKind, f: Identifier | undefined): Expression; + createClassPrivateFieldInHelper(state: Identifier, receiver: Expression): Expression; ++ // 'using' helpers ++ createAddDisposableResourceHelper(envBinding: Expression, value: Expression, async: boolean): Expression; ++ createDisposeResourcesHelper(envBinding: Expression): Expression; + } + + /** @internal */ +@@ -183,7 +186,10 @@ export function createEmitHelperFactory(context: TransformationContext): EmitHel + // Class Fields Helpers + createClassPrivateFieldGetHelper, + createClassPrivateFieldSetHelper, +- createClassPrivateFieldInHelper ++ createClassPrivateFieldInHelper, ++ // 'using' helpers ++ createAddDisposableResourceHelper, ++ createDisposeResourcesHelper, + }; + + /** +@@ -666,6 +672,20 @@ export function createEmitHelperFactory(context: TransformationContext): EmitHel + context.requestEmitHelper(classPrivateFieldInHelper); + return factory.createCallExpression(getUnscopedHelperName("__classPrivateFieldIn"), /*typeArguments*/ undefined, [state, receiver]); + } ++ ++ function createAddDisposableResourceHelper(envBinding: Expression, value: Expression, async: boolean): Expression { ++ context.requestEmitHelper(addDisposableResourceHelper); ++ return factory.createCallExpression( ++ getUnscopedHelperName("__addDisposableResource"), ++ /*typeArguments*/ undefined, ++ [envBinding, value, async ? factory.createTrue() : factory.createFalse()] ++ ); ++ } ++ ++ function createDisposeResourcesHelper(envBinding: Expression) { ++ context.requestEmitHelper(disposeResourcesHelper); ++ return factory.createCallExpression(getUnscopedHelperName("__disposeResources"), /*typeArguments*/ undefined, [envBinding]); ++ } + } + + /** @internal */ +@@ -1367,6 +1387,71 @@ export const classPrivateFieldInHelper: UnscopedEmitHelper = { + };` + }; + ++/** ++ * @internal ++ */ ++export const addDisposableResourceHelper: UnscopedEmitHelper = { ++ name: "typescript:addDisposableResource", ++ importName: "__addDisposableResource", ++ scoped: false, ++ text: ` ++ var __addDisposableResource = (this && this.__addDisposableResource) || function (env, value, async) { ++ if (value !== null && value !== void 0) { ++ if (typeof value !== "object") throw new TypeError("Object expected."); ++ var dispose; ++ if (async) { ++ if (!Symbol.asyncDispose) throw new TypeError("Symbol.asyncDispose is not defined."); ++ dispose = value[Symbol.asyncDispose]; ++ } ++ if (dispose === void 0) { ++ if (!Symbol.dispose) throw new TypeError("Symbol.dispose is not defined."); ++ dispose = value[Symbol.dispose]; ++ } ++ if (typeof dispose !== "function") throw new TypeError("Object not disposable."); ++ env.stack.push({ value: value, dispose: dispose, async: async }); ++ } ++ else if (async) { ++ env.stack.push({ async: true }); ++ } ++ return value; ++ };` ++}; ++ ++/** ++ * @internal ++ */ ++export const disposeResourcesHelper: UnscopedEmitHelper = { ++ name: "typescript:disposeResources", ++ importName: "__disposeResources", ++ scoped: false, ++ text: ` ++ var __disposeResources = (this && this.__disposeResources) || (function (SuppressedError) { ++ return function (env) { ++ function fail(e) { ++ env.error = env.hasError ? new SuppressedError(e, env.error, "An error was suppressed during disposal.") : e; ++ env.hasError = true; ++ } ++ function next() { ++ while (env.stack.length) { ++ var rec = env.stack.pop(); ++ try { ++ var result = rec.dispose && rec.dispose.call(rec.value); ++ if (rec.async) return Promise.resolve(result).then(next, function(e) { fail(e); return next(); }); ++ } ++ catch (e) { ++ fail(e); ++ } ++ } ++ if (env.hasError) throw env.error; ++ } ++ return next(); ++ }; ++ })(typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) { ++ var e = new Error(message); ++ return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e; ++ });` ++}; ++ + let allUnscopedEmitHelpers: ReadonlyMap | undefined; + + /** @internal */ +@@ -1399,7 +1484,9 @@ export function getAllUnscopedEmitHelpers() { + classPrivateFieldSetHelper, + classPrivateFieldInHelper, + createBindingHelper, +- setModuleDefaultHelper ++ setModuleDefaultHelper, ++ addDisposableResourceHelper, ++ disposeResourcesHelper, + ], helper => helper.name)); + } + +diff --git a/src/compiler/factory/nodeConverters.ts b/src/compiler/factory/nodeConverters.ts +index 1541d56bf..bc12cb58c 100644 +--- a/src/compiler/factory/nodeConverters.ts ++++ b/src/compiler/factory/nodeConverters.ts +@@ -6,6 +6,7 @@ import { + BindingOrAssignmentPattern, + Block, + cast, ++ ClassDeclaration, + ConciseBody, + Debug, + Expression, +@@ -17,6 +18,8 @@ import { + isBindingElement, + isBindingPattern, + isBlock, ++ isDefaultModifier, ++ isExportModifier, + isExpression, + isIdentifier, + isObjectBindingPattern, +@@ -39,6 +42,7 @@ export function createNodeConverters(factory: NodeFactory): NodeConverters { + return { + convertToFunctionBlock, + convertToFunctionExpression, ++ convertToClassExpression, + convertToArrayAssignmentElement, + convertToObjectAssignmentElement, + convertToAssignmentPattern, +@@ -59,7 +63,7 @@ export function createNodeConverters(factory: NodeFactory): NodeConverters { + function convertToFunctionExpression(node: FunctionDeclaration) { + if (!node.body) return Debug.fail(`Cannot convert a FunctionDeclaration without a body`); + const updated = factory.createFunctionExpression( +- getModifiers(node), ++ getModifiers(node)?.filter(modifier => !isExportModifier(modifier) && !isDefaultModifier(modifier)), + node.asteriskToken, + node.name, + node.typeParameters, +@@ -75,6 +79,22 @@ export function createNodeConverters(factory: NodeFactory): NodeConverters { + return updated; + } + ++ function convertToClassExpression(node: ClassDeclaration) { ++ const updated = factory.createClassExpression( ++ node.modifiers?.filter(modifier => !isExportModifier(modifier) && !isDefaultModifier(modifier)), ++ node.name, ++ node.typeParameters, ++ node.heritageClauses, ++ node.members ++ ); ++ setOriginalNode(updated, node); ++ setTextRange(updated, node); ++ if (getStartsOnNewLine(node)) { ++ setStartsOnNewLine(updated, /*newLine*/ true); ++ } ++ return updated; ++ } ++ + function convertToArrayAssignmentElement(element: ArrayBindingOrAssignmentElement) { + if (isBindingElement(element)) { + if (element.dotDotDotToken) { +@@ -163,6 +183,7 @@ export function createNodeConverters(factory: NodeFactory): NodeConverters { + export const nullNodeConverters: NodeConverters = { + convertToFunctionBlock: notImplemented, + convertToFunctionExpression: notImplemented, ++ convertToClassExpression: notImplemented, + convertToArrayAssignmentElement: notImplemented, + convertToObjectAssignmentElement: notImplemented, + convertToAssignmentPattern: notImplemented, +diff --git a/src/compiler/factory/nodeFactory.ts b/src/compiler/factory/nodeFactory.ts +index 638ff1547..9dd48e043 100644 +--- a/src/compiler/factory/nodeFactory.ts ++++ b/src/compiler/factory/nodeFactory.ts +@@ -134,6 +134,8 @@ import { + Identifier, + idText, + IfStatement, ++ ImmediatelyInvokedArrowFunction, ++ ImmediatelyInvokedFunctionExpression, + ImportClause, + ImportDeclaration, + ImportEqualsDeclaration, +@@ -991,6 +993,7 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode + createExportDefault, + createExternalModuleExport, + createTypeCheck, ++ createIsNotTypeCheck, + createMethodCall, + createGlobalMethodCall, + createFunctionBindCall, +@@ -1322,6 +1325,10 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode + TransformFlags.ContainsES2018; + break; + ++ case SyntaxKind.UsingKeyword: ++ transformFlags = TransformFlags.ContainsESNext; ++ break; ++ + case SyntaxKind.PublicKeyword: + case SyntaxKind.PrivateKeyword: + case SyntaxKind.ProtectedKeyword: +@@ -4178,6 +4185,9 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode + TransformFlags.ContainsES2015 | + TransformFlags.ContainsBlockScopedBinding; + } ++ if (flags & NodeFlags.Using) { ++ node.transformFlags |= TransformFlags.ContainsESNext; ++ } + return node; + } + +@@ -6314,8 +6324,8 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode + } + + // compound nodes +- function createImmediatelyInvokedFunctionExpression(statements: readonly Statement[]): CallExpression; +- function createImmediatelyInvokedFunctionExpression(statements: readonly Statement[], param: ParameterDeclaration, paramValue: Expression): CallExpression; ++ function createImmediatelyInvokedFunctionExpression(statements: readonly Statement[]): ImmediatelyInvokedFunctionExpression; ++ function createImmediatelyInvokedFunctionExpression(statements: readonly Statement[], param: ParameterDeclaration, paramValue: Expression): ImmediatelyInvokedFunctionExpression; + function createImmediatelyInvokedFunctionExpression(statements: readonly Statement[], param?: ParameterDeclaration, paramValue?: Expression) { + return createCallExpression( + createFunctionExpression( +@@ -6332,8 +6342,8 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode + ); + } + +- function createImmediatelyInvokedArrowFunction(statements: readonly Statement[]): CallExpression; +- function createImmediatelyInvokedArrowFunction(statements: readonly Statement[], param: ParameterDeclaration, paramValue: Expression): CallExpression; ++ function createImmediatelyInvokedArrowFunction(statements: readonly Statement[]): ImmediatelyInvokedArrowFunction; ++ function createImmediatelyInvokedArrowFunction(statements: readonly Statement[], param: ParameterDeclaration, paramValue: Expression): ImmediatelyInvokedArrowFunction; + function createImmediatelyInvokedArrowFunction(statements: readonly Statement[], param?: ParameterDeclaration, paramValue?: Expression) { + return createCallExpression( + createArrowFunction( +@@ -6375,9 +6385,15 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode + // + + function createTypeCheck(value: Expression, tag: TypeOfTag) { +- return tag === "undefined" +- ? factory.createStrictEquality(value, createVoidZero()) +- : factory.createStrictEquality(createTypeOfExpression(value), createStringLiteral(tag)); ++ return tag === "null" ? factory.createStrictEquality(value, createNull()) : ++ tag === "undefined" ? factory.createStrictEquality(value, createVoidZero()) : ++ factory.createStrictEquality(createTypeOfExpression(value), createStringLiteral(tag)); ++ } ++ ++ function createIsNotTypeCheck(value: Expression, tag: TypeOfTag) { ++ return tag === "null" ? factory.createStrictInequality(value, createNull()) : ++ tag === "undefined" ? factory.createStrictInequality(value, createVoidZero()) : ++ factory.createStrictInequality(createTypeOfExpression(value), createStringLiteral(tag)); + } + + function createMethodCall(object: Expression, methodName: string | Identifier, argumentsList: readonly Expression[]) { +@@ -7585,10 +7601,12 @@ export function createSourceMapSource(fileName: string, text: string, skipTrivia + // Utilities + + export function setOriginalNode(node: T, original: Node | undefined): T { +- node.original = original; +- if (original) { +- const emitNode = original.emitNode; +- if (emitNode) node.emitNode = mergeEmitNode(emitNode, node.emitNode); ++ if (node.original !== original) { ++ node.original = original; ++ if (original) { ++ const emitNode = original.emitNode; ++ if (emitNode) node.emitNode = mergeEmitNode(emitNode, node.emitNode); ++ } + } + return node; + } +@@ -7596,7 +7614,7 @@ export function setOriginalNode(node: T, original: Node | undefi + function mergeEmitNode(sourceEmitNode: EmitNode, destEmitNode: EmitNode | undefined) { + const { + flags, +- internalFlags, ++ internalFlags, + leadingComments, + trailingComments, + commentRange, +@@ -7606,24 +7624,95 @@ function mergeEmitNode(sourceEmitNode: EmitNode, destEmitNode: EmitNode | undefi + helpers, + startsOnNewLine, + snippetElement, ++ classThis, ++ assignedName, + } = sourceEmitNode; + if (!destEmitNode) destEmitNode = {} as EmitNode; +- // We are using `.slice()` here in case `destEmitNode.leadingComments` is pushed to later. +- if (leadingComments) destEmitNode.leadingComments = addRange(leadingComments.slice(), destEmitNode.leadingComments); +- if (trailingComments) destEmitNode.trailingComments = addRange(trailingComments.slice(), destEmitNode.trailingComments); +- if (flags) destEmitNode.flags = flags; +- if (internalFlags) destEmitNode.internalFlags = internalFlags & ~InternalEmitFlags.Immutable; +- if (commentRange) destEmitNode.commentRange = commentRange; +- if (sourceMapRange) destEmitNode.sourceMapRange = sourceMapRange; +- if (tokenSourceMapRanges) destEmitNode.tokenSourceMapRanges = mergeTokenSourceMapRanges(tokenSourceMapRanges, destEmitNode.tokenSourceMapRanges!); +- if (constantValue !== undefined) destEmitNode.constantValue = constantValue; ++ ++ // NOTE: We should have one or more lines here for each property in EmitNode, even if the line ++ // consists only of a comment indicating the property does not merge ++ ++ // `flags` overwrites the destination ++ if (flags) { ++ destEmitNode.flags = flags; ++ } ++ ++ // `internalFlags` overwrites the destination. We do not copy over the immutability of the source. ++ if (internalFlags) { ++ destEmitNode.internalFlags = internalFlags & ~InternalEmitFlags.Immutable; ++ } ++ ++ // `annotatedNodes` are not merged as they should only present on the parse tree node of a `SourceFile`. ++ ++ // `leadingComments` are concatenated with any existing leading comments on the destination ++ if (leadingComments) { ++ // We use `.slice()` in case `destEmitNode.leadingComments` is pushed to later ++ destEmitNode.leadingComments = addRange(leadingComments.slice(), destEmitNode.leadingComments); ++ } ++ ++ // `trailingComments` are concatenated with any existing trailing comments on the destination ++ if (trailingComments) { ++ // We use `.slice()` in case `destEmitNode.trailingComments` is pushed to later ++ destEmitNode.trailingComments = addRange(trailingComments.slice(), destEmitNode.trailingComments); ++ } ++ ++ // `commentRange` overwrites the destination ++ if (commentRange) { ++ destEmitNode.commentRange = commentRange; ++ } ++ ++ // `sourceMapRange` overwrites the destination ++ if (sourceMapRange) { ++ destEmitNode.sourceMapRange = sourceMapRange; ++ } ++ ++ // `tokenSourceMapRanges` are merged with the destination ++ if (tokenSourceMapRanges) { ++ destEmitNode.tokenSourceMapRanges = mergeTokenSourceMapRanges(tokenSourceMapRanges, destEmitNode.tokenSourceMapRanges!); ++ } ++ ++ // `constantValue` overwrites the destination ++ if (constantValue !== undefined) { ++ destEmitNode.constantValue = constantValue; ++ } ++ ++ // `externalHelpersModuleName` is not merged ++ // `externalHelpers` is not merged ++ ++ // `helpers` are merged into the destination + if (helpers) { + for (const helper of helpers) { + destEmitNode.helpers = appendIfUnique(destEmitNode.helpers, helper); + } + } +- if (startsOnNewLine !== undefined) destEmitNode.startsOnNewLine = startsOnNewLine; +- if (snippetElement !== undefined) destEmitNode.snippetElement = snippetElement; ++ ++ // `startsOnNewLine` overwrites the destination ++ if (startsOnNewLine !== undefined) { ++ destEmitNode.startsOnNewLine = startsOnNewLine; ++ } ++ ++ // `snippetElement` overwrites the destination ++ if (snippetElement !== undefined) { ++ destEmitNode.snippetElement = snippetElement; ++ } ++ ++ // `typeNode` is not merged as it only applies to comment emit for a variable declaration. ++ // TODO: `typeNode` should overwrite the destination ++ ++ // `classThis` overwrites the destination ++ if (classThis) { ++ destEmitNode.classThis = classThis; ++ } ++ ++ // `assignedName` overwrites the destination ++ if (assignedName) { ++ destEmitNode.assignedName = assignedName; ++ } ++ ++ // `identifierTypeArguments` are not merged as they only apply to an Identifier in quick info ++ // `autoGenerate` is not merged as it only applies to a specific generated Identifier/PrivateIdentifier ++ // `generatedImportReference` is not merged as it only applies to an Identifier ++ + return destEmitNode; + } + +diff --git a/src/compiler/factory/utilities.ts b/src/compiler/factory/utilities.ts +index 2e2721ead..bac8f690e 100644 +--- a/src/compiler/factory/utilities.ts ++++ b/src/compiler/factory/utilities.ts +@@ -178,6 +178,7 @@ import { + Token, + TransformFlags, + TypeNode, ++ WrappedExpression + } from "../_namespaces/ts"; + + // Compound nodes +@@ -655,6 +656,8 @@ export function isOuterExpression(node: Node, kinds = OuterExpressionKinds.All): + return false; + } + ++/** @internal */ ++export function skipOuterExpressions(node: WrappedExpression): T; + /** @internal */ + export function skipOuterExpressions(node: Expression, kinds?: OuterExpressionKinds): Expression; + /** @internal */ +diff --git a/src/compiler/parser.ts b/src/compiler/parser.ts +index f49b48bb4..436fb04ef 100644 +--- a/src/compiler/parser.ts ++++ b/src/compiler/parser.ts +@@ -6816,7 +6816,9 @@ namespace Parser { + + let initializer!: VariableDeclarationList | Expression; + if (token() !== SyntaxKind.SemicolonToken) { +- if (token() === SyntaxKind.VarKeyword || token() === SyntaxKind.LetKeyword || token() === SyntaxKind.ConstKeyword) { ++ if (token() === SyntaxKind.VarKeyword || token() === SyntaxKind.LetKeyword || token() === SyntaxKind.ConstKeyword || ++ token() === SyntaxKind.UsingKeyword && lookAhead(nextTokenIsBindingIdentifierOrStartOfDestructuringOnSameLineDisallowOf) || ++ token() === SyntaxKind.AwaitKeyword && lookAhead(nextTokenIsUsingKeywordThenBindingIdentifierOrStartOfObjectDestructuringOnSameLineDisallowOf)) { + initializer = parseVariableDeclarationList(/*inForStatementInitializer*/ true); + } + else { +@@ -7052,6 +7054,10 @@ namespace Parser { + case SyntaxKind.ClassKeyword: + case SyntaxKind.EnumKeyword: + return true; ++ case SyntaxKind.UsingKeyword: ++ return isUsingDeclaration(); ++ case SyntaxKind.AwaitKeyword: ++ return isAwaitUsingDeclaration(); + + // 'declare', 'module', 'namespace', 'interface'* and 'type' are all legal JavaScript identifiers; + // however, an identifier cannot be followed by another identifier on the same line. This is what we +@@ -7118,6 +7124,7 @@ namespace Parser { + case SyntaxKind.StaticKeyword: + nextToken(); + continue; ++ + default: + return false; + } +@@ -7135,6 +7142,7 @@ namespace Parser { + case SyntaxKind.OpenBraceToken: + case SyntaxKind.VarKeyword: + case SyntaxKind.LetKeyword: ++ case SyntaxKind.UsingKeyword: + case SyntaxKind.FunctionKeyword: + case SyntaxKind.ClassKeyword: + case SyntaxKind.EnumKeyword: +@@ -7200,6 +7208,41 @@ namespace Parser { + return lookAhead(nextTokenIsBindingIdentifierOrStartOfDestructuring); + } + ++ function nextTokenIsBindingIdentifierOrStartOfDestructuringOnSameLineDisallowOf() { ++ return nextTokenIsBindingIdentifierOrStartOfDestructuringOnSameLine(/*disallowOf*/ true); ++ } ++ ++ function nextTokenIsBindingIdentifierOrStartOfDestructuringOnSameLine(disallowOf?: boolean) { ++ nextToken(); ++ if (disallowOf && token() === SyntaxKind.OfKeyword) return false; ++ return (isBindingIdentifier() || token() === SyntaxKind.OpenBraceToken) && !scanner.hasPrecedingLineBreak(); ++ } ++ ++ function isUsingDeclaration() { ++ // 'using' always starts a lexical declaration if followed by an identifier. We also eagerly parse ++ // |ObjectBindingPattern| so that we can report a grammar error during check. We don't parse out ++ // |ArrayBindingPattern| since it potentially conflicts with element access (i.e., `using[x]`). ++ return lookAhead(nextTokenIsBindingIdentifierOrStartOfDestructuringOnSameLine); ++ } ++ ++ function nextTokenIsUsingKeywordThenBindingIdentifierOrStartOfObjectDestructuringOnSameLineDisallowOf() { ++ return nextTokenIsUsingKeywordThenBindingIdentifierOrStartOfObjectDestructuringOnSameLine(/*disallowOf*/ true); ++ } ++ ++ function nextTokenIsUsingKeywordThenBindingIdentifierOrStartOfObjectDestructuringOnSameLine(disallowOf?: boolean) { ++ if (nextToken() === SyntaxKind.UsingKeyword) { ++ return nextTokenIsBindingIdentifierOrStartOfDestructuringOnSameLine(disallowOf); ++ } ++ return false; ++ } ++ ++ function isAwaitUsingDeclaration() { ++ // 'await using' always starts a lexical declaration if followed by an identifier. We also eagerly parse ++ // |ObjectBindingPattern| so that we can report a grammar error during check. We don't parse out ++ // |ArrayBindingPattern| since it potentially conflicts with element access (i.e., `await using[x]`). ++ return lookAhead(nextTokenIsUsingKeywordThenBindingIdentifierOrStartOfObjectDestructuringOnSameLine); ++ } ++ + function parseStatement(): Statement { + switch (token()) { + case SyntaxKind.SemicolonToken: +@@ -7213,6 +7256,16 @@ namespace Parser { + return parseVariableStatement(getNodePos(), hasPrecedingJSDocComment(), /*modifiers*/ undefined); + } + break; ++ case SyntaxKind.AwaitKeyword: ++ if (isAwaitUsingDeclaration()) { ++ return parseVariableStatement(getNodePos(), hasPrecedingJSDocComment(), /*modifiers*/ undefined); ++ } ++ break; ++ case SyntaxKind.UsingKeyword: ++ if (isUsingDeclaration()) { ++ return parseVariableStatement(getNodePos(), hasPrecedingJSDocComment(), /*modifiers*/ undefined); ++ } ++ break; + case SyntaxKind.FunctionKeyword: + return parseFunctionDeclaration(getNodePos(), hasPrecedingJSDocComment(), /*modifiers*/ undefined); + case SyntaxKind.ClassKeyword: +@@ -7317,6 +7370,8 @@ namespace Parser { + case SyntaxKind.VarKeyword: + case SyntaxKind.LetKeyword: + case SyntaxKind.ConstKeyword: ++ case SyntaxKind.UsingKeyword: ++ case SyntaxKind.AwaitKeyword: + return parseVariableStatement(pos, hasJSDoc, modifiersIn); + case SyntaxKind.FunctionKeyword: + return parseFunctionDeclaration(pos, hasJSDoc, modifiersIn); +@@ -7473,6 +7528,14 @@ namespace Parser { + case SyntaxKind.ConstKeyword: + flags |= NodeFlags.Const; + break; ++ case SyntaxKind.UsingKeyword: ++ flags |= NodeFlags.Using; ++ break; ++ case SyntaxKind.AwaitKeyword: ++ Debug.assert(isAwaitUsingDeclaration()); ++ flags |= NodeFlags.AwaitUsing; ++ nextToken(); ++ break; + default: + Debug.fail(); + } +diff --git a/src/compiler/program.ts b/src/compiler/program.ts +index c095ebb6e..36571405c 100644 +--- a/src/compiler/program.ts ++++ b/src/compiler/program.ts +@@ -1392,7 +1392,7 @@ export const plainJSErrors: Set = new Set([ + Diagnostics.Did_you_mean_to_use_a_Colon_An_can_only_follow_a_property_name_when_the_containing_object_literal_is_part_of_a_destructuring_pattern.code, + Diagnostics.Duplicate_label_0.code, + Diagnostics.Dynamic_imports_can_only_accept_a_module_specifier_and_an_optional_assertion_as_arguments.code, +- Diagnostics.For_await_loops_cannot_be_used_inside_a_class_static_block.code, ++ Diagnostics.for_await_loops_cannot_be_used_inside_a_class_static_block.code, + Diagnostics.JSX_attributes_must_only_be_assigned_a_non_empty_expression.code, + Diagnostics.JSX_elements_cannot_have_multiple_attributes_with_the_same_name.code, + Diagnostics.JSX_expressions_may_not_use_the_comma_operator_Did_you_mean_to_write_an_array.code, +@@ -1422,14 +1422,14 @@ export const plainJSErrors: Set = new Set([ + Diagnostics._0_modifier_cannot_appear_on_class_elements_of_this_kind.code, + Diagnostics._0_modifier_cannot_be_used_here.code, + Diagnostics._0_modifier_must_precede_1_modifier.code, +- Diagnostics.const_declarations_can_only_be_declared_inside_a_block.code, +- Diagnostics.const_declarations_must_be_initialized.code, ++ Diagnostics._0_declarations_can_only_be_declared_inside_a_block.code, ++ Diagnostics._0_declarations_must_be_initialized.code, + Diagnostics.extends_clause_already_seen.code, +- Diagnostics.let_declarations_can_only_be_declared_inside_a_block.code, + Diagnostics.let_is_not_allowed_to_be_used_as_a_name_in_let_or_const_declarations.code, + Diagnostics.Class_constructor_may_not_be_a_generator.code, + Diagnostics.Class_constructor_may_not_be_an_accessor.code, + Diagnostics.await_expressions_are_only_allowed_within_async_functions_and_at_the_top_levels_of_modules.code, ++ Diagnostics.await_using_statements_are_only_allowed_within_async_functions_and_at_the_top_levels_of_modules.code, + // Type errors + Diagnostics.This_condition_will_always_return_0_since_JavaScript_compares_objects_by_reference_not_value.code, + ]); +diff --git a/src/compiler/scanner.ts b/src/compiler/scanner.ts +index 9f539aec4..c2d945a02 100644 +--- a/src/compiler/scanner.ts ++++ b/src/compiler/scanner.ts +@@ -194,6 +194,7 @@ export const textToKeywordObj: MapLike = { + undefined: SyntaxKind.UndefinedKeyword, + unique: SyntaxKind.UniqueKeyword, + unknown: SyntaxKind.UnknownKeyword, ++ using: SyntaxKind.UsingKeyword, + var: SyntaxKind.VarKeyword, + void: SyntaxKind.VoidKeyword, + while: SyntaxKind.WhileKeyword, +diff --git a/src/compiler/transformer.ts b/src/compiler/transformer.ts +index a6bf29119..f8c1ee5d5 100644 +--- a/src/compiler/transformer.ts ++++ b/src/compiler/transformer.ts +@@ -72,7 +72,7 @@ import { + transformNodeModule, + transformSystemModule, + transformTypeScript, +- VariableDeclaration, ++ VariableDeclaration + } from "./_namespaces/ts"; + import * as performance from "./_namespaces/ts.performance"; + +@@ -131,11 +131,6 @@ function getScriptTransformers(compilerOptions: CompilerOptions, customTransform + if (compilerOptions.experimentalDecorators) { + transformers.push(transformLegacyDecorators); + } +- else if (languageVersion < ScriptTarget.ESNext || !useDefineForClassFields) { +- transformers.push(transformESDecorators); +- } +- +- transformers.push(transformClassFields); + + if (getJSXTransformEnabled(compilerOptions)) { + transformers.push(transformJsx); +@@ -145,6 +140,12 @@ function getScriptTransformers(compilerOptions: CompilerOptions, customTransform + transformers.push(transformESNext); + } + ++ if (!compilerOptions.experimentalDecorators && (languageVersion < ScriptTarget.ESNext || !useDefineForClassFields)) { ++ transformers.push(transformESDecorators); ++ } ++ ++ transformers.push(transformClassFields); ++ + if (languageVersion < ScriptTarget.ES2021) { + transformers.push(transformES2021); + } +diff --git a/src/compiler/transformers/classFields.ts b/src/compiler/transformers/classFields.ts +index f038aa3d3..07adbf4b1 100644 +--- a/src/compiler/transformers/classFields.ts ++++ b/src/compiler/transformers/classFields.ts +@@ -20,6 +20,8 @@ import { + ClassDeclaration, + ClassElement, + ClassExpression, ++ classHasClassThisAssignment, ++ classHasExplicitlyAssignedName, + ClassLikeDeclaration, + classOrConstructorParameterIsDecorated, + ClassStaticBlockDeclaration, +@@ -44,7 +46,7 @@ import { + filter, + find, + findComputedPropertyNameCacheAssignment, +- findSuperStatementIndex, ++ findSuperStatementIndexPath, + flattenCommaList, + ForStatement, + GeneratedIdentifier, +@@ -80,14 +82,16 @@ import { + isArrowFunction, + isAssignmentExpression, + isAutoAccessorPropertyDeclaration, +- isBindingName, ++ isBlock, + isCallChain, + isCallToHelper, ++ isCatchClause, + isClassDeclaration, + isClassElement, + isClassExpression, +- isClassLike, ++ isClassNamedEvaluationHelperBlock, + isClassStaticBlockDeclaration, ++ isClassThisAssignmentBlock, + isCommaExpression, + isCompoundAssignment, + isComputedPropertyName, +@@ -96,7 +100,6 @@ import { + isElementAccessExpression, + isExportOrDefaultModifier, + isExpression, +- isExpressionStatement, + isForInitializer, + isGeneratedIdentifier, + isGeneratedPrivateIdentifier, +@@ -104,6 +107,7 @@ import { + isGetAccessorDeclaration, + isHeritageClause, + isIdentifier, ++ isIdentifierText, + isInitializedProperty, + isLeftHandSideExpression, + isMethodDeclaration, +@@ -127,7 +131,6 @@ import { + isPropertyAssignment, + isPropertyDeclaration, + isPropertyName, +- isPropertyNameLiteral, + isSetAccessor, + isSetAccessorDeclaration, + isShorthandPropertyAssignment, +@@ -138,9 +141,11 @@ import { + isStatement, + isStatic, + isStaticModifier, ++ isStringLiteral, + isSuperProperty, + isTemplateLiteral, + isThisProperty, ++ isTryStatement, + isVoidExpression, + LeftHandSideExpression, + LexicalEnvironment, +@@ -153,6 +158,7 @@ import { + moveRangePos, + newPrivateEnvironment, + Node, ++ NodeArray, + NodeCheckFlags, + NodeFactory, + nodeIsSynthesized, +@@ -161,7 +167,6 @@ import { + OuterExpressionKinds, + ParameterDeclaration, + ParenthesizedExpression, +- PartiallyEmittedExpression, + PostfixUnaryExpression, + PrefixUnaryExpression, + PrivateEnvironment, +@@ -203,6 +208,7 @@ import { + ThisExpression, + TransformationContext, + TransformFlags, ++ transformNamedEvaluation, + tryCast, + tryGetTextOfPropertyName, + unescapeLeadingUnderscores, +@@ -217,7 +223,7 @@ import { + visitNodes, + Visitor, + visitParameterList, +- VisitResult, ++ VisitResult + } from "../_namespaces/ts"; + + const enum ClassPropertySubstitutionFlags { +@@ -462,7 +468,7 @@ export function transformClassFields(context: TransformationContext): (x: Source + case SyntaxKind.ClassDeclaration: + return visitClassDeclaration(node as ClassDeclaration); + case SyntaxKind.ClassExpression: +- return visitClassExpression(node as ClassExpression, /*referencedName*/ undefined); ++ return visitClassExpression(node as ClassExpression); + case SyntaxKind.ClassStaticBlockDeclaration: + case SyntaxKind.PropertyDeclaration: + return Debug.fail("Use `classElementVisitor` instead."); +@@ -490,7 +496,7 @@ export function transformClassFields(context: TransformationContext): (x: Source + case SyntaxKind.BinaryExpression: + return visitBinaryExpression(node as BinaryExpression, /*discarded*/ false); + case SyntaxKind.ParenthesizedExpression: +- return visitParenthesizedExpression(node as ParenthesizedExpression, /*discarded*/ false, /*referencedName*/ undefined); ++ return visitParenthesizedExpression(node as ParenthesizedExpression, /*discarded*/ false); + case SyntaxKind.CallExpression: + return visitCallExpression(node as CallExpression); + case SyntaxKind.ExpressionStatement: +@@ -499,6 +505,8 @@ export function transformClassFields(context: TransformationContext): (x: Source + return visitTaggedTemplateExpression(node as TaggedTemplateExpression); + case SyntaxKind.ForStatement: + return visitForStatement(node as ForStatement); ++ case SyntaxKind.ThisKeyword: ++ return visitThisExpression(node as ThisExpression); + case SyntaxKind.FunctionDeclaration: + case SyntaxKind.FunctionExpression: + // If we are descending into a new scope, clear the current class element +@@ -527,19 +535,6 @@ export function transformClassFields(context: TransformationContext): (x: Source + return visitEachChild(node, visitor, context); + } + +- function namedEvaluationVisitor(node: Node, referencedName: Expression): VisitResult { +- switch (node.kind) { +- case SyntaxKind.PartiallyEmittedExpression: +- return visitPartiallyEmittedExpression(node as PartiallyEmittedExpression, /*discarded*/ false, referencedName); +- case SyntaxKind.ParenthesizedExpression: +- return visitParenthesizedExpression(node as ParenthesizedExpression, /*discarded*/ false, referencedName); +- case SyntaxKind.ClassExpression: +- return visitClassExpression(node as ClassExpression, referencedName); +- default: +- return visitor(node); +- } +- } +- + /** + * Visits a node in an expression whose result is discarded. + */ +@@ -553,7 +548,7 @@ export function transformClassFields(context: TransformationContext): (x: Source + case SyntaxKind.CommaListExpression: + return visitCommaListExpression(node as CommaListExpression, /*discarded*/ true); + case SyntaxKind.ParenthesizedExpression: +- return visitParenthesizedExpression(node as ParenthesizedExpression, /*discarded*/ true, /*referencedName*/ undefined); ++ return visitParenthesizedExpression(node as ParenthesizedExpression, /*discarded*/ true); + default: + return visitor(node); + } +@@ -692,9 +687,7 @@ export function transformClassFields(context: TransformationContext): (x: Source + // ... + + if (isNamedEvaluation(node, isAnonymousClassNeedingAssignedName)) { +- const { referencedName, name } = visitReferencedPropertyName(node.name); +- const initializer = visitNode(node.initializer, node => namedEvaluationVisitor(node, referencedName), isExpression); +- return factory.updatePropertyAssignment(node, name, initializer); ++ node = transformNamedEvaluation(context, node); + } + + return visitEachChild(node, visitor, context); +@@ -713,13 +706,6 @@ export function transformClassFields(context: TransformationContext): (x: Source + return statement; + } + +- function getAssignedNameOfIdentifier(name: Identifier, initializer: Expression) { +- const originalClass = getOriginalNode(initializer, isClassLike); +- return originalClass && !originalClass.name && hasSyntacticModifier(originalClass, ModifierFlags.Default) ? +- factory.createStringLiteral("default") : +- factory.createStringLiteralFromNode(name); +- } +- + function visitVariableDeclaration(node: VariableDeclaration) { + // 14.3.1.2 RS: Evaluation + // LexicalBinding : BindingIdentifier Initializer +@@ -736,10 +722,7 @@ export function transformClassFields(context: TransformationContext): (x: Source + // ... + + if (isNamedEvaluation(node, isAnonymousClassNeedingAssignedName)) { +- const assignedName = getAssignedNameOfIdentifier(node.name, node.initializer); +- const name = visitNode(node.name, visitor, isBindingName); +- const initializer = visitNode(node.initializer, node => namedEvaluationVisitor(node, assignedName), isExpression); +- return factory.updateVariableDeclaration(node, name, /*exclamationToken*/ undefined, /*type*/ undefined, initializer); ++ node = transformNamedEvaluation(context, node); + } + + return visitEachChild(node, visitor, context); +@@ -763,18 +746,7 @@ export function transformClassFields(context: TransformationContext): (x: Source + // ... + + if (isNamedEvaluation(node, isAnonymousClassNeedingAssignedName)) { +- const assignedName = getAssignedNameOfIdentifier(node.name, node.initializer); +- const name = visitNode(node.name, visitor, isBindingName); +- const initializer = visitNode(node.initializer, node => namedEvaluationVisitor(node, assignedName), isExpression); +- return factory.updateParameterDeclaration( +- node, +- /*modifiers*/ undefined, +- /*dotDotDotToken*/ undefined, +- name, +- /*questionToken*/ undefined, +- /*type*/ undefined, +- initializer +- ); ++ node = transformNamedEvaluation(context, node); + } + + return visitEachChild(node, visitor, context); +@@ -798,11 +770,7 @@ export function transformClassFields(context: TransformationContext): (x: Source + // ... + + if (isNamedEvaluation(node, isAnonymousClassNeedingAssignedName)) { +- const assignedName = getAssignedNameOfIdentifier(node.name, node.initializer); +- const propertyName = visitNode(node.propertyName, visitor, isPropertyName); +- const name = visitNode(node.name, visitor, isBindingName); +- const initializer = visitNode(node.initializer, node => namedEvaluationVisitor(node, assignedName), isExpression); +- return factory.updateBindingElement(node, /*dotDotDotToken*/ undefined, propertyName, name, initializer); ++ node = transformNamedEvaluation(context, node); + } + + return visitEachChild(node, visitor, context); +@@ -819,10 +787,7 @@ export function transformClassFields(context: TransformationContext): (x: Source + // is `""`. + + if (isNamedEvaluation(node, isAnonymousClassNeedingAssignedName)) { +- const assignedName = factory.createStringLiteral(node.isExportEquals ? "" : "default"); +- const modifiers = visitNodes(node.modifiers, modifierVisitor, isModifier); +- const expression = visitNode(node.expression, node => namedEvaluationVisitor(node, assignedName), isExpression); +- return factory.updateExportAssignment(node, modifiers, expression); ++ node = transformNamedEvaluation(context, node, /*ignoreEmptyStringLiteral*/ true, node.isExportEquals ? "" : "default"); + } + + return visitEachChild(node, visitor, context); +@@ -1023,15 +988,7 @@ export function transformClassFields(context: TransformationContext): (x: Source + } + + if (isNamedEvaluation(node, isAnonymousClassNeedingAssignedName)) { +- const { referencedName, name } = visitReferencedPropertyName(node.name); +- return factory.updatePropertyDeclaration( +- node, +- visitNodes(node.modifiers, modifierVisitor, isModifier), +- name, +- /*questionOrExclamationToken*/ undefined, +- /*type*/ undefined, +- visitNode(node.initializer, child => namedEvaluationVisitor(child, referencedName), isExpression) +- ); ++ node = transformNamedEvaluation(context, node); + } + + return factory.updatePropertyDeclaration( +@@ -1052,8 +1009,7 @@ export function transformClassFields(context: TransformationContext): (x: Source + + const expr = getPropertyNameExpressionIfNeeded( + node.name, +- /*shouldHoist*/ !!node.initializer || useDefineForClassFields, +- /*captureReferencedName*/ isNamedEvaluation(node, isAnonymousClassNeedingAssignedName)); ++ /*shouldHoist*/ !!node.initializer || useDefineForClassFields); + if (expr) { + getPendingExpressions().push(...flattenCommaList(expr)); + } +@@ -1448,6 +1404,21 @@ export function transformClassFields(context: TransformationContext): (x: Source + } + + if (shouldTransformPrivateElementsOrClassStaticBlocks) { ++ if (isClassThisAssignmentBlock(node)) { ++ const result = visitNode(node.body.statements[0].expression, visitor, isExpression); ++ // If the generated `_classThis` assignment is a noop (i.e., `_classThis = _classThis`), we can ++ // eliminate the expression ++ if (isAssignmentExpression(result, /*excludeCompoundAssignment*/ true) && ++ result.left === result.right) { ++ return undefined; ++ } ++ return result; ++ } ++ ++ if (isClassNamedEvaluationHelperBlock(node)) { ++ return visitNode(node.body.statements[0].expression, visitor, isExpression); ++ } ++ + startLexicalEnvironment(); + let statements = setCurrentClassElementAnd( + node, +@@ -1457,9 +1428,10 @@ export function transformClassFields(context: TransformationContext): (x: Source + statements = factory.mergeLexicalEnvironment(statements, endLexicalEnvironment()); + + const iife = factory.createImmediatelyInvokedArrowFunction(statements); ++ setOriginalNode(skipParentheses(iife.expression), node); ++ addEmitFlags(skipParentheses(iife.expression), EmitFlags.AdviseOnEmitNode); + setOriginalNode(iife, node); + setTextRange(iife, node); +- addEmitFlags(iife, EmitFlags.AdviseOnEmitNode); + return iife; + } + } +@@ -1467,14 +1439,8 @@ export function transformClassFields(context: TransformationContext): (x: Source + function isAnonymousClassNeedingAssignedName(node: AnonymousFunctionDefinition) { + if (isClassExpression(node) && !node.name) { + const staticPropertiesOrClassStaticBlocks = getStaticPropertiesAndClassStaticBlock(node); +- const classStaticBlock = find(staticPropertiesOrClassStaticBlocks, isClassStaticBlockDeclaration); +- if (classStaticBlock) { +- for (const statement of classStaticBlock.body.statements) { +- if (isExpressionStatement(statement) && +- isCallToHelper(statement.expression, "___setFunctionName" as __String)) { +- return false; +- } +- } ++ if (some(staticPropertiesOrClassStaticBlocks, isClassNamedEvaluationHelperBlock)) { ++ return false; + } + + const hasTransformableStatics = +@@ -1536,10 +1502,8 @@ export function transformClassFields(context: TransformationContext): (x: Source + // ... + + if (isNamedEvaluation(node, isAnonymousClassNeedingAssignedName)) { +- const assignedName = getAssignedNameOfIdentifier(node.left, node.right); +- const left = visitNode(node.left, visitor, isExpression); +- const right = visitNode(node.right, node => namedEvaluationVisitor(node, assignedName), isExpression); +- return factory.updateBinaryExpression(node, left, node.operatorToken, right); ++ node = transformNamedEvaluation(context, node); ++ Debug.assertNode(node, isAssignmentExpression); + } + + const left = skipOuterExpressions(node.left, OuterExpressionKinds.PartiallyEmittedExpressions | OuterExpressionKinds.Parentheses); +@@ -1645,7 +1609,7 @@ export function transformClassFields(context: TransformationContext): (x: Source + return factory.updateCommaListExpression(node, elements); + } + +- function visitParenthesizedExpression(node: ParenthesizedExpression, discarded: boolean, referencedName: Expression | undefined) { ++ function visitParenthesizedExpression(node: ParenthesizedExpression, discarded: boolean) { + // 8.4.5 RS: NamedEvaluation + // ParenthesizedExpression : `(` Expression `)` + // ... +@@ -1653,42 +1617,11 @@ export function transformClassFields(context: TransformationContext): (x: Source + + const visitorFunc: Visitor = + discarded ? discardedValueVisitor : +- referencedName ? node => namedEvaluationVisitor(node, referencedName) : + visitor; + const expression = visitNode(node.expression, visitorFunc, isExpression); + return factory.updateParenthesizedExpression(node, expression); + } + +- function visitPartiallyEmittedExpression(node: PartiallyEmittedExpression, discarded: boolean, referencedName: Expression | undefined) { +- // Emulates 8.4.5 RS: NamedEvaluation +- +- const visitorFunc: Visitor = +- discarded ? discardedValueVisitor : +- referencedName ? node => namedEvaluationVisitor(node, referencedName) : +- visitor; +- const expression = visitNode(node.expression, visitorFunc, isExpression); +- return factory.updatePartiallyEmittedExpression(node, expression); +- } +- +- function visitReferencedPropertyName(node: PropertyName) { +- if (isPropertyNameLiteral(node) || isPrivateIdentifier(node)) { +- const referencedName = factory.createStringLiteralFromNode(node); +- const name = visitNode(node, visitor, isPropertyName); +- return { referencedName, name }; +- } +- +- if (isPropertyNameLiteral(node.expression) && !isIdentifier(node.expression)) { +- const referencedName = factory.createStringLiteralFromNode(node.expression); +- const name = visitNode(node, visitor, isPropertyName); +- return { referencedName, name }; +- } +- +- const referencedName = factory.createTempVariable(hoistVariableDeclaration); +- const key = emitHelpers().createPropKeyHelper(visitNode(node.expression, visitor, isExpression)); +- const assignment = factory.createAssignment(referencedName, key); +- const name = factory.updateComputedPropertyName(node, injectPendingExpressions(assignment)); +- return { referencedName, name }; +- } + + function createPrivateIdentifierAssignment(info: PrivateIdentifierInfo, receiver: Expression, right: Expression, operator: AssignmentOperator): Expression { + receiver = visitNode(receiver, visitor, isExpression); +@@ -1750,6 +1683,9 @@ export function transformClassFields(context: TransformationContext): (x: Source + if (isClassDeclaration(original) && classOrConstructorParameterIsDecorated(legacyDecorators, original)) { + facts |= ClassFacts.ClassWasDecorated; + } ++ if (shouldTransformPrivateElementsOrClassStaticBlocks && (classHasClassThisAssignment(node) || classHasExplicitlyAssignedName(node))) { ++ facts |= ClassFacts.NeedsClassConstructorReference; ++ } + let containsPublicInstanceFields = false; + let containsInitializedPublicInstanceFields = false; + let containsInstancePrivateElements = false; +@@ -1820,7 +1756,7 @@ export function transformClassFields(context: TransformationContext): (x: Source + return visitEachChild(node, visitor, context); + } + +- function visitInNewClassLexicalEnvironment(node: T, referencedName: Expression | undefined, visitor: (node: T, facts: ClassFacts, referencedName: Expression | undefined) => U) { ++ function visitInNewClassLexicalEnvironment(node: T, visitor: (node: T, facts: ClassFacts) => U) { + const savedCurrentClassContainer = currentClassContainer; + const savedPendingExpressions = pendingExpressions; + const savedLexicalEnvironment = lexicalEnvironment; +@@ -1834,6 +1770,22 @@ export function transformClassFields(context: TransformationContext): (x: Source + if (name && isIdentifier(name)) { + getPrivateIdentifierEnvironment().data.className = name; + } ++ else if (node.emitNode?.assignedName) { ++ if (isStringLiteral(node.emitNode.assignedName)) { ++ // If the class name was assigned from a string literal based on an Identifier, use the Identifier ++ // as the prefix. ++ if (node.emitNode.assignedName.textSourceNode && ++ isIdentifier(node.emitNode.assignedName.textSourceNode)) { ++ getPrivateIdentifierEnvironment().data.className = node.emitNode.assignedName.textSourceNode; ++ } ++ // If the class name was assigned from a string literal that is a valid identifier, create an ++ // identifier from it. ++ else if (isIdentifierText(node.emitNode.assignedName.text, languageVersion)) { ++ const prefixName = factory.createIdentifier(node.emitNode.assignedName.text); ++ getPrivateIdentifierEnvironment().data.className = prefixName; ++ } ++ } ++ } + } + + if (shouldTransformPrivateElementsOrClassStaticBlocks) { +@@ -1855,7 +1807,7 @@ export function transformClassFields(context: TransformationContext): (x: Source + enableSubstitutionForClassStaticThisOrSuperReference(); + } + +- const result = visitor(node, facts, referencedName); ++ const result = visitor(node, facts); + endClassLexicalEnvironment(); + Debug.assert(lexicalEnvironment === savedLexicalEnvironment); + currentClassContainer = savedCurrentClassContainer; +@@ -1865,7 +1817,7 @@ export function transformClassFields(context: TransformationContext): (x: Source + } + + function visitClassDeclaration(node: ClassDeclaration) { +- return visitInNewClassLexicalEnvironment(node, /*referencedName*/ undefined, visitClassDeclarationInNewClassLexicalEnvironment); ++ return visitInNewClassLexicalEnvironment(node, visitClassDeclarationInNewClassLexicalEnvironment); + } + + function visitClassDeclarationInNewClassLexicalEnvironment(node: ClassDeclaration, facts: ClassFacts) { +@@ -1952,11 +1904,11 @@ export function transformClassFields(context: TransformationContext): (x: Source + return statements; + } + +- function visitClassExpression(node: ClassExpression, referencedName: Expression | undefined): Expression { +- return visitInNewClassLexicalEnvironment(node, referencedName, visitClassExpressionInNewClassLexicalEnvironment); ++ function visitClassExpression(node: ClassExpression): Expression { ++ return visitInNewClassLexicalEnvironment(node, visitClassExpressionInNewClassLexicalEnvironment); + } + +- function visitClassExpressionInNewClassLexicalEnvironment(node: ClassExpression, facts: ClassFacts, referencedName: Expression | undefined): Expression { ++ function visitClassExpressionInNewClassLexicalEnvironment(node: ClassExpression, facts: ClassFacts): Expression { + // If this class expression is a transformation of a decorated class declaration, + // then we want to output the pendingExpressions as statements, not as inlined + // expressions with the class statement. +@@ -2002,7 +1954,7 @@ export function transformClassFields(context: TransformationContext): (x: Source + const modifiers = visitNodes(node.modifiers, modifierVisitor, isModifier); + const heritageClauses = visitNodes(node.heritageClauses, heritageClauseVisitor, isHeritageClause); + const { members, prologue } = transformClassMembers(node); +- let classExpression = factory.updateClassExpression( ++ const classExpression = factory.updateClassExpression( + node, + modifiers, + node.name, +@@ -2025,7 +1977,7 @@ export function transformClassFields(context: TransformationContext): (x: Source + isPrivateIdentifierClassElementDeclaration(node) || + shouldTransformInitializers && isInitializedProperty(node)); + +- if (hasTransformableStatics || some(pendingExpressions) || referencedName) { ++ if (hasTransformableStatics || some(pendingExpressions)) { + if (isDecoratedClassDeclaration) { + Debug.assertIsDefined(pendingStatements, "Decorated classes transformed by TypeScript are expected to be within a variable declaration."); + +@@ -2034,30 +1986,6 @@ export function transformClassFields(context: TransformationContext): (x: Source + addRange(pendingStatements, map(pendingExpressions, factory.createExpressionStatement)); + } + +- if (referencedName) { +- if (shouldTransformPrivateElementsOrClassStaticBlocks) { +- const setNameExpression = emitHelpers().createSetFunctionNameHelper(temp ?? node.emitNode?.classThis ?? factory.getInternalName(node), referencedName); +- pendingStatements.push(factory.createExpressionStatement(setNameExpression)); +- } +- else { +- const setNameExpression = emitHelpers().createSetFunctionNameHelper(factory.createThis(), referencedName); +- classExpression = factory.updateClassExpression( +- classExpression, +- classExpression.modifiers, +- classExpression.name, +- classExpression.typeParameters, +- classExpression.heritageClauses, [ +- factory.createClassStaticBlockDeclaration( +- factory.createBlock([ +- factory.createExpressionStatement(setNameExpression) +- ]) +- ), +- ...classExpression.members +- ] +- ); +- } +- } +- + if (some(staticPropertiesOrClassStaticBlocks)) { + addPropertyOrClassStaticBlockStatements(pendingStatements, staticPropertiesOrClassStaticBlocks, node.emitNode?.classThis ?? factory.getInternalName(node)); + } +@@ -2086,9 +2014,6 @@ export function transformClassFields(context: TransformationContext): (x: Source + + // Add any pending expressions leftover from elided or relocated computed property names + addRange(expressions, pendingExpressions); +- if (referencedName) { +- expressions.push(emitHelpers().createSetFunctionNameHelper(temp, referencedName)); +- } + addRange(expressions, generateInitializedPropertyExpressionsOrClassStaticBlock(staticPropertiesOrClassStaticBlocks, temp)); + expressions.push(factory.cloneNode(temp)); + } +@@ -2115,6 +2040,17 @@ export function transformClassFields(context: TransformationContext): (x: Source + return undefined; + } + ++ function visitThisExpression(node: ThisExpression) { ++ if (shouldTransformThisInStaticInitializers && currentClassElement && ++ isClassStaticBlockDeclaration(currentClassElement) && ++ lexicalEnvironment?.data) { ++ const { classThis, classConstructor } = lexicalEnvironment.data; ++ return classThis ?? classConstructor ?? node; ++ } ++ ++ return node; ++ } ++ + function transformClassMembers(node: ClassDeclaration | ClassExpression) { + const shouldTransformPrivateStaticElementsInClass = !!(getInternalEmitFlags(node) & InternalEmitFlags.TransformPrivateStaticElements); + +@@ -2197,9 +2133,16 @@ export function transformClassFields(context: TransformationContext): (x: Source + // and return a new array. + if (syntheticConstructor || syntheticStaticBlock) { + let membersArray: ClassElement[] | undefined; ++ const classThisAssignmentBlock = find(members, isClassThisAssignmentBlock); ++ const classNamedEvaluationHelperBlock = find(members, isClassNamedEvaluationHelperBlock); ++ membersArray = append(membersArray, classThisAssignmentBlock); ++ membersArray = append(membersArray, classNamedEvaluationHelperBlock); + membersArray = append(membersArray, syntheticConstructor); + membersArray = append(membersArray, syntheticStaticBlock); +- membersArray = addRange(membersArray, members); ++ const remainingMembers = classThisAssignmentBlock || classNamedEvaluationHelperBlock ? ++ filter(members, member => member !== classThisAssignmentBlock && member !== classNamedEvaluationHelperBlock) : ++ members; ++ membersArray = addRange(membersArray, remainingMembers); + members = setTextRange(factory.createNodeArray(membersArray), /*location*/ node.members); + } + +@@ -2256,6 +2199,66 @@ export function transformClassFields(context: TransformationContext): (x: Source + ); + } + ++ function transformConstructorBodyWorker(statementsOut: Statement[], statementsIn: NodeArray, statementOffset: number, superPath: readonly number[], superPathDepth: number, initializerStatements: readonly Statement[], constructor: ConstructorDeclaration) { ++ const superStatementIndex = superPath[superPathDepth]; ++ const superStatement = statementsIn[superStatementIndex]; ++ addRange(statementsOut, visitNodes(statementsIn, visitor, isStatement, statementOffset, superStatementIndex - statementOffset)); ++ statementOffset = superStatementIndex + 1; ++ if (isTryStatement(superStatement)) { ++ const tryBlockStatements: Statement[] = []; ++ ++ transformConstructorBodyWorker( ++ tryBlockStatements, ++ superStatement.tryBlock.statements, ++ /*statementOffset*/ 0, ++ superPath, ++ superPathDepth + 1, ++ initializerStatements, ++ constructor); ++ ++ const tryBlockStatementsArray = factory.createNodeArray(tryBlockStatements); ++ setTextRange(tryBlockStatementsArray, superStatement.tryBlock.statements); ++ ++ statementsOut.push(factory.updateTryStatement( ++ superStatement, ++ factory.updateBlock(superStatement.tryBlock, tryBlockStatements), ++ visitNode(superStatement.catchClause, visitor, isCatchClause), ++ visitNode(superStatement.finallyBlock, visitor, isBlock))); ++ } ++ else { ++ addRange(statementsOut, visitNodes(statementsIn, visitor, isStatement, superStatementIndex, 1)); ++ ++ // Add the property initializers. Transforms this: ++ // ++ // public x = 1; ++ // ++ // Into this: ++ // ++ // constructor() { ++ // this.x = 1; ++ // } ++ // ++ // If we do useDefineForClassFields, they'll be converted elsewhere. ++ // We instead *remove* them from the transformed output at this stage. ++ ++ // parameter-property assignments should occur immediately after the prologue and `super()`, ++ // so only count the statements that immediately follow. ++ while (statementOffset < statementsIn.length) { ++ const statement = statementsIn[statementOffset]; ++ if (isParameterPropertyDeclaration(getOriginalNode(statement), constructor)) { ++ statementOffset++; ++ } ++ else { ++ break; ++ } ++ } ++ ++ addRange(statementsOut, initializerStatements); ++ } ++ ++ addRange(statementsOut, visitNodes(statementsIn, visitor, isStatement, statementOffset)); ++ } ++ + function transformConstructorBody(node: ClassDeclaration | ClassExpression, constructor: ConstructorDeclaration | undefined, isDerivedClass: boolean) { + const instanceProperties = getProperties(node, /*requireInitializer*/ false, /*isStatic*/ false); + let properties = instanceProperties; +@@ -2274,45 +2277,9 @@ export function transformClassFields(context: TransformationContext): (x: Source + resumeLexicalEnvironment(); + + const needsSyntheticConstructor = !constructor && isDerivedClass; +- let indexOfFirstStatementAfterSuperAndPrologue = 0; +- let prologueStatementCount = 0; +- let superStatementIndex = -1; ++ let statementOffset = 0; + let statements: Statement[] = []; + +- if (constructor?.body?.statements) { +- prologueStatementCount = factory.copyPrologue(constructor.body.statements, statements, /*ensureUseStrict*/ false, visitor); +- superStatementIndex = findSuperStatementIndex(constructor.body.statements, prologueStatementCount); +- +- // If there was a super call, visit existing statements up to and including it +- if (superStatementIndex >= 0) { +- indexOfFirstStatementAfterSuperAndPrologue = superStatementIndex + 1; +- statements = [ +- ...statements.slice(0, prologueStatementCount), +- ...visitNodes(constructor.body.statements, visitor, isStatement, prologueStatementCount, indexOfFirstStatementAfterSuperAndPrologue - prologueStatementCount), +- ...statements.slice(prologueStatementCount), +- ]; +- } +- else if (prologueStatementCount >= 0) { +- indexOfFirstStatementAfterSuperAndPrologue = prologueStatementCount; +- } +- } +- +- if (needsSyntheticConstructor) { +- // Add a synthetic `super` call: +- // +- // super(...arguments); +- // +- statements.push( +- factory.createExpressionStatement( +- factory.createCallExpression( +- factory.createSuper(), +- /*typeArguments*/ undefined, +- [factory.createSpreadElement(factory.createIdentifier("arguments"))] +- ) +- ) +- ); +- } +- + // Add the property initializers. Transforms this: + // + // public x = 1; +@@ -2323,42 +2290,68 @@ export function transformClassFields(context: TransformationContext): (x: Source + // this.x = 1; + // } + // +- // If we do useDefineForClassFields, they'll be converted elsewhere. +- // We instead *remove* them from the transformed output at this stage. +- let parameterPropertyDeclarationCount = 0; +- if (constructor?.body) { +- // parameter-property assignments should occur immediately after the prologue and `super()`, +- // so only count the statements that immediately follow. +- for (let i = indexOfFirstStatementAfterSuperAndPrologue; i < constructor.body.statements.length; i++) { +- const statement = constructor.body.statements[i]; +- if (isParameterPropertyDeclaration(getOriginalNode(statement), constructor)) { +- parameterPropertyDeclarationCount++; +- } +- else { +- break; +- } +- } +- if (parameterPropertyDeclarationCount > 0) { +- indexOfFirstStatementAfterSuperAndPrologue += parameterPropertyDeclarationCount; +- } +- } +- ++ const initializerStatements: Statement[] = []; + const receiver = factory.createThis(); ++ + // private methods can be called in property initializers, they should execute first. +- addInstanceMethodStatements(statements, privateMethodsAndAccessors, receiver); ++ addInstanceMethodStatements(initializerStatements, privateMethodsAndAccessors, receiver); + if (constructor) { + const parameterProperties = filter(instanceProperties, prop => isParameterPropertyDeclaration(getOriginalNode(prop), constructor)); + const nonParameterProperties = filter(properties, prop => !isParameterPropertyDeclaration(getOriginalNode(prop), constructor)); +- addPropertyOrClassStaticBlockStatements(statements, parameterProperties, receiver); +- addPropertyOrClassStaticBlockStatements(statements, nonParameterProperties, receiver); ++ addPropertyOrClassStaticBlockStatements(initializerStatements, parameterProperties, receiver); ++ addPropertyOrClassStaticBlockStatements(initializerStatements, nonParameterProperties, receiver); + } + else { +- addPropertyOrClassStaticBlockStatements(statements, properties, receiver); ++ addPropertyOrClassStaticBlockStatements(initializerStatements, properties, receiver); + } + +- // Add existing statements after the initial prologues and super call +- if (constructor) { +- addRange(statements, visitNodes(constructor.body!.statements, visitor, isStatement, indexOfFirstStatementAfterSuperAndPrologue)); ++ if (constructor?.body) { ++ statementOffset = factory.copyPrologue(constructor.body.statements, statements, /*ensureUseStrict*/ false, visitor); ++ const superStatementIndices = findSuperStatementIndexPath(constructor.body.statements, statementOffset); ++ if (superStatementIndices.length) { ++ transformConstructorBodyWorker( ++ statements, ++ constructor.body.statements, ++ statementOffset, ++ superStatementIndices, ++ /*superPathDepth*/ 0, ++ initializerStatements, ++ constructor ++ ); ++ } ++ else { ++ // parameter-property assignments should occur immediately after the prologue and `super()`, ++ // so only count the statements that immediately follow. ++ while (statementOffset < constructor.body.statements.length) { ++ const statement = constructor.body.statements[statementOffset]; ++ if (isParameterPropertyDeclaration(getOriginalNode(statement), constructor)) { ++ statementOffset++; ++ } ++ else { ++ break; ++ } ++ } ++ addRange(statements, initializerStatements); ++ addRange(statements, visitNodes(constructor.body.statements, visitor, isStatement, statementOffset)); ++ } ++ } ++ else { ++ if (needsSyntheticConstructor) { ++ // Add a synthetic `super` call: ++ // ++ // super(...arguments); ++ // ++ statements.push( ++ factory.createExpressionStatement( ++ factory.createCallExpression( ++ factory.createSuper(), ++ /*typeArguments*/ undefined, ++ [factory.createSpreadElement(factory.createIdentifier("arguments"))] ++ ) ++ ) ++ ); ++ } ++ addRange(statements, initializerStatements); + } + + statements = factory.mergeLexicalEnvironment(statements, endLexicalEnvironment()); +@@ -2406,7 +2399,7 @@ export function transformClassFields(context: TransformationContext): (x: Source + + function transformPropertyOrClassStaticBlock(property: PropertyDeclaration | ClassStaticBlockDeclaration, receiver: LeftHandSideExpression) { + const expression = isClassStaticBlockDeclaration(property) ? +- transformClassStaticBlockDeclaration(property) : ++ setCurrentClassElementAnd(property, transformClassStaticBlockDeclaration, property) : + transformProperty(property, receiver); + if (!expression) { + return undefined; +@@ -2451,7 +2444,9 @@ export function transformClassFields(context: TransformationContext): (x: Source + function generateInitializedPropertyExpressionsOrClassStaticBlock(propertiesOrClassStaticBlocks: readonly (PropertyDeclaration | ClassStaticBlockDeclaration)[], receiver: LeftHandSideExpression) { + const expressions: Expression[] = []; + for (const property of propertiesOrClassStaticBlocks) { +- const expression = isClassStaticBlockDeclaration(property) ? transformClassStaticBlockDeclaration(property) : transformProperty(property, receiver); ++ const expression = isClassStaticBlockDeclaration(property) ? ++ setCurrentClassElementAnd(property, transformClassStaticBlockDeclaration, property) : ++ setCurrentClassElementAnd(property, () => transformProperty(property, receiver), /*arg*/ undefined); + if (!expression) { + continue; + } +@@ -2490,17 +2485,8 @@ export function transformClassFields(context: TransformationContext): (x: Source + // We generate a name here in order to reuse the value cached by the relocated computed name expression (which uses the same generated name) + const emitAssignment = !useDefineForClassFields; + +- let referencedName: Expression | undefined; + if (isNamedEvaluation(property, isAnonymousClassNeedingAssignedName)) { +- if (isPropertyNameLiteral(property.name) || isPrivateIdentifier(property.name)) { +- referencedName = factory.createStringLiteralFromNode(property.name); +- } +- else if (isPropertyNameLiteral(property.name.expression) && !isIdentifier(property.name.expression)) { +- referencedName = factory.createStringLiteralFromNode(property.name.expression); +- } +- else { +- referencedName = factory.getGeneratedNameForNode(property.name); +- } ++ property = transformNamedEvaluation(context, property); + } + + const propertyName = +@@ -2514,10 +2500,6 @@ export function transformClassFields(context: TransformationContext): (x: Source + currentClassElement = property; + } + +- const initializerVisitor: Visitor = +- referencedName ? child => namedEvaluationVisitor(child, referencedName!) : +- visitor; +- + if (isPrivateIdentifier(propertyName) && shouldTransformClassElementToWeakMap(property as PrivateIdentifierPropertyDeclaration)) { + const privateIdentifierInfo = accessPrivateIdentifier(propertyName); + if (privateIdentifierInfo) { +@@ -2526,7 +2508,7 @@ export function transformClassFields(context: TransformationContext): (x: Source + return createPrivateInstanceFieldInitializer( + factory, + receiver, +- visitNode(property.initializer, initializerVisitor, isExpression), ++ visitNode(property.initializer, visitor, isExpression), + privateIdentifierInfo.brandCheckIdentifier + ); + } +@@ -2534,7 +2516,7 @@ export function transformClassFields(context: TransformationContext): (x: Source + return createPrivateStaticFieldInitializer( + factory, + privateIdentifierInfo.variableName, +- visitNode(property.initializer, initializerVisitor, isExpression) ++ visitNode(property.initializer, visitor, isExpression) + ); + } + } +@@ -2555,7 +2537,7 @@ export function transformClassFields(context: TransformationContext): (x: Source + return undefined; + } + +- let initializer = visitNode(property.initializer, initializerVisitor, isExpression); ++ let initializer = visitNode(property.initializer, visitor, isExpression); + if (isParameterPropertyDeclaration(propertyOriginalNode, propertyOriginalNode.parent) && isIdentifier(propertyName)) { + // A parameter-property declaration always overrides the initializer. The only time a parameter-property + // declaration *should* have an initializer is when decorators have added initializers that need to run before +@@ -2666,10 +2648,10 @@ export function transformClassFields(context: TransformationContext): (x: Source + * value of the result or the expression itself if the value is either unused or safe to inline into multiple locations + * @param shouldHoist Does the expression need to be reused? (ie, for an initializer or a decorator) + */ +- function getPropertyNameExpressionIfNeeded(name: PropertyName, shouldHoist: boolean, captureReferencedName: boolean): Expression | undefined { ++ function getPropertyNameExpressionIfNeeded(name: PropertyName, shouldHoist: boolean): Expression | undefined { + if (isComputedPropertyName(name)) { + const cacheAssignment = findComputedPropertyNameCacheAssignment(name); +- let expression = visitNode(name.expression, visitor, isExpression); ++ const expression = visitNode(name.expression, visitor, isExpression); + const innerExpression = skipPartiallyEmittedExpressions(expression); + const inlinable = isSimpleInlineableExpression(innerExpression); + const alreadyTransformed = !!cacheAssignment || isAssignmentExpression(innerExpression) && isGeneratedIdentifier(innerExpression.left); +@@ -2681,9 +2663,6 @@ export function transformClassFields(context: TransformationContext): (x: Source + else { + hoistVariableDeclaration(generatedName); + } +- if (captureReferencedName) { +- expression = emitHelpers().createPropKeyHelper(expression); +- } + return factory.createAssignment(generatedName, expression); + } + return (inlinable || isIdentifier(innerExpression)) ? undefined : expression; +@@ -3024,10 +3003,7 @@ export function transformClassFields(context: TransformationContext): (x: Source + // ... + + if (isNamedEvaluation(node, isAnonymousClassNeedingAssignedName)) { +- const left = visitDestructuringAssignmentTarget(node.left); +- const assignedName = getAssignedNameOfIdentifier(node.left, node.right); +- const right = visitNode(node.right, node => namedEvaluationVisitor(node, assignedName), isExpression); +- return factory.updateBinaryExpression(node, left, node.operatorToken, right) as AssignmentExpression; ++ node = transformNamedEvaluation(context, node); + } + if (isAssignmentExpression(node, /*excludeCompoundAssignment*/ true)) { + const left = visitDestructuringAssignmentTarget(node.left); +@@ -3092,9 +3068,7 @@ export function transformClassFields(context: TransformationContext): (x: Source + // ... + + if (isNamedEvaluation(node, isAnonymousClassNeedingAssignedName)) { +- const assignedName = getAssignedNameOfIdentifier(node.name, node.objectAssignmentInitializer); +- const objectAssignmentInitializer = visitNode(node.objectAssignmentInitializer, node => namedEvaluationVisitor(node, assignedName), isExpression); +- return factory.updateShorthandPropertyAssignment(node, node.name, objectAssignmentInitializer); ++ node = transformNamedEvaluation(context, node); + } + + return visitEachChild(node, visitor, context); +@@ -3240,9 +3214,6 @@ export function transformClassFields(context: TransformationContext): (x: Source + lexicalEnvironment?.data && + !noSubstitution.has(node)) { + const { facts, classConstructor, classThis } = lexicalEnvironment.data; +- if (facts & ClassFacts.ClassWasDecorated && legacyDecorators) { +- return factory.createParenthesizedExpression(factory.createVoidZero()); +- } + const substituteThis = shouldSubstituteThisWithClassThis ? classThis ?? classConstructor : classConstructor; + if (substituteThis) { + return setTextRange( +@@ -3253,6 +3224,9 @@ export function transformClassFields(context: TransformationContext): (x: Source + node + ); + } ++ if (facts & ClassFacts.ClassWasDecorated && legacyDecorators) { ++ return factory.createParenthesizedExpression(factory.createVoidZero()); ++ } + } + return node; + } +diff --git a/src/compiler/transformers/classThis.ts b/src/compiler/transformers/classThis.ts +new file mode 100644 +index 000000000..b03cd6814 +--- /dev/null ++++ b/src/compiler/transformers/classThis.ts +@@ -0,0 +1,148 @@ ++import { ++ AssignmentExpression, ++ Block, ++ ClassLikeDeclaration, ++ ClassStaticBlockDeclaration, ++ EqualsToken, ++ ExpressionStatement, ++ getOrCreateEmitNode, ++ Identifier, ++ isAssignmentExpression, ++ isClassDeclaration, ++ isClassStaticBlockDeclaration, ++ isExpressionStatement, ++ isIdentifier, ++ Node, ++ NodeArray, ++ NodeFactory, ++ setSourceMapRange, ++ setTextRange, ++ some, ++ Statement, ++ SyntaxKind, ++ ThisExpression ++} from "../_namespaces/ts"; ++ ++/** ++ * Creates a class `static {}` block used to assign the static `this` to a `_classThis` (or similar) variable. ++ * ++ * @param classThis The identifier to use for the captured static `this` reference, usually with the name `_classThis`. ++ * @param thisExpression Overrides the expression to use for the actual `this` reference. This can be used to provide an ++ * expression that has already had its `EmitFlags` set or may have been tracked to prevent substitution. ++ * @internal ++ */ ++export function createClassThisAssignmentBlock(factory: NodeFactory, classThis: Identifier, thisExpression = factory.createThis()): ClassThisAssignmentBlock { ++ // produces: ++ // ++ // static { _classThis = this; } ++ // ++ ++ const expression = factory.createAssignment(classThis, thisExpression); ++ const statement = factory.createExpressionStatement(expression); ++ const body = factory.createBlock([statement], /*multiLine*/ false); ++ const block = factory.createClassStaticBlockDeclaration(body); ++ ++ // We use `emitNode.classThis` to indicate this is a `_classThis` assignment helper block ++ // and to stash the variable used for `_classThis`. ++ getOrCreateEmitNode(block).classThis = classThis; ++ ++ return block as ClassThisAssignmentBlock; ++} ++ ++/** @internal */ ++export type ClassThisAssignmentBlock = ClassStaticBlockDeclaration & { ++ readonly body: Block & { ++ readonly statements: NodeArray & readonly [ ++ ExpressionStatement & { ++ readonly expression: AssignmentExpression & { ++ readonly left: Identifier; ++ readonly right: ThisExpression; ++ }; ++ } ++ ]; ++ }; ++}; ++ ++/** ++ * Gets whether a node is a `static {}` block containing only a single assignment of the static `this` to the `_classThis` ++ * (or similar) variable stored in the `classthis` property of the block's `EmitNode`. ++ * @internal ++ */ ++export function isClassThisAssignmentBlock(node: Node): node is ClassThisAssignmentBlock { ++ if (!isClassStaticBlockDeclaration(node) || node.body.statements.length !== 1) { ++ return false; ++ } ++ ++ const statement = node.body.statements[0]; ++ return isExpressionStatement(statement) && ++ isAssignmentExpression(statement.expression, /*excludeCompoundAssignment*/ true) && ++ isIdentifier(statement.expression.left) && ++ node.emitNode?.classThis === statement.expression.left && ++ statement.expression.right.kind === SyntaxKind.ThisKeyword; ++} ++ ++/** ++ * Gets whether a `ClassLikeDeclaration` has a `static {}` block containing only a single assignment to a ++ * `_classThis` (or similar) variable. ++ * @internal ++ */ ++export function classHasClassThisAssignment(node: ClassLikeDeclaration) { ++ return !!node.emitNode?.classThis && some(node.members, isClassThisAssignmentBlock); ++} ++ ++/** ++ * Injects a class `static {}` block containing only an assignment of the static `this` to a `_classThis` (or similar) ++ * variable. ++ * ++ * @param classThis The identifier to use for the captured static `this` reference, usually with the name `_classThis`. ++ * @param thisExpression Overrides the expression to use for the actual `this` reference. This can be used to provide an ++ * expression that has already had its `EmitFlags` set or may have been tracked to prevent substitution. ++ * @internal ++ */ ++export function injectClassThisAssignmentIfMissing(factory: NodeFactory, node: T, ++ classThis: Identifier, thisExpression?: ThisExpression): Extract>; ++export function injectClassThisAssignmentIfMissing(factory: NodeFactory, node: T, ++ classThis: Identifier, thisExpression?: ThisExpression) { ++ ++ // given: ++ // ++ // class C { ++ // } ++ // ++ // produces: ++ // ++ // class C { ++ // static { _classThis = this; } ++ // } ++ ++ if (classHasClassThisAssignment(node)) { ++ return node; ++ } ++ ++ const staticBlock = createClassThisAssignmentBlock(factory, classThis, thisExpression); ++ if (node.name) { ++ setSourceMapRange(staticBlock.body.statements[0], node.name); ++ } ++ ++ const members = factory.createNodeArray([staticBlock, ...node.members]); ++ setTextRange(members, node.members); ++ ++ const updatedNode = isClassDeclaration(node) ? ++ factory.updateClassDeclaration( ++ node, ++ node.modifiers, ++ node.name, ++ node.typeParameters, ++ node.heritageClauses, ++ members) : ++ factory.updateClassExpression( ++ node, ++ node.modifiers, ++ node.name, ++ node.typeParameters, ++ node.heritageClauses, ++ members); ++ ++ getOrCreateEmitNode(updatedNode).classThis = classThis; ++ return updatedNode; ++} +diff --git a/src/compiler/transformers/declarations.ts b/src/compiler/transformers/declarations.ts +index 4be05fd79..e94128e8e 100644 +--- a/src/compiler/transformers/declarations.ts ++++ b/src/compiler/transformers/declarations.ts +@@ -150,7 +150,9 @@ import { + isTypeParameterDeclaration, + isTypeQueryNode, + isUnparsedSource, ++ isVarAwaitUsing, + isVariableDeclaration, ++ isVarUsing, + last, + LateBoundDeclaration, + LateVisibilityPaintedStatement, +@@ -217,6 +219,7 @@ import { + unescapeLeadingUnderscores, + UnparsedSource, + VariableDeclaration, ++ VariableDeclarationList, + VariableStatement, + visitArray, + visitEachChild, +@@ -1763,7 +1766,19 @@ export function transformDeclarations(context: TransformationContext) { + if (!forEach(input.declarationList.declarations, getBindingNameVisible)) return; + const nodes = visitNodes(input.declarationList.declarations, visitDeclarationSubtree, isVariableDeclaration); + if (!length(nodes)) return; +- return factory.updateVariableStatement(input, factory.createNodeArray(ensureModifiers(input)), factory.updateVariableDeclarationList(input.declarationList, nodes)); ++ ++ const modifiers = factory.createNodeArray(ensureModifiers(input)); ++ let declList: VariableDeclarationList; ++ if (isVarUsing(input.declarationList) || isVarAwaitUsing(input.declarationList)) { ++ declList = factory.createVariableDeclarationList(nodes, NodeFlags.Const); ++ setOriginalNode(declList, input.declarationList); ++ setTextRange(declList, input.declarationList); ++ setCommentRange(declList, input.declarationList); ++ } ++ else { ++ declList = factory.updateVariableDeclarationList(input.declarationList, nodes); ++ } ++ return factory.updateVariableStatement(input, modifiers, declList); + } + + function recreateBindingPattern(d: BindingPattern): VariableDeclaration[] { +diff --git a/src/compiler/transformers/es2015.ts b/src/compiler/transformers/es2015.ts +index a6e9222b4..5e2b895a2 100644 +--- a/src/compiler/transformers/es2015.ts ++++ b/src/compiler/transformers/es2015.ts +@@ -39,11 +39,12 @@ import { + elementAt, + EmitFlags, + EmitHint, +- emptyArray, ++ every, + Expression, + ExpressionStatement, + ExpressionWithTypeArguments, + filter, ++ findSuperStatementIndexPath, + first, + firstOrUndefined, + flatten, +@@ -112,11 +113,13 @@ import { + isIterationStatement, + isLabeledStatement, + isModifier, ++ isNumericLiteral, + isObjectLiteralElementLike, ++ isObjectLiteralExpression, + isOmittedExpression, + isPackedArrayLiteral, + isPrivateIdentifier, +- isPrologueDirective, ++ isPropertyAssignment, + isPropertyDeclaration, + isPropertyName, + isReturnStatement, +@@ -129,6 +132,7 @@ import { + isVariableDeclaration, + isVariableDeclarationList, + isVariableStatement, ++ isVoidExpression, + isWithStatement, + IterationStatement, + LabeledStatement, +@@ -186,7 +190,6 @@ import { + SwitchStatement, + SyntaxKind, + TaggedTemplateExpression, +- takeWhile, + TemplateExpression, + TextRange, + TokenFlags, +@@ -205,7 +208,7 @@ import { + VisitResult, + VoidExpression, + WhileStatement, +- YieldExpression, ++ YieldExpression + } from "../_namespaces/ts"; + + const enum ES2015SubstitutionFlags { +@@ -1188,6 +1191,190 @@ export function transformES2015(context: TransformationContext): (x: SourceFile + return block; + } + ++ function transformConstructorBodyWorker( ++ prologueOut: Statement[], ++ statementsOut: Statement[], ++ statementsIn: NodeArray, ++ statementOffset: number, ++ superPath: readonly number[], ++ superPathDepth: number, ++ constructor: ConstructorDeclaration & { body: FunctionBody }, ++ isDerivedClass: boolean, ++ hasSynthesizedSuper: boolean, ++ isFirstStatement: boolean, ++ ): boolean { ++ let mayReplaceThis = false; ++ ++ const superStatementIndex = superPathDepth < superPath.length ? superPath[superPathDepth] : -1; ++ const leadingStatementsEnd = superStatementIndex >= 0 ? superStatementIndex : statementsIn.length; ++ ++ // find the index of the first statement material to evaluation ++ if (isFirstStatement && superStatementIndex >= 0) { ++ let firstMaterialIndex = statementOffset; ++ while (isFirstStatement && firstMaterialIndex < superStatementIndex) { ++ const statement = constructor.body.statements[firstMaterialIndex]; ++ if (!isUninitializedVariableStatement(statement) && !isUsingDeclarationStateVariableStatement(statement)) break; ++ firstMaterialIndex++; ++ } ++ ++ isFirstStatement = superStatementIndex === firstMaterialIndex; ++ } ++ ++ // visit everything prior to the statement containing `super()`. ++ addRange(statementsOut, visitNodes(statementsIn, visitor, isStatement, statementOffset, leadingStatementsEnd - statementOffset)); ++ ++ const superStatement = superStatementIndex >= 0 ? statementsIn[superStatementIndex] : undefined; ++ if (superStatement && isTryStatement(superStatement)) { ++ const tryBlockStatements: Statement[] = []; ++ ++ mayReplaceThis = transformConstructorBodyWorker( ++ prologueOut, ++ tryBlockStatements, ++ superStatement.tryBlock.statements, ++ /*statementOffset*/ 0, ++ superPath, ++ superPathDepth + 1, ++ constructor, ++ isDerivedClass, ++ hasSynthesizedSuper, ++ isFirstStatement); ++ ++ const tryBlockStatementsArray = factory.createNodeArray(tryBlockStatements); ++ setTextRange(tryBlockStatementsArray, superStatement.tryBlock.statements); ++ ++ statementsOut.push(factory.updateTryStatement( ++ superStatement, ++ factory.updateBlock(superStatement.tryBlock, tryBlockStatements), ++ visitNode(superStatement.catchClause, visitor, isCatchClause), ++ visitNode(superStatement.finallyBlock, visitor, isBlock))); ++ } ++ else { ++ const superCall = superStatement && getSuperCallFromStatement(superStatement); ++ let superCallExpression: Expression | undefined; ++ if (hasSynthesizedSuper) { ++ superCallExpression = createDefaultSuperCallOrThis(); ++ hierarchyFacts |= HierarchyFacts.ConstructorWithCapturedSuper; ++ } ++ else if (superCall) { ++ superCallExpression = visitSuperCallInBody(superCall); ++ hierarchyFacts |= HierarchyFacts.ConstructorWithCapturedSuper; ++ } ++ ++ if (isDerivedClass || superCallExpression) { ++ if (superCallExpression && ++ superStatementIndex === statementsIn.length - 1 && ++ !(constructor.body.transformFlags & TransformFlags.ContainsLexicalThis)) { ++ // If the subclass constructor does *not* contain `this` and *ends* with a `super()` call, we will use the ++ // following representation: ++ // ++ // ``` ++ // // es2015 (source) ++ // class C extends Base { ++ // constructor() { ++ // super("foo"); ++ // } ++ // } ++ // ++ // // es5 (transformed) ++ // var C = (function (_super) { ++ // function C() { ++ // return _super.call(this, "foo") || this; ++ // } ++ // return C; ++ // })(Base); ++ // ``` ++ ++ const superCall = cast(cast(superCallExpression, isBinaryExpression).left, isCallExpression); ++ const returnStatement = factory.createReturnStatement(superCallExpression); ++ setCommentRange(returnStatement, getCommentRange(superCall)); ++ setEmitFlags(superCall, EmitFlags.NoComments); ++ statementsOut.push(returnStatement); ++ return false; ++ } ++ else { ++ // Otherwise, we will use the following transformed representation for calls to `super()` in a constructor: ++ // ++ // ``` ++ // // es2015 (source) ++ // class C extends Base { ++ // constructor() { ++ // super("foo"); ++ // this.x = 1; ++ // } ++ // } ++ // ++ // // es5 (transformed) ++ // var C = (function (_super) { ++ // function C() { ++ // var _this = _super.call(this, "foo") || this; ++ // _this.x = 1; ++ // return _this; ++ // } ++ // return C; ++ // })(Base); ++ // ``` ++ ++ // If the super() call is the first statement, we can directly create and assign its result to `_this` ++ if (isFirstStatement) { ++ insertCaptureThisForNode(statementsOut, constructor, superCallExpression || createActualThis()); ++ } ++ // Since the `super()` call isn't the first statement, it's split across 1-2 statements: ++ // * A prologue `var _this = this;`, in case the constructor accesses this before super() ++ // * If it exists, a reassignment to that `_this` of the super() call ++ else { ++ insertCaptureThisForNode(prologueOut, constructor, createActualThis()); ++ if (superCallExpression) { ++ addSuperThisCaptureThisForNode(statementsOut, superCallExpression); ++ } ++ } ++ ++ mayReplaceThis = true; ++ } ++ } ++ else { ++ // If a class is not derived from a base class or does not have a call to `super()`, `this` is only ++ // captured when necessitated by an arrow function capturing the lexical `this`: ++ // ++ // ``` ++ // // es2015 ++ // class C {} ++ // ++ // // es5 ++ // var C = (function () { ++ // function C() { ++ // } ++ // return C; ++ // })(); ++ // ``` ++ insertCaptureThisForNodeIfNeeded(prologueOut, constructor); ++ } ++ } ++ ++ // visit everything following the statement containing `super()`. ++ if (superStatementIndex >= 0) { ++ addRange(statementsOut, visitNodes(statementsIn, visitor, isStatement, superStatementIndex + 1)); ++ } ++ ++ return mayReplaceThis; ++ } ++ ++ function isUninitializedVariableStatement(node: Statement) { ++ return isVariableStatement(node) && every(node.declarationList.declarations, decl => isIdentifier(decl.name) && !decl.initializer); ++ } ++ ++ function isUsingDeclarationStateVariableStatement(node: Statement) { ++ if (!isVariableStatement(node) || node.declarationList.declarations.length !== 1) return false; ++ const varDecl = node.declarationList.declarations[0]; ++ if (!isIdentifier(varDecl.name) || !varDecl.initializer) return false; ++ const initializer = varDecl.initializer; ++ if (!isObjectLiteralExpression(initializer) || initializer.properties.length !== 3) return false; ++ const [stackProp, errorProp, hasErrorProp] = initializer.properties; ++ if (!isPropertyAssignment(stackProp) || !isIdentifier(stackProp.name) || idText(stackProp.name) !== "stack" || !isArrayLiteralExpression(stackProp.initializer)) return false; ++ if (!isPropertyAssignment(errorProp) || !isIdentifier(errorProp.name) || idText(errorProp.name) !== "error" || !isVoidExpression(errorProp.initializer) || !isNumericLiteral(errorProp.initializer.expression)) return false; ++ if (!isPropertyAssignment(hasErrorProp) || !isIdentifier(hasErrorProp.name) || idText(hasErrorProp.name) !== "hasError" || hasErrorProp.initializer.kind !== SyntaxKind.FalseKeyword) return false; ++ return true; ++ } ++ + /** + * Transforms the body of a constructor declaration of a class. + * +@@ -1226,134 +1413,40 @@ export function transformES2015(context: TransformationContext): (x: SourceFile + + // In derived classes, there may be code before the necessary super() call + // We'll remove pre-super statements to be tacked on after the rest of the body +- const existingPrologue = takeWhile(constructor.body.statements, isPrologueDirective); +- const { superCall, superStatementIndex } = findSuperCallAndStatementIndex(constructor.body.statements, existingPrologue); +- const postSuperStatementsStart = superStatementIndex === -1 ? existingPrologue.length : superStatementIndex + 1; +- +- // If a super call has already been synthesized, +- // we're going to assume that we should just transform everything after that. +- // The assumption is that no prior step in the pipeline has added any prologue directives. +- let statementOffset = postSuperStatementsStart; +- if (!hasSynthesizedSuper) statementOffset = factory.copyStandardPrologue(constructor.body.statements, prologue, statementOffset, /*ensureUseStrict*/ false); +- if (!hasSynthesizedSuper) statementOffset = factory.copyCustomPrologue(constructor.body.statements, statements, statementOffset, visitor, /*filter*/ undefined); +- +- // If there already exists a call to `super()`, visit the statement directly +- let superCallExpression: Expression | undefined; +- if (hasSynthesizedSuper) { +- superCallExpression = createDefaultSuperCallOrThis(); +- } +- else if (superCall) { +- superCallExpression = visitSuperCallInBody(superCall); +- } +- +- if (superCallExpression) { ++ const standardPrologueEnd = factory.copyStandardPrologue(constructor.body.statements, prologue, /*statementOffset*/ 0); ++ const superStatementIndices = findSuperStatementIndexPath(constructor.body.statements, standardPrologueEnd); ++ if (hasSynthesizedSuper || superStatementIndices.length > 0) { + hierarchyFacts |= HierarchyFacts.ConstructorWithCapturedSuper; + } + ++ const mayReplaceThis = transformConstructorBodyWorker( ++ prologue, ++ statements, ++ constructor.body.statements, ++ standardPrologueEnd, ++ superStatementIndices, ++ /*superPathDepth*/ 0, ++ constructor, ++ isDerivedClass, ++ hasSynthesizedSuper, ++ /*isFirstStatement*/ true // NOTE: this will be recalculated inside of transformConstructorBodyWorker ++ ); ++ + // Add parameter defaults at the beginning of the output, with prologue statements + addDefaultValueAssignmentsIfNeeded(prologue, constructor); + addRestParameterIfNeeded(prologue, constructor, hasSynthesizedSuper); +- +- // visit the remaining statements +- addRange(statements, visitNodes(constructor.body.statements, visitor, isStatement, /*start*/ statementOffset)); +- ++ insertCaptureNewTargetIfNeeded(prologue, constructor); + factory.mergeLexicalEnvironment(prologue, endLexicalEnvironment()); +- insertCaptureNewTargetIfNeeded(prologue, constructor, /*copyOnWrite*/ false); + +- if (isDerivedClass || superCallExpression) { +- if (superCallExpression && postSuperStatementsStart === constructor.body.statements.length && !(constructor.body.transformFlags & TransformFlags.ContainsLexicalThis)) { +- // If the subclass constructor does *not* contain `this` and *ends* with a `super()` call, we will use the +- // following representation: +- // +- // ``` +- // // es2015 (source) +- // class C extends Base { +- // constructor() { +- // super("foo"); +- // } +- // } +- // +- // // es5 (transformed) +- // var C = (function (_super) { +- // function C() { +- // return _super.call(this, "foo") || this; +- // } +- // return C; +- // })(Base); +- // ``` +- const superCall = cast(cast(superCallExpression, isBinaryExpression).left, isCallExpression); +- const returnStatement = factory.createReturnStatement(superCallExpression); +- setCommentRange(returnStatement, getCommentRange(superCall)); +- setEmitFlags(superCall, EmitFlags.NoComments); +- statements.push(returnStatement); +- } +- else { +- // Otherwise, we will use the following transformed representation for calls to `super()` in a constructor: +- // +- // ``` +- // // es2015 (source) +- // class C extends Base { +- // constructor() { +- // super("foo"); +- // this.x = 1; +- // } +- // } +- // +- // // es5 (transformed) +- // var C = (function (_super) { +- // function C() { +- // var _this = _super.call(this, "foo") || this; +- // _this.x = 1; +- // return _this; +- // } +- // return C; +- // })(Base); +- // ``` +- +- // If the super() call is the first statement, we can directly create and assign its result to `_this` +- if (superStatementIndex <= existingPrologue.length) { +- insertCaptureThisForNode(statements, constructor, superCallExpression || createActualThis()); +- } +- // Since the `super()` call isn't the first statement, it's split across 1-2 statements: +- // * A prologue `var _this = this;`, in case the constructor accesses this before super() +- // * If it exists, a reassignment to that `_this` of the super() call +- else { +- insertCaptureThisForNode(prologue, constructor, createActualThis()); +- if (superCallExpression) { +- insertSuperThisCaptureThisForNode(statements, superCallExpression); +- } +- } +- +- if (!isSufficientlyCoveredByReturnStatements(constructor.body)) { +- statements.push(factory.createReturnStatement(factory.createUniqueName("_this", GeneratedIdentifierFlags.Optimistic | GeneratedIdentifierFlags.FileLevel))); +- } +- } +- } +- else { +- // If a class is not derived from a base class or does not have a call to `super()`, `this` is only +- // captured when necessitated by an arrow function capturing the lexical `this`: +- // +- // ``` +- // // es2015 +- // class C {} +- // +- // // es5 +- // var C = (function () { +- // function C() { +- // } +- // return C; +- // })(); +- // ``` +- insertCaptureThisForNodeIfNeeded(prologue, constructor); ++ if (mayReplaceThis && !isSufficientlyCoveredByReturnStatements(constructor.body)) { ++ statements.push(factory.createReturnStatement(factory.createUniqueName("_this", GeneratedIdentifierFlags.Optimistic | GeneratedIdentifierFlags.FileLevel))); + } + + const body = factory.createBlock( + setTextRange( + factory.createNodeArray( + [ +- ...existingPrologue, + ...prologue, +- ...(superStatementIndex <= existingPrologue.length ? emptyArray : visitNodes(constructor.body.statements, visitor, isStatement, existingPrologue.length, superStatementIndex - existingPrologue.length)), + ...statements + ] + ), +@@ -1366,24 +1459,6 @@ export function transformES2015(context: TransformationContext): (x: SourceFile + return body; + } + +- function findSuperCallAndStatementIndex(originalBodyStatements: NodeArray, existingPrologue: Statement[]) { +- for (let i = existingPrologue.length; i < originalBodyStatements.length; i += 1) { +- const superCall = getSuperCallFromStatement(originalBodyStatements[i]); +- if (superCall) { +- // With a super() call, split the statements into pre-super() and 'body' (post-super()) +- return { +- superCall, +- superStatementIndex: i, +- }; +- } +- } +- +- // Since there was no super() call found, consider all statements to be in the main 'body' (post-super()) +- return { +- superStatementIndex: -1, +- }; +- } +- + /** + * We want to try to avoid emitting a return statement in certain cases if a user already returned something. + * It would generate obviously dead code, so we'll try to make things a little bit prettier +@@ -1758,7 +1833,7 @@ export function transformES2015(context: TransformationContext): (x: SourceFile + * @param statements Statements in the constructor body. + * @param superExpression Existing `super()` call for the constructor. + */ +- function insertSuperThisCaptureThisForNode(statements: Statement[], superExpression: Expression): void { ++ function addSuperThisCaptureThisForNode(statements: Statement[], superExpression: Expression): void { + enableSubstitutionsForCapturedThis(); + const assignSuperExpression = factory.createExpressionStatement( + factory.createBinaryExpression( +@@ -1767,7 +1842,7 @@ export function transformES2015(context: TransformationContext): (x: SourceFile + superExpression + ) + ); +- insertStatementAfterCustomPrologue(statements, assignSuperExpression); ++ statements.push(assignSuperExpression); + setCommentRange(assignSuperExpression, getOriginalNode(superExpression).parent); + } + +@@ -1789,7 +1864,7 @@ export function transformES2015(context: TransformationContext): (x: SourceFile + insertStatementAfterCustomPrologue(statements, captureThisStatement); + } + +- function insertCaptureNewTargetIfNeeded(statements: Statement[], node: FunctionLikeDeclaration, copyOnWrite: boolean): Statement[] { ++ function insertCaptureNewTargetIfNeeded(statements: Statement[], node: FunctionLikeDeclaration): Statement[] { + if (hierarchyFacts & HierarchyFacts.NewTarget) { + let newTarget: Expression; + switch (node.kind) { +@@ -1853,11 +1928,6 @@ export function transformES2015(context: TransformationContext): (x: SourceFile + ); + + setEmitFlags(captureNewTargetStatement, EmitFlags.NoComments | EmitFlags.CustomPrologue); +- +- if (copyOnWrite) { +- statements = statements.slice(); +- } +- + insertStatementAfterCustomPrologue(statements, captureNewTargetStatement); + } + +@@ -2232,7 +2302,7 @@ export function transformES2015(context: TransformationContext): (x: SourceFile + } + + factory.mergeLexicalEnvironment(prologue, endLexicalEnvironment()); +- insertCaptureNewTargetIfNeeded(prologue, node, /*copyOnWrite*/ false); ++ insertCaptureNewTargetIfNeeded(prologue, node); + insertCaptureThisForNodeIfNeeded(prologue, node); + + // If we added any final generated statements, this must be a multi-line block +diff --git a/src/compiler/transformers/esDecorators.ts b/src/compiler/transformers/esDecorators.ts +index cdb69e629..d68dda028 100644 +--- a/src/compiler/transformers/esDecorators.ts ++++ b/src/compiler/transformers/esDecorators.ts +@@ -18,6 +18,7 @@ import { + ClassDeclaration, + ClassElement, + ClassExpression, ++ classHasDeclaredOrExplicitlyAssignedName, + ClassLikeDeclaration, + classOrConstructorParameterIsDecorated, + ClassStaticBlockDeclaration, +@@ -36,7 +37,7 @@ import { + Expression, + ExpressionStatement, + findComputedPropertyNameCacheAssignment, +- findSuperStatementIndex, ++ findSuperStatementIndexPath, + firstOrUndefined, + forEachEntry, + ForStatement, +@@ -46,11 +47,9 @@ import { + getAllDecoratorsOfClassElement, + getCommentRange, + getEffectiveBaseTypeNode, +- getEmitScriptTarget, + getFirstConstructorWithBody, + getHeritageClause, + getNonAssignmentOperatorForCompoundAssignment, +- getOrCreateEmitNode, + getOriginalNode, + getSourceMapRange, + hasAccessorModifier, +@@ -60,6 +59,8 @@ import { + HeritageClause, + Identifier, + idText, ++ injectClassNamedEvaluationHelperBlockIfMissing, ++ injectClassThisAssignmentIfMissing, + InternalEmitFlags, + isAmbientPropertyDeclaration, + isArrayBindingOrAssignmentElement, +@@ -70,15 +71,18 @@ import { + isAutoAccessorPropertyDeclaration, + isBindingName, + isBlock, ++ isCatchClause, + isClassElement, + isClassExpression, + isClassLike, ++ isClassNamedEvaluationHelperBlock, + isClassStaticBlockDeclaration, ++ isClassThisAssignmentBlock, + isCompoundAssignment, + isComputedPropertyName, + isDestructuringAssignment, + isElementAccessExpression, +- isEmptyStringLiteral, ++ isExportModifier, + isExpression, + isForInitializer, + isFunctionExpression, +@@ -118,6 +122,7 @@ import { + isStringLiteral, + isSuperProperty, + isTemplateLiteral, ++ isTryStatement, + LeftHandSideExpression, + map, + MethodDeclaration, +@@ -156,6 +161,7 @@ import { + setSourceMapRange, + setTextRange, + ShorthandPropertyAssignment, ++ singleOrMany, + skipOuterExpressions, + skipParentheses, + some, +@@ -168,6 +174,7 @@ import { + ThisExpression, + TransformationContext, + TransformFlags, ++ transformNamedEvaluation, + tryCast, + VariableDeclaration, + visitCommaListElements, +@@ -177,6 +184,7 @@ import { + visitNodes, + Visitor, + VisitResult, ++ WrappedExpression + } from "../_namespaces/ts"; + + // Class/Decorator evaluation order, as it pertains to this transformer: +@@ -280,9 +288,6 @@ export function transformESDecorators(context: TransformationContext): (x: Sourc + hoistVariableDeclaration, + } = context; + +- const compilerOptions = context.getCompilerOptions(); +- const languageVersion = getEmitScriptTarget(compilerOptions); +- + let top: LexicalEnvironmentStackEntry | undefined; + let classInfo: ClassInfo | undefined; + let classThis: Identifier | undefined; +@@ -412,7 +417,7 @@ export function transformESDecorators(context: TransformationContext): (x: Sourc + case SyntaxKind.ClassDeclaration: + return visitClassDeclaration(node as ClassDeclaration); + case SyntaxKind.ClassExpression: +- return visitClassExpression(node as ClassExpression, /*referencedName*/ undefined); ++ return visitClassExpression(node as ClassExpression); + case SyntaxKind.Constructor: + case SyntaxKind.PropertyDeclaration: + case SyntaxKind.ClassStaticBlockDeclaration: +@@ -440,9 +445,9 @@ export function transformESDecorators(context: TransformationContext): (x: Sourc + case SyntaxKind.CommaListExpression: + return visitCommaListExpression(node as CommaListExpression, /*discarded*/ false); + case SyntaxKind.ParenthesizedExpression: +- return visitParenthesizedExpression(node as ParenthesizedExpression, /*discarded*/ false, /*referencedName*/ undefined); ++ return visitParenthesizedExpression(node as ParenthesizedExpression, /*discarded*/ false); + case SyntaxKind.PartiallyEmittedExpression: +- return visitPartiallyEmittedExpression(node as PartiallyEmittedExpression, /*discarded*/ false, /*referencedName*/ undefined); ++ return visitPartiallyEmittedExpression(node as PartiallyEmittedExpression, /*discarded*/ false); + case SyntaxKind.CallExpression: + return visitCallExpression(node as CallExpression); + case SyntaxKind.TaggedTemplateExpression: +@@ -510,19 +515,6 @@ export function transformESDecorators(context: TransformationContext): (x: Sourc + } + } + +- function namedEvaluationVisitor(node: Node, referencedName: Expression): VisitResult { +- switch (node.kind) { +- case SyntaxKind.PartiallyEmittedExpression: +- return visitPartiallyEmittedExpression(node as PartiallyEmittedExpression, /*discarded*/ false, referencedName); +- case SyntaxKind.ParenthesizedExpression: +- return visitParenthesizedExpression(node as ParenthesizedExpression, /*discarded*/ false, referencedName); +- case SyntaxKind.ClassExpression: +- return visitClassExpression(node as ClassExpression, referencedName); +- default: +- return visitor(node); +- } +- } +- + function discardedValueVisitor(node: Node): VisitResult { + switch (node.kind) { + case SyntaxKind.PrefixUnaryExpression: +@@ -533,7 +525,7 @@ export function transformESDecorators(context: TransformationContext): (x: Sourc + case SyntaxKind.CommaListExpression: + return visitCommaListExpression(node as CommaListExpression, /*discarded*/ true); + case SyntaxKind.ParenthesizedExpression: +- return visitParenthesizedExpression(node as ParenthesizedExpression, /*discarded*/ true, /*referencedName*/ undefined); ++ return visitParenthesizedExpression(node as ParenthesizedExpression, /*discarded*/ true); + default: + return visitor(node); + } +@@ -583,14 +575,16 @@ export function transformESDecorators(context: TransformationContext): (x: Sourc + for (const member of node.members) { + if (isNamedClassElement(member) && nodeOrChildIsDecorated(/*useLegacyDecorators*/ false, member, node)) { + if (hasStaticModifier(member)) { +- staticExtraInitializersName ??= factory.createUniqueName("_staticExtraInitializers", GeneratedIdentifierFlags.Optimistic); ++ staticExtraInitializersName ??= factory.createUniqueName("_staticExtraInitializers", GeneratedIdentifierFlags.Optimistic | GeneratedIdentifierFlags.FileLevel); + } + else { +- instanceExtraInitializersName ??= factory.createUniqueName("_instanceExtraInitializers", GeneratedIdentifierFlags.Optimistic); ++ instanceExtraInitializersName ??= factory.createUniqueName("_instanceExtraInitializers", GeneratedIdentifierFlags.Optimistic | GeneratedIdentifierFlags.FileLevel); + } + } + if (isClassStaticBlockDeclaration(member)) { +- hasStaticInitializers = true; ++ if (!isClassNamedEvaluationHelperBlock(member)) { ++ hasStaticInitializers = true; ++ } + } + else if (isPropertyDeclaration(member)) { + if (hasStaticModifier(member)) { +@@ -637,9 +631,15 @@ export function transformESDecorators(context: TransformationContext): (x: Sourc + return false; + } + +- function transformClassLike(node: ClassLikeDeclaration, className: Expression) { ++ function transformClassLike(node: ClassLikeDeclaration) { + startLexicalEnvironment(); + ++ // When a class has class decorators we end up transforming it into a statement that would otherwise give it an ++ // assigned name. If the class doesn't have an assigned name, we'll give it an assigned name of `""`) ++ if (!classHasDeclaredOrExplicitlyAssignedName(node) && classOrConstructorParameterIsDecorated(/*useLegacyDecorators*/ false, node)) { ++ node = injectClassNamedEvaluationHelperBlockIfMissing(context, node, factory.createStringLiteral("")); ++ } ++ + const classReference = factory.getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ false, /*ignoreAssignedName*/ true); + const classInfo = createClassInfo(node); + const classDefinitionStatements: Statement[] = []; +@@ -658,10 +658,15 @@ export function transformESDecorators(context: TransformationContext): (x: Sourc + // of the mutated class. + // - Since a class decorator can add extra initializers, we must define a variable to keep track of + // extra initializers. +- classInfo.classDecoratorsName = factory.createUniqueName("_classDecorators", GeneratedIdentifierFlags.Optimistic); +- classInfo.classDescriptorName = factory.createUniqueName("_classDescriptor", GeneratedIdentifierFlags.Optimistic); +- classInfo.classExtraInitializersName = factory.createUniqueName("_classExtraInitializers", GeneratedIdentifierFlags.Optimistic); +- classInfo.classThis = factory.createUniqueName("_classThis", GeneratedIdentifierFlags.Optimistic); ++ classInfo.classDecoratorsName = factory.createUniqueName("_classDecorators", GeneratedIdentifierFlags.Optimistic | GeneratedIdentifierFlags.FileLevel); ++ classInfo.classDescriptorName = factory.createUniqueName("_classDescriptor", GeneratedIdentifierFlags.Optimistic | GeneratedIdentifierFlags.FileLevel); ++ classInfo.classExtraInitializersName = factory.createUniqueName("_classExtraInitializers", GeneratedIdentifierFlags.Optimistic | GeneratedIdentifierFlags.FileLevel); ++ // We do not mark _classThis as FileLevel if it may be reused by class private fields, which requires the ++ // ability access the captured `_classThis` of outer scopes. ++ const needsUniqueClassThis = some(node.members, member => (isPrivateIdentifierClassElementDeclaration(member) || isAutoAccessorPropertyDeclaration(member)) && hasStaticModifier(member)); ++ classInfo.classThis = factory.createUniqueName("_classThis", needsUniqueClassThis ? ++ GeneratedIdentifierFlags.Optimistic | GeneratedIdentifierFlags.ReservedInNestedScopes : ++ GeneratedIdentifierFlags.Optimistic | GeneratedIdentifierFlags.FileLevel); + classDefinitionStatements.push( + createLet(classInfo.classDecoratorsName, factory.createArrayLiteralExpression(classDecorators)), + createLet(classInfo.classDescriptorName), +@@ -681,7 +686,7 @@ export function transformESDecorators(context: TransformationContext): (x: Sourc + const extendsElement = extendsClause && firstOrUndefined(extendsClause.types); + const extendsExpression = extendsElement && visitNode(extendsElement.expression, visitor, isExpression); + if (extendsExpression) { +- classInfo.classSuper = factory.createUniqueName("_classSuper", GeneratedIdentifierFlags.Optimistic); ++ classInfo.classSuper = factory.createUniqueName("_classSuper", GeneratedIdentifierFlags.Optimistic | GeneratedIdentifierFlags.FileLevel); + + // Ensure we do not give the class or function an assigned name due to the variable by prefixing it + // with `0, `. +@@ -707,15 +712,8 @@ export function transformESDecorators(context: TransformationContext): (x: Sourc + + // 3. The name of the class is assigned. + // +- // If the class did not have a name, set the assigned name as if from NamedEvaluation. +- // We don't need to use the assigned name if it consists of the empty string and the transformed class +- // expression won't get its name from any other source (such as the variable we create to handle +- // class decorators) +- const needsSetNameHelper = !getOriginalNode(node, isClassLike)?.name && (classDecorators || !isStringLiteral(className) || !isEmptyStringLiteral(className)); +- if (needsSetNameHelper) { +- const setNameExpr = emitHelpers().createSetFunctionNameHelper(factory.createThis(), className); +- leadingBlockStatements = append(leadingBlockStatements, factory.createExpressionStatement(setNameExpr)); +- } ++ // If the class did not have a name, the caller should have performed injectClassNamedEvaluationHelperBlockIfMissing ++ // prior to calling this function if a name was needed. + + // 4. For each member: + // a. Member Decorators are evaluated +@@ -841,11 +839,12 @@ export function transformESDecorators(context: TransformationContext): (x: Sourc + if (classInfo.classDescriptorName && classInfo.classDecoratorsName && classInfo.classExtraInitializersName && classInfo.classThis) { + leadingBlockStatements ??= []; + ++ // produces: + // __esDecorate(null, _classDescriptor = { value: this }, _classDecorators, { kind: "class", name: this.name }, _classExtraInitializers); +- const valueProperty = factory.createPropertyAssignment("value", factory.createThis()); ++ const valueProperty = factory.createPropertyAssignment("value", renamedClassThis); + const classDescriptor = factory.createObjectLiteralExpression([valueProperty]); + const classDescriptorAssignment = factory.createAssignment(classInfo.classDescriptorName, classDescriptor); +- const classNameReference = factory.createPropertyAccessExpression(factory.createThis(), "name"); ++ const classNameReference = factory.createPropertyAccessExpression(renamedClassThis, "name"); + const esDecorateHelper = emitHelpers().createESDecorateHelper( + factory.createNull(), + classDescriptorAssignment, +@@ -858,6 +857,7 @@ export function transformESDecorators(context: TransformationContext): (x: Sourc + setSourceMapRange(esDecorateStatement, moveRangePastDecorators(node)); + leadingBlockStatements.push(esDecorateStatement); + ++ // produces: + // C = _classThis = _classDescriptor.value; + const classDescriptorValueReference = factory.createPropertyAccessExpression(classInfo.classDescriptorName, "value"); + const classThisAssignment = factory.createAssignment(classInfo.classThis, classDescriptorValueReference); +@@ -889,43 +889,60 @@ export function transformESDecorators(context: TransformationContext): (x: Sourc + trailingBlockStatements = undefined; + } + +- let newMembers: readonly ClassElement[] = members; ++ // prepare a leading `static {}` block, if necessary ++ // ++ // produces: ++ // class C { ++ // static { ... } ++ // ... ++ // } ++ const leadingStaticBlock = leadingBlockStatements && ++ factory.createClassStaticBlockDeclaration(factory.createBlock(leadingBlockStatements, /*multiLine*/ true)); + +- // insert a leading `static {}` block, if necessary +- if (leadingBlockStatements) { +- // class C { +- // static { ... } +- // ... +- // } +- const leadingStaticBlockBody = factory.createBlock(leadingBlockStatements, /*multiLine*/ true); +- const leadingStaticBlock = factory.createClassStaticBlockDeclaration(leadingStaticBlockBody); +- if (shouldTransformPrivateStaticElementsInClass) { +- // We use `InternalEmitFlags.TransformPrivateStaticElements` as a marker on a class static block +- // to inform the classFields transform that it shouldn't rename `this` to `_classThis` in the +- // transformed class static block. +- setInternalEmitFlags(leadingStaticBlock, InternalEmitFlags.TransformPrivateStaticElements); +- } +- newMembers = [leadingStaticBlock, ...newMembers]; ++ if (leadingStaticBlock && shouldTransformPrivateStaticElementsInClass) { ++ // We use `InternalEmitFlags.TransformPrivateStaticElements` as a marker on a class static block ++ // to inform the classFields transform that it shouldn't rename `this` to `_classThis` in the ++ // transformed class static block. ++ setInternalEmitFlags(leadingStaticBlock, InternalEmitFlags.TransformPrivateStaticElements); + } + +- // append the synthetic constructor, if necessary +- if (syntheticConstructor) { +- newMembers = [...newMembers, syntheticConstructor]; +- } ++ // prepare a trailing `static {}` block, if necessary ++ // ++ // produces: ++ // class C { ++ // ... ++ // static { ... } ++ // } ++ const trailingStaticBlock = trailingBlockStatements && ++ factory.createClassStaticBlockDeclaration(factory.createBlock(trailingBlockStatements, /*multiLine*/ true)); + +- // append a trailing `static {}` block, if necessary +- if (trailingBlockStatements) { +- // class C { +- // ... +- // static { ... } +- // } +- const trailingStaticBlockBody = factory.createBlock(trailingBlockStatements, /*multiLine*/ true); +- const trailingStaticBlock = factory.createClassStaticBlockDeclaration(trailingStaticBlockBody); +- newMembers = [...newMembers, trailingStaticBlock]; +- } ++ if (leadingStaticBlock || syntheticConstructor || trailingStaticBlock) { ++ const newMembers: ClassElement[] = []; ++ ++ // add the NamedEvaluation helper block, if needed ++ const existingNamedEvaluationHelperBlockIndex = members.findIndex(isClassNamedEvaluationHelperBlock); ++ ++ // add the leading `static {}` block ++ if (leadingStaticBlock) { ++ // add the `static {}` block after any existing NamedEvaluation helper block, if one exists. ++ addRange(newMembers, members, 0, existingNamedEvaluationHelperBlockIndex + 1); ++ newMembers.push(leadingStaticBlock); ++ addRange(newMembers, members, existingNamedEvaluationHelperBlockIndex + 1); ++ } ++ else { ++ addRange(newMembers, members); ++ } ++ ++ // append the synthetic constructor, if necessary ++ if (syntheticConstructor) { ++ newMembers.push(syntheticConstructor); ++ } ++ ++ // append a trailing `static {}` block, if necessary ++ if (trailingStaticBlock) { ++ newMembers.push(trailingStaticBlock); ++ } + +- // Update members with newly added members. +- if (newMembers !== members) { + members = setTextRange(factory.createNodeArray(newMembers), members); + } + +@@ -935,6 +952,7 @@ export function transformESDecorators(context: TransformationContext): (x: Sourc + // We use `var` instead of `let` so we can leverage NamedEvaluation to define the class name + // and still be able to ensure it is initialized prior to any use in `static {}`. + ++ // produces: + // (() => { + // let _classDecorators = [...]; + // let _classDescriptor; +@@ -955,6 +973,10 @@ export function transformESDecorators(context: TransformationContext): (x: Sourc + // })(); + + classExpression = factory.createClassExpression(/*modifiers*/ undefined, /*name*/ undefined, /*typeParameters*/ undefined, heritageClauses, members); ++ if (classInfo.classThis) { ++ classExpression = injectClassThisAssignmentIfMissing(factory, classExpression, classInfo.classThis); ++ } ++ + const classReferenceDeclaration = factory.createVariableDeclaration(classReference, /*exclamationToken*/ undefined, /*type*/ undefined, classExpression); + const classReferenceVarDeclList = factory.createVariableDeclarationList([classReferenceDeclaration]); + const returnExpr = classInfo.classThis ? factory.createAssignment(classReference, classInfo.classThis) : classReference; +@@ -964,6 +986,7 @@ export function transformESDecorators(context: TransformationContext): (x: Sourc + ); + } + else { ++ // produces: + // return ; + classExpression = factory.createClassExpression(/*modifiers*/ undefined, node.name, /*typeParameters*/ undefined, heritageClauses, members); + classDefinitionStatements.push(factory.createReturnStatement(classExpression)); +@@ -979,7 +1002,6 @@ export function transformESDecorators(context: TransformationContext): (x: Sourc + } + + setOriginalNode(classExpression, node); +- getOrCreateEmitNode(classExpression).classThis = classInfo.classThis; + return factory.createImmediatelyInvokedArrowFunction(factory.mergeLexicalEnvironment(classDefinitionStatements, lexicalEnvironment)); + } + +@@ -990,37 +1012,64 @@ export function transformESDecorators(context: TransformationContext): (x: Sourc + + function visitClassDeclaration(node: ClassDeclaration): VisitResult { + if (isDecoratedClassLike(node)) { +- if (hasSyntacticModifier(node, ModifierFlags.Export) && +- hasSyntacticModifier(node, ModifierFlags.Default)) { +- // export default (() => { ... })(); +- const originalClass = getOriginalNode(node, isClassLike) ?? node; +- const className = originalClass.name ? factory.createStringLiteralFromNode(originalClass.name) : factory.createStringLiteral("default"); +- const iife = transformClassLike(node, className); +- const statement = factory.createExportDefault(iife); +- setOriginalNode(statement, node); +- setCommentRange(statement, getCommentRange(node)); +- setSourceMapRange(statement, moveRangePastDecorators(node)); +- return statement; ++ const statements: Statement[] = []; ++ const originalClass = getOriginalNode(node, isClassLike) ?? node; ++ const className = originalClass.name ? factory.createStringLiteralFromNode(originalClass.name) : factory.createStringLiteral("default"); ++ const isExport = hasSyntacticModifier(node, ModifierFlags.Export); ++ const isDefault = hasSyntacticModifier(node, ModifierFlags.Default); ++ if (!node.name) { ++ node = injectClassNamedEvaluationHelperBlockIfMissing(context, node, className); ++ } ++ if (isExport && isDefault) { ++ const iife = transformClassLike(node); ++ if (node.name) { ++ // let C = (() => { ... })(); ++ // export default C; ++ const varDecl = factory.createVariableDeclaration(factory.getLocalName(node), /*exclamationToken*/ undefined, /*type*/ undefined, iife); ++ setOriginalNode(varDecl, node); ++ ++ const varDecls = factory.createVariableDeclarationList([varDecl], NodeFlags.Let); ++ const varStatement = factory.createVariableStatement(/*modifiers*/ undefined, varDecls); ++ statements.push(varStatement); ++ ++ const exportStatement = factory.createExportDefault(factory.getDeclarationName(node)); ++ setOriginalNode(exportStatement, node); ++ setCommentRange(exportStatement, getCommentRange(node)); ++ setSourceMapRange(exportStatement, moveRangePastDecorators(node)); ++ statements.push(exportStatement); ++ } ++ else { ++ // export default (() => { ... })(); ++ const exportStatement = factory.createExportDefault(iife); ++ setOriginalNode(exportStatement, node); ++ setCommentRange(exportStatement, getCommentRange(node)); ++ setSourceMapRange(exportStatement, moveRangePastDecorators(node)); ++ statements.push(exportStatement); ++ } + } + else { + // let C = (() => { ... })(); + Debug.assertIsDefined(node.name, "A class declaration that is not a default export must have a name."); +- const iife = transformClassLike(node, factory.createStringLiteralFromNode(node.name)); +- const modifiers = visitNodes(node.modifiers, modifierVisitor, isModifier); +- // When we transform to ES5/3 this will be moved inside an IIFE and should reference the name +- // without any block-scoped variable collision handling +- const declName = languageVersion <= ScriptTarget.ES2015 ? +- factory.getInternalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true) : +- factory.getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true); ++ const iife = transformClassLike(node); ++ const modifierVisitorNoExport = isExport ? ((node: ModifierLike) => isExportModifier(node) ? undefined : modifierVisitor(node)) : modifierVisitor; ++ const modifiers = visitNodes(node.modifiers, modifierVisitorNoExport, isModifier); ++ const declName = factory.getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true); + const varDecl = factory.createVariableDeclaration(declName, /*exclamationToken*/ undefined, /*type*/ undefined, iife); + setOriginalNode(varDecl, node); + + const varDecls = factory.createVariableDeclarationList([varDecl], NodeFlags.Let); +- const statement = factory.createVariableStatement(modifiers, varDecls); +- setOriginalNode(statement, node); +- setCommentRange(statement, getCommentRange(node)); +- return statement; ++ const varStatement = factory.createVariableStatement(modifiers, varDecls); ++ setOriginalNode(varStatement, node); ++ setCommentRange(varStatement, getCommentRange(node)); ++ statements.push(varStatement); ++ if (isExport) { ++ // export { C }; ++ const exportStatement = factory.createExternalModuleExport(declName); ++ setOriginalNode(exportStatement, node); ++ statements.push(exportStatement); ++ } + } ++ return singleOrMany(statements); + } + else { + const modifiers = visitNodes(node.modifiers, modifierVisitor, isModifier); +@@ -1032,10 +1081,9 @@ export function transformESDecorators(context: TransformationContext): (x: Sourc + } + } + +- function visitClassExpression(node: ClassExpression, referencedName: Expression | undefined) { ++ function visitClassExpression(node: ClassExpression) { + if (isDecoratedClassLike(node)) { +- const className = node.name ? factory.createStringLiteralFromNode(node.name) : referencedName ?? factory.createStringLiteral(""); +- const iife = transformClassLike(node, className); ++ const iife = transformClassLike(node); + setOriginalNode(iife, node); + return iife; + } +@@ -1072,6 +1120,37 @@ export function transformESDecorators(context: TransformationContext): (x: Sourc + } + } + ++ function transformConstructorBodyWorker(statementsOut: Statement[], statementsIn: NodeArray, statementOffset: number, superPath: readonly number[], superPathDepth: number, initializerStatements: readonly Statement[]) { ++ const superStatementIndex = superPath[superPathDepth]; ++ const superStatement = statementsIn[superStatementIndex]; ++ addRange(statementsOut, visitNodes(statementsIn, visitor, isStatement, statementOffset, superStatementIndex - statementOffset)); ++ if (isTryStatement(superStatement)) { ++ const tryBlockStatements: Statement[] = []; ++ ++ transformConstructorBodyWorker( ++ tryBlockStatements, ++ superStatement.tryBlock.statements, ++ /*statementOffset*/ 0, ++ superPath, ++ superPathDepth + 1, ++ initializerStatements); ++ ++ const tryBlockStatementsArray = factory.createNodeArray(tryBlockStatements); ++ setTextRange(tryBlockStatementsArray, superStatement.tryBlock.statements); ++ ++ statementsOut.push(factory.updateTryStatement( ++ superStatement, ++ factory.updateBlock(superStatement.tryBlock, tryBlockStatements), ++ visitNode(superStatement.catchClause, visitor, isCatchClause), ++ visitNode(superStatement.finallyBlock, visitor, isBlock))); ++ } ++ else { ++ addRange(statementsOut, visitNodes(statementsIn, visitor, isStatement, superStatementIndex, 1)); ++ addRange(statementsOut, initializerStatements); ++ } ++ addRange(statementsOut, visitNodes(statementsIn, visitor, isStatement, superStatementIndex + 1)); ++ } ++ + function visitConstructorDeclaration(node: ConstructorDeclaration) { + enterClassElement(node); + const modifiers = visitNodes(node.modifiers, modifierVisitor, isModifier); +@@ -1084,11 +1163,9 @@ export function transformESDecorators(context: TransformationContext): (x: Sourc + if (initializerStatements) { + const statements: Statement[] = []; + const nonPrologueStart = factory.copyPrologue(node.body.statements, statements, /*ensureUseStrict*/ false, visitor); +- const superStatementIndex = findSuperStatementIndex(node.body.statements, nonPrologueStart); +- if (superStatementIndex >= 0) { +- addRange(statements, visitNodes(node.body.statements, visitor, isStatement, nonPrologueStart, superStatementIndex + 1 - nonPrologueStart)); +- addRange(statements, initializerStatements); +- addRange(statements, visitNodes(node.body.statements, visitor, isStatement, superStatementIndex + 1)); ++ const superStatementIndices = findSuperStatementIndexPath(node.body.statements, nonPrologueStart); ++ if (superStatementIndices.length > 0) { ++ transformConstructorBodyWorker(statements, node.body.statements, nonPrologueStart, superStatementIndices, 0, initializerStatements); + } + else { + addRange(statements, initializerStatements); +@@ -1119,7 +1196,6 @@ export function transformESDecorators(context: TransformationContext): (x: Sourc + TNode extends MethodDeclaration | PropertyDeclaration | GetAccessorDeclaration | SetAccessorDeclaration, + >( + member: TNode, +- useNamedEvaluation: boolean, + classInfo: ClassInfo | undefined, + createDescriptor?: (node: TNode & { readonly name: PrivateIdentifier }, modifiers: ModifiersArray | undefined) => Expression + ) { +@@ -1131,12 +1207,7 @@ export function transformESDecorators(context: TransformationContext): (x: Sourc + if (!classInfo) { + const modifiers = visitNodes(member.modifiers, modifierVisitor, isModifier); + enterName(); +- if (useNamedEvaluation) { +- ({ referencedName, name } = visitReferencedPropertyName(member.name)); +- } +- else { +- name = visitPropertyName(member.name); +- } ++ name = visitPropertyName(member.name); + exitName(); + return { modifiers, referencedName, name, initializersName, descriptorName, thisArg }; + } +@@ -1215,8 +1286,8 @@ export function transformESDecorators(context: TransformationContext): (x: Sourc + }; + + const extraInitializers = isStatic(member) ? +- classInfo.staticExtraInitializersName ??= factory.createUniqueName("_staticExtraInitializers", GeneratedIdentifierFlags.Optimistic) : +- classInfo.instanceExtraInitializersName ??= factory.createUniqueName("_instanceExtraInitializers", GeneratedIdentifierFlags.Optimistic); ++ classInfo.staticExtraInitializersName ??= factory.createUniqueName("_staticExtraInitializers", GeneratedIdentifierFlags.Optimistic | GeneratedIdentifierFlags.FileLevel) : ++ classInfo.instanceExtraInitializersName ??= factory.createUniqueName("_instanceExtraInitializers", GeneratedIdentifierFlags.Optimistic | GeneratedIdentifierFlags.FileLevel); + + if (isMethodOrAccessor(member)) { + // __esDecorate(this, null, _static_member_decorators, { kind: "method", name: "...", static: true, private: false, access: { ... } }, _staticExtraInitializers); +@@ -1278,12 +1349,7 @@ export function transformESDecorators(context: TransformationContext): (x: Sourc + + if (name === undefined) { + enterName(); +- if (useNamedEvaluation) { +- ({ referencedName, name } = visitReferencedPropertyName(member.name)); +- } +- else { +- name = visitPropertyName(member.name); +- } ++ name = visitPropertyName(member.name); + exitName(); + } + +@@ -1298,7 +1364,7 @@ export function transformESDecorators(context: TransformationContext): (x: Sourc + + function visitMethodDeclaration(node: MethodDeclaration) { + enterClassElement(node); +- const { modifiers, name, descriptorName } = partialTransformClassElement(node, /*useNamedEvaluation*/ false, classInfo, createMethodDescriptorObject); ++ const { modifiers, name, descriptorName } = partialTransformClassElement(node, classInfo, createMethodDescriptorObject); + if (descriptorName) { + exitClassElement(); + return finishClassElement(createMethodDescriptorForwarder(modifiers, name, descriptorName), node); +@@ -1313,7 +1379,7 @@ export function transformESDecorators(context: TransformationContext): (x: Sourc + + function visitGetAccessorDeclaration(node: GetAccessorDeclaration) { + enterClassElement(node); +- const { modifiers, name, descriptorName } = partialTransformClassElement(node, /*useNamedEvaluation*/ false, classInfo, createGetAccessorDescriptorObject); ++ const { modifiers, name, descriptorName } = partialTransformClassElement(node, classInfo, createGetAccessorDescriptorObject); + if (descriptorName) { + exitClassElement(); + return finishClassElement(createGetAccessorDescriptorForwarder(modifiers, name, descriptorName), node); +@@ -1328,7 +1394,7 @@ export function transformESDecorators(context: TransformationContext): (x: Sourc + + function visitSetAccessorDeclaration(node: SetAccessorDeclaration) { + enterClassElement(node); +- const { modifiers, name, descriptorName } = partialTransformClassElement(node, /*useNamedEvaluation*/ false, classInfo, createSetAccessorDescriptorObject); ++ const { modifiers, name, descriptorName } = partialTransformClassElement(node, classInfo, createSetAccessorDescriptorObject); + if (descriptorName) { + exitClassElement(); + return finishClassElement(createSetAccessorDescriptorForwarder(modifiers, name, descriptorName), node); +@@ -1344,14 +1410,30 @@ export function transformESDecorators(context: TransformationContext): (x: Sourc + function visitClassStaticBlockDeclaration(node: ClassStaticBlockDeclaration) { + enterClassElement(node); + +- if (classInfo) classInfo.hasStaticInitializers = true; +- const result = visitEachChild(node, visitor, context); ++ let result: ClassStaticBlockDeclaration; ++ if (isClassNamedEvaluationHelperBlock(node)) { ++ result = visitEachChild(node, visitor, context); ++ } ++ else if (isClassThisAssignmentBlock(node)) { ++ const savedClassThis = classThis; ++ classThis = undefined; ++ result = visitEachChild(node, visitor, context); ++ classThis = savedClassThis; ++ } ++ else { ++ if (classInfo) classInfo.hasStaticInitializers = true; ++ result = visitEachChild(node, visitor, context); ++ } + + exitClassElement(); + return result; + } + + function visitPropertyDeclaration(node: PropertyDeclaration) { ++ if (isNamedEvaluation(node, isAnonymousClassNeedingAssignedName)) { ++ node = transformNamedEvaluation(context, node, canIgnoreEmptyStringLiteralInAssignedName(node.initializer)); ++ } ++ + enterClassElement(node); + + // TODO(rbuckton): We support decorating `declare x` fields with legacyDecorators, but we currently don't +@@ -1366,15 +1448,11 @@ export function transformESDecorators(context: TransformationContext): (x: Sourc + // a. Let _value_ be ? NamedEvaluation of |Initializer| with argument _functionObject_.[[ClassFieldInitializerName]]. + // ... + +- const useNamedEvaluation = isNamedEvaluation(node, isAnonymousClassNeedingAssignedName); +- const { modifiers, name, referencedName, initializersName, descriptorName, thisArg } = partialTransformClassElement(node, useNamedEvaluation, classInfo, hasAccessorModifier(node) ? createAccessorPropertyDescriptorObject : undefined); ++ const { modifiers, name, initializersName, descriptorName, thisArg } = partialTransformClassElement(node, classInfo, hasAccessorModifier(node) ? createAccessorPropertyDescriptorObject : undefined); + + startLexicalEnvironment(); + +- let initializer = referencedName ? +- visitNode(node.initializer, node => namedEvaluationVisitor(node, referencedName), isExpression): +- visitNode(node.initializer, visitor, isExpression); +- ++ let initializer = visitNode(node.initializer, visitor, isExpression); + if (initializersName) { + initializer = emitHelpers().createRunInitializersHelper( + thisArg ?? factory.createThis(), +@@ -1542,32 +1620,20 @@ export function transformESDecorators(context: TransformationContext): (x: Sourc + // i. Set _v_ to ? NamedEvaluation of |Initializer| with argument _bindingId_. + // ... + +- let updated: ParameterDeclaration; + if (isNamedEvaluation(node, isAnonymousClassNeedingAssignedName)) { +- const assignedName = getAssignedNameOfIdentifier(node.name, node.initializer); +- const name = visitNode(node.name, visitor, isBindingName); +- const initializer = visitNode(node.initializer, node => namedEvaluationVisitor(node, assignedName), isExpression); +- updated = factory.updateParameterDeclaration( +- node, +- /*modifiers*/ undefined, +- /*dotDotDotToken*/ undefined, +- name, +- /*questionToken*/ undefined, +- /*type*/ undefined, +- initializer); +- } +- else { +- updated = factory.updateParameterDeclaration( +- node, +- /*modifiers*/ undefined, +- node.dotDotDotToken, +- visitNode(node.name, visitor, isBindingName), +- /*questionToken*/ undefined, +- /*type*/ undefined, +- visitNode(node.initializer, visitor, isExpression) +- ); ++ node = transformNamedEvaluation(context, node, canIgnoreEmptyStringLiteralInAssignedName(node.initializer)); + } + ++ const updated = factory.updateParameterDeclaration( ++ node, ++ /*modifiers*/ undefined, ++ node.dotDotDotToken, ++ visitNode(node.name, visitor, isBindingName), ++ /*questionToken*/ undefined, ++ /*type*/ undefined, ++ visitNode(node.initializer, visitor, isExpression) ++ ); ++ + if (updated !== node) { + // While we emit the source map for the node after skipping decorators and modifiers, + // we need to emit the comments for the original range. +@@ -1583,6 +1649,16 @@ export function transformESDecorators(context: TransformationContext): (x: Sourc + return isClassExpression(node) && !node.name && isDecoratedClassLike(node); + } + ++ function canIgnoreEmptyStringLiteralInAssignedName(node: WrappedExpression) { ++ // The IIFE produced for `(@dec class {})` will result in an assigned name of the form ++ // `var class_1 = class { };`, and thus the empty string cannot be ignored. However, The IIFE ++ // produced for `(class { @dec x; })` will not result in an assigned name since it ++ // transforms to `return class { };`, and thus the empty string *can* be ignored. ++ ++ const innerExpression = skipOuterExpressions(node); ++ return isClassExpression(innerExpression) && !innerExpression.name && !classOrConstructorParameterIsDecorated(/*useLegacyDecorators*/ false, innerExpression); ++ } ++ + function visitForStatement(node: ForStatement) { + return factory.updateForStatement( + node, +@@ -1632,10 +1708,8 @@ export function transformESDecorators(context: TransformationContext): (x: Sourc + // ... + + if (isNamedEvaluation(node, isAnonymousClassNeedingAssignedName)) { +- const assignedName = getAssignedNameOfIdentifier(node.left, node.right); +- const left = visitNode(node.left, visitor, isExpression); +- const right = visitNode(node.right, node => namedEvaluationVisitor(node, assignedName), isExpression); +- return factory.updateBinaryExpression(node, left, node.operatorToken, right); ++ node = transformNamedEvaluation(context, node, canIgnoreEmptyStringLiteralInAssignedName(node.right)); ++ return visitEachChild(node, visitor, context); + } + + if (isSuperProperty(node.left) && classThis && classSuper) { +@@ -1818,9 +1892,7 @@ export function transformESDecorators(context: TransformationContext): (x: Sourc + // ... + + if (isNamedEvaluation(node, isAnonymousClassNeedingAssignedName)) { +- const { referencedName, name } = visitReferencedPropertyName(node.name); +- const initializer = visitNode(node.initializer, node => namedEvaluationVisitor(node, referencedName), isExpression); +- return factory.updatePropertyAssignment(node, name, initializer); ++ node = transformNamedEvaluation(context, node, canIgnoreEmptyStringLiteralInAssignedName(node.initializer)); + } + + return visitEachChild(node, visitor, context); +@@ -1842,10 +1914,7 @@ export function transformESDecorators(context: TransformationContext): (x: Sourc + // ... + + if (isNamedEvaluation(node, isAnonymousClassNeedingAssignedName)) { +- const assignedName = getAssignedNameOfIdentifier(node.name, node.initializer); +- const name = visitNode(node.name, visitor, isBindingName); +- const initializer = visitNode(node.initializer, node => namedEvaluationVisitor(node, assignedName), isExpression); +- return factory.updateVariableDeclaration(node, name, /*exclamationToken*/ undefined, /*type*/ undefined, initializer); ++ node = transformNamedEvaluation(context, node, canIgnoreEmptyStringLiteralInAssignedName(node.initializer)); + } + + return visitEachChild(node, visitor, context); +@@ -1869,11 +1938,7 @@ export function transformESDecorators(context: TransformationContext): (x: Sourc + // ... + + if (isNamedEvaluation(node, isAnonymousClassNeedingAssignedName)) { +- const assignedName = getAssignedNameOfIdentifier(node.name, node.initializer); +- const propertyName = visitNode(node.propertyName, visitor, isPropertyName); +- const name = visitNode(node.name, visitor, isBindingName); +- const initializer = visitNode(node.initializer, node => namedEvaluationVisitor(node, assignedName), isExpression); +- return factory.updateBindingElement(node, /*dotDotDotToken*/ undefined, propertyName, name, initializer); ++ node = transformNamedEvaluation(context, node, canIgnoreEmptyStringLiteralInAssignedName(node.initializer)); + } + + return visitEachChild(node, visitor, context); +@@ -1919,15 +1984,12 @@ export function transformESDecorators(context: TransformationContext): (x: Sourc + // ... + + if (isAssignmentExpression(node, /*excludeCompoundAssignment*/ true)) { +- const assignmentTarget = visitDestructuringAssignmentTarget(node.left); +- let initializer: Expression; + if (isNamedEvaluation(node, isAnonymousClassNeedingAssignedName)) { +- const assignedName = getAssignedNameOfIdentifier(node.left, node.right); +- initializer = visitNode(node.right, node => namedEvaluationVisitor(node, assignedName), isExpression); +- } +- else { +- initializer = visitNode(node.right, visitor, isExpression); ++ node = transformNamedEvaluation(context, node, canIgnoreEmptyStringLiteralInAssignedName(node.right)); + } ++ ++ const assignmentTarget = visitDestructuringAssignmentTarget(node.left); ++ const initializer = visitNode(node.right, visitor, isExpression); + return factory.updateBinaryExpression(node, assignmentTarget, node.operatorToken, initializer) as ArrayAssignmentElement; + } + else { +@@ -1989,10 +2051,7 @@ export function transformESDecorators(context: TransformationContext): (x: Sourc + // ... + + if (isNamedEvaluation(node, isAnonymousClassNeedingAssignedName)) { +- const assignedName = getAssignedNameOfIdentifier(node.name, node.objectAssignmentInitializer); +- const name = visitNode(node.name, visitor, isIdentifier); +- const objectAssignmentInitializer = visitNode(node.objectAssignmentInitializer, node => namedEvaluationVisitor(node, assignedName), isExpression); +- return factory.updateShorthandPropertyAssignment(node, name, objectAssignmentInitializer); ++ node = transformNamedEvaluation(context, node, canIgnoreEmptyStringLiteralInAssignedName(node.objectAssignmentInitializer)); + } + + return visitEachChild(node, visitor, context); +@@ -2033,40 +2092,28 @@ export function transformESDecorators(context: TransformationContext): (x: Sourc + // a. Let _value_ be ? NamedEvaluation of |AssignmentExpression| with argument `"default"`. + // ... + +- // NOTE: Since emit for `export =` translates to `module.exports = ...`, the assigned nameof the class +- // is `""`. +- + if (isNamedEvaluation(node, isAnonymousClassNeedingAssignedName)) { +- const referencedName = factory.createStringLiteral(node.isExportEquals ? "" : "default"); +- const modifiers = visitNodes(node.modifiers, modifierVisitor, isModifier); +- const expression = visitNode(node.expression, node => namedEvaluationVisitor(node, referencedName), isExpression); +- return factory.updateExportAssignment(node, modifiers, expression); ++ node = transformNamedEvaluation(context, node, canIgnoreEmptyStringLiteralInAssignedName(node.expression)); + } + + return visitEachChild(node, visitor, context); + } + +- function visitParenthesizedExpression(node: ParenthesizedExpression, discarded: boolean, referencedName: Expression | undefined) { ++ function visitParenthesizedExpression(node: ParenthesizedExpression, discarded: boolean) { + // 8.4.5 RS: NamedEvaluation + // ParenthesizedExpression : `(` Expression `)` + // ... + // 2. Return ? NamedEvaluation of |Expression| with argument _name_. + +- const visitorFunc: Visitor = +- discarded ? discardedValueVisitor : +- referencedName ? node => namedEvaluationVisitor(node, referencedName) : +- visitor; ++ const visitorFunc: Visitor = discarded ? discardedValueVisitor : visitor; + const expression = visitNode(node.expression, visitorFunc, isExpression); + return factory.updateParenthesizedExpression(node, expression); + } + +- function visitPartiallyEmittedExpression(node: PartiallyEmittedExpression, discarded: boolean, referencedName: Expression | undefined) { ++ function visitPartiallyEmittedExpression(node: PartiallyEmittedExpression, discarded: boolean) { + // Emulates 8.4.5 RS: NamedEvaluation + +- const visitorFunc: Visitor = +- discarded ? discardedValueVisitor : +- referencedName ? node => namedEvaluationVisitor(node, referencedName) : +- visitor; ++ const visitorFunc: Visitor = discarded ? discardedValueVisitor : visitor; + const expression = visitNode(node.expression, visitorFunc, isExpression); + return factory.updatePartiallyEmittedExpression(node, expression); + } +@@ -2132,7 +2179,6 @@ export function transformESDecorators(context: TransformationContext): (x: Sourc + const prefix = kind === "get" || kind === "set" ? kind : undefined; + const functionName = factory.createStringLiteralFromNode(name, /*isSingleQuote*/ undefined); + const namedFunction = emitHelpers().createSetFunctionNameHelper(func, functionName, prefix); +- + const method = factory.createPropertyAssignment(factory.createIdentifier(kind), namedFunction); + setOriginalNode(method, original); + setSourceMapRange(method, moveRangePastDecorators(original)); +@@ -2325,11 +2371,4 @@ export function transformESDecorators(context: TransformationContext): (x: Sourc + ]) + ); + } +- +- function getAssignedNameOfIdentifier(name: Identifier, initializer: Expression) { +- const originalClass = getOriginalNode(initializer, isClassLike); +- return originalClass && !originalClass.name && hasSyntacticModifier(originalClass, ModifierFlags.Default) ? +- factory.createStringLiteral("default") : +- factory.createStringLiteralFromNode(name); +- } + } +diff --git a/src/compiler/transformers/esnext.ts b/src/compiler/transformers/esnext.ts +index 730958dae..d20cdd511 100644 +--- a/src/compiler/transformers/esnext.ts ++++ b/src/compiler/transformers/esnext.ts +@@ -1,33 +1,875 @@ + import { ++ addEmitHelpers, ++ addRange, ++ append, ++ arrayFrom, ++ BindingElement, ++ Block, + Bundle, ++ CaseOrDefaultClause, + chainBundle, ++ ClassDeclaration, ++ Debug, ++ EmitFlags, ++ ExportAssignment, ++ ExportSpecifier, ++ Expression, ++ ForOfStatement, ++ ForStatement, ++ GeneratedIdentifierFlags, ++ getEmitFlags, ++ hasSyntacticModifier, ++ Identifier, ++ IdentifierNameMap, ++ isArray, ++ isBindingPattern, ++ isBlock, ++ isCaseClause, ++ isCustomPrologue, ++ isExpression, ++ isGeneratedIdentifier, ++ isIdentifier, ++ isLocalName, ++ isNamedEvaluation, ++ isOmittedExpression, ++ isPrologueDirective, ++ isSourceFile, ++ isStatement, ++ isVariableDeclarationList, ++ isVariableStatement, ++ ModifierFlags, + Node, ++ NodeFlags, ++ setCommentRange, ++ setEmitFlags, ++ setOriginalNode, ++ setSourceMapRange, ++ setTextRange, ++ skipOuterExpressions, + SourceFile, ++ Statement, ++ SwitchStatement, ++ SyntaxKind, + TransformationContext, + TransformFlags, ++ transformNamedEvaluation, ++ VariableDeclaration, ++ VariableDeclarationList, ++ VariableStatement, ++ visitArray, + visitEachChild, +- VisitResult, ++ visitNode, ++ visitNodes, ++ VisitResult + } from "../_namespaces/ts"; + ++const enum UsingKind { ++ None, ++ Sync, ++ Async, ++} ++ + /** @internal */ + export function transformESNext(context: TransformationContext): (x: SourceFile | Bundle) => SourceFile | Bundle { +- return chainBundle(context, transformSourceFile); +- +- function transformSourceFile(node: SourceFile) { +- if (node.isDeclarationFile) { +- return node; +- } +- +- return visitEachChild(node, visitor, context); +- } +- +- function visitor(node: Node): VisitResult { +- if ((node.transformFlags & TransformFlags.ContainsESNext) === 0) { +- return node; +- } +- switch (node.kind) { +- default: +- return visitEachChild(node, visitor, context); +- } +- } ++ const { ++ factory, ++ getEmitHelperFactory: emitHelpers, ++ hoistVariableDeclaration, ++ startLexicalEnvironment, ++ endLexicalEnvironment, ++ } = context; ++ ++ let exportBindings: IdentifierNameMap; ++ let exportVars: VariableDeclaration[]; ++ let defaultExportBinding: Identifier | undefined; ++ let exportEqualsBinding: Identifier | undefined; ++ ++ return chainBundle(context, transformSourceFile); ++ ++ function transformSourceFile(node: SourceFile) { ++ if (node.isDeclarationFile) { ++ return node; ++ } ++ ++ const visited = visitNode(node, visitor, isSourceFile); ++ addEmitHelpers(visited, context.readEmitHelpers()); ++ exportVars = undefined!; ++ exportBindings = undefined!; ++ defaultExportBinding = undefined; ++ return visited; ++ } ++ ++ function visitor(node: Node): VisitResult { ++ if ((node.transformFlags & TransformFlags.ContainsESNext) === 0) { ++ return node; ++ } ++ ++ switch (node.kind) { ++ case SyntaxKind.SourceFile: ++ return visitSourceFile(node as SourceFile); ++ ++ case SyntaxKind.Block: ++ return visitBlock(node as Block); ++ ++ case SyntaxKind.ForStatement: ++ return visitForStatement(node as ForStatement); ++ ++ case SyntaxKind.ForOfStatement: ++ return visitForOfStatement(node as ForOfStatement); ++ ++ case SyntaxKind.SwitchStatement: ++ return visitSwitchStatement(node as SwitchStatement); ++ ++ default: ++ return visitEachChild(node, visitor, context); ++ } ++ } ++ ++ function visitSourceFile(node: SourceFile): SourceFile { ++ const usingKind = getUsingKindOfStatements(node.statements); ++ if (usingKind) { ++ // Imports and exports must stay at the top level. This means we must hoist all imports, exports, and ++ // top-level function declarations and bindings out of the `try` statements we generate. For example: ++ // ++ // given: ++ // ++ // import { w } from "mod"; ++ // const x = expr1; ++ // using y = expr2; ++ // const z = expr3; ++ // export function f() { ++ // console.log(z); ++ // } ++ // ++ // produces: ++ // ++ // import { x } from "mod"; // <-- preserved ++ // const x = expr1; // <-- preserved ++ // var y, z; // <-- hoisted ++ // export function f() { // <-- hoisted ++ // console.log(z); ++ // } ++ // const env_1 = { stack: [], error: void 0, hasError: false }; ++ // try { ++ // y = __addDisposableResource(env_1, expr2, false); ++ // z = expr3; ++ // } ++ // catch (e_1) { ++ // env_1.error = e_1; ++ // env_1.hasError = true; ++ // } ++ // finally { ++ // __disposeResource(env_1); ++ // } ++ // ++ // In this transformation, we hoist `y`, `z`, and `f` to a new outer statement list while moving all other ++ // statements in the source file into the `try` block, which is the same approach we use for System module ++ // emit. Unlike System module emit, we attempt to preserve all statements prior to the first top-level ++ // `using` to isolate the complexity of the transformed output to only where it is necessary. ++ startLexicalEnvironment(); ++ ++ exportBindings = new IdentifierNameMap(); ++ exportVars = []; ++ ++ const prologueCount = countPrologueStatements(node.statements); ++ const topLevelStatements: Statement[] = []; ++ addRange(topLevelStatements, visitArray(node.statements, visitor, isStatement, 0, prologueCount)); ++ ++ // Collect and transform any leading statements up to the first `using` or `await using`. This preserves ++ // the original statement order much as is possible. ++ let pos = prologueCount; ++ while (pos < node.statements.length) { ++ const statement = node.statements[pos]; ++ if (getUsingKind(statement) !== UsingKind.None) { ++ if (pos > prologueCount) { ++ addRange(topLevelStatements, visitNodes(node.statements, visitor, isStatement, prologueCount, pos - prologueCount)); ++ } ++ break; ++ } ++ pos++; ++ } ++ ++ Debug.assert(pos < node.statements.length, "Should have encountered at least one 'using' statement."); ++ ++ // transform the rest of the body ++ const envBinding = createEnvBinding(); ++ const bodyStatements = transformUsingDeclarations(node.statements, pos, node.statements.length, envBinding, topLevelStatements); ++ ++ // add `export {}` declarations for any hoisted bindings. ++ if (exportBindings.size) { ++ append(topLevelStatements, factory.createExportDeclaration( ++ /*modifiers*/ undefined, ++ /*isTypeOnly*/ false, ++ factory.createNamedExports(arrayFrom(exportBindings.values())) ++ )); ++ } ++ ++ addRange(topLevelStatements, endLexicalEnvironment()); ++ if (exportVars.length) { ++ topLevelStatements.push(factory.createVariableStatement( ++ factory.createModifiersFromModifierFlags(ModifierFlags.Export), ++ factory.createVariableDeclarationList( ++ exportVars, ++ NodeFlags.Let ++ ) ++ )); ++ } ++ addRange(topLevelStatements, createDownlevelUsingStatements(bodyStatements, envBinding, usingKind === UsingKind.Async)); ++ ++ if (exportEqualsBinding) { ++ topLevelStatements.push(factory.createExportAssignment( ++ /*modifiers*/ undefined, ++ /*isExportEquals*/ true, ++ exportEqualsBinding ++ )); ++ } ++ ++ return factory.updateSourceFile(node, topLevelStatements); ++ } ++ ++ return visitEachChild(node, visitor, context); ++ } ++ ++ function visitBlock(node: Block): VisitResult { ++ const usingKind = getUsingKindOfStatements(node.statements); ++ if (usingKind) { ++ const prologueCount = countPrologueStatements(node.statements); ++ const envBinding = createEnvBinding(); ++ return factory.updateBlock( ++ node, ++ [ ++ ...visitArray(node.statements, visitor, isStatement, 0, prologueCount), ++ ...createDownlevelUsingStatements( ++ transformUsingDeclarations(node.statements, prologueCount, node.statements.length, envBinding, /*topLevelStatements*/ undefined), ++ envBinding, ++ usingKind === UsingKind.Async, ++ ) ++ ] ++ ); ++ } ++ return visitEachChild(node, visitor, context); ++ } ++ ++ function visitForStatement(node: ForStatement): VisitResult { ++ if (node.initializer && isUsingVariableDeclarationList(node.initializer)) { ++ // given: ++ // ++ // for (using x = expr; cond; incr) { ... } ++ // ++ // produces a shallow transformation to: ++ // ++ // { ++ // using x = expr; ++ // for (; cond; incr) { ... } ++ // } ++ // ++ // before handing the shallow transformation back to the visitor for an in-depth transformation. ++ return visitNode( ++ factory.createBlock([ ++ factory.createVariableStatement(/*modifiers*/ undefined, node.initializer), ++ factory.updateForStatement( ++ node, ++ /*initializer*/ undefined, ++ node.condition, ++ node.incrementor, ++ node.statement ++ ) ++ ]), ++ visitor, ++ isStatement ++ ); ++ } ++ ++ return visitEachChild(node, visitor, context); ++ } ++ ++ function visitForOfStatement(node: ForOfStatement) { ++ if (isUsingVariableDeclarationList(node.initializer)) { ++ // given: ++ // ++ // for (using x of y) { ... } ++ // ++ // produces a shallow transformation to: ++ // ++ // for (const x_1 of y) { ++ // using x = x; ++ // ... ++ // } ++ // ++ // before handing the shallow transformation back to the visitor for an in-depth transformation. ++ const forInitializer = node.initializer; ++ Debug.assertNode(forInitializer, isUsingVariableDeclarationList); ++ Debug.assert(forInitializer.declarations.length === 1, "ForInitializer may only have one declaration"); ++ ++ const forDecl = forInitializer.declarations[0]; ++ Debug.assert(!forDecl.initializer, "ForInitializer may not have an initializer"); ++ ++ const isAwaitUsing = getUsingKindOfVariableDeclarationList(forInitializer) === UsingKind.Async; ++ const temp = factory.getGeneratedNameForNode(forDecl.name); ++ const usingVar = factory.updateVariableDeclaration(forDecl, forDecl.name, /*exclamationToken*/ undefined, /*type*/ undefined, temp); ++ const usingVarList = factory.createVariableDeclarationList([usingVar], isAwaitUsing ? NodeFlags.AwaitUsing : NodeFlags.Using); ++ const usingVarStatement = factory.createVariableStatement(/*modifiers*/ undefined, usingVarList); ++ return visitNode( ++ factory.updateForOfStatement( ++ node, ++ node.awaitModifier, ++ factory.createVariableDeclarationList([ ++ factory.createVariableDeclaration(temp) ++ ], NodeFlags.Const), ++ node.expression, ++ isBlock(node.statement) ? ++ factory.updateBlock(node.statement, [ ++ usingVarStatement, ++ ...node.statement.statements ++ ]) : ++ factory.createBlock([ ++ usingVarStatement, ++ node.statement ++ ], /*multiLine*/ true) ++ ), ++ visitor, ++ isStatement ++ ); ++ } ++ return visitEachChild(node, visitor, context); ++ } ++ ++ function visitCaseOrDefaultClause(node: CaseOrDefaultClause, envBinding: Identifier) { ++ if (getUsingKindOfStatements(node.statements) !== UsingKind.None) { ++ if (isCaseClause(node)) { ++ return factory.updateCaseClause( ++ node, ++ visitNode(node.expression, visitor, isExpression), ++ transformUsingDeclarations(node.statements, /*start*/ 0, node.statements.length, envBinding, /*topLevelStatements*/ undefined) ++ ); ++ } ++ else { ++ return factory.updateDefaultClause( ++ node, ++ transformUsingDeclarations(node.statements, /*start*/ 0, node.statements.length, envBinding, /*topLevelStatements*/ undefined) ++ ); ++ } ++ } ++ return visitEachChild(node, visitor, context); ++ } ++ ++ function visitSwitchStatement(node: SwitchStatement) { ++ // given: ++ // ++ // switch (expr) { ++ // case expr: ++ // using res = expr; ++ // } ++ // ++ // produces: ++ // ++ // const env_1 = { stack: [], error: void 0, hasError: false }; ++ // try { ++ // switch(expr) { ++ // case expr: ++ // const res = __addDisposableResource(env_1, expr, false); ++ // } ++ // } ++ // catch (e_1) { ++ // env_1.error = e_1; ++ // env_1.hasError = true; ++ // } ++ // finally { ++ // __disposeResources(env_1); ++ // } ++ // ++ const usingKind = getUsingKindOfCaseOrDefaultClauses(node.caseBlock.clauses); ++ if (usingKind) { ++ const envBinding = createEnvBinding(); ++ return createDownlevelUsingStatements( ++ [ ++ factory.updateSwitchStatement( ++ node, ++ visitNode(node.expression, visitor, isExpression), ++ factory.updateCaseBlock( ++ node.caseBlock, ++ node.caseBlock.clauses.map(clause => visitCaseOrDefaultClause(clause, envBinding)) ++ ) ++ ) ++ ], ++ envBinding, ++ usingKind === UsingKind.Async, ++ ); ++ } ++ ++ return visitEachChild(node, visitor, context); ++ } ++ ++ /** ++ * Transform `using` declarations in a statement list. ++ */ ++ function transformUsingDeclarations(statementsIn: readonly Statement[], start: number, end: number, envBinding: Identifier, topLevelStatements: Statement[] | undefined) { ++ const statements: Statement[] = []; ++ ++ for (let i = start; i < end; i++) { ++ const statement = statementsIn[i]; ++ const usingKind = getUsingKind(statement); ++ if (usingKind) { ++ Debug.assertNode(statement, isVariableStatement); ++ const declarations: VariableDeclaration[] = []; ++ for (let declaration of statement.declarationList.declarations) { ++ if (!isIdentifier(declaration.name)) { ++ // Since binding patterns are a grammar error, we reset `declarations` so we don't process this as a `using`. ++ declarations.length = 0; ++ break; ++ } ++ ++ // perform a shallow transform for any named evaluation ++ if (isNamedEvaluation(declaration)) { ++ declaration = transformNamedEvaluation(context, declaration); ++ } ++ ++ const initializer = visitNode(declaration.initializer, visitor, isExpression) ?? factory.createVoidZero(); ++ declarations.push(factory.updateVariableDeclaration( ++ declaration, ++ declaration.name, ++ /*exclamationToken*/ undefined, ++ /*type*/ undefined, ++ emitHelpers().createAddDisposableResourceHelper( ++ envBinding, ++ initializer, ++ usingKind === UsingKind.Async ++ ) ++ )); ++ } ++ ++ // Only replace the statement if it was valid. ++ if (declarations.length) { ++ const varList = factory.createVariableDeclarationList(declarations, NodeFlags.Const); ++ setOriginalNode(varList, statement.declarationList); ++ setTextRange(varList, statement.declarationList); ++ hoistOrAppendNode(factory.updateVariableStatement(statement, /*modifiers*/ undefined, varList)); ++ continue; ++ } ++ } ++ ++ const result = visitor(statement); ++ if (isArray(result)) { ++ result.forEach(hoistOrAppendNode); ++ } ++ else if (result) { ++ hoistOrAppendNode(result); ++ } ++ } ++ ++ return statements; ++ ++ function hoistOrAppendNode(node: Node) { ++ Debug.assertNode(node, isStatement); ++ append(statements, hoist(node)); ++ } ++ ++ function hoist(node: Statement) { ++ if (!topLevelStatements) return node; ++ ++ switch (node.kind) { ++ case SyntaxKind.ImportDeclaration: ++ case SyntaxKind.ImportEqualsDeclaration: ++ case SyntaxKind.ExportDeclaration: ++ case SyntaxKind.FunctionDeclaration: ++ return hoistImportOrExportOrHoistedDeclaration(node, topLevelStatements); ++ case SyntaxKind.ExportAssignment: ++ return hoistExportAssignment(node as ExportAssignment); ++ case SyntaxKind.ClassDeclaration: ++ return hoistClassDeclaration(node as ClassDeclaration); ++ case SyntaxKind.VariableStatement: ++ return hoistVariableStatement(node as VariableStatement); ++ } ++ ++ return node; ++ } ++ } ++ ++ function hoistImportOrExportOrHoistedDeclaration(node: Statement, topLevelStatements: Statement[]) { ++ // NOTE: `node` has already been visited ++ topLevelStatements.push(node); ++ return undefined; ++ } ++ ++ function hoistExportAssignment(node: ExportAssignment) { ++ return node.isExportEquals ? hoistExportEquals(node) : hoistExportDefault(node); ++ } ++ ++ function hoistExportDefault(node: ExportAssignment) { ++ // NOTE: `node` has already been visited ++ if (defaultExportBinding) { ++ // invalid case of multiple `export default` declarations. Don't assert here, just pass it through ++ return node; ++ } ++ ++ // given: ++ // ++ // export default expr; ++ // ++ // produces: ++ // ++ // // top level ++ // var default_1; ++ // export { default_1 as default }; ++ // ++ // // body ++ // default_1 = expr; ++ ++ defaultExportBinding = factory.createUniqueName("_default", GeneratedIdentifierFlags.ReservedInNestedScopes | GeneratedIdentifierFlags.FileLevel | GeneratedIdentifierFlags.Optimistic); ++ hoistBindingIdentifier(defaultExportBinding, /*isExport*/ true, "default", node); ++ ++ // give a class or function expression an assigned name, if needed. ++ let expression = node.expression; ++ let innerExpression = skipOuterExpressions(expression); ++ if (isNamedEvaluation(innerExpression)) { ++ innerExpression = transformNamedEvaluation(context, innerExpression, /*ignoreEmptyStringLiteral*/ false, "default"); ++ expression = factory.restoreOuterExpressions(expression, innerExpression); ++ } ++ ++ const assignment = factory.createAssignment(defaultExportBinding, expression); ++ return factory.createExpressionStatement(assignment); ++ } ++ ++ function hoistExportEquals(node: ExportAssignment) { ++ // NOTE: `node` has already been visited ++ if (exportEqualsBinding) { ++ // invalid case of multiple `export default` declarations. Don't assert here, just pass it through ++ return node; ++ } ++ ++ // given: ++ // ++ // export = expr; ++ // ++ // produces: ++ // ++ // // top level ++ // var default_1; ++ // ++ // try { ++ // // body ++ // default_1 = expr; ++ // } ... ++ // ++ // // top level suffix ++ // export = default_1; ++ ++ exportEqualsBinding = factory.createUniqueName("_default", GeneratedIdentifierFlags.ReservedInNestedScopes | GeneratedIdentifierFlags.FileLevel | GeneratedIdentifierFlags.Optimistic); ++ hoistVariableDeclaration(exportEqualsBinding); ++ ++ // give a class or function expression an assigned name, if needed. ++ const assignment = factory.createAssignment(exportEqualsBinding, node.expression); ++ return factory.createExpressionStatement(assignment); ++ } ++ ++ function hoistClassDeclaration(node: ClassDeclaration) { ++ // NOTE: `node` has already been visited ++ if (!node.name && defaultExportBinding) { ++ // invalid case of multiple `export default` declarations. Don't assert here, just pass it through ++ return node; ++ } ++ ++ const isExported = hasSyntacticModifier(node, ModifierFlags.Export); ++ const isDefault = hasSyntacticModifier(node, ModifierFlags.Default); ++ ++ // When hoisting a class declaration at the top level of a file containing a top-level `using` statement, we ++ // must first convert it to a class expression so that we can hoist the binding outside of the `try`. ++ let expression: Expression = factory.converters.convertToClassExpression(node); ++ if (node.name) { ++ // given: ++ // ++ // using x = expr; ++ // class C {} ++ // ++ // produces: ++ // ++ // var x, C; ++ // const env_1 = { ... }; ++ // try { ++ // x = __addDisposableResource(env_1, expr, false); ++ // C = class {}; ++ // } ++ // catch (e_1) { ++ // env_1.error = e_1; ++ // env_1.hasError = true; ++ // } ++ // finally { ++ // __disposeResources(env_1); ++ // } ++ // ++ // If the class is exported, we also produce an `export { C };` ++ hoistBindingIdentifier(factory.getLocalName(node), isExported && !isDefault, /*exportAlias*/ undefined, node); ++ expression = factory.createAssignment(factory.getDeclarationName(node), expression); ++ if (isNamedEvaluation(expression)) { ++ expression = transformNamedEvaluation(context, expression, /*ignoreEmptyStringLiteral*/ false); ++ } ++ setOriginalNode(expression, node); ++ setSourceMapRange(expression, node); ++ setCommentRange(expression, node); ++ } ++ ++ if (isDefault && !defaultExportBinding) { ++ // In the case of a default export, we create a temporary variable that we export as the default and then ++ // assign to that variable. ++ // ++ // given: ++ // ++ // using x = expr; ++ // export default class C {} ++ // ++ // produces: ++ // ++ // export { default_1 as default }; ++ // var x, C, default_1; ++ // const env_1 = { ... }; ++ // try { ++ // x = __addDisposableResource(env_1, expr, false); ++ // default_1 = C = class {}; ++ // } ++ // catch (e_1) { ++ // env_1.error = e_1; ++ // env_1.hasError = true; ++ // } ++ // finally { ++ // __disposeResources(env_1); ++ // } ++ // ++ // Though we will never reassign `default_1`, this most closely matches the specified runtime semantics. ++ defaultExportBinding = factory.createUniqueName("_default", GeneratedIdentifierFlags.ReservedInNestedScopes | GeneratedIdentifierFlags.FileLevel | GeneratedIdentifierFlags.Optimistic); ++ hoistBindingIdentifier(defaultExportBinding, /*isExport*/ true, "default", node); ++ expression = factory.createAssignment(defaultExportBinding, expression); ++ if (isNamedEvaluation(expression)) { ++ expression = transformNamedEvaluation(context, expression, /*ignoreEmptyStringLiteral*/ false, "default"); ++ } ++ setOriginalNode(expression, node); ++ } ++ ++ return factory.createExpressionStatement(expression); ++ } ++ ++ function hoistVariableStatement(node: VariableStatement) { ++ // NOTE: `node` has already been visited ++ let expressions: Expression[] | undefined; ++ const isExported = hasSyntacticModifier(node, ModifierFlags.Export); ++ for (const variable of node.declarationList.declarations) { ++ hoistBindingElement(variable, isExported, variable); ++ if (variable.initializer) { ++ expressions = append(expressions, hoistInitializedVariable(variable)); ++ } ++ } ++ if (expressions) { ++ const statement = factory.createExpressionStatement(factory.inlineExpressions(expressions)); ++ setOriginalNode(statement, node); ++ setCommentRange(statement, node); ++ setSourceMapRange(statement, node); ++ return statement; ++ } ++ return undefined; ++ } ++ ++ function hoistInitializedVariable(node: VariableDeclaration) { ++ // NOTE: `node` has already been visited ++ Debug.assertIsDefined(node.initializer); ++ let target: Expression; ++ if (isIdentifier(node.name)) { ++ target = factory.cloneNode(node.name); ++ setEmitFlags(target, getEmitFlags(target) & ~(EmitFlags.LocalName | EmitFlags.ExportName | EmitFlags.InternalName)); ++ } ++ else { ++ target = factory.converters.convertToAssignmentPattern(node.name); ++ } ++ ++ const assignment = factory.createAssignment(target, node.initializer); ++ setOriginalNode(assignment, node); ++ setCommentRange(assignment, node); ++ setSourceMapRange(assignment, node); ++ return assignment; ++ } ++ ++ function hoistBindingElement(node: VariableDeclaration | BindingElement, isExportedDeclaration: boolean, original: Node | undefined) { ++ // NOTE: `node` has already been visited ++ if (isBindingPattern(node.name)) { ++ for (const element of node.name.elements) { ++ if (!isOmittedExpression(element)) { ++ hoistBindingElement(element, isExportedDeclaration, original); ++ } ++ } ++ } ++ else { ++ hoistBindingIdentifier(node.name, isExportedDeclaration, /*exportAlias*/ undefined, original); ++ } ++ } ++ ++ function hoistBindingIdentifier(node: Identifier, isExport: boolean, exportAlias: string | Identifier | undefined, original: Node | undefined) { ++ // NOTE: `node` has already been visited ++ const name = isGeneratedIdentifier(node) ? node : factory.cloneNode(node); ++ if (isExport) { ++ if (exportAlias === undefined && !isLocalName(name)) { ++ const varDecl = factory.createVariableDeclaration(name); ++ if (original) { ++ setOriginalNode(varDecl, original); ++ } ++ exportVars.push(varDecl); ++ return; ++ } ++ ++ const localName = exportAlias !== undefined ? name : undefined; ++ const exportName = exportAlias !== undefined ? exportAlias : name; ++ const specifier = factory.createExportSpecifier(/*isTypeOnly*/ false, localName, exportName); ++ if (original) { ++ setOriginalNode(specifier, original); ++ } ++ exportBindings.set(name, specifier); ++ } ++ hoistVariableDeclaration(name); ++ } ++ ++ function createEnvBinding() { ++ return factory.createUniqueName("env"); ++ } ++ ++ function createDownlevelUsingStatements(bodyStatements: readonly Statement[], envBinding: Identifier, async: boolean) { ++ const statements: Statement[] = []; ++ ++ // produces: ++ // ++ // const env_1 = { stack: [], error: void 0, hasError: false }; ++ // ++ const envObject = factory.createObjectLiteralExpression([ ++ factory.createPropertyAssignment("stack", factory.createArrayLiteralExpression()), ++ factory.createPropertyAssignment("error", factory.createVoidZero()), ++ factory.createPropertyAssignment("hasError", factory.createFalse()) ++ ]); ++ const envVar = factory.createVariableDeclaration(envBinding, /*exclamationToken*/ undefined, /*type*/ undefined, envObject); ++ const envVarList = factory.createVariableDeclarationList([envVar], NodeFlags.Const); ++ const envVarStatement = factory.createVariableStatement(/*modifiers*/ undefined, envVarList); ++ statements.push(envVarStatement); ++ ++ // when `async` is `false`, produces: ++ // ++ // try { ++ // ++ // } ++ // catch (e_1) { ++ // env_1.error = e_1; ++ // env_1.hasError = true; ++ // } ++ // finally { ++ // __disposeResources(env_1); ++ // } ++ ++ // when `async` is `true`, produces: ++ // ++ // try { ++ // ++ // } ++ // catch (e_1) { ++ // env_1.error = e_1; ++ // env_1.hasError = true; ++ // } ++ // finally { ++ // const result_1 = __disposeResources(env_1); ++ // if (result_1) { ++ // await result_1; ++ // } ++ // } ++ ++ // Unfortunately, it is necessary to use two properties to indicate an error because `throw undefined` is legal ++ // JavaScript. ++ const tryBlock = factory.createBlock(bodyStatements, /*multiLine*/ true); ++ const bodyCatchBinding = factory.createUniqueName("e"); ++ const catchClause = factory.createCatchClause( ++ bodyCatchBinding, ++ factory.createBlock([ ++ factory.createExpressionStatement( ++ factory.createAssignment( ++ factory.createPropertyAccessExpression(envBinding, "error"), ++ bodyCatchBinding) ++ ), ++ factory.createExpressionStatement( ++ factory.createAssignment( ++ factory.createPropertyAccessExpression(envBinding, "hasError"), ++ factory.createTrue()) ++ ), ++ ], /*multiLine*/ true) ++ ); ++ ++ let finallyBlock: Block; ++ if (async) { ++ const result = factory.createUniqueName("result"); ++ finallyBlock = factory.createBlock([ ++ factory.createVariableStatement( ++ /*modifiers*/ undefined, ++ factory.createVariableDeclarationList([ ++ factory.createVariableDeclaration( ++ result, ++ /*exclamationToken*/ undefined, ++ /*type*/ undefined, ++ emitHelpers().createDisposeResourcesHelper(envBinding) ++ ) ++ ], NodeFlags.Const) ++ ), ++ factory.createIfStatement(result, factory.createExpressionStatement(factory.createAwaitExpression(result))) ++ ], /*multiLine*/ true); ++ } ++ else { ++ finallyBlock = factory.createBlock([ ++ factory.createExpressionStatement( ++ emitHelpers().createDisposeResourcesHelper(envBinding) ++ ) ++ ], /*multiLine*/ true); ++ } ++ ++ const tryStatement = factory.createTryStatement(tryBlock, catchClause, finallyBlock); ++ statements.push(tryStatement); ++ ++ return statements; ++ } ++} ++ ++function countPrologueStatements(statements: readonly Statement[]) { ++ for (let i = 0; i < statements.length; i++) { ++ if (!isPrologueDirective(statements[i]) && !isCustomPrologue(statements[i])) { ++ return i; ++ } ++ } ++ return 0; ++} ++ ++function isUsingVariableDeclarationList(node: Node): node is VariableDeclarationList & { _usingBrand: any } { ++ return isVariableDeclarationList(node) && getUsingKindOfVariableDeclarationList(node) !== UsingKind.None; ++} ++ ++function getUsingKindOfVariableDeclarationList(node: VariableDeclarationList) { ++ return (node.flags & NodeFlags.BlockScoped) === NodeFlags.AwaitUsing ? UsingKind.Async : ++ (node.flags & NodeFlags.BlockScoped) === NodeFlags.Using ? UsingKind.Sync : ++ UsingKind.None; ++} ++ ++function getUsingKindOfVariableStatement(node: VariableStatement) { ++ return getUsingKindOfVariableDeclarationList(node.declarationList); ++} ++ ++function getUsingKind(statement: Statement): UsingKind { ++ return isVariableStatement(statement) ? getUsingKindOfVariableStatement(statement) : UsingKind.None; ++} ++ ++function getUsingKindOfStatements(statements: readonly Statement[]): UsingKind { ++ let result = UsingKind.None; ++ for (const statement of statements) { ++ const usingKind = getUsingKind(statement); ++ if (usingKind === UsingKind.Async) return UsingKind.Async; ++ if (usingKind > result) result = usingKind; ++ } ++ return result; ++} ++ ++function getUsingKindOfCaseOrDefaultClauses(clauses: readonly CaseOrDefaultClause[]): UsingKind { ++ let result = UsingKind.None; ++ for (const clause of clauses) { ++ const usingKind = getUsingKindOfStatements(clause.statements); ++ if (usingKind === UsingKind.Async) return UsingKind.Async; ++ if (usingKind > result) result = usingKind; ++ } ++ return result; + } +diff --git a/src/compiler/transformers/legacyDecorators.ts b/src/compiler/transformers/legacyDecorators.ts +index f175fe71a..87b3b162c 100644 +--- a/src/compiler/transformers/legacyDecorators.ts ++++ b/src/compiler/transformers/legacyDecorators.ts +@@ -55,7 +55,6 @@ import { + isStatic, + map, + MethodDeclaration, +- Modifier, + ModifierFlags, + moveRangePastModifiers, + Node, +@@ -373,39 +372,29 @@ export function transformLegacyDecorators(context: TransformationContext): (x: S + + // let ${name} = ${classExpression} where name is either declaredName if the class doesn't contain self-reference + // or decoratedClassAlias if the class contain self-reference. +- const varDecl = factory.createVariableDeclaration( +- declName, +- /*exclamationToken*/ undefined, +- /*type*/ undefined, +- classAlias && !assignClassAliasInStaticBlock ? factory.createAssignment(classAlias, classExpression) : classExpression +- ); ++ const varInitializer = classAlias && !assignClassAliasInStaticBlock ? factory.createAssignment(classAlias, classExpression) : classExpression; ++ const varDecl = factory.createVariableDeclaration(declName, /*exclamationToken*/ undefined, /*type*/ undefined, varInitializer); + setOriginalNode(varDecl, node); + +- let varModifiers: Modifier[] | undefined; +- if (isExport && !isDefault) { +- varModifiers = factory.createModifiersFromModifierFlags(ModifierFlags.Export); +- } ++ const varDeclList = factory.createVariableDeclarationList([varDecl], NodeFlags.Let); ++ const varStatement = factory.createVariableStatement(/*modifiers*/ undefined, varDeclList); ++ setOriginalNode(varStatement, node); ++ setTextRange(varStatement, location); ++ setCommentRange(varStatement, node); + +- const statement = factory.createVariableStatement( +- varModifiers, +- factory.createVariableDeclarationList([ +- varDecl +- ], NodeFlags.Let) +- ); +- setOriginalNode(statement, node); +- setTextRange(statement, location); +- setCommentRange(statement, node); +- +- const statements: Statement[] = [statement]; ++ const statements: Statement[] = [varStatement]; + addRange(statements, decorationStatements); + addConstructorDecorationStatement(statements, node); + +- if (isExport && isDefault) { +- statements.push(factory.createExportAssignment( +- /*modifiers*/ undefined, +- /*isExportEquals*/ false, +- declName +- )); ++ if (isExport) { ++ if (isDefault) { ++ const exportStatement = factory.createExportDefault(declName); ++ statements.push(exportStatement); ++ } ++ else { ++ const exportStatement = factory.createExternalModuleExport(factory.getDeclarationName(node)); ++ statements.push(exportStatement); ++ } + } + + return statements; +diff --git a/src/compiler/transformers/module/module.ts b/src/compiler/transformers/module/module.ts +index fc95446ce..b6339fcc1 100644 +--- a/src/compiler/transformers/module/module.ts ++++ b/src/compiler/transformers/module/module.ts +@@ -59,6 +59,7 @@ import { + hasJsonModuleEmitEnabled, + hasSyntacticModifier, + Identifier, ++ IdentifierNameMap, + idText, + IfStatement, + ImportCall, +@@ -86,6 +87,7 @@ import { + isExpression, + isExternalModule, + isExternalModuleImportEqualsDeclaration, ++ isFileLevelReservedGeneratedIdentifier, + isForInitializer, + isFunctionExpression, + isGeneratedIdentifier, +@@ -224,7 +226,7 @@ export function transformModule(context: TransformationContext): (x: SourceFile + } + + currentSourceFile = node; +- currentModuleInfo = collectExternalModuleInfo(context, node, resolver, compilerOptions); ++ currentModuleInfo = collectExternalModuleInfo(context, node); + moduleInfoMap[getOriginalNodeId(node)] = currentModuleInfo; + + // Perform the transformation. +@@ -668,22 +670,16 @@ export function transformModule(context: TransformationContext): (x: SourceFile + function topLevelVisitor(node: Node): VisitResult { + switch (node.kind) { + case SyntaxKind.ImportDeclaration: +- return visitImportDeclaration(node as ImportDeclaration); ++ return visitTopLevelImportDeclaration(node as ImportDeclaration); + + case SyntaxKind.ImportEqualsDeclaration: +- return visitImportEqualsDeclaration(node as ImportEqualsDeclaration); ++ return visitTopLevelImportEqualsDeclaration(node as ImportEqualsDeclaration); + + case SyntaxKind.ExportDeclaration: +- return visitExportDeclaration(node as ExportDeclaration); ++ return visitTopLevelExportDeclaration(node as ExportDeclaration); + + case SyntaxKind.ExportAssignment: +- return visitExportAssignment(node as ExportAssignment); +- +- case SyntaxKind.FunctionDeclaration: +- return visitFunctionDeclaration(node as FunctionDeclaration); +- +- case SyntaxKind.ClassDeclaration: +- return visitClassDeclaration(node as ClassDeclaration); ++ return visitTopLevelExportAssignment(node as ExportAssignment); + + default: + return topLevelNestedVisitor(node); +@@ -1358,7 +1354,7 @@ export function transformModule(context: TransformationContext): (x: SourceFile + * + * @param node The node to visit. + */ +- function visitImportDeclaration(node: ImportDeclaration): VisitResult { ++ function visitTopLevelImportDeclaration(node: ImportDeclaration): VisitResult { + let statements: Statement[] | undefined; + const namespaceDeclaration = getNamespaceDeclarationNode(node); + if (moduleKind !== ModuleKind.AMD) { +@@ -1470,7 +1466,7 @@ export function transformModule(context: TransformationContext): (x: SourceFile + * + * @param node The node to visit. + */ +- function visitImportEqualsDeclaration(node: ImportEqualsDeclaration): VisitResult { ++ function visitTopLevelImportEqualsDeclaration(node: ImportEqualsDeclaration): VisitResult { + Debug.assert(isExternalModuleImportEqualsDeclaration(node), "import= for internal module references should be handled in an earlier transformer."); + + let statements: Statement[] | undefined; +@@ -1538,7 +1534,7 @@ export function transformModule(context: TransformationContext): (x: SourceFile + * + * @param The node to visit. + */ +- function visitExportDeclaration(node: ExportDeclaration): VisitResult { ++ function visitTopLevelExportDeclaration(node: ExportDeclaration): VisitResult { + if (!node.moduleSpecifier) { + // Elide export declarations with no module specifier as they are handled + // elsewhere. +@@ -1648,7 +1644,7 @@ export function transformModule(context: TransformationContext): (x: SourceFile + * + * @param node The node to visit. + */ +- function visitExportAssignment(node: ExportAssignment): VisitResult { ++ function visitTopLevelExportAssignment(node: ExportAssignment): VisitResult { + if (node.isExportEquals) { + return undefined; + } +@@ -1878,20 +1874,21 @@ export function transformModule(context: TransformationContext): (x: SourceFile + return statements; + } + ++ const seen = new IdentifierNameMap(); + if (importClause.name) { +- statements = appendExportsOfDeclaration(statements, importClause); ++ statements = appendExportsOfDeclaration(statements, seen, importClause); + } + + const namedBindings = importClause.namedBindings; + if (namedBindings) { + switch (namedBindings.kind) { + case SyntaxKind.NamespaceImport: +- statements = appendExportsOfDeclaration(statements, namedBindings); ++ statements = appendExportsOfDeclaration(statements, seen, namedBindings); + break; + + case SyntaxKind.NamedImports: + for (const importBinding of namedBindings.elements) { +- statements = appendExportsOfDeclaration(statements, importBinding, /*liveBinding*/ true); ++ statements = appendExportsOfDeclaration(statements, seen, importBinding, /*liveBinding*/ true); + } + + break; +@@ -1915,7 +1912,7 @@ export function transformModule(context: TransformationContext): (x: SourceFile + return statements; + } + +- return appendExportsOfDeclaration(statements, decl); ++ return appendExportsOfDeclaration(statements, new IdentifierNameMap(), decl); + } + + /** +@@ -1974,7 +1971,7 @@ export function transformModule(context: TransformationContext): (x: SourceFile + } + } + else if (!isGeneratedIdentifier(decl.name) && (!isVariableDeclaration(decl) || decl.initializer || isForInOrOfInitializer)) { +- statements = appendExportsOfDeclaration(statements, decl); ++ statements = appendExportsOfDeclaration(statements, new IdentifierNameMap(), decl); + } + + return statements; +@@ -1994,13 +1991,14 @@ export function transformModule(context: TransformationContext): (x: SourceFile + return statements; + } + ++ const seen = new IdentifierNameMap(); + if (hasSyntacticModifier(decl, ModifierFlags.Export)) { + const exportName = hasSyntacticModifier(decl, ModifierFlags.Default) ? factory.createIdentifier("default") : factory.getDeclarationName(decl); +- statements = appendExportStatement(statements, exportName, factory.getLocalName(decl), /*location*/ decl); ++ statements = appendExportStatement(statements, seen, exportName, factory.getLocalName(decl), /*location*/ decl); + } + + if (decl.name) { +- statements = appendExportsOfDeclaration(statements, decl); ++ statements = appendExportsOfDeclaration(statements, seen, decl); + } + + return statements; +@@ -2014,12 +2012,12 @@ export function transformModule(context: TransformationContext): (x: SourceFile + * appended. + * @param decl The declaration to export. + */ +- function appendExportsOfDeclaration(statements: Statement[] | undefined, decl: Declaration, liveBinding?: boolean): Statement[] | undefined { ++ function appendExportsOfDeclaration(statements: Statement[] | undefined, seen: IdentifierNameMap, decl: Declaration, liveBinding?: boolean): Statement[] | undefined { + const name = factory.getDeclarationName(decl); +- const exportSpecifiers = currentModuleInfo.exportSpecifiers.get(idText(name)); ++ const exportSpecifiers = currentModuleInfo.exportSpecifiers.get(name); + if (exportSpecifiers) { + for (const exportSpecifier of exportSpecifiers) { +- statements = appendExportStatement(statements, exportSpecifier.name, name, /*location*/ exportSpecifier.name, /*allowComments*/ undefined, liveBinding); ++ statements = appendExportStatement(statements, seen, exportSpecifier.name, name, /*location*/ exportSpecifier.name, /*allowComments*/ undefined, liveBinding); + } + } + return statements; +@@ -2037,8 +2035,11 @@ export function transformModule(context: TransformationContext): (x: SourceFile + * @param location The location to use for source maps and comments for the export. + * @param allowComments Whether to allow comments on the export. + */ +- function appendExportStatement(statements: Statement[] | undefined, exportName: Identifier, expression: Expression, location?: TextRange, allowComments?: boolean, liveBinding?: boolean): Statement[] | undefined { +- statements = append(statements, createExportStatement(exportName, expression, location, allowComments, liveBinding)); ++ function appendExportStatement(statements: Statement[] | undefined, seen: IdentifierNameMap, exportName: Identifier, expression: Expression, location?: TextRange, allowComments?: boolean, liveBinding?: boolean): Statement[] | undefined { ++ if (!seen.has(exportName)) { ++ seen.set(exportName, true); ++ statements = append(statements, createExportStatement(exportName, expression, location, allowComments, liveBinding)); ++ } + return statements; + } + +@@ -2341,12 +2342,12 @@ export function transformModule(context: TransformationContext): (x: SourceFile + // When we see an assignment expression whose left-hand side is an exported symbol, + // we should ensure all exports of that symbol are updated with the correct value. + // +- // - We do not substitute generated identifiers for any reason. ++ // - We do not substitute generated identifiers unless they are file-level reserved names. + // - We do not substitute identifiers tagged with the LocalName flag. + // - We only substitute identifiers that are exported at the top level. + if (isAssignmentOperator(node.operatorToken.kind) + && isIdentifier(node.left) +- && !isGeneratedIdentifier(node.left) ++ && (!isGeneratedIdentifier(node.left) || isFileLevelReservedGeneratedIdentifier(node.left)) + && !isLocalName(node.left)) { + const exportedNames = getExports(node.left); + if (exportedNames) { +@@ -2395,6 +2396,16 @@ export function transformModule(context: TransformationContext): (x: SourceFile + } + } + } ++ else if (isFileLevelReservedGeneratedIdentifier(name)) { ++ const exportSpecifiers = currentModuleInfo?.exportSpecifiers.get(name); ++ if (exportSpecifiers) { ++ const exportedNames: Identifier[] = []; ++ for (const exportSpecifier of exportSpecifiers) { ++ exportedNames.push(exportSpecifier.name); ++ } ++ return exportedNames; ++ } ++ } + } + } + +diff --git a/src/compiler/transformers/module/system.ts b/src/compiler/transformers/module/system.ts +index 4e2d9b954..b83bf5244 100644 +--- a/src/compiler/transformers/module/system.ts ++++ b/src/compiler/transformers/module/system.ts +@@ -64,6 +64,7 @@ import { + isExpression, + isExternalModule, + isExternalModuleImportEqualsDeclaration, ++ isFileLevelReservedGeneratedIdentifier, + isForInitializer, + isGeneratedIdentifier, + isHeritageClause, +@@ -84,7 +85,9 @@ import { + isSpreadElement, + isStatement, + isStringLiteral, ++ isVarAwaitUsing, + isVariableDeclarationList, ++ isVarUsing, + LabeledStatement, + map, + MetaProperty, +@@ -198,7 +201,7 @@ export function transformSystemModule(context: TransformationContext): (x: Sourc + // see comment to 'substitutePostfixUnaryExpression' for more details + + // Collect information about the external module and dependency groups. +- moduleInfo = moduleInfoMap[id] = collectExternalModuleInfo(context, node, resolver, compilerOptions); ++ moduleInfo = moduleInfoMap[id] = collectExternalModuleInfo(context, node); + + // Make sure that the name of the 'exports' function does not conflict with + // existing identifiers. +@@ -845,20 +848,44 @@ export function transformSystemModule(context: TransformationContext): (x: Sourc + return visitNode(node, visitor, isStatement); + } + +- let expressions: Expression[] | undefined; +- const isExportedDeclaration = hasSyntacticModifier(node, ModifierFlags.Export); +- for (const variable of node.declarationList.declarations) { +- if (variable.initializer) { +- expressions = append(expressions, transformInitializedVariable(variable, isExportedDeclaration)); +- } +- else { +- hoistBindingElement(variable); ++ let statements: Statement[] | undefined; ++ // `using` and `await using` declarations cannot be hoisted directly, so we will hoist the variable name ++ // as a normal variable, and declare it as a temp variable that remains as a `using` to ensure the correct ++ // lifetime. ++ if (isVarUsing(node.declarationList) || isVarAwaitUsing(node.declarationList)) { ++ const modifiers = visitNodes(node.modifiers, modifierVisitor, isModifierLike); ++ const declarations: VariableDeclaration[] = []; ++ for (const variable of node.declarationList.declarations) { ++ declarations.push(factory.updateVariableDeclaration( ++ variable, ++ factory.getGeneratedNameForNode(variable.name), ++ /*exclamationToken*/ undefined, ++ /*type*/ undefined, ++ transformInitializedVariable(variable, /*isExportedDeclaration*/ false) ++ )); + } ++ ++ const declarationList = factory.updateVariableDeclarationList( ++ node.declarationList, ++ declarations ++ ); ++ statements = append(statements, factory.updateVariableStatement(node, modifiers, declarationList)); + } ++ else { ++ let expressions: Expression[] | undefined; ++ const isExportedDeclaration = hasSyntacticModifier(node, ModifierFlags.Export); ++ for (const variable of node.declarationList.declarations) { ++ if (variable.initializer) { ++ expressions = append(expressions, transformInitializedVariable(variable, isExportedDeclaration)); ++ } ++ else { ++ hoistBindingElement(variable); ++ } ++ } + +- let statements: Statement[] | undefined; +- if (expressions) { +- statements = append(statements, setTextRange(factory.createExpressionStatement(factory.inlineExpressions(expressions)), node)); ++ if (expressions) { ++ statements = append(statements, setTextRange(factory.createExpressionStatement(factory.inlineExpressions(expressions)), node)); ++ } + } + + statements = appendExportsOfVariableStatement(statements, node, /*exportSelf*/ false); +@@ -1114,7 +1141,7 @@ export function transformSystemModule(context: TransformationContext): (x: Sourc + } + + const name = factory.getDeclarationName(decl); +- const exportSpecifiers = moduleInfo.exportSpecifiers.get(idText(name)); ++ const exportSpecifiers = moduleInfo.exportSpecifiers.get(name); + if (exportSpecifiers) { + for (const exportSpecifier of exportSpecifiers) { + if (exportSpecifier.name.escapedText !== excludeName) { +@@ -1894,12 +1921,12 @@ export function transformSystemModule(context: TransformationContext): (x: Sourc + // When we see an assignment expression whose left-hand side is an exported symbol, + // we should ensure all exports of that symbol are updated with the correct value. + // +- // - We do not substitute generated identifiers for any reason. ++ // - We do not substitute generated identifiers unless they are file-level reserved names. + // - We do not substitute identifiers tagged with the LocalName flag. + // - We only substitute identifiers that are exported at the top level. + if (isAssignmentOperator(node.operatorToken.kind) + && isIdentifier(node.left) +- && !isGeneratedIdentifier(node.left) ++ && (!isGeneratedIdentifier(node.left) || isFileLevelReservedGeneratedIdentifier(node.left)) + && !isLocalName(node.left)) { + const exportedNames = getExports(node.left); + if (exportedNames) { +@@ -1939,6 +1966,16 @@ export function transformSystemModule(context: TransformationContext): (x: Sourc + + exportedNames = addRange(exportedNames, moduleInfo?.exportedBindings[getOriginalNodeId(valueDeclaration)]); + } ++ else if (isGeneratedIdentifier(name) && isFileLevelReservedGeneratedIdentifier(name)) { ++ const exportSpecifiers = moduleInfo?.exportSpecifiers.get(name); ++ if (exportSpecifiers) { ++ const exportedNames: Identifier[] = []; ++ for (const exportSpecifier of exportSpecifiers) { ++ exportedNames.push(exportSpecifier.name); ++ } ++ return exportedNames; ++ } ++ } + return exportedNames; + } + +diff --git a/src/compiler/transformers/namedEvaluation.ts b/src/compiler/transformers/namedEvaluation.ts +new file mode 100644 +index 000000000..5af5d9078 +--- /dev/null ++++ b/src/compiler/transformers/namedEvaluation.ts +@@ -0,0 +1,478 @@ ++import { ++ __String, ++ AnonymousFunctionDefinition, ++ BinaryExpression, ++ BindingElement, ++ Block, ++ CallExpression, ++ cast, ++ ClassLikeDeclaration, ++ ClassStaticBlockDeclaration, ++ ExportAssignment, ++ Expression, ++ ExpressionStatement, ++ findIndex, ++ getOrCreateEmitNode, ++ getOriginalNode, ++ hasSyntacticModifier, ++ Identifier, ++ isCallToHelper, ++ isClassDeclaration, ++ isClassExpression, ++ isClassStaticBlockDeclaration, ++ isClassThisAssignmentBlock, ++ isEmptyStringLiteral, ++ isExpressionStatement, ++ isFunctionDeclaration, ++ isIdentifier, ++ isPrivateIdentifier, ++ isPropertyNameLiteral, ++ isStringLiteral, ++ ModifierFlags, ++ NamedEvaluation, ++ Node, ++ NodeArray, ++ NodeFactory, ++ ParameterDeclaration, ++ PropertyAssignment, ++ PropertyDeclaration, ++ PropertyName, ++ setSourceMapRange, ++ setTextRange, ++ ShorthandPropertyAssignment, ++ skipOuterExpressions, ++ some, ++ Statement, ++ StringLiteral, ++ SyntaxKind, ++ TransformationContext, ++ VariableDeclaration, ++ WrappedExpression ++} from "../_namespaces/ts"; ++ ++/** ++ * Gets a string literal to use as the assigned name of an anonymous class or function declaration. ++ * @internal ++ */ ++export function getAssignedNameOfIdentifier(factory: NodeFactory, name: Identifier, expression: WrappedExpression): StringLiteral { ++ const original = getOriginalNode(skipOuterExpressions(expression)); ++ if ((isClassDeclaration(original) || isFunctionDeclaration(original)) && ++ !original.name && hasSyntacticModifier(original, ModifierFlags.Default)) { ++ return factory.createStringLiteral("default"); ++ } ++ return factory.createStringLiteralFromNode(name); ++} ++ ++function getAssignedNameOfPropertyName(context: TransformationContext, name: PropertyName, assignedNameText: string | undefined) { ++ const { factory } = context; ++ if (assignedNameText !== undefined) { ++ const assignedName = factory.createStringLiteral(assignedNameText); ++ return { assignedName, name }; ++ } ++ ++ if (isPropertyNameLiteral(name) || isPrivateIdentifier(name)) { ++ const assignedName = factory.createStringLiteralFromNode(name); ++ return { assignedName, name }; ++ } ++ ++ if (isPropertyNameLiteral(name.expression) && !isIdentifier(name.expression)) { ++ const assignedName = factory.createStringLiteralFromNode(name.expression); ++ return { assignedName, name }; ++ } ++ ++ const assignedName = factory.getGeneratedNameForNode(name); ++ context.hoistVariableDeclaration(assignedName); ++ ++ const key = context.getEmitHelperFactory().createPropKeyHelper(name.expression); ++ const assignment = factory.createAssignment(assignedName, key); ++ const updatedName = factory.updateComputedPropertyName(name, assignment); ++ return { assignedName, name: updatedName }; ++} ++ ++/** ++ * Creates a class `static {}` block used to dynamically set the name of a class. ++ * ++ * @param assignedName The expression used to resolve the assigned name at runtime. This expression should not produce ++ * side effects. ++ * @param thisExpression Overrides the expression to use for the actual `this` reference. This can be used to provide an ++ * expression that has already had its `EmitFlags` set or may have been tracked to prevent substitution. ++ * @internal ++ */ ++export function createClassNamedEvaluationHelperBlock(context: TransformationContext, assignedName: Expression, thisExpression: Expression = context.factory.createThis()): ClassNamedEvaluationHelperBlock { ++ // produces: ++ // ++ // static { __setFunctionName(this, "C"); } ++ // ++ ++ const { factory } = context; ++ const expression = context.getEmitHelperFactory().createSetFunctionNameHelper(thisExpression, assignedName); ++ const statement = factory.createExpressionStatement(expression); ++ const body = factory.createBlock([statement], /*multiLine*/ false); ++ const block = factory.createClassStaticBlockDeclaration(body); ++ ++ // We use `emitNode.assignedName` to indicate this is a NamedEvaluation helper block ++ // and to stash the expression used to resolve the assigned name. ++ getOrCreateEmitNode(block).assignedName = assignedName; ++ return block as ClassNamedEvaluationHelperBlock; ++} ++ ++/** @internal */ ++export type ClassNamedEvaluationHelperBlock = ClassStaticBlockDeclaration & { ++ readonly body: Block & { ++ readonly statements: NodeArray & readonly [ ++ ExpressionStatement & { ++ readonly expression: CallExpression & { ++ readonly expression: Identifier; ++ }; ++ } ++ ]; ++ }; ++}; ++ ++ ++/** ++ * Gets whether a node is a `static {}` block containing only a single call to the `__setFunctionName` helper where that ++ * call's second argument is the value stored in the `assignedName` property of the block's `EmitNode`. ++ * @internal ++ */ ++export function isClassNamedEvaluationHelperBlock(node: Node): node is ClassNamedEvaluationHelperBlock { ++ if (!isClassStaticBlockDeclaration(node) || node.body.statements.length !== 1) { ++ return false; ++ } ++ ++ const statement = node.body.statements[0]; ++ return isExpressionStatement(statement) && ++ isCallToHelper(statement.expression, "___setFunctionName" as __String) && ++ (statement.expression as CallExpression).arguments.length >= 2 && ++ (statement.expression as CallExpression).arguments[1] === node.emitNode?.assignedName; ++} ++ ++/** ++ * Gets whether a `ClassLikeDeclaration` has a `static {}` block containing only a single call to the ++ * `__setFunctionName` helper. ++ * @internal ++ */ ++export function classHasExplicitlyAssignedName(node: ClassLikeDeclaration): boolean { ++ return !!node.emitNode?.assignedName && some(node.members, isClassNamedEvaluationHelperBlock); ++} ++ ++/** ++ * Gets whether a `ClassLikeDeclaration` has a declared name or contains a `static {}` block containing only a single ++ * call to the `__setFunctionName` helper. ++ * @internal ++ */ ++export function classHasDeclaredOrExplicitlyAssignedName(node: ClassLikeDeclaration): boolean { ++ return !!node.name || classHasExplicitlyAssignedName(node); ++} ++ ++/** ++ * Injects a class `static {}` block used to dynamically set the name of a class, if one does not already exist. ++ * @internal ++ */ ++export function injectClassNamedEvaluationHelperBlockIfMissing( ++ context: TransformationContext, ++ node: T, ++ assignedName: Expression, ++ thisExpression?: Expression ++): Extract>; ++export function injectClassNamedEvaluationHelperBlockIfMissing( ++ context: TransformationContext, ++ node: ClassLikeDeclaration, ++ assignedName: Expression, ++ thisExpression?: Expression ++) { ++ // given: ++ // ++ // let C = class { ++ // }; ++ // ++ // produces: ++ // ++ // let C = class { ++ // static { __setFunctionName(this, "C"); } ++ // }; ++ ++ // NOTE: If the class has a `_classThis` assignment block, this helper will be injected after that block. ++ ++ if (classHasExplicitlyAssignedName(node)) { ++ return node; ++ } ++ ++ const { factory } = context; ++ const namedEvaluationBlock = createClassNamedEvaluationHelperBlock(context, assignedName, thisExpression); ++ if (node.name) { ++ setSourceMapRange(namedEvaluationBlock.body.statements[0], node.name); ++ } ++ ++ const insertionIndex = findIndex(node.members, isClassThisAssignmentBlock) + 1; ++ const leading = node.members.slice(0, insertionIndex); ++ const trailing = node.members.slice(insertionIndex); ++ const members = factory.createNodeArray([...leading, namedEvaluationBlock, ...trailing]); ++ setTextRange(members, node.members); ++ ++ node = isClassDeclaration(node) ? ++ factory.updateClassDeclaration( ++ node, ++ node.modifiers, ++ node.name, ++ node.typeParameters, ++ node.heritageClauses, ++ members) : ++ factory.updateClassExpression( ++ node, ++ node.modifiers, ++ node.name, ++ node.typeParameters, ++ node.heritageClauses, ++ members); ++ ++ getOrCreateEmitNode(node).assignedName = assignedName; ++ return node; ++} ++ ++function finishTransformNamedEvaluation( ++ context: TransformationContext, ++ expression: WrappedExpression, ++ assignedName: Expression, ++ ignoreEmptyStringLiteral?: boolean, ++): Expression { ++ if (ignoreEmptyStringLiteral && isStringLiteral(assignedName) && isEmptyStringLiteral(assignedName)) { ++ return expression; ++ } ++ ++ const { factory } = context; ++ const innerExpression = skipOuterExpressions(expression); ++ ++ const updatedExpression = isClassExpression(innerExpression) ? ++ cast(injectClassNamedEvaluationHelperBlockIfMissing(context, innerExpression, assignedName), isClassExpression) : ++ context.getEmitHelperFactory().createSetFunctionNameHelper(innerExpression, assignedName); ++ ++ return factory.restoreOuterExpressions(expression, updatedExpression); ++} ++ ++function transformNamedEvaluationOfPropertyAssignment(context: TransformationContext, node: NamedEvaluation & PropertyAssignment, ignoreEmptyStringLiteral?: boolean, assignedNameText?: string) { ++ // 13.2.5.5 RS: PropertyDefinitionEvaluation ++ // PropertyAssignment : PropertyName `:` AssignmentExpression ++ // ... ++ // 5. If IsAnonymousFunctionDefinition(|AssignmentExpression|) is *true* and _isProtoSetter_ is *false*, then ++ // a. Let _popValue_ be ? NamedEvaluation of |AssignmentExpression| with argument _propKey_. ++ // ... ++ ++ const { factory } = context; ++ const { assignedName, name } = getAssignedNameOfPropertyName(context, node.name, assignedNameText); ++ const initializer = finishTransformNamedEvaluation(context, node.initializer, assignedName, ignoreEmptyStringLiteral); ++ return factory.updatePropertyAssignment( ++ node, ++ name, ++ initializer); ++} ++ ++function transformNamedEvaluationOfShorthandAssignmentProperty(context: TransformationContext, node: NamedEvaluation & ShorthandPropertyAssignment, ignoreEmptyStringLiteral?: boolean, assignedNameText?: string) { ++ // 13.15.5.3 RS: PropertyDestructuringAssignmentEvaluation ++ // AssignmentProperty : IdentifierReference Initializer? ++ // ... ++ // 4. If |Initializer?| is present and _v_ is *undefined*, then ++ // a. If IsAnonymousFunctionDefinition(|Initializer|) is *true*, then ++ // i. Set _v_ to ? NamedEvaluation of |Initializer| with argument _P_. ++ // ... ++ ++ const { factory } = context; ++ const assignedName = assignedNameText !== undefined ? factory.createStringLiteral(assignedNameText) : ++ getAssignedNameOfIdentifier(factory, node.name, node.objectAssignmentInitializer); ++ const objectAssignmentInitializer = finishTransformNamedEvaluation(context, node.objectAssignmentInitializer, assignedName, ignoreEmptyStringLiteral); ++ return factory.updateShorthandPropertyAssignment( ++ node, ++ node.name, ++ objectAssignmentInitializer); ++} ++ ++function transformNamedEvaluationOfVariableDeclaration(context: TransformationContext, node: NamedEvaluation & VariableDeclaration, ignoreEmptyStringLiteral?: boolean, assignedNameText?: string) { ++ // 14.3.1.2 RS: Evaluation ++ // LexicalBinding : BindingIdentifier Initializer ++ // ... ++ // 3. If IsAnonymousFunctionDefinition(|Initializer|) is *true*, then ++ // a. Let _value_ be ? NamedEvaluation of |Initializer| with argument _bindingId_. ++ // ... ++ // ++ // 14.3.2.1 RS: Evaluation ++ // VariableDeclaration : BindingIdentifier Initializer ++ // ... ++ // 3. If IsAnonymousFunctionDefinition(|Initializer|) is *true*, then ++ // a. Let _value_ be ? NamedEvaluation of |Initializer| with argument _bindingId_. ++ // ... ++ ++ const { factory } = context; ++ const assignedName = assignedNameText !== undefined ? factory.createStringLiteral(assignedNameText) : ++ getAssignedNameOfIdentifier(factory, node.name, node.initializer); ++ const initializer = finishTransformNamedEvaluation(context, node.initializer, assignedName, ignoreEmptyStringLiteral); ++ return factory.updateVariableDeclaration( ++ node, ++ node.name, ++ node.exclamationToken, ++ node.type, ++ initializer); ++} ++ ++function transformNamedEvaluationOfParameterDeclaration(context: TransformationContext, node: NamedEvaluation & ParameterDeclaration, ignoreEmptyStringLiteral?: boolean, assignedNameText?: string) { ++ // 8.6.3 RS: IteratorBindingInitialization ++ // SingleNameBinding : BindingIdentifier Initializer? ++ // ... ++ // 5. If |Initializer| is present and _v_ is *undefined*, then ++ // a. If IsAnonymousFunctionDefinition(|Initializer|) is *true*, then ++ // i. Set _v_ to ? NamedEvaluation of |Initializer| with argument _bindingId_. ++ // ... ++ // ++ // 14.3.3.3 RS: KeyedBindingInitialization ++ // SingleNameBinding : BindingIdentifier Initializer? ++ // ... ++ // 4. If |Initializer| is present and _v_ is *undefined*, then ++ // a. If IsAnonymousFunctionDefinition(|Initializer|) is *true*, then ++ // i. Set _v_ to ? NamedEvaluation of |Initializer| with argument _bindingId_. ++ // ... ++ ++ const { factory } = context; ++ const assignedName = assignedNameText !== undefined ? factory.createStringLiteral(assignedNameText) : ++ getAssignedNameOfIdentifier(factory, node.name, node.initializer); ++ const initializer = finishTransformNamedEvaluation(context, node.initializer, assignedName, ignoreEmptyStringLiteral); ++ return factory.updateParameterDeclaration( ++ node, ++ node.modifiers, ++ node.dotDotDotToken, ++ node.name, ++ node.questionToken, ++ node.type, ++ initializer); ++} ++ ++function transformNamedEvaluationOfBindingElement(context: TransformationContext, node: NamedEvaluation & BindingElement, ignoreEmptyStringLiteral?: boolean, assignedNameText?: string) { ++ // 8.6.3 RS: IteratorBindingInitialization ++ // SingleNameBinding : BindingIdentifier Initializer? ++ // ... ++ // 5. If |Initializer| is present and _v_ is *undefined*, then ++ // a. If IsAnonymousFunctionDefinition(|Initializer|) is *true*, then ++ // i. Set _v_ to ? NamedEvaluation of |Initializer| with argument _bindingId_. ++ // ... ++ // ++ // 14.3.3.3 RS: KeyedBindingInitialization ++ // SingleNameBinding : BindingIdentifier Initializer? ++ // ... ++ // 4. If |Initializer| is present and _v_ is *undefined*, then ++ // a. If IsAnonymousFunctionDefinition(|Initializer|) is *true*, then ++ // i. Set _v_ to ? NamedEvaluation of |Initializer| with argument _bindingId_. ++ // ... ++ ++ const { factory } = context; ++ const assignedName = assignedNameText !== undefined ? factory.createStringLiteral(assignedNameText) : ++ getAssignedNameOfIdentifier(factory, node.name, node.initializer); ++ const initializer = finishTransformNamedEvaluation(context, node.initializer, assignedName, ignoreEmptyStringLiteral); ++ return factory.updateBindingElement( ++ node, ++ node.dotDotDotToken, ++ node.propertyName, ++ node.name, ++ initializer); ++} ++ ++function transformNamedEvaluationOfPropertyDeclaration(context: TransformationContext, node: NamedEvaluation & PropertyDeclaration, ignoreEmptyStringLiteral?: boolean, assignedNameText?: string) { ++ // 10.2.1.3 RS: EvaluateBody ++ // Initializer : `=` AssignmentExpression ++ // ... ++ // 3. If IsAnonymousFunctionDefinition(|AssignmentExpression|) is *true*, then ++ // a. Let _value_ be ? NamedEvaluation of |Initializer| with argument _functionObject_.[[ClassFieldInitializerName]]. ++ // ... ++ ++ const { factory } = context; ++ const { assignedName, name } = getAssignedNameOfPropertyName(context, node.name, assignedNameText); ++ const initializer = finishTransformNamedEvaluation(context, node.initializer, assignedName, ignoreEmptyStringLiteral); ++ return factory.updatePropertyDeclaration( ++ node, ++ node.modifiers, ++ name, ++ node.questionToken ?? node.exclamationToken, ++ node.type, ++ initializer); ++} ++ ++function transformNamedEvaluationOfAssignmentExpression(context: TransformationContext, node: NamedEvaluation & BinaryExpression, ignoreEmptyStringLiteral?: boolean, assignedNameText?: string) { ++ // 13.15.2 RS: Evaluation ++ // AssignmentExpression : LeftHandSideExpression `=` AssignmentExpression ++ // 1. If |LeftHandSideExpression| is neither an |ObjectLiteral| nor an |ArrayLiteral|, then ++ // a. Let _lref_ be ? Evaluation of |LeftHandSideExpression|. ++ // b. If IsAnonymousFunctionDefinition(|AssignmentExpression|) and IsIdentifierRef of |LeftHandSideExpression| are both *true*, then ++ // i. Let _rval_ be ? NamedEvaluation of |AssignmentExpression| with argument _lref_.[[ReferencedName]]. ++ // ... ++ // ++ // AssignmentExpression : LeftHandSideExpression `&&=` AssignmentExpression ++ // ... ++ // 5. If IsAnonymousFunctionDefinition(|AssignmentExpression|) is *true* and IsIdentifierRef of |LeftHandSideExpression| is *true*, then ++ // a. Let _rval_ be ? NamedEvaluation of |AssignmentExpression| with argument _lref_.[[ReferencedName]]. ++ // ... ++ // ++ // AssignmentExpression : LeftHandSideExpression `||=` AssignmentExpression ++ // ... ++ // 5. If IsAnonymousFunctionDefinition(|AssignmentExpression|) is *true* and IsIdentifierRef of |LeftHandSideExpression| is *true*, then ++ // a. Let _rval_ be ? NamedEvaluation of |AssignmentExpression| with argument _lref_.[[ReferencedName]]. ++ // ... ++ // ++ // AssignmentExpression : LeftHandSideExpression `??=` AssignmentExpression ++ // ... ++ // 4. If IsAnonymousFunctionDefinition(|AssignmentExpression|) is *true* and IsIdentifierRef of |LeftHandSideExpression| is *true*, then ++ // a. Let _rval_ be ? NamedEvaluation of |AssignmentExpression| with argument _lref_.[[ReferencedName]]. ++ // ... ++ ++ const { factory } = context; ++ const assignedName = assignedNameText !== undefined ? factory.createStringLiteral(assignedNameText) : ++ getAssignedNameOfIdentifier(factory, node.left, node.right); ++ const right = finishTransformNamedEvaluation(context, node.right, assignedName, ignoreEmptyStringLiteral); ++ return factory.updateBinaryExpression( ++ node, ++ node.left, ++ node.operatorToken, ++ right); ++} ++ ++function transformNamedEvaluationOfExportAssignment(context: TransformationContext, node: NamedEvaluation & ExportAssignment, ignoreEmptyStringLiteral?: boolean, assignedNameText?: string) { ++ // 16.2.3.7 RS: Evaluation ++ // ExportDeclaration : `export` `default` AssignmentExpression `;` ++ // 1. If IsAnonymousFunctionDefinition(|AssignmentExpression|) is *true*, then ++ // a. Let _value_ be ? NamedEvaluation of |AssignmentExpression| with argument `"default"`. ++ // ... ++ ++ // NOTE: Since emit for `export =` translates to `module.exports = ...`, the assigned name of the class or function ++ // is `""`. ++ ++ const { factory } = context; ++ const assignedName = assignedNameText !== undefined ? factory.createStringLiteral(assignedNameText) : ++ factory.createStringLiteral(node.isExportEquals ? "" : "default"); ++ const expression = finishTransformNamedEvaluation(context, node.expression, assignedName, ignoreEmptyStringLiteral); ++ return factory.updateExportAssignment( ++ node, ++ node.modifiers, ++ expression); ++} ++ ++/** ++ * Performs a shallow transformation of a `NamedEvaluation` node, such that a valid name will be assigned. ++ * @internal ++ */ ++export function transformNamedEvaluation(context: TransformationContext, node: T, ignoreEmptyStringLiteral?: boolean, assignedName?: string): Extract>; ++export function transformNamedEvaluation(context: TransformationContext, node: NamedEvaluation, ignoreEmptyStringLiteral?: boolean, assignedName?: string) { ++ switch (node.kind) { ++ case SyntaxKind.PropertyAssignment: ++ return transformNamedEvaluationOfPropertyAssignment(context, node, ignoreEmptyStringLiteral, assignedName); ++ case SyntaxKind.ShorthandPropertyAssignment: ++ return transformNamedEvaluationOfShorthandAssignmentProperty(context, node, ignoreEmptyStringLiteral, assignedName); ++ case SyntaxKind.VariableDeclaration: ++ return transformNamedEvaluationOfVariableDeclaration(context, node, ignoreEmptyStringLiteral, assignedName); ++ case SyntaxKind.Parameter: ++ return transformNamedEvaluationOfParameterDeclaration(context, node, ignoreEmptyStringLiteral, assignedName); ++ case SyntaxKind.BindingElement: ++ return transformNamedEvaluationOfBindingElement(context, node, ignoreEmptyStringLiteral, assignedName); ++ case SyntaxKind.PropertyDeclaration: ++ return transformNamedEvaluationOfPropertyDeclaration(context, node, ignoreEmptyStringLiteral, assignedName); ++ case SyntaxKind.BinaryExpression: ++ return transformNamedEvaluationOfAssignmentExpression(context, node, ignoreEmptyStringLiteral, assignedName); ++ case SyntaxKind.ExportAssignment: ++ return transformNamedEvaluationOfExportAssignment(context, node, ignoreEmptyStringLiteral, assignedName); ++ } ++} +diff --git a/src/compiler/transformers/ts.ts b/src/compiler/transformers/ts.ts +index 6fec0b61b..8b97637c0 100644 +--- a/src/compiler/transformers/ts.ts ++++ b/src/compiler/transformers/ts.ts +@@ -41,7 +41,7 @@ import { + Expression, + ExpressionWithTypeArguments, + filter, +- findSuperStatementIndex, ++ findSuperStatementIndexPath, + flattenDestructuringAssignment, + FlattenLevel, + FunctionDeclaration, +@@ -79,6 +79,8 @@ import { + isAssertionExpression, + isBindingName, + isBindingPattern, ++ isBlock, ++ isCatchClause, + isClassElement, + isClassLike, + isComputedPropertyName, +@@ -118,6 +120,7 @@ import { + isSourceFile, + isStatement, + isTemplateLiteral, ++ isTryStatement, + JsxOpeningElement, + JsxSelfClosingElement, + LeftHandSideExpression, +@@ -194,7 +197,7 @@ import { + visitNode, + visitNodes, + visitParameterList, +- VisitResult, ++ VisitResult + } from "../_namespaces/ts"; + + /** +@@ -922,24 +925,19 @@ export function transformTypeScript(context: TransformationContext) { + const iife = factory.createImmediatelyInvokedArrowFunction(statements); + setInternalEmitFlags(iife, InternalEmitFlags.TypeScriptClassWrapper); + +- // export let C = (() => { ... })(); +- const modifiers = facts & ClassFacts.IsNamedExternalExport ? +- factory.createModifiersFromModifierFlags(ModifierFlags.Export) : +- undefined; +- + // let C = (() => { ... })(); +- const varStatement = factory.createVariableStatement( +- modifiers, +- factory.createVariableDeclarationList([ +- factory.createVariableDeclaration( +- factory.getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ false), +- /*exclamationToken*/ undefined, +- /*type*/ undefined, +- iife +- ) +- ], NodeFlags.Let) ++ const varDecl = factory.createVariableDeclaration( ++ factory.getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ false), ++ /*exclamationToken*/ undefined, ++ /*type*/ undefined, ++ iife + ); ++ setOriginalNode(varDecl, node); + ++ const varStatement = factory.createVariableStatement( ++ /*modifiers*/ undefined, ++ factory.createVariableDeclarationList([varDecl], NodeFlags.Let) ++ ); + setOriginalNode(varStatement, node); + setCommentRange(varStatement, node); + setSourceMapRange(varStatement, moveRangePastDecorators(node)); +@@ -963,10 +961,10 @@ export function transformTypeScript(context: TransformationContext) { + factory.createExportDefault(factory.getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true)) + ]; + } +- if (facts & ClassFacts.IsNamedExternalExport && !promoteToIIFE) { ++ if (facts & ClassFacts.IsNamedExternalExport) { + return [ + statement, +- factory.createExternalModuleExport(factory.getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true)) ++ factory.createExternalModuleExport(factory.getDeclarationName(node, /*allowComments*/ false, /*allowSourceMaps*/ true)) + ]; + } + } +@@ -1293,6 +1291,37 @@ export function transformTypeScript(context: TransformationContext) { + ); + } + ++ function transformConstructorBodyWorker(statementsOut: Statement[], statementsIn: NodeArray, statementOffset: number, superPath: readonly number[], superPathDepth: number, initializerStatements: readonly Statement[]) { ++ const superStatementIndex = superPath[superPathDepth]; ++ const superStatement = statementsIn[superStatementIndex]; ++ addRange(statementsOut, visitNodes(statementsIn, visitor, isStatement, statementOffset, superStatementIndex - statementOffset)); ++ if (isTryStatement(superStatement)) { ++ const tryBlockStatements: Statement[] = []; ++ ++ transformConstructorBodyWorker( ++ tryBlockStatements, ++ superStatement.tryBlock.statements, ++ /*statementOffset*/ 0, ++ superPath, ++ superPathDepth + 1, ++ initializerStatements); ++ ++ const tryBlockStatementsArray = factory.createNodeArray(tryBlockStatements); ++ setTextRange(tryBlockStatementsArray, superStatement.tryBlock.statements); ++ ++ statementsOut.push(factory.updateTryStatement( ++ superStatement, ++ factory.updateBlock(superStatement.tryBlock, tryBlockStatements), ++ visitNode(superStatement.catchClause, visitor, isCatchClause), ++ visitNode(superStatement.finallyBlock, visitor, isBlock))); ++ } ++ else { ++ addRange(statementsOut, visitNodes(statementsIn, visitor, isStatement, superStatementIndex, 1)); ++ addRange(statementsOut, initializerStatements); ++ } ++ addRange(statementsOut, visitNodes(statementsIn, visitor, isStatement, superStatementIndex + 1)); ++ } ++ + function transformConstructorBody(body: Block, constructor: ConstructorDeclaration) { + const parametersWithPropertyAssignments = constructor && + filter(constructor.parameters, p => isParameterPropertyDeclaration(p, constructor)) as readonly ParameterPropertyDeclaration[] | undefined; +@@ -1305,15 +1334,7 @@ export function transformTypeScript(context: TransformationContext) { + resumeLexicalEnvironment(); + + const prologueStatementCount = factory.copyPrologue(body.statements, statements, /*ensureUseStrict*/ false, visitor); +- const superStatementIndex = findSuperStatementIndex(body.statements, prologueStatementCount); +- +- // If there was a super call, visit existing statements up to and including it +- if (superStatementIndex >= 0) { +- addRange( +- statements, +- visitNodes(body.statements, visitor, isStatement, prologueStatementCount, superStatementIndex + 1 - prologueStatementCount), +- ); +- } ++ const superPath = findSuperStatementIndexPath(body.statements, prologueStatementCount); + + // Transform parameters into property assignments. Transforms this: + // +@@ -1328,24 +1349,14 @@ export function transformTypeScript(context: TransformationContext) { + // } + // + const parameterPropertyAssignments = mapDefined(parametersWithPropertyAssignments, transformParameterWithPropertyAssignment); +- +- // If there is a super() call, the parameter properties go immediately after it +- if (superStatementIndex >= 0) { +- addRange(statements, parameterPropertyAssignments); ++ if (superPath.length) { ++ transformConstructorBodyWorker(statements, body.statements, prologueStatementCount, superPath, /*superPathDepth*/ 0, parameterPropertyAssignments); + } +- // Since there was no super() call, parameter properties are the first statements in the constructor after any prologue statements + else { +- statements = [ +- ...statements.slice(0, prologueStatementCount), +- ...parameterPropertyAssignments, +- ...statements.slice(prologueStatementCount), +- ]; ++ addRange(statements, parameterPropertyAssignments); ++ addRange(statements, visitNodes(body.statements, visitor, isStatement, prologueStatementCount)); + } + +- // Add remaining statements from the body, skipping the super() call if it was found and any (already added) prologue statements +- const start = superStatementIndex >= 0 ? superStatementIndex + 1 : prologueStatementCount; +- addRange(statements, visitNodes(body.statements, visitor, isStatement, start)); +- + // End the lexical environment. + statements = factory.mergeLexicalEnvironment(statements, endLexicalEnvironment()); + const block = factory.createBlock(setTextRange(factory.createNodeArray(statements), body.statements), /*multiLine*/ true); +diff --git a/src/compiler/transformers/utilities.ts b/src/compiler/transformers/utilities.ts +index c094a8dc0..d01206af9 100644 +--- a/src/compiler/transformers/utilities.ts ++++ b/src/compiler/transformers/utilities.ts +@@ -12,20 +12,19 @@ import { + ClassExpression, + ClassLikeDeclaration, + ClassStaticBlockDeclaration, +- CompilerOptions, + CompoundAssignmentOperator, + CoreTransformationContext, + createExternalHelpersImportDeclarationIfNeeded, +- createMultiMap, + Decorator, +- EmitResolver, + ExportAssignment, + ExportDeclaration, + ExportSpecifier, + Expression, + filter, ++ formatGeneratedName, + FunctionDeclaration, + FunctionLikeDeclaration, ++ GeneratedIdentifierFlags, + getAllAccessorDeclarations, + getDecorators, + getFirstConstructorWithBody, +@@ -53,6 +52,7 @@ import { + isIdentifier, + isKeyword, + isLocalName, ++ isMemberName, + isMethodOrAccessor, + isNamedExports, + isNamedImports, +@@ -62,6 +62,7 @@ import { + isStatic, + isStringLiteralLike, + isSuperCall, ++ isTryStatement, + LogicalOperatorOrHigher, + map, + MethodDeclaration, +@@ -83,8 +84,9 @@ import { + SuperCall, + SyntaxKind, + TransformationContext, ++ unorderedRemoveItem, + VariableDeclaration, +- VariableStatement, ++ VariableStatement + } from "../_namespaces/ts"; + + /** @internal */ +@@ -97,7 +99,7 @@ export function getOriginalNodeId(node: Node) { + export interface ExternalModuleInfo { + externalImports: (ImportDeclaration | ImportEqualsDeclaration | ExportDeclaration)[]; // imports of other external modules + externalHelpersImportDeclaration: ImportDeclaration | undefined; // import of external helpers +- exportSpecifiers: Map; // file-local export specifiers by name (no reexports) ++ exportSpecifiers: IdentifierNameMap; // file-local export specifiers by name (no reexports) + exportedBindings: Identifier[][]; // exported names of local declarations + exportedNames: Identifier[] | undefined; // all exported names in the module, both local and reexported + exportEquals: ExportAssignment | undefined; // an export= declaration if one was present +@@ -159,9 +161,11 @@ export function getImportNeedsImportDefaultHelper(node: ImportDeclaration): bool + } + + /** @internal */ +-export function collectExternalModuleInfo(context: TransformationContext, sourceFile: SourceFile, resolver: EmitResolver, compilerOptions: CompilerOptions): ExternalModuleInfo { ++export function collectExternalModuleInfo(context: TransformationContext, sourceFile: SourceFile): ExternalModuleInfo { ++ const resolver = context.getEmitResolver(); ++ const compilerOptions = context.getCompilerOptions(); + const externalImports: (ImportDeclaration | ImportEqualsDeclaration | ExportDeclaration)[] = []; +- const exportSpecifiers = createMultiMap(); ++ const exportSpecifiers = new IdentifierNameMultiMap(); + const exportedBindings: Identifier[][] = []; + const uniqueExports = new Map(); + let exportedNames: Identifier[] | undefined; +@@ -298,7 +302,7 @@ export function collectExternalModuleInfo(context: TransformationContext, source + if (!uniqueExports.get(idText(specifier.name))) { + const name = specifier.propertyName || specifier.name; + if (!node.moduleSpecifier) { +- exportSpecifiers.add(idText(name), specifier); ++ exportSpecifiers.add(name, specifier); + } + + const decl = resolver.getReferencedImportDeclaration(name) +@@ -348,6 +352,83 @@ function multiMapSparseArrayAdd(map: V[][], key: number, value: V): V[] { + return values; + } + ++/** @internal */ ++export class IdentifierNameMap { ++ private readonly _map = new Map(); ++ ++ get size() { ++ return this._map.size; ++ } ++ ++ has(key: Identifier) { ++ return this._map.has(IdentifierNameMap.toKey(key)); ++ } ++ ++ get(key: Identifier) { ++ return this._map.get(IdentifierNameMap.toKey(key)); ++ } ++ ++ set(key: Identifier, value: V) { ++ this._map.set(IdentifierNameMap.toKey(key), value); ++ return this; ++ } ++ ++ delete(key: Identifier): boolean { ++ return this._map?.delete(IdentifierNameMap.toKey(key)) ?? false; ++ } ++ ++ clear(): void { ++ this._map.clear(); ++ } ++ ++ values() { ++ return this._map.values(); ++ } ++ ++ private static toKey(name: Identifier | PrivateIdentifier): string { ++ if (isGeneratedPrivateIdentifier(name) || isGeneratedIdentifier(name)) { ++ const autoGenerate = name.emitNode.autoGenerate; ++ if ((autoGenerate.flags & GeneratedIdentifierFlags.KindMask) === GeneratedIdentifierFlags.Node) { ++ const node = getNodeForGeneratedName(name); ++ const baseName = isMemberName(node) && node !== name ? IdentifierNameMap.toKey(node) : `(generated@${getNodeId(node)})`; ++ return formatGeneratedName(/*privateName*/ false, autoGenerate.prefix, baseName, autoGenerate.suffix, IdentifierNameMap.toKey); ++ } ++ else { ++ const baseName = `(auto@${autoGenerate.id})`; ++ return formatGeneratedName(/*privateName*/ false, autoGenerate.prefix, baseName, autoGenerate.suffix, IdentifierNameMap.toKey); ++ } ++ } ++ if (isPrivateIdentifier(name)) { ++ return idText(name).slice(1); ++ } ++ return idText(name); ++ } ++} ++ ++/** @internal */ ++export class IdentifierNameMultiMap extends IdentifierNameMap { ++ add(key: Identifier, value: V): V[] { ++ let values = this.get(key); ++ if (values) { ++ values.push(value); ++ } ++ else { ++ this.set(key, values = [value]); ++ } ++ return values; ++ } ++ ++ remove(key: Identifier, value: V) { ++ const values = this.get(key); ++ if (values) { ++ unorderedRemoveItem(values, value); ++ if (!values.length) { ++ this.delete(key); ++ } ++ } ++ } ++} ++ + /** + * Used in the module transformer to check if an expression is reasonably without sideeffect, + * and thus better to copy into multiple places rather than to cache in a temporary variable +@@ -417,21 +498,34 @@ export function getSuperCallFromStatement(statement: Statement): SuperCall | und + : undefined; + } + +-/** +- * @returns The index (after prologue statements) of a super call, or -1 if not found. +- * +- * @internal +- */ +-export function findSuperStatementIndex(statements: NodeArray, indexAfterLastPrologueStatement: number) { +- for (let i = indexAfterLastPrologueStatement; i < statements.length; i += 1) { ++function findSuperStatementIndexPathWorker(statements: NodeArray, start: number, indices: number[]) { ++ for (let i = start; i < statements.length; i += 1) { + const statement = statements[i]; +- + if (getSuperCallFromStatement(statement)) { +- return i; ++ indices.unshift(i); ++ return true; ++ } ++ else if (isTryStatement(statement) && findSuperStatementIndexPathWorker(statement.tryBlock.statements, 0, indices)) { ++ indices.unshift(i); ++ return true; + } + } + +- return -1; ++ return false; ++} ++ ++/** ++ * Finds a path of indices to navigate to a `super()` call, descending only through `try` statements. ++ * ++ * @returns An array of indicies to walk down through `try` statements, with the last element being the index of ++ * the statement containing `super()`. Otherwise, an empty array if `super()` was not found. ++ * ++ * @internal ++ */ ++export function findSuperStatementIndexPath(statements: NodeArray, start: number) { ++ const indices: number[] = []; ++ findSuperStatementIndexPathWorker(statements, start, indices); ++ return indices; + } + + /** +diff --git a/src/compiler/types.ts b/src/compiler/types.ts +index a5edcc4a7..06d4d1799 100644 +--- a/src/compiler/types.ts ++++ b/src/compiler/types.ts +@@ -218,6 +218,7 @@ export const enum SyntaxKind { + UndefinedKeyword, + UniqueKeyword, + UnknownKeyword, ++ UsingKeyword, + FromKeyword, + GlobalKeyword, + BigIntKeyword, +@@ -663,6 +664,7 @@ export type KeywordSyntaxKind = + | SyntaxKind.UndefinedKeyword + | SyntaxKind.UniqueKeyword + | SyntaxKind.UnknownKeyword ++ | SyntaxKind.UsingKeyword + | SyntaxKind.VarKeyword + | SyntaxKind.VoidKeyword + | SyntaxKind.WhileKeyword +@@ -791,25 +793,27 @@ export const enum NodeFlags { + None = 0, + Let = 1 << 0, // Variable declaration + Const = 1 << 1, // Variable declaration +- NestedNamespace = 1 << 2, // Namespace declaration +- Synthesized = 1 << 3, // Node was synthesized during transformation +- Namespace = 1 << 4, // Namespace declaration +- OptionalChain = 1 << 5, // Chained MemberExpression rooted to a pseudo-OptionalExpression +- ExportContext = 1 << 6, // Export context (initialized by binding) +- ContainsThis = 1 << 7, // Interface contains references to "this" +- HasImplicitReturn = 1 << 8, // If function implicitly returns on one of codepaths (initialized by binding) +- HasExplicitReturn = 1 << 9, // If function has explicit reachable return on one of codepaths (initialized by binding) +- GlobalAugmentation = 1 << 10, // Set if module declaration is an augmentation for the global scope +- HasAsyncFunctions = 1 << 11, // If the file has async functions (initialized by binding) +- DisallowInContext = 1 << 12, // If node was parsed in a context where 'in-expressions' are not allowed +- YieldContext = 1 << 13, // If node was parsed in the 'yield' context created when parsing a generator +- DecoratorContext = 1 << 14, // If node was parsed as part of a decorator +- AwaitContext = 1 << 15, // If node was parsed in the 'await' context created when parsing an async function +- DisallowConditionalTypesContext = 1 << 16, // If node was parsed in a context where conditional types are not allowed +- ThisNodeHasError = 1 << 17, // If the parser encountered an error when parsing the code that created this node +- JavaScriptFile = 1 << 18, // If node was parsed in a JavaScript +- ThisNodeOrAnySubNodesHasError = 1 << 19, // If this node or any of its children had an error +- HasAggregatedChildData = 1 << 20, // If we've computed data from children and cached it in this node ++ Using = 1 << 2, // Variable declaration ++ AwaitUsing = Const | Using, // Variable declaration (NOTE: on a single node these flags would otherwise be mutually exclusive) ++ NestedNamespace = 1 << 3, // Namespace declaration ++ Synthesized = 1 << 4, // Node was synthesized during transformation ++ Namespace = 1 << 5, // Namespace declaration ++ OptionalChain = 1 << 6, // Chained MemberExpression rooted to a pseudo-OptionalExpression ++ ExportContext = 1 << 7, // Export context (initialized by binding) ++ ContainsThis = 1 << 8, // Interface contains references to "this" ++ HasImplicitReturn = 1 << 9, // If function implicitly returns on one of codepaths (initialized by binding) ++ HasExplicitReturn = 1 << 10, // If function has explicit reachable return on one of codepaths (initialized by binding) ++ GlobalAugmentation = 1 << 11, // Set if module declaration is an augmentation for the global scope ++ HasAsyncFunctions = 1 << 12, // If the file has async functions (initialized by binding) ++ DisallowInContext = 1 << 13, // If node was parsed in a context where 'in-expressions' are not allowed ++ YieldContext = 1 << 14, // If node was parsed in the 'yield' context created when parsing a generator ++ DecoratorContext = 1 << 15, // If node was parsed as part of a decorator ++ AwaitContext = 1 << 16, // If node was parsed in the 'await' context created when parsing an async function ++ DisallowConditionalTypesContext = 1 << 17, // If node was parsed in a context where conditional types are not allowed ++ ThisNodeHasError = 1 << 18, // If the parser encountered an error when parsing the code that created this node ++ JavaScriptFile = 1 << 19, // If node was parsed in a JavaScript ++ ThisNodeOrAnySubNodesHasError = 1 << 20, // If this node or any of its children had an error ++ HasAggregatedChildData = 1 << 21, // If we've computed data from children and cached it in this node + + // These flags will be set when the parser encounters a dynamic import expression or 'import.meta' to avoid + // walking the tree if the flags are not set. However, these flags are just a approximation +@@ -820,17 +824,18 @@ export const enum NodeFlags { + // removal, it is likely that users will add the import anyway. + // The advantage of this approach is its simplicity. For the case of batch compilation, + // we guarantee that users won't have to pay the price of walking the tree if a dynamic import isn't used. +- /** @internal */ PossiblyContainsDynamicImport = 1 << 21, +- /** @internal */ PossiblyContainsImportMeta = 1 << 22, ++ /** @internal */ PossiblyContainsDynamicImport = 1 << 22, ++ /** @internal */ PossiblyContainsImportMeta = 1 << 23, + +- JSDoc = 1 << 23, // If node was parsed inside jsdoc +- /** @internal */ Ambient = 1 << 24, // If node was inside an ambient context -- a declaration file, or inside something with the `declare` modifier. +- /** @internal */ InWithStatement = 1 << 25, // If any ancestor of node was the `statement` of a WithStatement (not the `expression`) +- JsonFile = 1 << 26, // If node was parsed in a Json +- /** @internal */ TypeCached = 1 << 27, // If a type was cached for node at any point +- /** @internal */ Deprecated = 1 << 28, // If has '@deprecated' JSDoc tag ++ JSDoc = 1 << 24, // If node was parsed inside jsdoc ++ /** @internal */ Ambient = 1 << 25, // If node was inside an ambient context -- a declaration file, or inside something with the `declare` modifier. ++ /** @internal */ InWithStatement = 1 << 26, // If any ancestor of node was the `statement` of a WithStatement (not the `expression`) ++ JsonFile = 1 << 27, // If node was parsed in a Json ++ /** @internal */ TypeCached = 1 << 28, // If a type was cached for node at any point ++ /** @internal */ Deprecated = 1 << 29, // If has '@deprecated' JSDoc tag + +- BlockScoped = Let | Const, ++ BlockScoped = Let | Const | Using, ++ Constant = Const | Using, + + ReachabilityCheckFlags = HasImplicitReturn | HasExplicitReturn, + ReachabilityAndEmitFlags = ReachabilityCheckFlags | HasAsyncFunctions, +@@ -7945,10 +7950,11 @@ export interface SourceMapSource { + } + + /** @internal */ ++// NOTE: Any new properties should be accounted for in `mergeEmitNode` in factory/nodeFactory.ts + export interface EmitNode { +- annotatedNodes?: Node[]; // Tracks Parse-tree nodes with EmitNodes for eventual cleanup. + flags: EmitFlags; // Flags that customize emit + internalFlags: InternalEmitFlags; // Internal flags that customize emit ++ annotatedNodes?: Node[]; // Tracks Parse-tree nodes with EmitNodes for eventual cleanup. + leadingComments?: SynthesizedComment[]; // Synthesized leading comments + trailingComments?: SynthesizedComment[]; // Synthesized trailing comments + commentRange?: TextRange; // The text range to use when emitting leading or trailing comments +@@ -7961,7 +7967,8 @@ export interface EmitNode { + startsOnNewLine?: boolean; // If the node should begin on a new line + snippetElement?: SnippetElement; // Snippet element of the node + typeNode?: TypeNode; // VariableDeclaration type +- classThis?: Identifier; // Identifier that points to the final class constructor after decorators are applied ++ classThis?: Identifier; // Identifier that points to a captured static `this` for a class which may be updated after decorators are applied ++ assignedName?: Expression; // Expression used as the assigned name of a class or function + identifierTypeArguments?: NodeArray; // Only defined on synthesized identifiers. Though not syntactically valid, used in emitting diagnostics, quickinfo, and signature help. + autoGenerate: AutoGenerateInfo | undefined; // Used for auto-generated identifiers and private identifiers. + generatedImportReference?: ImportSpecifier; // Reference to the generated import specifier this identifier refers to +@@ -8093,9 +8100,10 @@ export const enum ExternalEmitHelpers { + CreateBinding = 1 << 22, // __createBinding (use by the module transform for (re)exports and namespace imports) + SetFunctionName = 1 << 23, // __setFunctionName (used by class fields and ECMAScript decorators) + PropKey = 1 << 24, // __propKey (used by class fields and ECMAScript decorators) ++ AddDisposableResourceAndDisposeResources = 1 << 25, // __addDisposableResource and __disposeResources (used by ESNext transformations) + + FirstEmitHelper = Extends, +- LastEmitHelper = PropKey, ++ LastEmitHelper = AddDisposableResourceAndDisposeResources, + + // Helpers included by ES2015 for..of + ForOfIncludes = Values, +@@ -8190,7 +8198,8 @@ export type WrappedExpression = + | T + ; + +-export type TypeOfTag = "undefined" | "number" | "bigint" | "boolean" | "string" | "symbol" | "object" | "function"; ++/** @internal */ ++export type TypeOfTag = "null" | "undefined" | "number" | "bigint" | "boolean" | "string" | "symbol" | "object" | "function"; + + /** @internal */ + export interface CallBinding { +@@ -8237,6 +8246,7 @@ export interface ParenthesizerRules { + export interface NodeConverters { + convertToFunctionBlock(node: ConciseBody, multiLine?: boolean): Block; + convertToFunctionExpression(node: FunctionDeclaration): FunctionExpression; ++ convertToClassExpression(node: ClassDeclaration): ClassExpression; + convertToArrayAssignmentElement(element: ArrayBindingOrAssignmentElement): Expression; + convertToObjectAssignmentElement(element: ObjectBindingOrAssignmentElement): ObjectLiteralElementLike; + convertToAssignmentPattern(node: BindingOrAssignmentPattern): AssignmentPattern; +@@ -8254,11 +8264,15 @@ export interface GeneratedNamePart { + suffix?: string; + } + ++export type ImmediatelyInvokedFunctionExpression = CallExpression & { readonly expression: FunctionExpression; }; ++export type ImmediatelyInvokedArrowFunction = CallExpression & { readonly expression: ParenthesizedExpression & { readonly expression: ArrowFunction; }; }; ++ + export interface NodeFactory { + /** @internal */ readonly parenthesizer: ParenthesizerRules; + /** @internal */ readonly converters: NodeConverters; + /** @internal */ readonly baseFactory: BaseNodeFactory; + /** @internal */ readonly flags: NodeFactoryFlags; ++ + createNodeArray(elements?: readonly T[], hasTrailingComma?: boolean): NodeArray; + + // +@@ -8877,8 +8891,8 @@ export interface NodeFactory { + + createImmediatelyInvokedFunctionExpression(statements: readonly Statement[]): CallExpression; + createImmediatelyInvokedFunctionExpression(statements: readonly Statement[], param: ParameterDeclaration, paramValue: Expression): CallExpression; +- createImmediatelyInvokedArrowFunction(statements: readonly Statement[]): CallExpression; +- createImmediatelyInvokedArrowFunction(statements: readonly Statement[], param: ParameterDeclaration, paramValue: Expression): CallExpression; ++ createImmediatelyInvokedArrowFunction(statements: readonly Statement[]): ImmediatelyInvokedArrowFunction; ++ createImmediatelyInvokedArrowFunction(statements: readonly Statement[], param: ParameterDeclaration, paramValue: Expression): ImmediatelyInvokedArrowFunction; + + + createVoidZero(): VoidExpression; +@@ -8886,6 +8900,7 @@ export interface NodeFactory { + createExternalModuleExport(exportName: Identifier): ExportDeclaration; + + /** @internal */ createTypeCheck(value: Expression, tag: TypeOfTag): Expression; ++ /** @internal */ createIsNotTypeCheck(value: Expression, tag: TypeOfTag): Expression; + /** @internal */ createMethodCall(object: Expression, methodName: string | Identifier, argumentsList: readonly Expression[]): CallExpression; + /** @internal */ createGlobalMethodCall(globalObjectName: string, globalMethodName: string, argumentsList: readonly Expression[]): CallExpression; + /** @internal */ createFunctionBindCall(target: Expression, thisArg: Expression, argumentsList: readonly Expression[]): CallExpression; +diff --git a/src/compiler/utilities.ts b/src/compiler/utilities.ts +index c681495ed..44a62be7e 100644 +--- a/src/compiler/utilities.ts ++++ b/src/compiler/utilities.ts +@@ -52,6 +52,7 @@ import { + ClassDeclaration, + ClassElement, + ClassExpression, ++ classHasDeclaredOrExplicitlyAssignedName, + ClassLikeDeclaration, + ClassStaticBlockDeclaration, + combinePaths, +@@ -2335,14 +2336,36 @@ export function isDeclarationReadonly(declaration: Declaration): boolean { + return !!(getCombinedModifierFlags(declaration) & ModifierFlags.Readonly && !isParameterPropertyDeclaration(declaration, declaration.parent)); + } + +-/** @internal */ ++/** ++ * Gets whether a bound `VariableDeclaration` or `VariableDeclarationList` is part of an `await using` declaration. ++ * @internal ++ */ ++export function isVarAwaitUsing(node: VariableDeclaration | VariableDeclarationList): boolean { ++ return (getCombinedNodeFlags(node) & NodeFlags.BlockScoped) === NodeFlags.AwaitUsing; ++} ++ ++/** ++ * Gets whether a bound `VariableDeclaration` or `VariableDeclarationList` is part of a `using` declaration. ++ * @internal ++ */ ++export function isVarUsing(node: VariableDeclaration | VariableDeclarationList): boolean { ++ return (getCombinedNodeFlags(node) & NodeFlags.BlockScoped) === NodeFlags.Using; ++} ++ ++/** ++ * Gets whether a bound `VariableDeclaration` or `VariableDeclarationList` is part of a `const` declaration. ++ * @internal ++ */ + export function isVarConst(node: VariableDeclaration | VariableDeclarationList): boolean { +- return !!(getCombinedNodeFlags(node) & NodeFlags.Const); ++ return (getCombinedNodeFlags(node) & NodeFlags.BlockScoped) === NodeFlags.Const; + } + +-/** @internal */ ++/** ++ * Gets whether a bound `VariableDeclaration` or `VariableDeclarationList` is part of a `let` declaration. ++ * @internal ++ */ + export function isLet(node: Node): boolean { +- return !!(getCombinedNodeFlags(node) & NodeFlags.Let); ++ return (getCombinedNodeFlags(node) & NodeFlags.BlockScoped) === NodeFlags.Let; + } + + /** @internal */ +@@ -5104,8 +5127,12 @@ export function isAnonymousFunctionDefinition(node: Expression, cb?: (node: Anon + node = skipOuterExpressions(node); + switch (node.kind) { + case SyntaxKind.ClassExpression: ++ if (classHasDeclaredOrExplicitlyAssignedName(node as ClassExpression)) { ++ return false; ++ } ++ break; + case SyntaxKind.FunctionExpression: +- if ((node as ClassExpression | FunctionExpression).name) { ++ if ((node as FunctionExpression).name) { + return false; + } + break; +@@ -5171,7 +5198,8 @@ export type NamedEvaluation = + | ParameterDeclaration & { readonly name: Identifier, readonly dotDotDotToken: undefined, readonly initializer: WrappedExpression } + | BindingElement & { readonly name: Identifier, readonly dotDotDotToken: undefined, readonly initializer: WrappedExpression } + | PropertyDeclaration & { readonly initializer: WrappedExpression } +- | AssignmentExpression & { readonly left: Identifier, readonly right: WrappedExpression } ++ | AssignmentExpression & { readonly left: Identifier, readonly right: WrappedExpression } ++ | AssignmentExpression & { readonly left: Identifier, readonly right: WrappedExpression } + | ExportAssignment & { readonly expression: WrappedExpression } + ; + +diff --git a/src/compiler/utilitiesPublic.ts b/src/compiler/utilitiesPublic.ts +index 4d0220bdf..62be65647 100644 +--- a/src/compiler/utilitiesPublic.ts ++++ b/src/compiler/utilitiesPublic.ts +@@ -68,6 +68,7 @@ import { + FunctionLikeDeclaration, + FunctionTypeNode, + GeneratedIdentifier, ++ GeneratedIdentifierFlags, + GeneratedPrivateIdentifier, + GetAccessorDeclaration, + getAssignmentDeclarationKind, +@@ -604,7 +605,11 @@ export function getCombinedNodeFlagsAlwaysIncludeJSDoc(node: Declaration): Modif + // list. By calling this function, all those flags are combined so that the client can treat + // the node as if it actually had those flags. + export function getCombinedNodeFlags(node: Node): NodeFlags { +- return getCombinedFlags(node, n => n.flags); ++ return getCombinedFlags(node, getNodeFlags); ++} ++ ++function getNodeFlags(node: Node) { ++ return node.flags; + } + + /** @internal */ +@@ -1533,6 +1538,14 @@ export function isGeneratedPrivateIdentifier(node: Node): node is GeneratedPriva + return isPrivateIdentifier(node) && node.emitNode?.autoGenerate !== undefined; + } + ++/** @internal */ ++export function isFileLevelReservedGeneratedIdentifier(node: GeneratedIdentifier) { ++ const flags = node.emitNode.autoGenerate.flags; ++ return !!(flags & GeneratedIdentifierFlags.FileLevel) ++ && !!(flags & GeneratedIdentifierFlags.Optimistic) ++ && !!(flags & GeneratedIdentifierFlags.ReservedInNestedScopes); ++} ++ + // Private Identifiers + /** @internal */ + export function isPrivateIdentifierClassElementDeclaration(node: Node): node is PrivateClassElementDeclaration { +diff --git a/src/lib/esnext.d.ts b/src/lib/esnext.d.ts +index 30eaf070b..efec17999 100644 +--- a/src/lib/esnext.d.ts ++++ b/src/lib/esnext.d.ts +@@ -1,2 +1,3 @@ + /// + /// ++/// +diff --git a/src/lib/esnext.disposable.d.ts b/src/lib/esnext.disposable.d.ts +new file mode 100644 +index 000000000..318b7395a +--- /dev/null ++++ b/src/lib/esnext.disposable.d.ts +@@ -0,0 +1,167 @@ ++/// ++ ++interface SymbolConstructor { ++ /** ++ * A method that is used to release resources held by an object. Called by the semantics of the `using` statement. ++ */ ++ readonly dispose: unique symbol; ++ ++ /** ++ * A method that is used to asynchronously release resources held by an object. Called by the semantics of the `await using` statement. ++ */ ++ readonly asyncDispose: unique symbol; ++} ++ ++interface Disposable { ++ [Symbol.dispose](): void; ++} ++ ++interface AsyncDisposable { ++ [Symbol.asyncDispose](): PromiseLike; ++} ++ ++interface SuppressedError extends Error { ++ error: any; ++ suppressed: any; ++} ++ ++interface SuppressedErrorConstructor extends ErrorConstructor { ++ new (error: any, suppressed: any, message?: string): SuppressedError; ++ (error: any, suppressed: any, message?: string): SuppressedError; ++ readonly prototype: SuppressedError; ++} ++declare var SuppressedError: SuppressedErrorConstructor; ++ ++interface DisposableStack { ++ /** ++ * Returns a value indicating whether this stack has been disposed. ++ */ ++ readonly disposed: boolean; ++ /** ++ * Disposes each resource in the stack in the reverse order that they were added. ++ */ ++ dispose(): void; ++ /** ++ * Adds a disposable resource to the stack, returning the resource. ++ * @param value The resource to add. `null` and `undefined` will not be added, but will be returned. ++ * @returns The provided {@link value}. ++ */ ++ use(value: T): T; ++ /** ++ * Adds a value and associated disposal callback as a resource to the stack. ++ * @param value The value to add. ++ * @param onDispose The callback to use in place of a `[Symbol.dispose]()` method. Will be invoked with `value` ++ * as the first parameter. ++ * @returns The provided {@link value}. ++ */ ++ adopt(value: T, onDispose: (value: T) => void): T; ++ /** ++ * Adds a callback to be invoked when the stack is disposed. ++ */ ++ defer(onDispose: () => void): void; ++ /** ++ * Move all resources out of this stack and into a new `DisposableStack`, and marks this stack as disposed. ++ * @example ++ * ```ts ++ * class C { ++ * #res1: Disposable; ++ * #res2: Disposable; ++ * #disposables: DisposableStack; ++ * constructor() { ++ * // stack will be disposed when exiting constructor for any reason ++ * using stack = new DisposableStack(); ++ * ++ * // get first resource ++ * this.#res1 = stack.use(getResource1()); ++ * ++ * // get second resource. If this fails, both `stack` and `#res1` will be disposed. ++ * this.#res2 = stack.use(getResource2()); ++ * ++ * // all operations succeeded, move resources out of `stack` so that they aren't disposed ++ * // when constructor exits ++ * this.#disposables = stack.move(); ++ * } ++ * ++ * [Symbol.dispose]() { ++ * this.#disposables.dispose(); ++ * } ++ * } ++ * ``` ++ */ ++ move(): DisposableStack; ++ [Symbol.dispose](): void; ++ readonly [Symbol.toStringTag]: string; ++} ++ ++interface DisposableStackConstructor { ++ new(): DisposableStack; ++ readonly prototype: DisposableStack; ++} ++declare var DisposableStack: DisposableStackConstructor; ++ ++interface AsyncDisposableStack { ++ /** ++ * Returns a value indicating whether this stack has been disposed. ++ */ ++ readonly disposed: boolean; ++ /** ++ * Disposes each resource in the stack in the reverse order that they were added. ++ */ ++ disposeAsync(): Promise; ++ /** ++ * Adds a disposable resource to the stack, returning the resource. ++ * @param value The resource to add. `null` and `undefined` will not be added, but will be returned. ++ * @returns The provided {@link value}. ++ */ ++ use(value: T): T; ++ /** ++ * Adds a value and associated disposal callback as a resource to the stack. ++ * @param value The value to add. ++ * @param onDisposeAsync The callback to use in place of a `[Symbol.asyncDispose]()` method. Will be invoked with `value` ++ * as the first parameter. ++ * @returns The provided {@link value}. ++ */ ++ adopt(value: T, onDisposeAsync: (value: T) => PromiseLike | void): T; ++ /** ++ * Adds a callback to be invoked when the stack is disposed. ++ */ ++ defer(onDisposeAsync: () => PromiseLike | void): void; ++ /** ++ * Move all resources out of this stack and into a new `DisposableStack`, and marks this stack as disposed. ++ * @example ++ * ```ts ++ * class C { ++ * #res1: Disposable; ++ * #res2: Disposable; ++ * #disposables: DisposableStack; ++ * constructor() { ++ * // stack will be disposed when exiting constructor for any reason ++ * using stack = new DisposableStack(); ++ * ++ * // get first resource ++ * this.#res1 = stack.use(getResource1()); ++ * ++ * // get second resource. If this fails, both `stack` and `#res1` will be disposed. ++ * this.#res2 = stack.use(getResource2()); ++ * ++ * // all operations succeeded, move resources out of `stack` so that they aren't disposed ++ * // when constructor exits ++ * this.#disposables = stack.move(); ++ * } ++ * ++ * [Symbol.dispose]() { ++ * this.#disposables.dispose(); ++ * } ++ * } ++ * ``` ++ */ ++ move(): AsyncDisposableStack; ++ [Symbol.asyncDispose](): Promise; ++ readonly [Symbol.toStringTag]: string; ++} ++ ++interface AsyncDisposableStackConstructor { ++ new(): AsyncDisposableStack; ++ readonly prototype: AsyncDisposableStack; ++} ++declare var AsyncDisposableStack: AsyncDisposableStackConstructor; +diff --git a/src/lib/libs.json b/src/lib/libs.json +index a7a07d9d2..260379879 100644 +--- a/src/lib/libs.json ++++ b/src/lib/libs.json +@@ -68,6 +68,7 @@ + "es2023.array", + "es2023.collection", + "esnext.intl", ++ "esnext.disposable", + "decorators", + "decorators.legacy", + // Default libraries +diff --git a/src/services/codefixes/addEmptyExportDeclaration.ts b/src/services/codefixes/addEmptyExportDeclaration.ts +index d4020fea8..b490c66af 100644 +--- a/src/services/codefixes/addEmptyExportDeclaration.ts ++++ b/src/services/codefixes/addEmptyExportDeclaration.ts +@@ -11,6 +11,7 @@ import { + registerCodeFix({ + errorCodes: [ + Diagnostics.await_expressions_are_only_allowed_at_the_top_level_of_a_file_when_that_file_is_a_module_but_this_file_has_no_imports_or_exports_Consider_adding_an_empty_export_to_make_this_file_a_module.code, ++ Diagnostics.await_using_statements_are_only_allowed_at_the_top_level_of_a_file_when_that_file_is_a_module_but_this_file_has_no_imports_or_exports_Consider_adding_an_empty_export_to_make_this_file_a_module.code, + Diagnostics.for_await_loops_are_only_allowed_at_the_top_level_of_a_file_when_that_file_is_a_module_but_this_file_has_no_imports_or_exports_Consider_adding_an_empty_export_to_make_this_file_a_module.code, + ], + getCodeActions: function getCodeActionsToAddEmptyExportDeclaration(context) { +diff --git a/src/services/codefixes/fixAwaitInSyncFunction.ts b/src/services/codefixes/fixAwaitInSyncFunction.ts +index f12ba12e3..ee1f5f73a 100644 +--- a/src/services/codefixes/fixAwaitInSyncFunction.ts ++++ b/src/services/codefixes/fixAwaitInSyncFunction.ts +@@ -29,6 +29,7 @@ import { + const fixId = "fixAwaitInSyncFunction"; + const errorCodes = [ + Diagnostics.await_expressions_are_only_allowed_within_async_functions_and_at_the_top_levels_of_modules.code, ++ Diagnostics.await_using_statements_are_only_allowed_within_async_functions_and_at_the_top_levels_of_modules.code, + Diagnostics.for_await_loops_are_only_allowed_within_async_functions_and_at_the_top_levels_of_modules.code, + Diagnostics.Cannot_find_name_0_Did_you_mean_to_write_this_in_an_async_function.code + ]; +diff --git a/src/services/codefixes/fixModuleAndTargetOptions.ts b/src/services/codefixes/fixModuleAndTargetOptions.ts +index 9a223fa10..0cc3e489a 100644 +--- a/src/services/codefixes/fixModuleAndTargetOptions.ts ++++ b/src/services/codefixes/fixModuleAndTargetOptions.ts +@@ -20,6 +20,7 @@ import { + registerCodeFix({ + errorCodes: [ + Diagnostics.Top_level_await_expressions_are_only_allowed_when_the_module_option_is_set_to_es2022_esnext_system_node16_or_nodenext_and_the_target_option_is_set_to_es2017_or_higher.code, ++ Diagnostics.Top_level_await_using_statements_are_only_allowed_when_the_module_option_is_set_to_es2022_esnext_system_node16_or_nodenext_and_the_target_option_is_set_to_es2017_or_higher.code, + Diagnostics.Top_level_for_await_loops_are_only_allowed_when_the_module_option_is_set_to_es2022_esnext_system_node16_or_nodenext_and_the_target_option_is_set_to_es2017_or_higher.code, + ], + getCodeActions: function getCodeActionsToFixModuleAndTarget(context) { diff --git a/TypeScript_2/solution/solve.sh b/TypeScript_2/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..04d2cdd558a05593c6373ab47313e0e441927403 --- /dev/null +++ b/TypeScript_2/solution/solve.sh @@ -0,0 +1,7 @@ +#!/usr/bin/env bash +set -euo pipefail + +cd /workspace/typescript +patch=${LOLBENCH_ORACLE_PATCH:-/solution/solution.patch} +git apply "$patch" +lolbench-submit diff --git a/TypeScript_2/task.toml b/TypeScript_2/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..45b9ab8950c967fe49aa74c05d436a2a8d41ed22 --- /dev/null +++ b/TypeScript_2/task.toml @@ -0,0 +1,60 @@ +schema_version = "1.3" + +[task] +name = "lolbench/TypeScript_2" +description = "Implement TypeScript using and await using declarations." +authors = [{ name = "LoLBench maintainers" }] +keywords = ["lolbench", "coding-agent", "typescript"] + +[metadata] +instance_id = "TypeScript_2" +source_instance_id = "TypeScript_PR-54505_Using-and-await-using-declarations" +source_slug = "TypeScript_PR-54505_Using-and-await-using-declarations" +docker_slug = "TypeScript_PR-54505_Using-and-await-using-declarations" +dockerhub_image = "smartdub26/lolbench-linux:TypeScript_2-1.0.0" +project = "TypeScript" +repo = "microsoft/TypeScript" +requirement_doc = "https://github.com/tc39/proposal-explicit-resource-management" +pr_link = "https://github.com/microsoft/TypeScript/pull/54505" +base_commit = "d90eb0d731c3f74b131dcfafe69ef5341ed14934" +merge_commit = "558a5028b785e962e7a26a9d820fc77ca094faf6" +test_level = "system" +source_history_policy = "ancestors-only" +lolbench_test_modes = ["orig", "aug", "union"] +default_lolbench_suite = "union" +canonical_lolbench_suite = "union" +augmentation_available = true +verifier_network_policy = "public" +verifier_network_reason = "The Harbor verifier runs in a separate container and may use network access; migrated LoLBench verifier assets are mounted only in the verifier phase." + +[environment] +build_timeout_sec = 3600.0 +docker_image = "smartdub26/lolbench-linux:TypeScript_2-1.0.0" +network_mode = "public" +os = "linux" +cpus = 4 +memory_mb = 7168 +storage_mb = 20480 + +[agent] +timeout_sec = 21600.0 +user = "agent" +network_mode = "allowlist" +allowed_hosts = ["openrouter.ai", "api.openai.com", "api.anthropic.com"] + +[verifier] +timeout_sec = 7200.0 +user = "root" +environment_mode = "separate" +network_mode = "public" + +[verifier.env] +LOLBENCH_SUITE = "union" + +[verifier.environment] +docker_image = "smartdub26/lolbench-linux:TypeScript_2-1.0.0" +network_mode = "public" +os = "linux" +cpus = 4 +memory_mb = 7168 +storage_mb = 20480 diff --git a/TypeScript_2/tests/docker-compose.yaml b/TypeScript_2/tests/docker-compose.yaml new file mode 100644 index 0000000000000000000000000000000000000000..f5091b9298e127a1efbe69deeed699c907e025c1 --- /dev/null +++ b/TypeScript_2/tests/docker-compose.yaml @@ -0,0 +1,16 @@ +services: + main: + pull_policy: missing + volumes: + - type: bind + source: . + target: /tests + read_only: true + - type: bind + source: ./private + target: /opt/lolbench/private + read_only: true + - type: bind + source: ../solution + target: /solution + read_only: true diff --git a/TypeScript_2/tests/private/eval_tests.patch b/TypeScript_2/tests/private/eval_tests.patch new file mode 100644 index 0000000000000000000000000000000000000000..30e12c1f7fea459b9e9ae3066f94835fe6d8f46f --- /dev/null +++ b/TypeScript_2/tests/private/eval_tests.patch @@ -0,0 +1,32075 @@ +diff --git a/tests/baselines/reference/amdImportNotAsPrimaryExpression.js b/tests/baselines/reference/amdImportNotAsPrimaryExpression.js +index e2c5aae28..c6f5699f6 100644 +--- a/tests/baselines/reference/amdImportNotAsPrimaryExpression.js ++++ b/tests/baselines/reference/amdImportNotAsPrimaryExpression.js +@@ -36,13 +36,14 @@ define(["require", "exports"], function (require, exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.E1 = exports.C1 = void 0; +- var C1 = exports.C1 = /** @class */ (function () { ++ var C1 = /** @class */ (function () { + function C1() { + this.m1 = 42; + } + C1.s1 = true; + return C1; + }()); ++ exports.C1 = C1; + var E1; + (function (E1) { + E1[E1["A"] = 0] = "A"; +diff --git a/tests/baselines/reference/api/tsserverlibrary.d.ts b/tests/baselines/reference/api/tsserverlibrary.d.ts +index 2860761a9..eff2717fe 100644 +--- a/tests/baselines/reference/api/tsserverlibrary.d.ts ++++ b/tests/baselines/reference/api/tsserverlibrary.d.ts +@@ -4257,211 +4257,212 @@ declare namespace ts { + UndefinedKeyword = 157, + UniqueKeyword = 158, + UnknownKeyword = 159, +- FromKeyword = 160, +- GlobalKeyword = 161, +- BigIntKeyword = 162, +- OverrideKeyword = 163, +- OfKeyword = 164, +- QualifiedName = 165, +- ComputedPropertyName = 166, +- TypeParameter = 167, +- Parameter = 168, +- Decorator = 169, +- PropertySignature = 170, +- PropertyDeclaration = 171, +- MethodSignature = 172, +- MethodDeclaration = 173, +- ClassStaticBlockDeclaration = 174, +- Constructor = 175, +- GetAccessor = 176, +- SetAccessor = 177, +- CallSignature = 178, +- ConstructSignature = 179, +- IndexSignature = 180, +- TypePredicate = 181, +- TypeReference = 182, +- FunctionType = 183, +- ConstructorType = 184, +- TypeQuery = 185, +- TypeLiteral = 186, +- ArrayType = 187, +- TupleType = 188, +- OptionalType = 189, +- RestType = 190, +- UnionType = 191, +- IntersectionType = 192, +- ConditionalType = 193, +- InferType = 194, +- ParenthesizedType = 195, +- ThisType = 196, +- TypeOperator = 197, +- IndexedAccessType = 198, +- MappedType = 199, +- LiteralType = 200, +- NamedTupleMember = 201, +- TemplateLiteralType = 202, +- TemplateLiteralTypeSpan = 203, +- ImportType = 204, +- ObjectBindingPattern = 205, +- ArrayBindingPattern = 206, +- BindingElement = 207, +- ArrayLiteralExpression = 208, +- ObjectLiteralExpression = 209, +- PropertyAccessExpression = 210, +- ElementAccessExpression = 211, +- CallExpression = 212, +- NewExpression = 213, +- TaggedTemplateExpression = 214, +- TypeAssertionExpression = 215, +- ParenthesizedExpression = 216, +- FunctionExpression = 217, +- ArrowFunction = 218, +- DeleteExpression = 219, +- TypeOfExpression = 220, +- VoidExpression = 221, +- AwaitExpression = 222, +- PrefixUnaryExpression = 223, +- PostfixUnaryExpression = 224, +- BinaryExpression = 225, +- ConditionalExpression = 226, +- TemplateExpression = 227, +- YieldExpression = 228, +- SpreadElement = 229, +- ClassExpression = 230, +- OmittedExpression = 231, +- ExpressionWithTypeArguments = 232, +- AsExpression = 233, +- NonNullExpression = 234, +- MetaProperty = 235, +- SyntheticExpression = 236, +- SatisfiesExpression = 237, +- TemplateSpan = 238, +- SemicolonClassElement = 239, +- Block = 240, +- EmptyStatement = 241, +- VariableStatement = 242, +- ExpressionStatement = 243, +- IfStatement = 244, +- DoStatement = 245, +- WhileStatement = 246, +- ForStatement = 247, +- ForInStatement = 248, +- ForOfStatement = 249, +- ContinueStatement = 250, +- BreakStatement = 251, +- ReturnStatement = 252, +- WithStatement = 253, +- SwitchStatement = 254, +- LabeledStatement = 255, +- ThrowStatement = 256, +- TryStatement = 257, +- DebuggerStatement = 258, +- VariableDeclaration = 259, +- VariableDeclarationList = 260, +- FunctionDeclaration = 261, +- ClassDeclaration = 262, +- InterfaceDeclaration = 263, +- TypeAliasDeclaration = 264, +- EnumDeclaration = 265, +- ModuleDeclaration = 266, +- ModuleBlock = 267, +- CaseBlock = 268, +- NamespaceExportDeclaration = 269, +- ImportEqualsDeclaration = 270, +- ImportDeclaration = 271, +- ImportClause = 272, +- NamespaceImport = 273, +- NamedImports = 274, +- ImportSpecifier = 275, +- ExportAssignment = 276, +- ExportDeclaration = 277, +- NamedExports = 278, +- NamespaceExport = 279, +- ExportSpecifier = 280, +- MissingDeclaration = 281, +- ExternalModuleReference = 282, +- JsxElement = 283, +- JsxSelfClosingElement = 284, +- JsxOpeningElement = 285, +- JsxClosingElement = 286, +- JsxFragment = 287, +- JsxOpeningFragment = 288, +- JsxClosingFragment = 289, +- JsxAttribute = 290, +- JsxAttributes = 291, +- JsxSpreadAttribute = 292, +- JsxExpression = 293, +- JsxNamespacedName = 294, +- CaseClause = 295, +- DefaultClause = 296, +- HeritageClause = 297, +- CatchClause = 298, +- AssertClause = 299, +- AssertEntry = 300, +- ImportTypeAssertionContainer = 301, +- PropertyAssignment = 302, +- ShorthandPropertyAssignment = 303, +- SpreadAssignment = 304, +- EnumMember = 305, +- /** @deprecated */ UnparsedPrologue = 306, +- /** @deprecated */ UnparsedPrepend = 307, +- /** @deprecated */ UnparsedText = 308, +- /** @deprecated */ UnparsedInternalText = 309, +- /** @deprecated */ UnparsedSyntheticReference = 310, +- SourceFile = 311, +- Bundle = 312, +- /** @deprecated */ UnparsedSource = 313, +- /** @deprecated */ InputFiles = 314, +- JSDocTypeExpression = 315, +- JSDocNameReference = 316, +- JSDocMemberName = 317, +- JSDocAllType = 318, +- JSDocUnknownType = 319, +- JSDocNullableType = 320, +- JSDocNonNullableType = 321, +- JSDocOptionalType = 322, +- JSDocFunctionType = 323, +- JSDocVariadicType = 324, +- JSDocNamepathType = 325, +- JSDoc = 326, ++ UsingKeyword = 160, ++ FromKeyword = 161, ++ GlobalKeyword = 162, ++ BigIntKeyword = 163, ++ OverrideKeyword = 164, ++ OfKeyword = 165, ++ QualifiedName = 166, ++ ComputedPropertyName = 167, ++ TypeParameter = 168, ++ Parameter = 169, ++ Decorator = 170, ++ PropertySignature = 171, ++ PropertyDeclaration = 172, ++ MethodSignature = 173, ++ MethodDeclaration = 174, ++ ClassStaticBlockDeclaration = 175, ++ Constructor = 176, ++ GetAccessor = 177, ++ SetAccessor = 178, ++ CallSignature = 179, ++ ConstructSignature = 180, ++ IndexSignature = 181, ++ TypePredicate = 182, ++ TypeReference = 183, ++ FunctionType = 184, ++ ConstructorType = 185, ++ TypeQuery = 186, ++ TypeLiteral = 187, ++ ArrayType = 188, ++ TupleType = 189, ++ OptionalType = 190, ++ RestType = 191, ++ UnionType = 192, ++ IntersectionType = 193, ++ ConditionalType = 194, ++ InferType = 195, ++ ParenthesizedType = 196, ++ ThisType = 197, ++ TypeOperator = 198, ++ IndexedAccessType = 199, ++ MappedType = 200, ++ LiteralType = 201, ++ NamedTupleMember = 202, ++ TemplateLiteralType = 203, ++ TemplateLiteralTypeSpan = 204, ++ ImportType = 205, ++ ObjectBindingPattern = 206, ++ ArrayBindingPattern = 207, ++ BindingElement = 208, ++ ArrayLiteralExpression = 209, ++ ObjectLiteralExpression = 210, ++ PropertyAccessExpression = 211, ++ ElementAccessExpression = 212, ++ CallExpression = 213, ++ NewExpression = 214, ++ TaggedTemplateExpression = 215, ++ TypeAssertionExpression = 216, ++ ParenthesizedExpression = 217, ++ FunctionExpression = 218, ++ ArrowFunction = 219, ++ DeleteExpression = 220, ++ TypeOfExpression = 221, ++ VoidExpression = 222, ++ AwaitExpression = 223, ++ PrefixUnaryExpression = 224, ++ PostfixUnaryExpression = 225, ++ BinaryExpression = 226, ++ ConditionalExpression = 227, ++ TemplateExpression = 228, ++ YieldExpression = 229, ++ SpreadElement = 230, ++ ClassExpression = 231, ++ OmittedExpression = 232, ++ ExpressionWithTypeArguments = 233, ++ AsExpression = 234, ++ NonNullExpression = 235, ++ MetaProperty = 236, ++ SyntheticExpression = 237, ++ SatisfiesExpression = 238, ++ TemplateSpan = 239, ++ SemicolonClassElement = 240, ++ Block = 241, ++ EmptyStatement = 242, ++ VariableStatement = 243, ++ ExpressionStatement = 244, ++ IfStatement = 245, ++ DoStatement = 246, ++ WhileStatement = 247, ++ ForStatement = 248, ++ ForInStatement = 249, ++ ForOfStatement = 250, ++ ContinueStatement = 251, ++ BreakStatement = 252, ++ ReturnStatement = 253, ++ WithStatement = 254, ++ SwitchStatement = 255, ++ LabeledStatement = 256, ++ ThrowStatement = 257, ++ TryStatement = 258, ++ DebuggerStatement = 259, ++ VariableDeclaration = 260, ++ VariableDeclarationList = 261, ++ FunctionDeclaration = 262, ++ ClassDeclaration = 263, ++ InterfaceDeclaration = 264, ++ TypeAliasDeclaration = 265, ++ EnumDeclaration = 266, ++ ModuleDeclaration = 267, ++ ModuleBlock = 268, ++ CaseBlock = 269, ++ NamespaceExportDeclaration = 270, ++ ImportEqualsDeclaration = 271, ++ ImportDeclaration = 272, ++ ImportClause = 273, ++ NamespaceImport = 274, ++ NamedImports = 275, ++ ImportSpecifier = 276, ++ ExportAssignment = 277, ++ ExportDeclaration = 278, ++ NamedExports = 279, ++ NamespaceExport = 280, ++ ExportSpecifier = 281, ++ MissingDeclaration = 282, ++ ExternalModuleReference = 283, ++ JsxElement = 284, ++ JsxSelfClosingElement = 285, ++ JsxOpeningElement = 286, ++ JsxClosingElement = 287, ++ JsxFragment = 288, ++ JsxOpeningFragment = 289, ++ JsxClosingFragment = 290, ++ JsxAttribute = 291, ++ JsxAttributes = 292, ++ JsxSpreadAttribute = 293, ++ JsxExpression = 294, ++ JsxNamespacedName = 295, ++ CaseClause = 296, ++ DefaultClause = 297, ++ HeritageClause = 298, ++ CatchClause = 299, ++ AssertClause = 300, ++ AssertEntry = 301, ++ ImportTypeAssertionContainer = 302, ++ PropertyAssignment = 303, ++ ShorthandPropertyAssignment = 304, ++ SpreadAssignment = 305, ++ EnumMember = 306, ++ /** @deprecated */ UnparsedPrologue = 307, ++ /** @deprecated */ UnparsedPrepend = 308, ++ /** @deprecated */ UnparsedText = 309, ++ /** @deprecated */ UnparsedInternalText = 310, ++ /** @deprecated */ UnparsedSyntheticReference = 311, ++ SourceFile = 312, ++ Bundle = 313, ++ /** @deprecated */ UnparsedSource = 314, ++ /** @deprecated */ InputFiles = 315, ++ JSDocTypeExpression = 316, ++ JSDocNameReference = 317, ++ JSDocMemberName = 318, ++ JSDocAllType = 319, ++ JSDocUnknownType = 320, ++ JSDocNullableType = 321, ++ JSDocNonNullableType = 322, ++ JSDocOptionalType = 323, ++ JSDocFunctionType = 324, ++ JSDocVariadicType = 325, ++ JSDocNamepathType = 326, ++ JSDoc = 327, + /** @deprecated Use SyntaxKind.JSDoc */ +- JSDocComment = 326, +- JSDocText = 327, +- JSDocTypeLiteral = 328, +- JSDocSignature = 329, +- JSDocLink = 330, +- JSDocLinkCode = 331, +- JSDocLinkPlain = 332, +- JSDocTag = 333, +- JSDocAugmentsTag = 334, +- JSDocImplementsTag = 335, +- JSDocAuthorTag = 336, +- JSDocDeprecatedTag = 337, +- JSDocClassTag = 338, +- JSDocPublicTag = 339, +- JSDocPrivateTag = 340, +- JSDocProtectedTag = 341, +- JSDocReadonlyTag = 342, +- JSDocOverrideTag = 343, +- JSDocCallbackTag = 344, +- JSDocOverloadTag = 345, +- JSDocEnumTag = 346, +- JSDocParameterTag = 347, +- JSDocReturnTag = 348, +- JSDocThisTag = 349, +- JSDocTypeTag = 350, +- JSDocTemplateTag = 351, +- JSDocTypedefTag = 352, +- JSDocSeeTag = 353, +- JSDocPropertyTag = 354, +- JSDocThrowsTag = 355, +- JSDocSatisfiesTag = 356, +- SyntaxList = 357, +- NotEmittedStatement = 358, +- PartiallyEmittedExpression = 359, +- CommaListExpression = 360, +- SyntheticReferenceExpression = 361, +- Count = 362, ++ JSDocComment = 327, ++ JSDocText = 328, ++ JSDocTypeLiteral = 329, ++ JSDocSignature = 330, ++ JSDocLink = 331, ++ JSDocLinkCode = 332, ++ JSDocLinkPlain = 333, ++ JSDocTag = 334, ++ JSDocAugmentsTag = 335, ++ JSDocImplementsTag = 336, ++ JSDocAuthorTag = 337, ++ JSDocDeprecatedTag = 338, ++ JSDocClassTag = 339, ++ JSDocPublicTag = 340, ++ JSDocPrivateTag = 341, ++ JSDocProtectedTag = 342, ++ JSDocReadonlyTag = 343, ++ JSDocOverrideTag = 344, ++ JSDocCallbackTag = 345, ++ JSDocOverloadTag = 346, ++ JSDocEnumTag = 347, ++ JSDocParameterTag = 348, ++ JSDocReturnTag = 349, ++ JSDocThisTag = 350, ++ JSDocTypeTag = 351, ++ JSDocTemplateTag = 352, ++ JSDocTypedefTag = 353, ++ JSDocSeeTag = 354, ++ JSDocPropertyTag = 355, ++ JSDocThrowsTag = 356, ++ JSDocSatisfiesTag = 357, ++ SyntaxList = 358, ++ NotEmittedStatement = 359, ++ PartiallyEmittedExpression = 360, ++ CommaListExpression = 361, ++ SyntheticReferenceExpression = 362, ++ Count = 363, + FirstAssignment = 64, + LastAssignment = 79, + FirstCompoundAssignment = 65, +@@ -4469,15 +4470,15 @@ declare namespace ts { + FirstReservedWord = 83, + LastReservedWord = 118, + FirstKeyword = 83, +- LastKeyword = 164, ++ LastKeyword = 165, + FirstFutureReservedWord = 119, + LastFutureReservedWord = 127, +- FirstTypeNode = 181, +- LastTypeNode = 204, ++ FirstTypeNode = 182, ++ LastTypeNode = 205, + FirstPunctuation = 19, + LastPunctuation = 79, + FirstToken = 0, +- LastToken = 164, ++ LastToken = 165, + FirstTriviaToken = 2, + LastTriviaToken = 7, + FirstLiteralToken = 9, +@@ -4486,19 +4487,19 @@ declare namespace ts { + LastTemplateToken = 18, + FirstBinaryOperator = 30, + LastBinaryOperator = 79, +- FirstStatement = 242, +- LastStatement = 258, +- FirstNode = 165, +- FirstJSDocNode = 315, +- LastJSDocNode = 356, +- FirstJSDocTagNode = 333, +- LastJSDocTagNode = 356 ++ FirstStatement = 243, ++ LastStatement = 259, ++ FirstNode = 166, ++ FirstJSDocNode = 316, ++ LastJSDocNode = 357, ++ FirstJSDocTagNode = 334, ++ LastJSDocTagNode = 357 + } + type TriviaSyntaxKind = SyntaxKind.SingleLineCommentTrivia | SyntaxKind.MultiLineCommentTrivia | SyntaxKind.NewLineTrivia | SyntaxKind.WhitespaceTrivia | SyntaxKind.ShebangTrivia | SyntaxKind.ConflictMarkerTrivia; + type LiteralSyntaxKind = SyntaxKind.NumericLiteral | SyntaxKind.BigIntLiteral | SyntaxKind.StringLiteral | SyntaxKind.JsxText | SyntaxKind.JsxTextAllWhiteSpaces | SyntaxKind.RegularExpressionLiteral | SyntaxKind.NoSubstitutionTemplateLiteral; + type PseudoLiteralSyntaxKind = SyntaxKind.TemplateHead | SyntaxKind.TemplateMiddle | SyntaxKind.TemplateTail; + type PunctuationSyntaxKind = SyntaxKind.OpenBraceToken | SyntaxKind.CloseBraceToken | SyntaxKind.OpenParenToken | SyntaxKind.CloseParenToken | SyntaxKind.OpenBracketToken | SyntaxKind.CloseBracketToken | SyntaxKind.DotToken | SyntaxKind.DotDotDotToken | SyntaxKind.SemicolonToken | SyntaxKind.CommaToken | SyntaxKind.QuestionDotToken | SyntaxKind.LessThanToken | SyntaxKind.LessThanSlashToken | SyntaxKind.GreaterThanToken | SyntaxKind.LessThanEqualsToken | SyntaxKind.GreaterThanEqualsToken | SyntaxKind.EqualsEqualsToken | SyntaxKind.ExclamationEqualsToken | SyntaxKind.EqualsEqualsEqualsToken | SyntaxKind.ExclamationEqualsEqualsToken | SyntaxKind.EqualsGreaterThanToken | SyntaxKind.PlusToken | SyntaxKind.MinusToken | SyntaxKind.AsteriskToken | SyntaxKind.AsteriskAsteriskToken | SyntaxKind.SlashToken | SyntaxKind.PercentToken | SyntaxKind.PlusPlusToken | SyntaxKind.MinusMinusToken | SyntaxKind.LessThanLessThanToken | SyntaxKind.GreaterThanGreaterThanToken | SyntaxKind.GreaterThanGreaterThanGreaterThanToken | SyntaxKind.AmpersandToken | SyntaxKind.BarToken | SyntaxKind.CaretToken | SyntaxKind.ExclamationToken | SyntaxKind.TildeToken | SyntaxKind.AmpersandAmpersandToken | SyntaxKind.AmpersandAmpersandEqualsToken | SyntaxKind.BarBarToken | SyntaxKind.BarBarEqualsToken | SyntaxKind.QuestionQuestionToken | SyntaxKind.QuestionQuestionEqualsToken | SyntaxKind.QuestionToken | SyntaxKind.ColonToken | SyntaxKind.AtToken | SyntaxKind.BacktickToken | SyntaxKind.HashToken | SyntaxKind.EqualsToken | SyntaxKind.PlusEqualsToken | SyntaxKind.MinusEqualsToken | SyntaxKind.AsteriskEqualsToken | SyntaxKind.AsteriskAsteriskEqualsToken | SyntaxKind.SlashEqualsToken | SyntaxKind.PercentEqualsToken | SyntaxKind.LessThanLessThanEqualsToken | SyntaxKind.GreaterThanGreaterThanEqualsToken | SyntaxKind.GreaterThanGreaterThanGreaterThanEqualsToken | SyntaxKind.AmpersandEqualsToken | SyntaxKind.BarEqualsToken | SyntaxKind.CaretEqualsToken; +- type KeywordSyntaxKind = SyntaxKind.AbstractKeyword | SyntaxKind.AccessorKeyword | SyntaxKind.AnyKeyword | SyntaxKind.AsKeyword | SyntaxKind.AssertsKeyword | SyntaxKind.AssertKeyword | SyntaxKind.AsyncKeyword | SyntaxKind.AwaitKeyword | SyntaxKind.BigIntKeyword | SyntaxKind.BooleanKeyword | SyntaxKind.BreakKeyword | SyntaxKind.CaseKeyword | SyntaxKind.CatchKeyword | SyntaxKind.ClassKeyword | SyntaxKind.ConstKeyword | SyntaxKind.ConstructorKeyword | SyntaxKind.ContinueKeyword | SyntaxKind.DebuggerKeyword | SyntaxKind.DeclareKeyword | SyntaxKind.DefaultKeyword | SyntaxKind.DeleteKeyword | SyntaxKind.DoKeyword | SyntaxKind.ElseKeyword | SyntaxKind.EnumKeyword | SyntaxKind.ExportKeyword | SyntaxKind.ExtendsKeyword | SyntaxKind.FalseKeyword | SyntaxKind.FinallyKeyword | SyntaxKind.ForKeyword | SyntaxKind.FromKeyword | SyntaxKind.FunctionKeyword | SyntaxKind.GetKeyword | SyntaxKind.GlobalKeyword | SyntaxKind.IfKeyword | SyntaxKind.ImplementsKeyword | SyntaxKind.ImportKeyword | SyntaxKind.InferKeyword | SyntaxKind.InKeyword | SyntaxKind.InstanceOfKeyword | SyntaxKind.InterfaceKeyword | SyntaxKind.IntrinsicKeyword | SyntaxKind.IsKeyword | SyntaxKind.KeyOfKeyword | SyntaxKind.LetKeyword | SyntaxKind.ModuleKeyword | SyntaxKind.NamespaceKeyword | SyntaxKind.NeverKeyword | SyntaxKind.NewKeyword | SyntaxKind.NullKeyword | SyntaxKind.NumberKeyword | SyntaxKind.ObjectKeyword | SyntaxKind.OfKeyword | SyntaxKind.PackageKeyword | SyntaxKind.PrivateKeyword | SyntaxKind.ProtectedKeyword | SyntaxKind.PublicKeyword | SyntaxKind.ReadonlyKeyword | SyntaxKind.OutKeyword | SyntaxKind.OverrideKeyword | SyntaxKind.RequireKeyword | SyntaxKind.ReturnKeyword | SyntaxKind.SatisfiesKeyword | SyntaxKind.SetKeyword | SyntaxKind.StaticKeyword | SyntaxKind.StringKeyword | SyntaxKind.SuperKeyword | SyntaxKind.SwitchKeyword | SyntaxKind.SymbolKeyword | SyntaxKind.ThisKeyword | SyntaxKind.ThrowKeyword | SyntaxKind.TrueKeyword | SyntaxKind.TryKeyword | SyntaxKind.TypeKeyword | SyntaxKind.TypeOfKeyword | SyntaxKind.UndefinedKeyword | SyntaxKind.UniqueKeyword | SyntaxKind.UnknownKeyword | SyntaxKind.VarKeyword | SyntaxKind.VoidKeyword | SyntaxKind.WhileKeyword | SyntaxKind.WithKeyword | SyntaxKind.YieldKeyword; ++ type KeywordSyntaxKind = SyntaxKind.AbstractKeyword | SyntaxKind.AccessorKeyword | SyntaxKind.AnyKeyword | SyntaxKind.AsKeyword | SyntaxKind.AssertsKeyword | SyntaxKind.AssertKeyword | SyntaxKind.AsyncKeyword | SyntaxKind.AwaitKeyword | SyntaxKind.BigIntKeyword | SyntaxKind.BooleanKeyword | SyntaxKind.BreakKeyword | SyntaxKind.CaseKeyword | SyntaxKind.CatchKeyword | SyntaxKind.ClassKeyword | SyntaxKind.ConstKeyword | SyntaxKind.ConstructorKeyword | SyntaxKind.ContinueKeyword | SyntaxKind.DebuggerKeyword | SyntaxKind.DeclareKeyword | SyntaxKind.DefaultKeyword | SyntaxKind.DeleteKeyword | SyntaxKind.DoKeyword | SyntaxKind.ElseKeyword | SyntaxKind.EnumKeyword | SyntaxKind.ExportKeyword | SyntaxKind.ExtendsKeyword | SyntaxKind.FalseKeyword | SyntaxKind.FinallyKeyword | SyntaxKind.ForKeyword | SyntaxKind.FromKeyword | SyntaxKind.FunctionKeyword | SyntaxKind.GetKeyword | SyntaxKind.GlobalKeyword | SyntaxKind.IfKeyword | SyntaxKind.ImplementsKeyword | SyntaxKind.ImportKeyword | SyntaxKind.InferKeyword | SyntaxKind.InKeyword | SyntaxKind.InstanceOfKeyword | SyntaxKind.InterfaceKeyword | SyntaxKind.IntrinsicKeyword | SyntaxKind.IsKeyword | SyntaxKind.KeyOfKeyword | SyntaxKind.LetKeyword | SyntaxKind.ModuleKeyword | SyntaxKind.NamespaceKeyword | SyntaxKind.NeverKeyword | SyntaxKind.NewKeyword | SyntaxKind.NullKeyword | SyntaxKind.NumberKeyword | SyntaxKind.ObjectKeyword | SyntaxKind.OfKeyword | SyntaxKind.PackageKeyword | SyntaxKind.PrivateKeyword | SyntaxKind.ProtectedKeyword | SyntaxKind.PublicKeyword | SyntaxKind.ReadonlyKeyword | SyntaxKind.OutKeyword | SyntaxKind.OverrideKeyword | SyntaxKind.RequireKeyword | SyntaxKind.ReturnKeyword | SyntaxKind.SatisfiesKeyword | SyntaxKind.SetKeyword | SyntaxKind.StaticKeyword | SyntaxKind.StringKeyword | SyntaxKind.SuperKeyword | SyntaxKind.SwitchKeyword | SyntaxKind.SymbolKeyword | SyntaxKind.ThisKeyword | SyntaxKind.ThrowKeyword | SyntaxKind.TrueKeyword | SyntaxKind.TryKeyword | SyntaxKind.TypeKeyword | SyntaxKind.TypeOfKeyword | SyntaxKind.UndefinedKeyword | SyntaxKind.UniqueKeyword | SyntaxKind.UnknownKeyword | SyntaxKind.UsingKeyword | SyntaxKind.VarKeyword | SyntaxKind.VoidKeyword | SyntaxKind.WhileKeyword | SyntaxKind.WithKeyword | SyntaxKind.YieldKeyword; + type ModifierSyntaxKind = SyntaxKind.AbstractKeyword | SyntaxKind.AccessorKeyword | SyntaxKind.AsyncKeyword | SyntaxKind.ConstKeyword | SyntaxKind.DeclareKeyword | SyntaxKind.DefaultKeyword | SyntaxKind.ExportKeyword | SyntaxKind.InKeyword | SyntaxKind.PrivateKeyword | SyntaxKind.ProtectedKeyword | SyntaxKind.PublicKeyword | SyntaxKind.ReadonlyKeyword | SyntaxKind.OutKeyword | SyntaxKind.OverrideKeyword | SyntaxKind.StaticKeyword; + type KeywordTypeSyntaxKind = SyntaxKind.AnyKeyword | SyntaxKind.BigIntKeyword | SyntaxKind.BooleanKeyword | SyntaxKind.IntrinsicKeyword | SyntaxKind.NeverKeyword | SyntaxKind.NumberKeyword | SyntaxKind.ObjectKeyword | SyntaxKind.StringKeyword | SyntaxKind.SymbolKeyword | SyntaxKind.UndefinedKeyword | SyntaxKind.UnknownKeyword | SyntaxKind.VoidKeyword; + type TokenSyntaxKind = SyntaxKind.Unknown | SyntaxKind.EndOfFileToken | TriviaSyntaxKind | LiteralSyntaxKind | PseudoLiteralSyntaxKind | PunctuationSyntaxKind | SyntaxKind.Identifier | KeywordSyntaxKind; +@@ -4508,32 +4509,35 @@ declare namespace ts { + None = 0, + Let = 1, + Const = 2, +- NestedNamespace = 4, +- Synthesized = 8, +- Namespace = 16, +- OptionalChain = 32, +- ExportContext = 64, +- ContainsThis = 128, +- HasImplicitReturn = 256, +- HasExplicitReturn = 512, +- GlobalAugmentation = 1024, +- HasAsyncFunctions = 2048, +- DisallowInContext = 4096, +- YieldContext = 8192, +- DecoratorContext = 16384, +- AwaitContext = 32768, +- DisallowConditionalTypesContext = 65536, +- ThisNodeHasError = 131072, +- JavaScriptFile = 262144, +- ThisNodeOrAnySubNodesHasError = 524288, +- HasAggregatedChildData = 1048576, +- JSDoc = 8388608, +- JsonFile = 67108864, +- BlockScoped = 3, +- ReachabilityCheckFlags = 768, +- ReachabilityAndEmitFlags = 2816, +- ContextFlags = 50720768, +- TypeExcludesFlags = 40960 ++ Using = 4, ++ AwaitUsing = 6, ++ NestedNamespace = 8, ++ Synthesized = 16, ++ Namespace = 32, ++ OptionalChain = 64, ++ ExportContext = 128, ++ ContainsThis = 256, ++ HasImplicitReturn = 512, ++ HasExplicitReturn = 1024, ++ GlobalAugmentation = 2048, ++ HasAsyncFunctions = 4096, ++ DisallowInContext = 8192, ++ YieldContext = 16384, ++ DecoratorContext = 32768, ++ AwaitContext = 65536, ++ DisallowConditionalTypesContext = 131072, ++ ThisNodeHasError = 262144, ++ JavaScriptFile = 524288, ++ ThisNodeOrAnySubNodesHasError = 1048576, ++ HasAggregatedChildData = 2097152, ++ JSDoc = 16777216, ++ JsonFile = 134217728, ++ BlockScoped = 7, ++ Constant = 6, ++ ReachabilityCheckFlags = 1536, ++ ReachabilityAndEmitFlags = 5632, ++ ContextFlags = 101441536, ++ TypeExcludesFlags = 81920 + } + enum ModifierFlags { + None = 0, +@@ -7588,7 +7592,14 @@ declare namespace ts { + All = 15, + ExcludeJSDocTypeAssertion = 16 + } +- type TypeOfTag = "undefined" | "number" | "bigint" | "boolean" | "string" | "symbol" | "object" | "function"; ++ type ImmediatelyInvokedFunctionExpression = CallExpression & { ++ readonly expression: FunctionExpression; ++ }; ++ type ImmediatelyInvokedArrowFunction = CallExpression & { ++ readonly expression: ParenthesizedExpression & { ++ readonly expression: ArrowFunction; ++ }; ++ }; + interface NodeFactory { + createNodeArray(elements?: readonly T[], hasTrailingComma?: boolean): NodeArray; + createNumericLiteral(value: string | number, numericLiteralFlags?: TokenFlags): NumericLiteral; +@@ -8058,8 +8069,8 @@ declare namespace ts { + createPostfixDecrement(operand: Expression): PostfixUnaryExpression; + createImmediatelyInvokedFunctionExpression(statements: readonly Statement[]): CallExpression; + createImmediatelyInvokedFunctionExpression(statements: readonly Statement[], param: ParameterDeclaration, paramValue: Expression): CallExpression; +- createImmediatelyInvokedArrowFunction(statements: readonly Statement[]): CallExpression; +- createImmediatelyInvokedArrowFunction(statements: readonly Statement[], param: ParameterDeclaration, paramValue: Expression): CallExpression; ++ createImmediatelyInvokedArrowFunction(statements: readonly Statement[]): ImmediatelyInvokedArrowFunction; ++ createImmediatelyInvokedArrowFunction(statements: readonly Statement[], param: ParameterDeclaration, paramValue: Expression): ImmediatelyInvokedArrowFunction; + createVoidZero(): VoidExpression; + createExportDefault(expression: Expression): ExportAssignment; + createExternalModuleExport(exportName: Identifier): ExportDeclaration; +diff --git a/tests/baselines/reference/api/typescript.d.ts b/tests/baselines/reference/api/typescript.d.ts +index 266025222..3f78e1ae2 100644 +--- a/tests/baselines/reference/api/typescript.d.ts ++++ b/tests/baselines/reference/api/typescript.d.ts +@@ -204,211 +204,212 @@ declare namespace ts { + UndefinedKeyword = 157, + UniqueKeyword = 158, + UnknownKeyword = 159, +- FromKeyword = 160, +- GlobalKeyword = 161, +- BigIntKeyword = 162, +- OverrideKeyword = 163, +- OfKeyword = 164, +- QualifiedName = 165, +- ComputedPropertyName = 166, +- TypeParameter = 167, +- Parameter = 168, +- Decorator = 169, +- PropertySignature = 170, +- PropertyDeclaration = 171, +- MethodSignature = 172, +- MethodDeclaration = 173, +- ClassStaticBlockDeclaration = 174, +- Constructor = 175, +- GetAccessor = 176, +- SetAccessor = 177, +- CallSignature = 178, +- ConstructSignature = 179, +- IndexSignature = 180, +- TypePredicate = 181, +- TypeReference = 182, +- FunctionType = 183, +- ConstructorType = 184, +- TypeQuery = 185, +- TypeLiteral = 186, +- ArrayType = 187, +- TupleType = 188, +- OptionalType = 189, +- RestType = 190, +- UnionType = 191, +- IntersectionType = 192, +- ConditionalType = 193, +- InferType = 194, +- ParenthesizedType = 195, +- ThisType = 196, +- TypeOperator = 197, +- IndexedAccessType = 198, +- MappedType = 199, +- LiteralType = 200, +- NamedTupleMember = 201, +- TemplateLiteralType = 202, +- TemplateLiteralTypeSpan = 203, +- ImportType = 204, +- ObjectBindingPattern = 205, +- ArrayBindingPattern = 206, +- BindingElement = 207, +- ArrayLiteralExpression = 208, +- ObjectLiteralExpression = 209, +- PropertyAccessExpression = 210, +- ElementAccessExpression = 211, +- CallExpression = 212, +- NewExpression = 213, +- TaggedTemplateExpression = 214, +- TypeAssertionExpression = 215, +- ParenthesizedExpression = 216, +- FunctionExpression = 217, +- ArrowFunction = 218, +- DeleteExpression = 219, +- TypeOfExpression = 220, +- VoidExpression = 221, +- AwaitExpression = 222, +- PrefixUnaryExpression = 223, +- PostfixUnaryExpression = 224, +- BinaryExpression = 225, +- ConditionalExpression = 226, +- TemplateExpression = 227, +- YieldExpression = 228, +- SpreadElement = 229, +- ClassExpression = 230, +- OmittedExpression = 231, +- ExpressionWithTypeArguments = 232, +- AsExpression = 233, +- NonNullExpression = 234, +- MetaProperty = 235, +- SyntheticExpression = 236, +- SatisfiesExpression = 237, +- TemplateSpan = 238, +- SemicolonClassElement = 239, +- Block = 240, +- EmptyStatement = 241, +- VariableStatement = 242, +- ExpressionStatement = 243, +- IfStatement = 244, +- DoStatement = 245, +- WhileStatement = 246, +- ForStatement = 247, +- ForInStatement = 248, +- ForOfStatement = 249, +- ContinueStatement = 250, +- BreakStatement = 251, +- ReturnStatement = 252, +- WithStatement = 253, +- SwitchStatement = 254, +- LabeledStatement = 255, +- ThrowStatement = 256, +- TryStatement = 257, +- DebuggerStatement = 258, +- VariableDeclaration = 259, +- VariableDeclarationList = 260, +- FunctionDeclaration = 261, +- ClassDeclaration = 262, +- InterfaceDeclaration = 263, +- TypeAliasDeclaration = 264, +- EnumDeclaration = 265, +- ModuleDeclaration = 266, +- ModuleBlock = 267, +- CaseBlock = 268, +- NamespaceExportDeclaration = 269, +- ImportEqualsDeclaration = 270, +- ImportDeclaration = 271, +- ImportClause = 272, +- NamespaceImport = 273, +- NamedImports = 274, +- ImportSpecifier = 275, +- ExportAssignment = 276, +- ExportDeclaration = 277, +- NamedExports = 278, +- NamespaceExport = 279, +- ExportSpecifier = 280, +- MissingDeclaration = 281, +- ExternalModuleReference = 282, +- JsxElement = 283, +- JsxSelfClosingElement = 284, +- JsxOpeningElement = 285, +- JsxClosingElement = 286, +- JsxFragment = 287, +- JsxOpeningFragment = 288, +- JsxClosingFragment = 289, +- JsxAttribute = 290, +- JsxAttributes = 291, +- JsxSpreadAttribute = 292, +- JsxExpression = 293, +- JsxNamespacedName = 294, +- CaseClause = 295, +- DefaultClause = 296, +- HeritageClause = 297, +- CatchClause = 298, +- AssertClause = 299, +- AssertEntry = 300, +- ImportTypeAssertionContainer = 301, +- PropertyAssignment = 302, +- ShorthandPropertyAssignment = 303, +- SpreadAssignment = 304, +- EnumMember = 305, +- /** @deprecated */ UnparsedPrologue = 306, +- /** @deprecated */ UnparsedPrepend = 307, +- /** @deprecated */ UnparsedText = 308, +- /** @deprecated */ UnparsedInternalText = 309, +- /** @deprecated */ UnparsedSyntheticReference = 310, +- SourceFile = 311, +- Bundle = 312, +- /** @deprecated */ UnparsedSource = 313, +- /** @deprecated */ InputFiles = 314, +- JSDocTypeExpression = 315, +- JSDocNameReference = 316, +- JSDocMemberName = 317, +- JSDocAllType = 318, +- JSDocUnknownType = 319, +- JSDocNullableType = 320, +- JSDocNonNullableType = 321, +- JSDocOptionalType = 322, +- JSDocFunctionType = 323, +- JSDocVariadicType = 324, +- JSDocNamepathType = 325, +- JSDoc = 326, ++ UsingKeyword = 160, ++ FromKeyword = 161, ++ GlobalKeyword = 162, ++ BigIntKeyword = 163, ++ OverrideKeyword = 164, ++ OfKeyword = 165, ++ QualifiedName = 166, ++ ComputedPropertyName = 167, ++ TypeParameter = 168, ++ Parameter = 169, ++ Decorator = 170, ++ PropertySignature = 171, ++ PropertyDeclaration = 172, ++ MethodSignature = 173, ++ MethodDeclaration = 174, ++ ClassStaticBlockDeclaration = 175, ++ Constructor = 176, ++ GetAccessor = 177, ++ SetAccessor = 178, ++ CallSignature = 179, ++ ConstructSignature = 180, ++ IndexSignature = 181, ++ TypePredicate = 182, ++ TypeReference = 183, ++ FunctionType = 184, ++ ConstructorType = 185, ++ TypeQuery = 186, ++ TypeLiteral = 187, ++ ArrayType = 188, ++ TupleType = 189, ++ OptionalType = 190, ++ RestType = 191, ++ UnionType = 192, ++ IntersectionType = 193, ++ ConditionalType = 194, ++ InferType = 195, ++ ParenthesizedType = 196, ++ ThisType = 197, ++ TypeOperator = 198, ++ IndexedAccessType = 199, ++ MappedType = 200, ++ LiteralType = 201, ++ NamedTupleMember = 202, ++ TemplateLiteralType = 203, ++ TemplateLiteralTypeSpan = 204, ++ ImportType = 205, ++ ObjectBindingPattern = 206, ++ ArrayBindingPattern = 207, ++ BindingElement = 208, ++ ArrayLiteralExpression = 209, ++ ObjectLiteralExpression = 210, ++ PropertyAccessExpression = 211, ++ ElementAccessExpression = 212, ++ CallExpression = 213, ++ NewExpression = 214, ++ TaggedTemplateExpression = 215, ++ TypeAssertionExpression = 216, ++ ParenthesizedExpression = 217, ++ FunctionExpression = 218, ++ ArrowFunction = 219, ++ DeleteExpression = 220, ++ TypeOfExpression = 221, ++ VoidExpression = 222, ++ AwaitExpression = 223, ++ PrefixUnaryExpression = 224, ++ PostfixUnaryExpression = 225, ++ BinaryExpression = 226, ++ ConditionalExpression = 227, ++ TemplateExpression = 228, ++ YieldExpression = 229, ++ SpreadElement = 230, ++ ClassExpression = 231, ++ OmittedExpression = 232, ++ ExpressionWithTypeArguments = 233, ++ AsExpression = 234, ++ NonNullExpression = 235, ++ MetaProperty = 236, ++ SyntheticExpression = 237, ++ SatisfiesExpression = 238, ++ TemplateSpan = 239, ++ SemicolonClassElement = 240, ++ Block = 241, ++ EmptyStatement = 242, ++ VariableStatement = 243, ++ ExpressionStatement = 244, ++ IfStatement = 245, ++ DoStatement = 246, ++ WhileStatement = 247, ++ ForStatement = 248, ++ ForInStatement = 249, ++ ForOfStatement = 250, ++ ContinueStatement = 251, ++ BreakStatement = 252, ++ ReturnStatement = 253, ++ WithStatement = 254, ++ SwitchStatement = 255, ++ LabeledStatement = 256, ++ ThrowStatement = 257, ++ TryStatement = 258, ++ DebuggerStatement = 259, ++ VariableDeclaration = 260, ++ VariableDeclarationList = 261, ++ FunctionDeclaration = 262, ++ ClassDeclaration = 263, ++ InterfaceDeclaration = 264, ++ TypeAliasDeclaration = 265, ++ EnumDeclaration = 266, ++ ModuleDeclaration = 267, ++ ModuleBlock = 268, ++ CaseBlock = 269, ++ NamespaceExportDeclaration = 270, ++ ImportEqualsDeclaration = 271, ++ ImportDeclaration = 272, ++ ImportClause = 273, ++ NamespaceImport = 274, ++ NamedImports = 275, ++ ImportSpecifier = 276, ++ ExportAssignment = 277, ++ ExportDeclaration = 278, ++ NamedExports = 279, ++ NamespaceExport = 280, ++ ExportSpecifier = 281, ++ MissingDeclaration = 282, ++ ExternalModuleReference = 283, ++ JsxElement = 284, ++ JsxSelfClosingElement = 285, ++ JsxOpeningElement = 286, ++ JsxClosingElement = 287, ++ JsxFragment = 288, ++ JsxOpeningFragment = 289, ++ JsxClosingFragment = 290, ++ JsxAttribute = 291, ++ JsxAttributes = 292, ++ JsxSpreadAttribute = 293, ++ JsxExpression = 294, ++ JsxNamespacedName = 295, ++ CaseClause = 296, ++ DefaultClause = 297, ++ HeritageClause = 298, ++ CatchClause = 299, ++ AssertClause = 300, ++ AssertEntry = 301, ++ ImportTypeAssertionContainer = 302, ++ PropertyAssignment = 303, ++ ShorthandPropertyAssignment = 304, ++ SpreadAssignment = 305, ++ EnumMember = 306, ++ /** @deprecated */ UnparsedPrologue = 307, ++ /** @deprecated */ UnparsedPrepend = 308, ++ /** @deprecated */ UnparsedText = 309, ++ /** @deprecated */ UnparsedInternalText = 310, ++ /** @deprecated */ UnparsedSyntheticReference = 311, ++ SourceFile = 312, ++ Bundle = 313, ++ /** @deprecated */ UnparsedSource = 314, ++ /** @deprecated */ InputFiles = 315, ++ JSDocTypeExpression = 316, ++ JSDocNameReference = 317, ++ JSDocMemberName = 318, ++ JSDocAllType = 319, ++ JSDocUnknownType = 320, ++ JSDocNullableType = 321, ++ JSDocNonNullableType = 322, ++ JSDocOptionalType = 323, ++ JSDocFunctionType = 324, ++ JSDocVariadicType = 325, ++ JSDocNamepathType = 326, ++ JSDoc = 327, + /** @deprecated Use SyntaxKind.JSDoc */ +- JSDocComment = 326, +- JSDocText = 327, +- JSDocTypeLiteral = 328, +- JSDocSignature = 329, +- JSDocLink = 330, +- JSDocLinkCode = 331, +- JSDocLinkPlain = 332, +- JSDocTag = 333, +- JSDocAugmentsTag = 334, +- JSDocImplementsTag = 335, +- JSDocAuthorTag = 336, +- JSDocDeprecatedTag = 337, +- JSDocClassTag = 338, +- JSDocPublicTag = 339, +- JSDocPrivateTag = 340, +- JSDocProtectedTag = 341, +- JSDocReadonlyTag = 342, +- JSDocOverrideTag = 343, +- JSDocCallbackTag = 344, +- JSDocOverloadTag = 345, +- JSDocEnumTag = 346, +- JSDocParameterTag = 347, +- JSDocReturnTag = 348, +- JSDocThisTag = 349, +- JSDocTypeTag = 350, +- JSDocTemplateTag = 351, +- JSDocTypedefTag = 352, +- JSDocSeeTag = 353, +- JSDocPropertyTag = 354, +- JSDocThrowsTag = 355, +- JSDocSatisfiesTag = 356, +- SyntaxList = 357, +- NotEmittedStatement = 358, +- PartiallyEmittedExpression = 359, +- CommaListExpression = 360, +- SyntheticReferenceExpression = 361, +- Count = 362, ++ JSDocComment = 327, ++ JSDocText = 328, ++ JSDocTypeLiteral = 329, ++ JSDocSignature = 330, ++ JSDocLink = 331, ++ JSDocLinkCode = 332, ++ JSDocLinkPlain = 333, ++ JSDocTag = 334, ++ JSDocAugmentsTag = 335, ++ JSDocImplementsTag = 336, ++ JSDocAuthorTag = 337, ++ JSDocDeprecatedTag = 338, ++ JSDocClassTag = 339, ++ JSDocPublicTag = 340, ++ JSDocPrivateTag = 341, ++ JSDocProtectedTag = 342, ++ JSDocReadonlyTag = 343, ++ JSDocOverrideTag = 344, ++ JSDocCallbackTag = 345, ++ JSDocOverloadTag = 346, ++ JSDocEnumTag = 347, ++ JSDocParameterTag = 348, ++ JSDocReturnTag = 349, ++ JSDocThisTag = 350, ++ JSDocTypeTag = 351, ++ JSDocTemplateTag = 352, ++ JSDocTypedefTag = 353, ++ JSDocSeeTag = 354, ++ JSDocPropertyTag = 355, ++ JSDocThrowsTag = 356, ++ JSDocSatisfiesTag = 357, ++ SyntaxList = 358, ++ NotEmittedStatement = 359, ++ PartiallyEmittedExpression = 360, ++ CommaListExpression = 361, ++ SyntheticReferenceExpression = 362, ++ Count = 363, + FirstAssignment = 64, + LastAssignment = 79, + FirstCompoundAssignment = 65, +@@ -416,15 +417,15 @@ declare namespace ts { + FirstReservedWord = 83, + LastReservedWord = 118, + FirstKeyword = 83, +- LastKeyword = 164, ++ LastKeyword = 165, + FirstFutureReservedWord = 119, + LastFutureReservedWord = 127, +- FirstTypeNode = 181, +- LastTypeNode = 204, ++ FirstTypeNode = 182, ++ LastTypeNode = 205, + FirstPunctuation = 19, + LastPunctuation = 79, + FirstToken = 0, +- LastToken = 164, ++ LastToken = 165, + FirstTriviaToken = 2, + LastTriviaToken = 7, + FirstLiteralToken = 9, +@@ -433,19 +434,19 @@ declare namespace ts { + LastTemplateToken = 18, + FirstBinaryOperator = 30, + LastBinaryOperator = 79, +- FirstStatement = 242, +- LastStatement = 258, +- FirstNode = 165, +- FirstJSDocNode = 315, +- LastJSDocNode = 356, +- FirstJSDocTagNode = 333, +- LastJSDocTagNode = 356 ++ FirstStatement = 243, ++ LastStatement = 259, ++ FirstNode = 166, ++ FirstJSDocNode = 316, ++ LastJSDocNode = 357, ++ FirstJSDocTagNode = 334, ++ LastJSDocTagNode = 357 + } + type TriviaSyntaxKind = SyntaxKind.SingleLineCommentTrivia | SyntaxKind.MultiLineCommentTrivia | SyntaxKind.NewLineTrivia | SyntaxKind.WhitespaceTrivia | SyntaxKind.ShebangTrivia | SyntaxKind.ConflictMarkerTrivia; + type LiteralSyntaxKind = SyntaxKind.NumericLiteral | SyntaxKind.BigIntLiteral | SyntaxKind.StringLiteral | SyntaxKind.JsxText | SyntaxKind.JsxTextAllWhiteSpaces | SyntaxKind.RegularExpressionLiteral | SyntaxKind.NoSubstitutionTemplateLiteral; + type PseudoLiteralSyntaxKind = SyntaxKind.TemplateHead | SyntaxKind.TemplateMiddle | SyntaxKind.TemplateTail; + type PunctuationSyntaxKind = SyntaxKind.OpenBraceToken | SyntaxKind.CloseBraceToken | SyntaxKind.OpenParenToken | SyntaxKind.CloseParenToken | SyntaxKind.OpenBracketToken | SyntaxKind.CloseBracketToken | SyntaxKind.DotToken | SyntaxKind.DotDotDotToken | SyntaxKind.SemicolonToken | SyntaxKind.CommaToken | SyntaxKind.QuestionDotToken | SyntaxKind.LessThanToken | SyntaxKind.LessThanSlashToken | SyntaxKind.GreaterThanToken | SyntaxKind.LessThanEqualsToken | SyntaxKind.GreaterThanEqualsToken | SyntaxKind.EqualsEqualsToken | SyntaxKind.ExclamationEqualsToken | SyntaxKind.EqualsEqualsEqualsToken | SyntaxKind.ExclamationEqualsEqualsToken | SyntaxKind.EqualsGreaterThanToken | SyntaxKind.PlusToken | SyntaxKind.MinusToken | SyntaxKind.AsteriskToken | SyntaxKind.AsteriskAsteriskToken | SyntaxKind.SlashToken | SyntaxKind.PercentToken | SyntaxKind.PlusPlusToken | SyntaxKind.MinusMinusToken | SyntaxKind.LessThanLessThanToken | SyntaxKind.GreaterThanGreaterThanToken | SyntaxKind.GreaterThanGreaterThanGreaterThanToken | SyntaxKind.AmpersandToken | SyntaxKind.BarToken | SyntaxKind.CaretToken | SyntaxKind.ExclamationToken | SyntaxKind.TildeToken | SyntaxKind.AmpersandAmpersandToken | SyntaxKind.AmpersandAmpersandEqualsToken | SyntaxKind.BarBarToken | SyntaxKind.BarBarEqualsToken | SyntaxKind.QuestionQuestionToken | SyntaxKind.QuestionQuestionEqualsToken | SyntaxKind.QuestionToken | SyntaxKind.ColonToken | SyntaxKind.AtToken | SyntaxKind.BacktickToken | SyntaxKind.HashToken | SyntaxKind.EqualsToken | SyntaxKind.PlusEqualsToken | SyntaxKind.MinusEqualsToken | SyntaxKind.AsteriskEqualsToken | SyntaxKind.AsteriskAsteriskEqualsToken | SyntaxKind.SlashEqualsToken | SyntaxKind.PercentEqualsToken | SyntaxKind.LessThanLessThanEqualsToken | SyntaxKind.GreaterThanGreaterThanEqualsToken | SyntaxKind.GreaterThanGreaterThanGreaterThanEqualsToken | SyntaxKind.AmpersandEqualsToken | SyntaxKind.BarEqualsToken | SyntaxKind.CaretEqualsToken; +- type KeywordSyntaxKind = SyntaxKind.AbstractKeyword | SyntaxKind.AccessorKeyword | SyntaxKind.AnyKeyword | SyntaxKind.AsKeyword | SyntaxKind.AssertsKeyword | SyntaxKind.AssertKeyword | SyntaxKind.AsyncKeyword | SyntaxKind.AwaitKeyword | SyntaxKind.BigIntKeyword | SyntaxKind.BooleanKeyword | SyntaxKind.BreakKeyword | SyntaxKind.CaseKeyword | SyntaxKind.CatchKeyword | SyntaxKind.ClassKeyword | SyntaxKind.ConstKeyword | SyntaxKind.ConstructorKeyword | SyntaxKind.ContinueKeyword | SyntaxKind.DebuggerKeyword | SyntaxKind.DeclareKeyword | SyntaxKind.DefaultKeyword | SyntaxKind.DeleteKeyword | SyntaxKind.DoKeyword | SyntaxKind.ElseKeyword | SyntaxKind.EnumKeyword | SyntaxKind.ExportKeyword | SyntaxKind.ExtendsKeyword | SyntaxKind.FalseKeyword | SyntaxKind.FinallyKeyword | SyntaxKind.ForKeyword | SyntaxKind.FromKeyword | SyntaxKind.FunctionKeyword | SyntaxKind.GetKeyword | SyntaxKind.GlobalKeyword | SyntaxKind.IfKeyword | SyntaxKind.ImplementsKeyword | SyntaxKind.ImportKeyword | SyntaxKind.InferKeyword | SyntaxKind.InKeyword | SyntaxKind.InstanceOfKeyword | SyntaxKind.InterfaceKeyword | SyntaxKind.IntrinsicKeyword | SyntaxKind.IsKeyword | SyntaxKind.KeyOfKeyword | SyntaxKind.LetKeyword | SyntaxKind.ModuleKeyword | SyntaxKind.NamespaceKeyword | SyntaxKind.NeverKeyword | SyntaxKind.NewKeyword | SyntaxKind.NullKeyword | SyntaxKind.NumberKeyword | SyntaxKind.ObjectKeyword | SyntaxKind.OfKeyword | SyntaxKind.PackageKeyword | SyntaxKind.PrivateKeyword | SyntaxKind.ProtectedKeyword | SyntaxKind.PublicKeyword | SyntaxKind.ReadonlyKeyword | SyntaxKind.OutKeyword | SyntaxKind.OverrideKeyword | SyntaxKind.RequireKeyword | SyntaxKind.ReturnKeyword | SyntaxKind.SatisfiesKeyword | SyntaxKind.SetKeyword | SyntaxKind.StaticKeyword | SyntaxKind.StringKeyword | SyntaxKind.SuperKeyword | SyntaxKind.SwitchKeyword | SyntaxKind.SymbolKeyword | SyntaxKind.ThisKeyword | SyntaxKind.ThrowKeyword | SyntaxKind.TrueKeyword | SyntaxKind.TryKeyword | SyntaxKind.TypeKeyword | SyntaxKind.TypeOfKeyword | SyntaxKind.UndefinedKeyword | SyntaxKind.UniqueKeyword | SyntaxKind.UnknownKeyword | SyntaxKind.VarKeyword | SyntaxKind.VoidKeyword | SyntaxKind.WhileKeyword | SyntaxKind.WithKeyword | SyntaxKind.YieldKeyword; ++ type KeywordSyntaxKind = SyntaxKind.AbstractKeyword | SyntaxKind.AccessorKeyword | SyntaxKind.AnyKeyword | SyntaxKind.AsKeyword | SyntaxKind.AssertsKeyword | SyntaxKind.AssertKeyword | SyntaxKind.AsyncKeyword | SyntaxKind.AwaitKeyword | SyntaxKind.BigIntKeyword | SyntaxKind.BooleanKeyword | SyntaxKind.BreakKeyword | SyntaxKind.CaseKeyword | SyntaxKind.CatchKeyword | SyntaxKind.ClassKeyword | SyntaxKind.ConstKeyword | SyntaxKind.ConstructorKeyword | SyntaxKind.ContinueKeyword | SyntaxKind.DebuggerKeyword | SyntaxKind.DeclareKeyword | SyntaxKind.DefaultKeyword | SyntaxKind.DeleteKeyword | SyntaxKind.DoKeyword | SyntaxKind.ElseKeyword | SyntaxKind.EnumKeyword | SyntaxKind.ExportKeyword | SyntaxKind.ExtendsKeyword | SyntaxKind.FalseKeyword | SyntaxKind.FinallyKeyword | SyntaxKind.ForKeyword | SyntaxKind.FromKeyword | SyntaxKind.FunctionKeyword | SyntaxKind.GetKeyword | SyntaxKind.GlobalKeyword | SyntaxKind.IfKeyword | SyntaxKind.ImplementsKeyword | SyntaxKind.ImportKeyword | SyntaxKind.InferKeyword | SyntaxKind.InKeyword | SyntaxKind.InstanceOfKeyword | SyntaxKind.InterfaceKeyword | SyntaxKind.IntrinsicKeyword | SyntaxKind.IsKeyword | SyntaxKind.KeyOfKeyword | SyntaxKind.LetKeyword | SyntaxKind.ModuleKeyword | SyntaxKind.NamespaceKeyword | SyntaxKind.NeverKeyword | SyntaxKind.NewKeyword | SyntaxKind.NullKeyword | SyntaxKind.NumberKeyword | SyntaxKind.ObjectKeyword | SyntaxKind.OfKeyword | SyntaxKind.PackageKeyword | SyntaxKind.PrivateKeyword | SyntaxKind.ProtectedKeyword | SyntaxKind.PublicKeyword | SyntaxKind.ReadonlyKeyword | SyntaxKind.OutKeyword | SyntaxKind.OverrideKeyword | SyntaxKind.RequireKeyword | SyntaxKind.ReturnKeyword | SyntaxKind.SatisfiesKeyword | SyntaxKind.SetKeyword | SyntaxKind.StaticKeyword | SyntaxKind.StringKeyword | SyntaxKind.SuperKeyword | SyntaxKind.SwitchKeyword | SyntaxKind.SymbolKeyword | SyntaxKind.ThisKeyword | SyntaxKind.ThrowKeyword | SyntaxKind.TrueKeyword | SyntaxKind.TryKeyword | SyntaxKind.TypeKeyword | SyntaxKind.TypeOfKeyword | SyntaxKind.UndefinedKeyword | SyntaxKind.UniqueKeyword | SyntaxKind.UnknownKeyword | SyntaxKind.UsingKeyword | SyntaxKind.VarKeyword | SyntaxKind.VoidKeyword | SyntaxKind.WhileKeyword | SyntaxKind.WithKeyword | SyntaxKind.YieldKeyword; + type ModifierSyntaxKind = SyntaxKind.AbstractKeyword | SyntaxKind.AccessorKeyword | SyntaxKind.AsyncKeyword | SyntaxKind.ConstKeyword | SyntaxKind.DeclareKeyword | SyntaxKind.DefaultKeyword | SyntaxKind.ExportKeyword | SyntaxKind.InKeyword | SyntaxKind.PrivateKeyword | SyntaxKind.ProtectedKeyword | SyntaxKind.PublicKeyword | SyntaxKind.ReadonlyKeyword | SyntaxKind.OutKeyword | SyntaxKind.OverrideKeyword | SyntaxKind.StaticKeyword; + type KeywordTypeSyntaxKind = SyntaxKind.AnyKeyword | SyntaxKind.BigIntKeyword | SyntaxKind.BooleanKeyword | SyntaxKind.IntrinsicKeyword | SyntaxKind.NeverKeyword | SyntaxKind.NumberKeyword | SyntaxKind.ObjectKeyword | SyntaxKind.StringKeyword | SyntaxKind.SymbolKeyword | SyntaxKind.UndefinedKeyword | SyntaxKind.UnknownKeyword | SyntaxKind.VoidKeyword; + type TokenSyntaxKind = SyntaxKind.Unknown | SyntaxKind.EndOfFileToken | TriviaSyntaxKind | LiteralSyntaxKind | PseudoLiteralSyntaxKind | PunctuationSyntaxKind | SyntaxKind.Identifier | KeywordSyntaxKind; +@@ -455,32 +456,35 @@ declare namespace ts { + None = 0, + Let = 1, + Const = 2, +- NestedNamespace = 4, +- Synthesized = 8, +- Namespace = 16, +- OptionalChain = 32, +- ExportContext = 64, +- ContainsThis = 128, +- HasImplicitReturn = 256, +- HasExplicitReturn = 512, +- GlobalAugmentation = 1024, +- HasAsyncFunctions = 2048, +- DisallowInContext = 4096, +- YieldContext = 8192, +- DecoratorContext = 16384, +- AwaitContext = 32768, +- DisallowConditionalTypesContext = 65536, +- ThisNodeHasError = 131072, +- JavaScriptFile = 262144, +- ThisNodeOrAnySubNodesHasError = 524288, +- HasAggregatedChildData = 1048576, +- JSDoc = 8388608, +- JsonFile = 67108864, +- BlockScoped = 3, +- ReachabilityCheckFlags = 768, +- ReachabilityAndEmitFlags = 2816, +- ContextFlags = 50720768, +- TypeExcludesFlags = 40960 ++ Using = 4, ++ AwaitUsing = 6, ++ NestedNamespace = 8, ++ Synthesized = 16, ++ Namespace = 32, ++ OptionalChain = 64, ++ ExportContext = 128, ++ ContainsThis = 256, ++ HasImplicitReturn = 512, ++ HasExplicitReturn = 1024, ++ GlobalAugmentation = 2048, ++ HasAsyncFunctions = 4096, ++ DisallowInContext = 8192, ++ YieldContext = 16384, ++ DecoratorContext = 32768, ++ AwaitContext = 65536, ++ DisallowConditionalTypesContext = 131072, ++ ThisNodeHasError = 262144, ++ JavaScriptFile = 524288, ++ ThisNodeOrAnySubNodesHasError = 1048576, ++ HasAggregatedChildData = 2097152, ++ JSDoc = 16777216, ++ JsonFile = 134217728, ++ BlockScoped = 7, ++ Constant = 6, ++ ReachabilityCheckFlags = 1536, ++ ReachabilityAndEmitFlags = 5632, ++ ContextFlags = 101441536, ++ TypeExcludesFlags = 81920 + } + enum ModifierFlags { + None = 0, +@@ -3535,7 +3539,14 @@ declare namespace ts { + All = 15, + ExcludeJSDocTypeAssertion = 16 + } +- type TypeOfTag = "undefined" | "number" | "bigint" | "boolean" | "string" | "symbol" | "object" | "function"; ++ type ImmediatelyInvokedFunctionExpression = CallExpression & { ++ readonly expression: FunctionExpression; ++ }; ++ type ImmediatelyInvokedArrowFunction = CallExpression & { ++ readonly expression: ParenthesizedExpression & { ++ readonly expression: ArrowFunction; ++ }; ++ }; + interface NodeFactory { + createNodeArray(elements?: readonly T[], hasTrailingComma?: boolean): NodeArray; + createNumericLiteral(value: string | number, numericLiteralFlags?: TokenFlags): NumericLiteral; +@@ -4005,8 +4016,8 @@ declare namespace ts { + createPostfixDecrement(operand: Expression): PostfixUnaryExpression; + createImmediatelyInvokedFunctionExpression(statements: readonly Statement[]): CallExpression; + createImmediatelyInvokedFunctionExpression(statements: readonly Statement[], param: ParameterDeclaration, paramValue: Expression): CallExpression; +- createImmediatelyInvokedArrowFunction(statements: readonly Statement[]): CallExpression; +- createImmediatelyInvokedArrowFunction(statements: readonly Statement[], param: ParameterDeclaration, paramValue: Expression): CallExpression; ++ createImmediatelyInvokedArrowFunction(statements: readonly Statement[]): ImmediatelyInvokedArrowFunction; ++ createImmediatelyInvokedArrowFunction(statements: readonly Statement[], param: ParameterDeclaration, paramValue: Expression): ImmediatelyInvokedArrowFunction; + createVoidZero(): VoidExpression; + createExportDefault(expression: Expression): ExportAssignment; + createExternalModuleExport(exportName: Identifier): ExportDeclaration; +diff --git a/tests/baselines/reference/awaitUsingDeclarations.1(target=es2015).errors.txt b/tests/baselines/reference/awaitUsingDeclarations.1(target=es2015).errors.txt +new file mode 100644 +index 000000000..52470b245 +--- /dev/null ++++ b/tests/baselines/reference/awaitUsingDeclarations.1(target=es2015).errors.txt +@@ -0,0 +1,145 @@ ++awaitUsingDeclarations.1.ts(1,1): error TS2854: Top-level 'await using' statements are only allowed when the 'module' option is set to 'es2022', 'esnext', 'system', 'node16', or 'nodenext', and the 'target' option is set to 'es2017' or higher. ++awaitUsingDeclarations.1.ts(36,5): error TS2854: Top-level 'await using' statements are only allowed when the 'module' option is set to 'es2022', 'esnext', 'system', 'node16', or 'nodenext', and the 'target' option is set to 'es2017' or higher. ++awaitUsingDeclarations.1.ts(41,9): error TS2854: Top-level 'await using' statements are only allowed when the 'module' option is set to 'es2022', 'esnext', 'system', 'node16', or 'nodenext', and the 'target' option is set to 'es2017' or higher. ++awaitUsingDeclarations.1.ts(45,9): error TS2854: Top-level 'await using' statements are only allowed when the 'module' option is set to 'es2022', 'esnext', 'system', 'node16', or 'nodenext', and the 'target' option is set to 'es2017' or higher. ++awaitUsingDeclarations.1.ts(52,13): error TS2854: Top-level 'await using' statements are only allowed when the 'module' option is set to 'es2022', 'esnext', 'system', 'node16', or 'nodenext', and the 'target' option is set to 'es2017' or higher. ++awaitUsingDeclarations.1.ts(57,5): error TS2854: Top-level 'await using' statements are only allowed when the 'module' option is set to 'es2022', 'esnext', 'system', 'node16', or 'nodenext', and the 'target' option is set to 'es2017' or higher. ++awaitUsingDeclarations.1.ts(60,5): error TS2854: Top-level 'await using' statements are only allowed when the 'module' option is set to 'es2022', 'esnext', 'system', 'node16', or 'nodenext', and the 'target' option is set to 'es2017' or higher. ++awaitUsingDeclarations.1.ts(63,5): error TS2854: Top-level 'await using' statements are only allowed when the 'module' option is set to 'es2022', 'esnext', 'system', 'node16', or 'nodenext', and the 'target' option is set to 'es2017' or higher. ++awaitUsingDeclarations.1.ts(67,5): error TS2854: Top-level 'await using' statements are only allowed when the 'module' option is set to 'es2022', 'esnext', 'system', 'node16', or 'nodenext', and the 'target' option is set to 'es2017' or higher. ++awaitUsingDeclarations.1.ts(70,5): error TS2854: Top-level 'await using' statements are only allowed when the 'module' option is set to 'es2022', 'esnext', 'system', 'node16', or 'nodenext', and the 'target' option is set to 'es2017' or higher. ++awaitUsingDeclarations.1.ts(74,5): error TS2854: Top-level 'await using' statements are only allowed when the 'module' option is set to 'es2022', 'esnext', 'system', 'node16', or 'nodenext', and the 'target' option is set to 'es2017' or higher. ++awaitUsingDeclarations.1.ts(79,5): error TS2854: Top-level 'await using' statements are only allowed when the 'module' option is set to 'es2022', 'esnext', 'system', 'node16', or 'nodenext', and the 'target' option is set to 'es2017' or higher. ++awaitUsingDeclarations.1.ts(85,5): error TS2854: Top-level 'await using' statements are only allowed when the 'module' option is set to 'es2022', 'esnext', 'system', 'node16', or 'nodenext', and the 'target' option is set to 'es2017' or higher. ++awaitUsingDeclarations.1.ts(90,5): error TS2854: Top-level 'await using' statements are only allowed when the 'module' option is set to 'es2022', 'esnext', 'system', 'node16', or 'nodenext', and the 'target' option is set to 'es2017' or higher. ++awaitUsingDeclarations.1.ts(94,5): error TS2854: Top-level 'await using' statements are only allowed when the 'module' option is set to 'es2022', 'esnext', 'system', 'node16', or 'nodenext', and the 'target' option is set to 'es2017' or higher. ++ ++ ++==== awaitUsingDeclarations.1.ts (15 errors) ==== ++ await using d1 = { async [Symbol.asyncDispose]() {} }; ++ ~~~~~ ++!!! error TS2854: Top-level 'await using' statements are only allowed when the 'module' option is set to 'es2022', 'esnext', 'system', 'node16', or 'nodenext', and the 'target' option is set to 'es2017' or higher. ++ ++ async function af() { ++ await using d3 = { async [Symbol.asyncDispose]() {} }; ++ await null; ++ } ++ ++ async function * ag() { ++ await using d5 = { async [Symbol.asyncDispose]() {} }; ++ yield; ++ await null; ++ } ++ ++ const a = async () => { ++ await using d6 = { async [Symbol.asyncDispose]() {} }; ++ }; ++ ++ class C1 { ++ a = async () => { ++ await using d7 = { async [Symbol.asyncDispose]() {} }; ++ }; ++ ++ async am() { ++ await using d13 = { async [Symbol.asyncDispose]() {} }; ++ await null; ++ } ++ ++ async * ag() { ++ await using d15 = { async [Symbol.asyncDispose]() {} }; ++ yield; ++ await null; ++ } ++ } ++ ++ { ++ await using d19 = { async [Symbol.asyncDispose]() {} }; ++ ~~~~~ ++!!! error TS2854: Top-level 'await using' statements are only allowed when the 'module' option is set to 'es2022', 'esnext', 'system', 'node16', or 'nodenext', and the 'target' option is set to 'es2017' or higher. ++ } ++ ++ switch (Math.random()) { ++ case 0: ++ await using d20 = { async [Symbol.asyncDispose]() {} }; ++ ~~~~~ ++!!! error TS2854: Top-level 'await using' statements are only allowed when the 'module' option is set to 'es2022', 'esnext', 'system', 'node16', or 'nodenext', and the 'target' option is set to 'es2017' or higher. ++ break; ++ ++ case 1: ++ await using d21 = { async [Symbol.asyncDispose]() {} }; ++ ~~~~~ ++!!! error TS2854: Top-level 'await using' statements are only allowed when the 'module' option is set to 'es2022', 'esnext', 'system', 'node16', or 'nodenext', and the 'target' option is set to 'es2017' or higher. ++ break; ++ } ++ ++ if (true) ++ switch (0) { ++ case 0: ++ await using d22 = { async [Symbol.asyncDispose]() {} }; ++ ~~~~~ ++!!! error TS2854: Top-level 'await using' statements are only allowed when the 'module' option is set to 'es2022', 'esnext', 'system', 'node16', or 'nodenext', and the 'target' option is set to 'es2017' or higher. ++ break; ++ } ++ ++ try { ++ await using d23 = { async [Symbol.asyncDispose]() {} }; ++ ~~~~~ ++!!! error TS2854: Top-level 'await using' statements are only allowed when the 'module' option is set to 'es2022', 'esnext', 'system', 'node16', or 'nodenext', and the 'target' option is set to 'es2017' or higher. ++ } ++ catch { ++ await using d24 = { async [Symbol.asyncDispose]() {} }; ++ ~~~~~ ++!!! error TS2854: Top-level 'await using' statements are only allowed when the 'module' option is set to 'es2022', 'esnext', 'system', 'node16', or 'nodenext', and the 'target' option is set to 'es2017' or higher. ++ } ++ finally { ++ await using d25 = { async [Symbol.asyncDispose]() {} }; ++ ~~~~~ ++!!! error TS2854: Top-level 'await using' statements are only allowed when the 'module' option is set to 'es2022', 'esnext', 'system', 'node16', or 'nodenext', and the 'target' option is set to 'es2017' or higher. ++ } ++ ++ if (true) { ++ await using d26 = { async [Symbol.asyncDispose]() {} }; ++ ~~~~~ ++!!! error TS2854: Top-level 'await using' statements are only allowed when the 'module' option is set to 'es2022', 'esnext', 'system', 'node16', or 'nodenext', and the 'target' option is set to 'es2017' or higher. ++ } ++ else { ++ await using d27 = { async [Symbol.asyncDispose]() {} }; ++ ~~~~~ ++!!! error TS2854: Top-level 'await using' statements are only allowed when the 'module' option is set to 'es2022', 'esnext', 'system', 'node16', or 'nodenext', and the 'target' option is set to 'es2017' or higher. ++ } ++ ++ while (true) { ++ await using d28 = { async [Symbol.asyncDispose]() {} }; ++ ~~~~~ ++!!! error TS2854: Top-level 'await using' statements are only allowed when the 'module' option is set to 'es2022', 'esnext', 'system', 'node16', or 'nodenext', and the 'target' option is set to 'es2017' or higher. ++ break; ++ } ++ ++ do { ++ await using d29 = { async [Symbol.asyncDispose]() {} }; ++ ~~~~~ ++!!! error TS2854: Top-level 'await using' statements are only allowed when the 'module' option is set to 'es2022', 'esnext', 'system', 'node16', or 'nodenext', and the 'target' option is set to 'es2017' or higher. ++ break; ++ } ++ while (true); ++ ++ for (;;) { ++ await using d30 = { async [Symbol.asyncDispose]() {} }; ++ ~~~~~ ++!!! error TS2854: Top-level 'await using' statements are only allowed when the 'module' option is set to 'es2022', 'esnext', 'system', 'node16', or 'nodenext', and the 'target' option is set to 'es2017' or higher. ++ break; ++ } ++ ++ for (const x in {}) { ++ await using d31 = { async [Symbol.asyncDispose]() {} }; ++ ~~~~~ ++!!! error TS2854: Top-level 'await using' statements are only allowed when the 'module' option is set to 'es2022', 'esnext', 'system', 'node16', or 'nodenext', and the 'target' option is set to 'es2017' or higher. ++ } ++ ++ for (const x of []) { ++ await using d32 = { async [Symbol.asyncDispose]() {} }; ++ ~~~~~ ++!!! error TS2854: Top-level 'await using' statements are only allowed when the 'module' option is set to 'es2022', 'esnext', 'system', 'node16', or 'nodenext', and the 'target' option is set to 'es2017' or higher. ++ } ++ ++ export {}; +\ No newline at end of file +diff --git a/tests/baselines/reference/awaitUsingDeclarations.1(target=es2015).js b/tests/baselines/reference/awaitUsingDeclarations.1(target=es2015).js +new file mode 100644 +index 000000000..0d1aa5282 +--- /dev/null ++++ b/tests/baselines/reference/awaitUsingDeclarations.1(target=es2015).js +@@ -0,0 +1,540 @@ ++//// [tests/cases/conformance/statements/VariableStatements/usingDeclarations/awaitUsingDeclarations.1.ts] //// ++ ++//// [awaitUsingDeclarations.1.ts] ++await using d1 = { async [Symbol.asyncDispose]() {} }; ++ ++async function af() { ++ await using d3 = { async [Symbol.asyncDispose]() {} }; ++ await null; ++} ++ ++async function * ag() { ++ await using d5 = { async [Symbol.asyncDispose]() {} }; ++ yield; ++ await null; ++} ++ ++const a = async () => { ++ await using d6 = { async [Symbol.asyncDispose]() {} }; ++}; ++ ++class C1 { ++ a = async () => { ++ await using d7 = { async [Symbol.asyncDispose]() {} }; ++ }; ++ ++ async am() { ++ await using d13 = { async [Symbol.asyncDispose]() {} }; ++ await null; ++ } ++ ++ async * ag() { ++ await using d15 = { async [Symbol.asyncDispose]() {} }; ++ yield; ++ await null; ++ } ++} ++ ++{ ++ await using d19 = { async [Symbol.asyncDispose]() {} }; ++} ++ ++switch (Math.random()) { ++ case 0: ++ await using d20 = { async [Symbol.asyncDispose]() {} }; ++ break; ++ ++ case 1: ++ await using d21 = { async [Symbol.asyncDispose]() {} }; ++ break; ++} ++ ++if (true) ++ switch (0) { ++ case 0: ++ await using d22 = { async [Symbol.asyncDispose]() {} }; ++ break; ++ } ++ ++try { ++ await using d23 = { async [Symbol.asyncDispose]() {} }; ++} ++catch { ++ await using d24 = { async [Symbol.asyncDispose]() {} }; ++} ++finally { ++ await using d25 = { async [Symbol.asyncDispose]() {} }; ++} ++ ++if (true) { ++ await using d26 = { async [Symbol.asyncDispose]() {} }; ++} ++else { ++ await using d27 = { async [Symbol.asyncDispose]() {} }; ++} ++ ++while (true) { ++ await using d28 = { async [Symbol.asyncDispose]() {} }; ++ break; ++} ++ ++do { ++ await using d29 = { async [Symbol.asyncDispose]() {} }; ++ break; ++} ++while (true); ++ ++for (;;) { ++ await using d30 = { async [Symbol.asyncDispose]() {} }; ++ break; ++} ++ ++for (const x in {}) { ++ await using d31 = { async [Symbol.asyncDispose]() {} }; ++} ++ ++for (const x of []) { ++ await using d32 = { async [Symbol.asyncDispose]() {} }; ++} ++ ++export {}; ++ ++//// [awaitUsingDeclarations.1.js] ++var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { ++ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } ++ return new (P || (P = Promise))(function (resolve, reject) { ++ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } ++ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } ++ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } ++ step((generator = generator.apply(thisArg, _arguments || [])).next()); ++ }); ++}; ++var __addDisposableResource = (this && this.__addDisposableResource) || function (env, value, async) { ++ if (value !== null && value !== void 0) { ++ if (typeof value !== "object") throw new TypeError("Object expected."); ++ var dispose; ++ if (async) { ++ if (!Symbol.asyncDispose) throw new TypeError("Symbol.asyncDispose is not defined."); ++ dispose = value[Symbol.asyncDispose]; ++ } ++ if (dispose === void 0) { ++ if (!Symbol.dispose) throw new TypeError("Symbol.dispose is not defined."); ++ dispose = value[Symbol.dispose]; ++ } ++ if (typeof dispose !== "function") throw new TypeError("Object not disposable."); ++ env.stack.push({ value: value, dispose: dispose, async: async }); ++ } ++ else if (async) { ++ env.stack.push({ async: true }); ++ } ++ return value; ++}; ++var __disposeResources = (this && this.__disposeResources) || (function (SuppressedError) { ++ return function (env) { ++ function fail(e) { ++ env.error = env.hasError ? new SuppressedError(e, env.error, "An error was suppressed during disposal.") : e; ++ env.hasError = true; ++ } ++ function next() { ++ while (env.stack.length) { ++ var rec = env.stack.pop(); ++ try { ++ var result = rec.dispose && rec.dispose.call(rec.value); ++ if (rec.async) return Promise.resolve(result).then(next, function(e) { fail(e); return next(); }); ++ } ++ catch (e) { ++ fail(e); ++ } ++ } ++ if (env.hasError) throw env.error; ++ } ++ return next(); ++ }; ++})(typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) { ++ var e = new Error(message); ++ return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e; ++}); ++var __await = (this && this.__await) || function (v) { return this instanceof __await ? (this.v = v, this) : new __await(v); } ++var __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _arguments, generator) { ++ if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); ++ var g = generator.apply(thisArg, _arguments || []), i, q = []; ++ return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i; ++ function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; } ++ function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } } ++ function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); } ++ function fulfill(value) { resume("next", value); } ++ function reject(value) { resume("throw", value); } ++ function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); } ++}; ++function af() { ++ return __awaiter(this, void 0, void 0, function* () { ++ const env_15 = { stack: [], error: void 0, hasError: false }; ++ try { ++ const d3 = __addDisposableResource(env_15, { [Symbol.asyncDispose]() { ++ return __awaiter(this, void 0, void 0, function* () { }); ++ } }, true); ++ yield null; ++ } ++ catch (e_15) { ++ env_15.error = e_15; ++ env_15.hasError = true; ++ } ++ finally { ++ const result_15 = __disposeResources(env_15); ++ if (result_15) ++ yield result_15; ++ } ++ }); ++} ++function ag() { ++ return __asyncGenerator(this, arguments, function* ag_1() { ++ const env_16 = { stack: [], error: void 0, hasError: false }; ++ try { ++ const d5 = __addDisposableResource(env_16, { [Symbol.asyncDispose]() { ++ return __awaiter(this, void 0, void 0, function* () { }); ++ } }, true); ++ yield yield __await(void 0); ++ yield __await(null); ++ } ++ catch (e_16) { ++ env_16.error = e_16; ++ env_16.hasError = true; ++ } ++ finally { ++ const result_16 = __disposeResources(env_16); ++ if (result_16) ++ yield __await(result_16); ++ } ++ }); ++} ++var d1, a, C1, env_1; ++const env_2 = { stack: [], error: void 0, hasError: false }; ++try { ++ d1 = __addDisposableResource(env_2, { [Symbol.asyncDispose]() { ++ return __awaiter(this, void 0, void 0, function* () { }); ++ } }, true); ++ a = () => __awaiter(void 0, void 0, void 0, function* () { ++ const env_17 = { stack: [], error: void 0, hasError: false }; ++ try { ++ const d6 = __addDisposableResource(env_17, { [Symbol.asyncDispose]() { ++ return __awaiter(this, void 0, void 0, function* () { }); ++ } }, true); ++ } ++ catch (e_17) { ++ env_17.error = e_17; ++ env_17.hasError = true; ++ } ++ finally { ++ const result_17 = __disposeResources(env_17); ++ if (result_17) ++ yield result_17; ++ } ++ }); ++ C1 = class C1 { ++ constructor() { ++ this.a = () => __awaiter(this, void 0, void 0, function* () { ++ const env_18 = { stack: [], error: void 0, hasError: false }; ++ try { ++ const d7 = __addDisposableResource(env_18, { [Symbol.asyncDispose]() { ++ return __awaiter(this, void 0, void 0, function* () { }); ++ } }, true); ++ } ++ catch (e_18) { ++ env_18.error = e_18; ++ env_18.hasError = true; ++ } ++ finally { ++ const result_18 = __disposeResources(env_18); ++ if (result_18) ++ yield result_18; ++ } ++ }); ++ } ++ am() { ++ return __awaiter(this, void 0, void 0, function* () { ++ const env_19 = { stack: [], error: void 0, hasError: false }; ++ try { ++ const d13 = __addDisposableResource(env_19, { [Symbol.asyncDispose]() { ++ return __awaiter(this, void 0, void 0, function* () { }); ++ } }, true); ++ yield null; ++ } ++ catch (e_19) { ++ env_19.error = e_19; ++ env_19.hasError = true; ++ } ++ finally { ++ const result_19 = __disposeResources(env_19); ++ if (result_19) ++ yield result_19; ++ } ++ }); ++ } ++ ag() { ++ return __asyncGenerator(this, arguments, function* ag_2() { ++ const env_20 = { stack: [], error: void 0, hasError: false }; ++ try { ++ const d15 = __addDisposableResource(env_20, { [Symbol.asyncDispose]() { ++ return __awaiter(this, void 0, void 0, function* () { }); ++ } }, true); ++ yield yield __await(void 0); ++ yield __await(null); ++ } ++ catch (e_20) { ++ env_20.error = e_20; ++ env_20.hasError = true; ++ } ++ finally { ++ const result_20 = __disposeResources(env_20); ++ if (result_20) ++ yield __await(result_20); ++ } ++ }); ++ } ++ }; ++ { ++ const env_3 = { stack: [], error: void 0, hasError: false }; ++ try { ++ const d19 = __addDisposableResource(env_3, { [Symbol.asyncDispose]() { ++ return __awaiter(this, void 0, void 0, function* () { }); ++ } }, true); ++ } ++ catch (e_1) { ++ env_3.error = e_1; ++ env_3.hasError = true; ++ } ++ finally { ++ const result_1 = __disposeResources(env_3); ++ if (result_1) ++ await result_1; ++ } ++ } ++ env_1 = { stack: [], error: void 0, hasError: false }; ++ try { ++ switch (Math.random()) { ++ case 0: ++ const d20 = __addDisposableResource(env_1, { [Symbol.asyncDispose]() { ++ return __awaiter(this, void 0, void 0, function* () { }); ++ } }, true); ++ break; ++ case 1: ++ const d21 = __addDisposableResource(env_1, { [Symbol.asyncDispose]() { ++ return __awaiter(this, void 0, void 0, function* () { }); ++ } }, true); ++ break; ++ } ++ } ++ catch (e_2) { ++ env_1.error = e_2; ++ env_1.hasError = true; ++ } ++ finally { ++ const result_2 = __disposeResources(env_1); ++ if (result_2) ++ await result_2; ++ } ++ if (true) { ++ const env_4 = { stack: [], error: void 0, hasError: false }; ++ try { ++ switch (0) { ++ case 0: ++ const d22 = __addDisposableResource(env_4, { [Symbol.asyncDispose]() { ++ return __awaiter(this, void 0, void 0, function* () { }); ++ } }, true); ++ break; ++ } ++ } ++ catch (e_3) { ++ env_4.error = e_3; ++ env_4.hasError = true; ++ } ++ finally { ++ const result_3 = __disposeResources(env_4); ++ if (result_3) ++ await result_3; ++ } ++ } ++ try { ++ const env_5 = { stack: [], error: void 0, hasError: false }; ++ try { ++ const d23 = __addDisposableResource(env_5, { [Symbol.asyncDispose]() { ++ return __awaiter(this, void 0, void 0, function* () { }); ++ } }, true); ++ } ++ catch (e_4) { ++ env_5.error = e_4; ++ env_5.hasError = true; ++ } ++ finally { ++ const result_4 = __disposeResources(env_5); ++ if (result_4) ++ await result_4; ++ } ++ } ++ catch (_a) { ++ const env_6 = { stack: [], error: void 0, hasError: false }; ++ try { ++ const d24 = __addDisposableResource(env_6, { [Symbol.asyncDispose]() { ++ return __awaiter(this, void 0, void 0, function* () { }); ++ } }, true); ++ } ++ catch (e_5) { ++ env_6.error = e_5; ++ env_6.hasError = true; ++ } ++ finally { ++ const result_5 = __disposeResources(env_6); ++ if (result_5) ++ await result_5; ++ } ++ } ++ finally { ++ const env_7 = { stack: [], error: void 0, hasError: false }; ++ try { ++ const d25 = __addDisposableResource(env_7, { [Symbol.asyncDispose]() { ++ return __awaiter(this, void 0, void 0, function* () { }); ++ } }, true); ++ } ++ catch (e_6) { ++ env_7.error = e_6; ++ env_7.hasError = true; ++ } ++ finally { ++ const result_6 = __disposeResources(env_7); ++ if (result_6) ++ await result_6; ++ } ++ } ++ if (true) { ++ const env_8 = { stack: [], error: void 0, hasError: false }; ++ try { ++ const d26 = __addDisposableResource(env_8, { [Symbol.asyncDispose]() { ++ return __awaiter(this, void 0, void 0, function* () { }); ++ } }, true); ++ } ++ catch (e_7) { ++ env_8.error = e_7; ++ env_8.hasError = true; ++ } ++ finally { ++ const result_7 = __disposeResources(env_8); ++ if (result_7) ++ await result_7; ++ } ++ } ++ else { ++ const env_9 = { stack: [], error: void 0, hasError: false }; ++ try { ++ const d27 = __addDisposableResource(env_9, { [Symbol.asyncDispose]() { ++ return __awaiter(this, void 0, void 0, function* () { }); ++ } }, true); ++ } ++ catch (e_8) { ++ env_9.error = e_8; ++ env_9.hasError = true; ++ } ++ finally { ++ const result_8 = __disposeResources(env_9); ++ if (result_8) ++ await result_8; ++ } ++ } ++ while (true) { ++ const env_10 = { stack: [], error: void 0, hasError: false }; ++ try { ++ const d28 = __addDisposableResource(env_10, { [Symbol.asyncDispose]() { ++ return __awaiter(this, void 0, void 0, function* () { }); ++ } }, true); ++ break; ++ } ++ catch (e_9) { ++ env_10.error = e_9; ++ env_10.hasError = true; ++ } ++ finally { ++ const result_9 = __disposeResources(env_10); ++ if (result_9) ++ await result_9; ++ } ++ } ++ do { ++ const env_11 = { stack: [], error: void 0, hasError: false }; ++ try { ++ const d29 = __addDisposableResource(env_11, { [Symbol.asyncDispose]() { ++ return __awaiter(this, void 0, void 0, function* () { }); ++ } }, true); ++ break; ++ } ++ catch (e_10) { ++ env_11.error = e_10; ++ env_11.hasError = true; ++ } ++ finally { ++ const result_10 = __disposeResources(env_11); ++ if (result_10) ++ await result_10; ++ } ++ } while (true); ++ for (;;) { ++ const env_12 = { stack: [], error: void 0, hasError: false }; ++ try { ++ const d30 = __addDisposableResource(env_12, { [Symbol.asyncDispose]() { ++ return __awaiter(this, void 0, void 0, function* () { }); ++ } }, true); ++ break; ++ } ++ catch (e_11) { ++ env_12.error = e_11; ++ env_12.hasError = true; ++ } ++ finally { ++ const result_11 = __disposeResources(env_12); ++ if (result_11) ++ await result_11; ++ } ++ } ++ for (const x in {}) { ++ const env_13 = { stack: [], error: void 0, hasError: false }; ++ try { ++ const d31 = __addDisposableResource(env_13, { [Symbol.asyncDispose]() { ++ return __awaiter(this, void 0, void 0, function* () { }); ++ } }, true); ++ } ++ catch (e_12) { ++ env_13.error = e_12; ++ env_13.hasError = true; ++ } ++ finally { ++ const result_12 = __disposeResources(env_13); ++ if (result_12) ++ await result_12; ++ } ++ } ++ for (const x of []) { ++ const env_14 = { stack: [], error: void 0, hasError: false }; ++ try { ++ const d32 = __addDisposableResource(env_14, { [Symbol.asyncDispose]() { ++ return __awaiter(this, void 0, void 0, function* () { }); ++ } }, true); ++ } ++ catch (e_13) { ++ env_14.error = e_13; ++ env_14.hasError = true; ++ } ++ finally { ++ const result_13 = __disposeResources(env_14); ++ if (result_13) ++ await result_13; ++ } ++ } ++} ++catch (e_14) { ++ env_2.error = e_14; ++ env_2.hasError = true; ++} ++finally { ++ const result_14 = __disposeResources(env_2); ++ if (result_14) ++ await result_14; ++} ++export {}; +diff --git a/tests/baselines/reference/awaitUsingDeclarations.1(target=es2017).js b/tests/baselines/reference/awaitUsingDeclarations.1(target=es2017).js +new file mode 100644 +index 000000000..9732d266f +--- /dev/null ++++ b/tests/baselines/reference/awaitUsingDeclarations.1(target=es2017).js +@@ -0,0 +1,485 @@ ++//// [tests/cases/conformance/statements/VariableStatements/usingDeclarations/awaitUsingDeclarations.1.ts] //// ++ ++//// [awaitUsingDeclarations.1.ts] ++await using d1 = { async [Symbol.asyncDispose]() {} }; ++ ++async function af() { ++ await using d3 = { async [Symbol.asyncDispose]() {} }; ++ await null; ++} ++ ++async function * ag() { ++ await using d5 = { async [Symbol.asyncDispose]() {} }; ++ yield; ++ await null; ++} ++ ++const a = async () => { ++ await using d6 = { async [Symbol.asyncDispose]() {} }; ++}; ++ ++class C1 { ++ a = async () => { ++ await using d7 = { async [Symbol.asyncDispose]() {} }; ++ }; ++ ++ async am() { ++ await using d13 = { async [Symbol.asyncDispose]() {} }; ++ await null; ++ } ++ ++ async * ag() { ++ await using d15 = { async [Symbol.asyncDispose]() {} }; ++ yield; ++ await null; ++ } ++} ++ ++{ ++ await using d19 = { async [Symbol.asyncDispose]() {} }; ++} ++ ++switch (Math.random()) { ++ case 0: ++ await using d20 = { async [Symbol.asyncDispose]() {} }; ++ break; ++ ++ case 1: ++ await using d21 = { async [Symbol.asyncDispose]() {} }; ++ break; ++} ++ ++if (true) ++ switch (0) { ++ case 0: ++ await using d22 = { async [Symbol.asyncDispose]() {} }; ++ break; ++ } ++ ++try { ++ await using d23 = { async [Symbol.asyncDispose]() {} }; ++} ++catch { ++ await using d24 = { async [Symbol.asyncDispose]() {} }; ++} ++finally { ++ await using d25 = { async [Symbol.asyncDispose]() {} }; ++} ++ ++if (true) { ++ await using d26 = { async [Symbol.asyncDispose]() {} }; ++} ++else { ++ await using d27 = { async [Symbol.asyncDispose]() {} }; ++} ++ ++while (true) { ++ await using d28 = { async [Symbol.asyncDispose]() {} }; ++ break; ++} ++ ++do { ++ await using d29 = { async [Symbol.asyncDispose]() {} }; ++ break; ++} ++while (true); ++ ++for (;;) { ++ await using d30 = { async [Symbol.asyncDispose]() {} }; ++ break; ++} ++ ++for (const x in {}) { ++ await using d31 = { async [Symbol.asyncDispose]() {} }; ++} ++ ++for (const x of []) { ++ await using d32 = { async [Symbol.asyncDispose]() {} }; ++} ++ ++export {}; ++ ++//// [awaitUsingDeclarations.1.js] ++var __addDisposableResource = (this && this.__addDisposableResource) || function (env, value, async) { ++ if (value !== null && value !== void 0) { ++ if (typeof value !== "object") throw new TypeError("Object expected."); ++ var dispose; ++ if (async) { ++ if (!Symbol.asyncDispose) throw new TypeError("Symbol.asyncDispose is not defined."); ++ dispose = value[Symbol.asyncDispose]; ++ } ++ if (dispose === void 0) { ++ if (!Symbol.dispose) throw new TypeError("Symbol.dispose is not defined."); ++ dispose = value[Symbol.dispose]; ++ } ++ if (typeof dispose !== "function") throw new TypeError("Object not disposable."); ++ env.stack.push({ value: value, dispose: dispose, async: async }); ++ } ++ else if (async) { ++ env.stack.push({ async: true }); ++ } ++ return value; ++}; ++var __disposeResources = (this && this.__disposeResources) || (function (SuppressedError) { ++ return function (env) { ++ function fail(e) { ++ env.error = env.hasError ? new SuppressedError(e, env.error, "An error was suppressed during disposal.") : e; ++ env.hasError = true; ++ } ++ function next() { ++ while (env.stack.length) { ++ var rec = env.stack.pop(); ++ try { ++ var result = rec.dispose && rec.dispose.call(rec.value); ++ if (rec.async) return Promise.resolve(result).then(next, function(e) { fail(e); return next(); }); ++ } ++ catch (e) { ++ fail(e); ++ } ++ } ++ if (env.hasError) throw env.error; ++ } ++ return next(); ++ }; ++})(typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) { ++ var e = new Error(message); ++ return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e; ++}); ++var __await = (this && this.__await) || function (v) { return this instanceof __await ? (this.v = v, this) : new __await(v); } ++var __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _arguments, generator) { ++ if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); ++ var g = generator.apply(thisArg, _arguments || []), i, q = []; ++ return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i; ++ function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; } ++ function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } } ++ function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); } ++ function fulfill(value) { resume("next", value); } ++ function reject(value) { resume("throw", value); } ++ function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); } ++}; ++async function af() { ++ const env_15 = { stack: [], error: void 0, hasError: false }; ++ try { ++ const d3 = __addDisposableResource(env_15, { async [Symbol.asyncDispose]() { } }, true); ++ await null; ++ } ++ catch (e_15) { ++ env_15.error = e_15; ++ env_15.hasError = true; ++ } ++ finally { ++ const result_15 = __disposeResources(env_15); ++ if (result_15) ++ await result_15; ++ } ++} ++function ag() { ++ return __asyncGenerator(this, arguments, function* ag_1() { ++ const env_16 = { stack: [], error: void 0, hasError: false }; ++ try { ++ const d5 = __addDisposableResource(env_16, { async [Symbol.asyncDispose]() { } }, true); ++ yield yield __await(void 0); ++ yield __await(null); ++ } ++ catch (e_16) { ++ env_16.error = e_16; ++ env_16.hasError = true; ++ } ++ finally { ++ const result_16 = __disposeResources(env_16); ++ if (result_16) ++ yield __await(result_16); ++ } ++ }); ++} ++var d1, a, C1, env_1; ++const env_2 = { stack: [], error: void 0, hasError: false }; ++try { ++ d1 = __addDisposableResource(env_2, { async [Symbol.asyncDispose]() { } }, true); ++ a = async () => { ++ const env_17 = { stack: [], error: void 0, hasError: false }; ++ try { ++ const d6 = __addDisposableResource(env_17, { async [Symbol.asyncDispose]() { } }, true); ++ } ++ catch (e_17) { ++ env_17.error = e_17; ++ env_17.hasError = true; ++ } ++ finally { ++ const result_17 = __disposeResources(env_17); ++ if (result_17) ++ await result_17; ++ } ++ }; ++ C1 = class C1 { ++ constructor() { ++ this.a = async () => { ++ const env_18 = { stack: [], error: void 0, hasError: false }; ++ try { ++ const d7 = __addDisposableResource(env_18, { async [Symbol.asyncDispose]() { } }, true); ++ } ++ catch (e_18) { ++ env_18.error = e_18; ++ env_18.hasError = true; ++ } ++ finally { ++ const result_18 = __disposeResources(env_18); ++ if (result_18) ++ await result_18; ++ } ++ }; ++ } ++ async am() { ++ const env_19 = { stack: [], error: void 0, hasError: false }; ++ try { ++ const d13 = __addDisposableResource(env_19, { async [Symbol.asyncDispose]() { } }, true); ++ await null; ++ } ++ catch (e_19) { ++ env_19.error = e_19; ++ env_19.hasError = true; ++ } ++ finally { ++ const result_19 = __disposeResources(env_19); ++ if (result_19) ++ await result_19; ++ } ++ } ++ ag() { ++ return __asyncGenerator(this, arguments, function* ag_2() { ++ const env_20 = { stack: [], error: void 0, hasError: false }; ++ try { ++ const d15 = __addDisposableResource(env_20, { async [Symbol.asyncDispose]() { } }, true); ++ yield yield __await(void 0); ++ yield __await(null); ++ } ++ catch (e_20) { ++ env_20.error = e_20; ++ env_20.hasError = true; ++ } ++ finally { ++ const result_20 = __disposeResources(env_20); ++ if (result_20) ++ yield __await(result_20); ++ } ++ }); ++ } ++ }; ++ { ++ const env_3 = { stack: [], error: void 0, hasError: false }; ++ try { ++ const d19 = __addDisposableResource(env_3, { async [Symbol.asyncDispose]() { } }, true); ++ } ++ catch (e_1) { ++ env_3.error = e_1; ++ env_3.hasError = true; ++ } ++ finally { ++ const result_1 = __disposeResources(env_3); ++ if (result_1) ++ await result_1; ++ } ++ } ++ env_1 = { stack: [], error: void 0, hasError: false }; ++ try { ++ switch (Math.random()) { ++ case 0: ++ const d20 = __addDisposableResource(env_1, { async [Symbol.asyncDispose]() { } }, true); ++ break; ++ case 1: ++ const d21 = __addDisposableResource(env_1, { async [Symbol.asyncDispose]() { } }, true); ++ break; ++ } ++ } ++ catch (e_2) { ++ env_1.error = e_2; ++ env_1.hasError = true; ++ } ++ finally { ++ const result_2 = __disposeResources(env_1); ++ if (result_2) ++ await result_2; ++ } ++ if (true) { ++ const env_4 = { stack: [], error: void 0, hasError: false }; ++ try { ++ switch (0) { ++ case 0: ++ const d22 = __addDisposableResource(env_4, { async [Symbol.asyncDispose]() { } }, true); ++ break; ++ } ++ } ++ catch (e_3) { ++ env_4.error = e_3; ++ env_4.hasError = true; ++ } ++ finally { ++ const result_3 = __disposeResources(env_4); ++ if (result_3) ++ await result_3; ++ } ++ } ++ try { ++ const env_5 = { stack: [], error: void 0, hasError: false }; ++ try { ++ const d23 = __addDisposableResource(env_5, { async [Symbol.asyncDispose]() { } }, true); ++ } ++ catch (e_4) { ++ env_5.error = e_4; ++ env_5.hasError = true; ++ } ++ finally { ++ const result_4 = __disposeResources(env_5); ++ if (result_4) ++ await result_4; ++ } ++ } ++ catch (_a) { ++ const env_6 = { stack: [], error: void 0, hasError: false }; ++ try { ++ const d24 = __addDisposableResource(env_6, { async [Symbol.asyncDispose]() { } }, true); ++ } ++ catch (e_5) { ++ env_6.error = e_5; ++ env_6.hasError = true; ++ } ++ finally { ++ const result_5 = __disposeResources(env_6); ++ if (result_5) ++ await result_5; ++ } ++ } ++ finally { ++ const env_7 = { stack: [], error: void 0, hasError: false }; ++ try { ++ const d25 = __addDisposableResource(env_7, { async [Symbol.asyncDispose]() { } }, true); ++ } ++ catch (e_6) { ++ env_7.error = e_6; ++ env_7.hasError = true; ++ } ++ finally { ++ const result_6 = __disposeResources(env_7); ++ if (result_6) ++ await result_6; ++ } ++ } ++ if (true) { ++ const env_8 = { stack: [], error: void 0, hasError: false }; ++ try { ++ const d26 = __addDisposableResource(env_8, { async [Symbol.asyncDispose]() { } }, true); ++ } ++ catch (e_7) { ++ env_8.error = e_7; ++ env_8.hasError = true; ++ } ++ finally { ++ const result_7 = __disposeResources(env_8); ++ if (result_7) ++ await result_7; ++ } ++ } ++ else { ++ const env_9 = { stack: [], error: void 0, hasError: false }; ++ try { ++ const d27 = __addDisposableResource(env_9, { async [Symbol.asyncDispose]() { } }, true); ++ } ++ catch (e_8) { ++ env_9.error = e_8; ++ env_9.hasError = true; ++ } ++ finally { ++ const result_8 = __disposeResources(env_9); ++ if (result_8) ++ await result_8; ++ } ++ } ++ while (true) { ++ const env_10 = { stack: [], error: void 0, hasError: false }; ++ try { ++ const d28 = __addDisposableResource(env_10, { async [Symbol.asyncDispose]() { } }, true); ++ break; ++ } ++ catch (e_9) { ++ env_10.error = e_9; ++ env_10.hasError = true; ++ } ++ finally { ++ const result_9 = __disposeResources(env_10); ++ if (result_9) ++ await result_9; ++ } ++ } ++ do { ++ const env_11 = { stack: [], error: void 0, hasError: false }; ++ try { ++ const d29 = __addDisposableResource(env_11, { async [Symbol.asyncDispose]() { } }, true); ++ break; ++ } ++ catch (e_10) { ++ env_11.error = e_10; ++ env_11.hasError = true; ++ } ++ finally { ++ const result_10 = __disposeResources(env_11); ++ if (result_10) ++ await result_10; ++ } ++ } while (true); ++ for (;;) { ++ const env_12 = { stack: [], error: void 0, hasError: false }; ++ try { ++ const d30 = __addDisposableResource(env_12, { async [Symbol.asyncDispose]() { } }, true); ++ break; ++ } ++ catch (e_11) { ++ env_12.error = e_11; ++ env_12.hasError = true; ++ } ++ finally { ++ const result_11 = __disposeResources(env_12); ++ if (result_11) ++ await result_11; ++ } ++ } ++ for (const x in {}) { ++ const env_13 = { stack: [], error: void 0, hasError: false }; ++ try { ++ const d31 = __addDisposableResource(env_13, { async [Symbol.asyncDispose]() { } }, true); ++ } ++ catch (e_12) { ++ env_13.error = e_12; ++ env_13.hasError = true; ++ } ++ finally { ++ const result_12 = __disposeResources(env_13); ++ if (result_12) ++ await result_12; ++ } ++ } ++ for (const x of []) { ++ const env_14 = { stack: [], error: void 0, hasError: false }; ++ try { ++ const d32 = __addDisposableResource(env_14, { async [Symbol.asyncDispose]() { } }, true); ++ } ++ catch (e_13) { ++ env_14.error = e_13; ++ env_14.hasError = true; ++ } ++ finally { ++ const result_13 = __disposeResources(env_14); ++ if (result_13) ++ await result_13; ++ } ++ } ++} ++catch (e_14) { ++ env_2.error = e_14; ++ env_2.hasError = true; ++} ++finally { ++ const result_14 = __disposeResources(env_2); ++ if (result_14) ++ await result_14; ++} ++export {}; +diff --git a/tests/baselines/reference/awaitUsingDeclarations.1(target=es2022).js b/tests/baselines/reference/awaitUsingDeclarations.1(target=es2022).js +new file mode 100644 +index 000000000..41ca06958 +--- /dev/null ++++ b/tests/baselines/reference/awaitUsingDeclarations.1(target=es2022).js +@@ -0,0 +1,467 @@ ++//// [tests/cases/conformance/statements/VariableStatements/usingDeclarations/awaitUsingDeclarations.1.ts] //// ++ ++//// [awaitUsingDeclarations.1.ts] ++await using d1 = { async [Symbol.asyncDispose]() {} }; ++ ++async function af() { ++ await using d3 = { async [Symbol.asyncDispose]() {} }; ++ await null; ++} ++ ++async function * ag() { ++ await using d5 = { async [Symbol.asyncDispose]() {} }; ++ yield; ++ await null; ++} ++ ++const a = async () => { ++ await using d6 = { async [Symbol.asyncDispose]() {} }; ++}; ++ ++class C1 { ++ a = async () => { ++ await using d7 = { async [Symbol.asyncDispose]() {} }; ++ }; ++ ++ async am() { ++ await using d13 = { async [Symbol.asyncDispose]() {} }; ++ await null; ++ } ++ ++ async * ag() { ++ await using d15 = { async [Symbol.asyncDispose]() {} }; ++ yield; ++ await null; ++ } ++} ++ ++{ ++ await using d19 = { async [Symbol.asyncDispose]() {} }; ++} ++ ++switch (Math.random()) { ++ case 0: ++ await using d20 = { async [Symbol.asyncDispose]() {} }; ++ break; ++ ++ case 1: ++ await using d21 = { async [Symbol.asyncDispose]() {} }; ++ break; ++} ++ ++if (true) ++ switch (0) { ++ case 0: ++ await using d22 = { async [Symbol.asyncDispose]() {} }; ++ break; ++ } ++ ++try { ++ await using d23 = { async [Symbol.asyncDispose]() {} }; ++} ++catch { ++ await using d24 = { async [Symbol.asyncDispose]() {} }; ++} ++finally { ++ await using d25 = { async [Symbol.asyncDispose]() {} }; ++} ++ ++if (true) { ++ await using d26 = { async [Symbol.asyncDispose]() {} }; ++} ++else { ++ await using d27 = { async [Symbol.asyncDispose]() {} }; ++} ++ ++while (true) { ++ await using d28 = { async [Symbol.asyncDispose]() {} }; ++ break; ++} ++ ++do { ++ await using d29 = { async [Symbol.asyncDispose]() {} }; ++ break; ++} ++while (true); ++ ++for (;;) { ++ await using d30 = { async [Symbol.asyncDispose]() {} }; ++ break; ++} ++ ++for (const x in {}) { ++ await using d31 = { async [Symbol.asyncDispose]() {} }; ++} ++ ++for (const x of []) { ++ await using d32 = { async [Symbol.asyncDispose]() {} }; ++} ++ ++export {}; ++ ++//// [awaitUsingDeclarations.1.js] ++var __addDisposableResource = (this && this.__addDisposableResource) || function (env, value, async) { ++ if (value !== null && value !== void 0) { ++ if (typeof value !== "object") throw new TypeError("Object expected."); ++ var dispose; ++ if (async) { ++ if (!Symbol.asyncDispose) throw new TypeError("Symbol.asyncDispose is not defined."); ++ dispose = value[Symbol.asyncDispose]; ++ } ++ if (dispose === void 0) { ++ if (!Symbol.dispose) throw new TypeError("Symbol.dispose is not defined."); ++ dispose = value[Symbol.dispose]; ++ } ++ if (typeof dispose !== "function") throw new TypeError("Object not disposable."); ++ env.stack.push({ value: value, dispose: dispose, async: async }); ++ } ++ else if (async) { ++ env.stack.push({ async: true }); ++ } ++ return value; ++}; ++var __disposeResources = (this && this.__disposeResources) || (function (SuppressedError) { ++ return function (env) { ++ function fail(e) { ++ env.error = env.hasError ? new SuppressedError(e, env.error, "An error was suppressed during disposal.") : e; ++ env.hasError = true; ++ } ++ function next() { ++ while (env.stack.length) { ++ var rec = env.stack.pop(); ++ try { ++ var result = rec.dispose && rec.dispose.call(rec.value); ++ if (rec.async) return Promise.resolve(result).then(next, function(e) { fail(e); return next(); }); ++ } ++ catch (e) { ++ fail(e); ++ } ++ } ++ if (env.hasError) throw env.error; ++ } ++ return next(); ++ }; ++})(typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) { ++ var e = new Error(message); ++ return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e; ++}); ++async function af() { ++ const env_15 = { stack: [], error: void 0, hasError: false }; ++ try { ++ const d3 = __addDisposableResource(env_15, { async [Symbol.asyncDispose]() { } }, true); ++ await null; ++ } ++ catch (e_15) { ++ env_15.error = e_15; ++ env_15.hasError = true; ++ } ++ finally { ++ const result_15 = __disposeResources(env_15); ++ if (result_15) ++ await result_15; ++ } ++} ++async function* ag() { ++ const env_16 = { stack: [], error: void 0, hasError: false }; ++ try { ++ const d5 = __addDisposableResource(env_16, { async [Symbol.asyncDispose]() { } }, true); ++ yield; ++ await null; ++ } ++ catch (e_16) { ++ env_16.error = e_16; ++ env_16.hasError = true; ++ } ++ finally { ++ const result_16 = __disposeResources(env_16); ++ if (result_16) ++ await result_16; ++ } ++} ++var d1, a, C1, env_1; ++const env_2 = { stack: [], error: void 0, hasError: false }; ++try { ++ d1 = __addDisposableResource(env_2, { async [Symbol.asyncDispose]() { } }, true); ++ a = async () => { ++ const env_17 = { stack: [], error: void 0, hasError: false }; ++ try { ++ const d6 = __addDisposableResource(env_17, { async [Symbol.asyncDispose]() { } }, true); ++ } ++ catch (e_17) { ++ env_17.error = e_17; ++ env_17.hasError = true; ++ } ++ finally { ++ const result_17 = __disposeResources(env_17); ++ if (result_17) ++ await result_17; ++ } ++ }; ++ C1 = class C1 { ++ a = async () => { ++ const env_18 = { stack: [], error: void 0, hasError: false }; ++ try { ++ const d7 = __addDisposableResource(env_18, { async [Symbol.asyncDispose]() { } }, true); ++ } ++ catch (e_18) { ++ env_18.error = e_18; ++ env_18.hasError = true; ++ } ++ finally { ++ const result_18 = __disposeResources(env_18); ++ if (result_18) ++ await result_18; ++ } ++ }; ++ async am() { ++ const env_19 = { stack: [], error: void 0, hasError: false }; ++ try { ++ const d13 = __addDisposableResource(env_19, { async [Symbol.asyncDispose]() { } }, true); ++ await null; ++ } ++ catch (e_19) { ++ env_19.error = e_19; ++ env_19.hasError = true; ++ } ++ finally { ++ const result_19 = __disposeResources(env_19); ++ if (result_19) ++ await result_19; ++ } ++ } ++ async *ag() { ++ const env_20 = { stack: [], error: void 0, hasError: false }; ++ try { ++ const d15 = __addDisposableResource(env_20, { async [Symbol.asyncDispose]() { } }, true); ++ yield; ++ await null; ++ } ++ catch (e_20) { ++ env_20.error = e_20; ++ env_20.hasError = true; ++ } ++ finally { ++ const result_20 = __disposeResources(env_20); ++ if (result_20) ++ await result_20; ++ } ++ } ++ }; ++ { ++ const env_3 = { stack: [], error: void 0, hasError: false }; ++ try { ++ const d19 = __addDisposableResource(env_3, { async [Symbol.asyncDispose]() { } }, true); ++ } ++ catch (e_1) { ++ env_3.error = e_1; ++ env_3.hasError = true; ++ } ++ finally { ++ const result_1 = __disposeResources(env_3); ++ if (result_1) ++ await result_1; ++ } ++ } ++ env_1 = { stack: [], error: void 0, hasError: false }; ++ try { ++ switch (Math.random()) { ++ case 0: ++ const d20 = __addDisposableResource(env_1, { async [Symbol.asyncDispose]() { } }, true); ++ break; ++ case 1: ++ const d21 = __addDisposableResource(env_1, { async [Symbol.asyncDispose]() { } }, true); ++ break; ++ } ++ } ++ catch (e_2) { ++ env_1.error = e_2; ++ env_1.hasError = true; ++ } ++ finally { ++ const result_2 = __disposeResources(env_1); ++ if (result_2) ++ await result_2; ++ } ++ if (true) { ++ const env_4 = { stack: [], error: void 0, hasError: false }; ++ try { ++ switch (0) { ++ case 0: ++ const d22 = __addDisposableResource(env_4, { async [Symbol.asyncDispose]() { } }, true); ++ break; ++ } ++ } ++ catch (e_3) { ++ env_4.error = e_3; ++ env_4.hasError = true; ++ } ++ finally { ++ const result_3 = __disposeResources(env_4); ++ if (result_3) ++ await result_3; ++ } ++ } ++ try { ++ const env_5 = { stack: [], error: void 0, hasError: false }; ++ try { ++ const d23 = __addDisposableResource(env_5, { async [Symbol.asyncDispose]() { } }, true); ++ } ++ catch (e_4) { ++ env_5.error = e_4; ++ env_5.hasError = true; ++ } ++ finally { ++ const result_4 = __disposeResources(env_5); ++ if (result_4) ++ await result_4; ++ } ++ } ++ catch { ++ const env_6 = { stack: [], error: void 0, hasError: false }; ++ try { ++ const d24 = __addDisposableResource(env_6, { async [Symbol.asyncDispose]() { } }, true); ++ } ++ catch (e_5) { ++ env_6.error = e_5; ++ env_6.hasError = true; ++ } ++ finally { ++ const result_5 = __disposeResources(env_6); ++ if (result_5) ++ await result_5; ++ } ++ } ++ finally { ++ const env_7 = { stack: [], error: void 0, hasError: false }; ++ try { ++ const d25 = __addDisposableResource(env_7, { async [Symbol.asyncDispose]() { } }, true); ++ } ++ catch (e_6) { ++ env_7.error = e_6; ++ env_7.hasError = true; ++ } ++ finally { ++ const result_6 = __disposeResources(env_7); ++ if (result_6) ++ await result_6; ++ } ++ } ++ if (true) { ++ const env_8 = { stack: [], error: void 0, hasError: false }; ++ try { ++ const d26 = __addDisposableResource(env_8, { async [Symbol.asyncDispose]() { } }, true); ++ } ++ catch (e_7) { ++ env_8.error = e_7; ++ env_8.hasError = true; ++ } ++ finally { ++ const result_7 = __disposeResources(env_8); ++ if (result_7) ++ await result_7; ++ } ++ } ++ else { ++ const env_9 = { stack: [], error: void 0, hasError: false }; ++ try { ++ const d27 = __addDisposableResource(env_9, { async [Symbol.asyncDispose]() { } }, true); ++ } ++ catch (e_8) { ++ env_9.error = e_8; ++ env_9.hasError = true; ++ } ++ finally { ++ const result_8 = __disposeResources(env_9); ++ if (result_8) ++ await result_8; ++ } ++ } ++ while (true) { ++ const env_10 = { stack: [], error: void 0, hasError: false }; ++ try { ++ const d28 = __addDisposableResource(env_10, { async [Symbol.asyncDispose]() { } }, true); ++ break; ++ } ++ catch (e_9) { ++ env_10.error = e_9; ++ env_10.hasError = true; ++ } ++ finally { ++ const result_9 = __disposeResources(env_10); ++ if (result_9) ++ await result_9; ++ } ++ } ++ do { ++ const env_11 = { stack: [], error: void 0, hasError: false }; ++ try { ++ const d29 = __addDisposableResource(env_11, { async [Symbol.asyncDispose]() { } }, true); ++ break; ++ } ++ catch (e_10) { ++ env_11.error = e_10; ++ env_11.hasError = true; ++ } ++ finally { ++ const result_10 = __disposeResources(env_11); ++ if (result_10) ++ await result_10; ++ } ++ } while (true); ++ for (;;) { ++ const env_12 = { stack: [], error: void 0, hasError: false }; ++ try { ++ const d30 = __addDisposableResource(env_12, { async [Symbol.asyncDispose]() { } }, true); ++ break; ++ } ++ catch (e_11) { ++ env_12.error = e_11; ++ env_12.hasError = true; ++ } ++ finally { ++ const result_11 = __disposeResources(env_12); ++ if (result_11) ++ await result_11; ++ } ++ } ++ for (const x in {}) { ++ const env_13 = { stack: [], error: void 0, hasError: false }; ++ try { ++ const d31 = __addDisposableResource(env_13, { async [Symbol.asyncDispose]() { } }, true); ++ } ++ catch (e_12) { ++ env_13.error = e_12; ++ env_13.hasError = true; ++ } ++ finally { ++ const result_12 = __disposeResources(env_13); ++ if (result_12) ++ await result_12; ++ } ++ } ++ for (const x of []) { ++ const env_14 = { stack: [], error: void 0, hasError: false }; ++ try { ++ const d32 = __addDisposableResource(env_14, { async [Symbol.asyncDispose]() { } }, true); ++ } ++ catch (e_13) { ++ env_14.error = e_13; ++ env_14.hasError = true; ++ } ++ finally { ++ const result_13 = __disposeResources(env_14); ++ if (result_13) ++ await result_13; ++ } ++ } ++} ++catch (e_14) { ++ env_2.error = e_14; ++ env_2.hasError = true; ++} ++finally { ++ const result_14 = __disposeResources(env_2); ++ if (result_14) ++ await result_14; ++} ++export {}; +diff --git a/tests/baselines/reference/awaitUsingDeclarations.1(target=es5).errors.txt b/tests/baselines/reference/awaitUsingDeclarations.1(target=es5).errors.txt +new file mode 100644 +index 000000000..52470b245 +--- /dev/null ++++ b/tests/baselines/reference/awaitUsingDeclarations.1(target=es5).errors.txt +@@ -0,0 +1,145 @@ ++awaitUsingDeclarations.1.ts(1,1): error TS2854: Top-level 'await using' statements are only allowed when the 'module' option is set to 'es2022', 'esnext', 'system', 'node16', or 'nodenext', and the 'target' option is set to 'es2017' or higher. ++awaitUsingDeclarations.1.ts(36,5): error TS2854: Top-level 'await using' statements are only allowed when the 'module' option is set to 'es2022', 'esnext', 'system', 'node16', or 'nodenext', and the 'target' option is set to 'es2017' or higher. ++awaitUsingDeclarations.1.ts(41,9): error TS2854: Top-level 'await using' statements are only allowed when the 'module' option is set to 'es2022', 'esnext', 'system', 'node16', or 'nodenext', and the 'target' option is set to 'es2017' or higher. ++awaitUsingDeclarations.1.ts(45,9): error TS2854: Top-level 'await using' statements are only allowed when the 'module' option is set to 'es2022', 'esnext', 'system', 'node16', or 'nodenext', and the 'target' option is set to 'es2017' or higher. ++awaitUsingDeclarations.1.ts(52,13): error TS2854: Top-level 'await using' statements are only allowed when the 'module' option is set to 'es2022', 'esnext', 'system', 'node16', or 'nodenext', and the 'target' option is set to 'es2017' or higher. ++awaitUsingDeclarations.1.ts(57,5): error TS2854: Top-level 'await using' statements are only allowed when the 'module' option is set to 'es2022', 'esnext', 'system', 'node16', or 'nodenext', and the 'target' option is set to 'es2017' or higher. ++awaitUsingDeclarations.1.ts(60,5): error TS2854: Top-level 'await using' statements are only allowed when the 'module' option is set to 'es2022', 'esnext', 'system', 'node16', or 'nodenext', and the 'target' option is set to 'es2017' or higher. ++awaitUsingDeclarations.1.ts(63,5): error TS2854: Top-level 'await using' statements are only allowed when the 'module' option is set to 'es2022', 'esnext', 'system', 'node16', or 'nodenext', and the 'target' option is set to 'es2017' or higher. ++awaitUsingDeclarations.1.ts(67,5): error TS2854: Top-level 'await using' statements are only allowed when the 'module' option is set to 'es2022', 'esnext', 'system', 'node16', or 'nodenext', and the 'target' option is set to 'es2017' or higher. ++awaitUsingDeclarations.1.ts(70,5): error TS2854: Top-level 'await using' statements are only allowed when the 'module' option is set to 'es2022', 'esnext', 'system', 'node16', or 'nodenext', and the 'target' option is set to 'es2017' or higher. ++awaitUsingDeclarations.1.ts(74,5): error TS2854: Top-level 'await using' statements are only allowed when the 'module' option is set to 'es2022', 'esnext', 'system', 'node16', or 'nodenext', and the 'target' option is set to 'es2017' or higher. ++awaitUsingDeclarations.1.ts(79,5): error TS2854: Top-level 'await using' statements are only allowed when the 'module' option is set to 'es2022', 'esnext', 'system', 'node16', or 'nodenext', and the 'target' option is set to 'es2017' or higher. ++awaitUsingDeclarations.1.ts(85,5): error TS2854: Top-level 'await using' statements are only allowed when the 'module' option is set to 'es2022', 'esnext', 'system', 'node16', or 'nodenext', and the 'target' option is set to 'es2017' or higher. ++awaitUsingDeclarations.1.ts(90,5): error TS2854: Top-level 'await using' statements are only allowed when the 'module' option is set to 'es2022', 'esnext', 'system', 'node16', or 'nodenext', and the 'target' option is set to 'es2017' or higher. ++awaitUsingDeclarations.1.ts(94,5): error TS2854: Top-level 'await using' statements are only allowed when the 'module' option is set to 'es2022', 'esnext', 'system', 'node16', or 'nodenext', and the 'target' option is set to 'es2017' or higher. ++ ++ ++==== awaitUsingDeclarations.1.ts (15 errors) ==== ++ await using d1 = { async [Symbol.asyncDispose]() {} }; ++ ~~~~~ ++!!! error TS2854: Top-level 'await using' statements are only allowed when the 'module' option is set to 'es2022', 'esnext', 'system', 'node16', or 'nodenext', and the 'target' option is set to 'es2017' or higher. ++ ++ async function af() { ++ await using d3 = { async [Symbol.asyncDispose]() {} }; ++ await null; ++ } ++ ++ async function * ag() { ++ await using d5 = { async [Symbol.asyncDispose]() {} }; ++ yield; ++ await null; ++ } ++ ++ const a = async () => { ++ await using d6 = { async [Symbol.asyncDispose]() {} }; ++ }; ++ ++ class C1 { ++ a = async () => { ++ await using d7 = { async [Symbol.asyncDispose]() {} }; ++ }; ++ ++ async am() { ++ await using d13 = { async [Symbol.asyncDispose]() {} }; ++ await null; ++ } ++ ++ async * ag() { ++ await using d15 = { async [Symbol.asyncDispose]() {} }; ++ yield; ++ await null; ++ } ++ } ++ ++ { ++ await using d19 = { async [Symbol.asyncDispose]() {} }; ++ ~~~~~ ++!!! error TS2854: Top-level 'await using' statements are only allowed when the 'module' option is set to 'es2022', 'esnext', 'system', 'node16', or 'nodenext', and the 'target' option is set to 'es2017' or higher. ++ } ++ ++ switch (Math.random()) { ++ case 0: ++ await using d20 = { async [Symbol.asyncDispose]() {} }; ++ ~~~~~ ++!!! error TS2854: Top-level 'await using' statements are only allowed when the 'module' option is set to 'es2022', 'esnext', 'system', 'node16', or 'nodenext', and the 'target' option is set to 'es2017' or higher. ++ break; ++ ++ case 1: ++ await using d21 = { async [Symbol.asyncDispose]() {} }; ++ ~~~~~ ++!!! error TS2854: Top-level 'await using' statements are only allowed when the 'module' option is set to 'es2022', 'esnext', 'system', 'node16', or 'nodenext', and the 'target' option is set to 'es2017' or higher. ++ break; ++ } ++ ++ if (true) ++ switch (0) { ++ case 0: ++ await using d22 = { async [Symbol.asyncDispose]() {} }; ++ ~~~~~ ++!!! error TS2854: Top-level 'await using' statements are only allowed when the 'module' option is set to 'es2022', 'esnext', 'system', 'node16', or 'nodenext', and the 'target' option is set to 'es2017' or higher. ++ break; ++ } ++ ++ try { ++ await using d23 = { async [Symbol.asyncDispose]() {} }; ++ ~~~~~ ++!!! error TS2854: Top-level 'await using' statements are only allowed when the 'module' option is set to 'es2022', 'esnext', 'system', 'node16', or 'nodenext', and the 'target' option is set to 'es2017' or higher. ++ } ++ catch { ++ await using d24 = { async [Symbol.asyncDispose]() {} }; ++ ~~~~~ ++!!! error TS2854: Top-level 'await using' statements are only allowed when the 'module' option is set to 'es2022', 'esnext', 'system', 'node16', or 'nodenext', and the 'target' option is set to 'es2017' or higher. ++ } ++ finally { ++ await using d25 = { async [Symbol.asyncDispose]() {} }; ++ ~~~~~ ++!!! error TS2854: Top-level 'await using' statements are only allowed when the 'module' option is set to 'es2022', 'esnext', 'system', 'node16', or 'nodenext', and the 'target' option is set to 'es2017' or higher. ++ } ++ ++ if (true) { ++ await using d26 = { async [Symbol.asyncDispose]() {} }; ++ ~~~~~ ++!!! error TS2854: Top-level 'await using' statements are only allowed when the 'module' option is set to 'es2022', 'esnext', 'system', 'node16', or 'nodenext', and the 'target' option is set to 'es2017' or higher. ++ } ++ else { ++ await using d27 = { async [Symbol.asyncDispose]() {} }; ++ ~~~~~ ++!!! error TS2854: Top-level 'await using' statements are only allowed when the 'module' option is set to 'es2022', 'esnext', 'system', 'node16', or 'nodenext', and the 'target' option is set to 'es2017' or higher. ++ } ++ ++ while (true) { ++ await using d28 = { async [Symbol.asyncDispose]() {} }; ++ ~~~~~ ++!!! error TS2854: Top-level 'await using' statements are only allowed when the 'module' option is set to 'es2022', 'esnext', 'system', 'node16', or 'nodenext', and the 'target' option is set to 'es2017' or higher. ++ break; ++ } ++ ++ do { ++ await using d29 = { async [Symbol.asyncDispose]() {} }; ++ ~~~~~ ++!!! error TS2854: Top-level 'await using' statements are only allowed when the 'module' option is set to 'es2022', 'esnext', 'system', 'node16', or 'nodenext', and the 'target' option is set to 'es2017' or higher. ++ break; ++ } ++ while (true); ++ ++ for (;;) { ++ await using d30 = { async [Symbol.asyncDispose]() {} }; ++ ~~~~~ ++!!! error TS2854: Top-level 'await using' statements are only allowed when the 'module' option is set to 'es2022', 'esnext', 'system', 'node16', or 'nodenext', and the 'target' option is set to 'es2017' or higher. ++ break; ++ } ++ ++ for (const x in {}) { ++ await using d31 = { async [Symbol.asyncDispose]() {} }; ++ ~~~~~ ++!!! error TS2854: Top-level 'await using' statements are only allowed when the 'module' option is set to 'es2022', 'esnext', 'system', 'node16', or 'nodenext', and the 'target' option is set to 'es2017' or higher. ++ } ++ ++ for (const x of []) { ++ await using d32 = { async [Symbol.asyncDispose]() {} }; ++ ~~~~~ ++!!! error TS2854: Top-level 'await using' statements are only allowed when the 'module' option is set to 'es2022', 'esnext', 'system', 'node16', or 'nodenext', and the 'target' option is set to 'es2017' or higher. ++ } ++ ++ export {}; +\ No newline at end of file +diff --git a/tests/baselines/reference/awaitUsingDeclarations.1(target=es5).js b/tests/baselines/reference/awaitUsingDeclarations.1(target=es5).js +new file mode 100644 +index 000000000..7d7ec33b2 +--- /dev/null ++++ b/tests/baselines/reference/awaitUsingDeclarations.1(target=es5).js +@@ -0,0 +1,711 @@ ++//// [tests/cases/conformance/statements/VariableStatements/usingDeclarations/awaitUsingDeclarations.1.ts] //// ++ ++//// [awaitUsingDeclarations.1.ts] ++await using d1 = { async [Symbol.asyncDispose]() {} }; ++ ++async function af() { ++ await using d3 = { async [Symbol.asyncDispose]() {} }; ++ await null; ++} ++ ++async function * ag() { ++ await using d5 = { async [Symbol.asyncDispose]() {} }; ++ yield; ++ await null; ++} ++ ++const a = async () => { ++ await using d6 = { async [Symbol.asyncDispose]() {} }; ++}; ++ ++class C1 { ++ a = async () => { ++ await using d7 = { async [Symbol.asyncDispose]() {} }; ++ }; ++ ++ async am() { ++ await using d13 = { async [Symbol.asyncDispose]() {} }; ++ await null; ++ } ++ ++ async * ag() { ++ await using d15 = { async [Symbol.asyncDispose]() {} }; ++ yield; ++ await null; ++ } ++} ++ ++{ ++ await using d19 = { async [Symbol.asyncDispose]() {} }; ++} ++ ++switch (Math.random()) { ++ case 0: ++ await using d20 = { async [Symbol.asyncDispose]() {} }; ++ break; ++ ++ case 1: ++ await using d21 = { async [Symbol.asyncDispose]() {} }; ++ break; ++} ++ ++if (true) ++ switch (0) { ++ case 0: ++ await using d22 = { async [Symbol.asyncDispose]() {} }; ++ break; ++ } ++ ++try { ++ await using d23 = { async [Symbol.asyncDispose]() {} }; ++} ++catch { ++ await using d24 = { async [Symbol.asyncDispose]() {} }; ++} ++finally { ++ await using d25 = { async [Symbol.asyncDispose]() {} }; ++} ++ ++if (true) { ++ await using d26 = { async [Symbol.asyncDispose]() {} }; ++} ++else { ++ await using d27 = { async [Symbol.asyncDispose]() {} }; ++} ++ ++while (true) { ++ await using d28 = { async [Symbol.asyncDispose]() {} }; ++ break; ++} ++ ++do { ++ await using d29 = { async [Symbol.asyncDispose]() {} }; ++ break; ++} ++while (true); ++ ++for (;;) { ++ await using d30 = { async [Symbol.asyncDispose]() {} }; ++ break; ++} ++ ++for (const x in {}) { ++ await using d31 = { async [Symbol.asyncDispose]() {} }; ++} ++ ++for (const x of []) { ++ await using d32 = { async [Symbol.asyncDispose]() {} }; ++} ++ ++export {}; ++ ++//// [awaitUsingDeclarations.1.js] ++var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { ++ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } ++ return new (P || (P = Promise))(function (resolve, reject) { ++ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } ++ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } ++ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } ++ step((generator = generator.apply(thisArg, _arguments || [])).next()); ++ }); ++}; ++var __generator = (this && this.__generator) || function (thisArg, body) { ++ var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; ++ return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; ++ function verb(n) { return function (v) { return step([n, v]); }; } ++ function step(op) { ++ if (f) throw new TypeError("Generator is already executing."); ++ while (g && (g = 0, op[0] && (_ = 0)), _) try { ++ if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; ++ if (y = 0, t) op = [op[0] & 2, t.value]; ++ switch (op[0]) { ++ case 0: case 1: t = op; break; ++ case 4: _.label++; return { value: op[1], done: false }; ++ case 5: _.label++; y = op[1]; op = [0]; continue; ++ case 7: op = _.ops.pop(); _.trys.pop(); continue; ++ default: ++ if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } ++ if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } ++ if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } ++ if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } ++ if (t[2]) _.ops.pop(); ++ _.trys.pop(); continue; ++ } ++ op = body.call(thisArg, _); ++ } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } ++ if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; ++ } ++}; ++var __addDisposableResource = (this && this.__addDisposableResource) || function (env, value, async) { ++ if (value !== null && value !== void 0) { ++ if (typeof value !== "object") throw new TypeError("Object expected."); ++ var dispose; ++ if (async) { ++ if (!Symbol.asyncDispose) throw new TypeError("Symbol.asyncDispose is not defined."); ++ dispose = value[Symbol.asyncDispose]; ++ } ++ if (dispose === void 0) { ++ if (!Symbol.dispose) throw new TypeError("Symbol.dispose is not defined."); ++ dispose = value[Symbol.dispose]; ++ } ++ if (typeof dispose !== "function") throw new TypeError("Object not disposable."); ++ env.stack.push({ value: value, dispose: dispose, async: async }); ++ } ++ else if (async) { ++ env.stack.push({ async: true }); ++ } ++ return value; ++}; ++var __disposeResources = (this && this.__disposeResources) || (function (SuppressedError) { ++ return function (env) { ++ function fail(e) { ++ env.error = env.hasError ? new SuppressedError(e, env.error, "An error was suppressed during disposal.") : e; ++ env.hasError = true; ++ } ++ function next() { ++ while (env.stack.length) { ++ var rec = env.stack.pop(); ++ try { ++ var result = rec.dispose && rec.dispose.call(rec.value); ++ if (rec.async) return Promise.resolve(result).then(next, function(e) { fail(e); return next(); }); ++ } ++ catch (e) { ++ fail(e); ++ } ++ } ++ if (env.hasError) throw env.error; ++ } ++ return next(); ++ }; ++})(typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) { ++ var e = new Error(message); ++ return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e; ++}); ++var __await = (this && this.__await) || function (v) { return this instanceof __await ? (this.v = v, this) : new __await(v); } ++var __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _arguments, generator) { ++ if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); ++ var g = generator.apply(thisArg, _arguments || []), i, q = []; ++ return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i; ++ function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; } ++ function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } } ++ function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); } ++ function fulfill(value) { resume("next", value); } ++ function reject(value) { resume("throw", value); } ++ function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); } ++}; ++var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q; ++function af() { ++ return __awaiter(this, void 0, void 0, function () { ++ var env_15, d3, e_15, result_15; ++ var _a; ++ return __generator(this, function (_b) { ++ switch (_b.label) { ++ case 0: ++ env_15 = { stack: [], error: void 0, hasError: false }; ++ _b.label = 1; ++ case 1: ++ _b.trys.push([1, 3, 4, 7]); ++ d3 = __addDisposableResource(env_15, (_a = {}, _a[Symbol.asyncDispose] = function () { ++ return __awaiter(this, void 0, void 0, function () { return __generator(this, function (_a) { ++ return [2 /*return*/]; ++ }); }); ++ }, _a), true); ++ return [4 /*yield*/, null]; ++ case 2: ++ _b.sent(); ++ return [3 /*break*/, 7]; ++ case 3: ++ e_15 = _b.sent(); ++ env_15.error = e_15; ++ env_15.hasError = true; ++ return [3 /*break*/, 7]; ++ case 4: ++ result_15 = __disposeResources(env_15); ++ if (!result_15) return [3 /*break*/, 6]; ++ return [4 /*yield*/, result_15]; ++ case 5: ++ _b.sent(); ++ _b.label = 6; ++ case 6: return [7 /*endfinally*/]; ++ case 7: return [2 /*return*/]; ++ } ++ }); ++ }); ++} ++function ag() { ++ return __asyncGenerator(this, arguments, function ag_1() { ++ var env_16, d5, e_16, result_16; ++ var _a; ++ return __generator(this, function (_b) { ++ switch (_b.label) { ++ case 0: ++ env_16 = { stack: [], error: void 0, hasError: false }; ++ _b.label = 1; ++ case 1: ++ _b.trys.push([1, 5, 6, 9]); ++ d5 = __addDisposableResource(env_16, (_a = {}, _a[Symbol.asyncDispose] = function () { ++ return __awaiter(this, void 0, void 0, function () { return __generator(this, function (_a) { ++ return [2 /*return*/]; ++ }); }); ++ }, _a), true); ++ return [4 /*yield*/, __await(void 0)]; ++ case 2: return [4 /*yield*/, _b.sent()]; ++ case 3: ++ _b.sent(); ++ return [4 /*yield*/, __await(null)]; ++ case 4: ++ _b.sent(); ++ return [3 /*break*/, 9]; ++ case 5: ++ e_16 = _b.sent(); ++ env_16.error = e_16; ++ env_16.hasError = true; ++ return [3 /*break*/, 9]; ++ case 6: ++ result_16 = __disposeResources(env_16); ++ if (!result_16) return [3 /*break*/, 8]; ++ return [4 /*yield*/, __await(result_16)]; ++ case 7: ++ _b.sent(); ++ _b.label = 8; ++ case 8: return [7 /*endfinally*/]; ++ case 9: return [2 /*return*/]; ++ } ++ }); ++ }); ++} ++var d1, a, C1, env_1; ++var env_2 = { stack: [], error: void 0, hasError: false }; ++try { ++ d1 = __addDisposableResource(env_2, (_a = {}, _a[Symbol.asyncDispose] = function () { ++ return __awaiter(this, void 0, void 0, function () { return __generator(this, function (_a) { ++ return [2 /*return*/]; ++ }); }); ++ }, _a), true); ++ a = function () { return __awaiter(void 0, void 0, void 0, function () { ++ var env_17, d6, e_17, result_17; ++ var _a; ++ return __generator(this, function (_b) { ++ switch (_b.label) { ++ case 0: ++ env_17 = { stack: [], error: void 0, hasError: false }; ++ _b.label = 1; ++ case 1: ++ _b.trys.push([1, 2, 3, 6]); ++ d6 = __addDisposableResource(env_17, (_a = {}, _a[Symbol.asyncDispose] = function () { ++ return __awaiter(this, void 0, void 0, function () { return __generator(this, function (_a) { ++ return [2 /*return*/]; ++ }); }); ++ }, _a), true); ++ return [3 /*break*/, 6]; ++ case 2: ++ e_17 = _b.sent(); ++ env_17.error = e_17; ++ env_17.hasError = true; ++ return [3 /*break*/, 6]; ++ case 3: ++ result_17 = __disposeResources(env_17); ++ if (!result_17) return [3 /*break*/, 5]; ++ return [4 /*yield*/, result_17]; ++ case 4: ++ _b.sent(); ++ _b.label = 5; ++ case 5: return [7 /*endfinally*/]; ++ case 6: return [2 /*return*/]; ++ } ++ }); ++ }); }; ++ C1 = /** @class */ (function () { ++ function C1() { ++ var _this = this; ++ this.a = function () { return __awaiter(_this, void 0, void 0, function () { ++ var env_18, d7, e_18, result_18; ++ var _a; ++ return __generator(this, function (_b) { ++ switch (_b.label) { ++ case 0: ++ env_18 = { stack: [], error: void 0, hasError: false }; ++ _b.label = 1; ++ case 1: ++ _b.trys.push([1, 2, 3, 6]); ++ d7 = __addDisposableResource(env_18, (_a = {}, _a[Symbol.asyncDispose] = function () { ++ return __awaiter(this, void 0, void 0, function () { return __generator(this, function (_a) { ++ return [2 /*return*/]; ++ }); }); ++ }, _a), true); ++ return [3 /*break*/, 6]; ++ case 2: ++ e_18 = _b.sent(); ++ env_18.error = e_18; ++ env_18.hasError = true; ++ return [3 /*break*/, 6]; ++ case 3: ++ result_18 = __disposeResources(env_18); ++ if (!result_18) return [3 /*break*/, 5]; ++ return [4 /*yield*/, result_18]; ++ case 4: ++ _b.sent(); ++ _b.label = 5; ++ case 5: return [7 /*endfinally*/]; ++ case 6: return [2 /*return*/]; ++ } ++ }); ++ }); }; ++ } ++ C1.prototype.am = function () { ++ return __awaiter(this, void 0, void 0, function () { ++ var env_19, d13, e_19, result_19; ++ var _a; ++ return __generator(this, function (_b) { ++ switch (_b.label) { ++ case 0: ++ env_19 = { stack: [], error: void 0, hasError: false }; ++ _b.label = 1; ++ case 1: ++ _b.trys.push([1, 3, 4, 7]); ++ d13 = __addDisposableResource(env_19, (_a = {}, _a[Symbol.asyncDispose] = function () { ++ return __awaiter(this, void 0, void 0, function () { return __generator(this, function (_a) { ++ return [2 /*return*/]; ++ }); }); ++ }, _a), true); ++ return [4 /*yield*/, null]; ++ case 2: ++ _b.sent(); ++ return [3 /*break*/, 7]; ++ case 3: ++ e_19 = _b.sent(); ++ env_19.error = e_19; ++ env_19.hasError = true; ++ return [3 /*break*/, 7]; ++ case 4: ++ result_19 = __disposeResources(env_19); ++ if (!result_19) return [3 /*break*/, 6]; ++ return [4 /*yield*/, result_19]; ++ case 5: ++ _b.sent(); ++ _b.label = 6; ++ case 6: return [7 /*endfinally*/]; ++ case 7: return [2 /*return*/]; ++ } ++ }); ++ }); ++ }; ++ C1.prototype.ag = function () { ++ return __asyncGenerator(this, arguments, function ag_2() { ++ var env_20, d15, e_20, result_20; ++ var _a; ++ return __generator(this, function (_b) { ++ switch (_b.label) { ++ case 0: ++ env_20 = { stack: [], error: void 0, hasError: false }; ++ _b.label = 1; ++ case 1: ++ _b.trys.push([1, 5, 6, 9]); ++ d15 = __addDisposableResource(env_20, (_a = {}, _a[Symbol.asyncDispose] = function () { ++ return __awaiter(this, void 0, void 0, function () { return __generator(this, function (_a) { ++ return [2 /*return*/]; ++ }); }); ++ }, _a), true); ++ return [4 /*yield*/, __await(void 0)]; ++ case 2: return [4 /*yield*/, _b.sent()]; ++ case 3: ++ _b.sent(); ++ return [4 /*yield*/, __await(null)]; ++ case 4: ++ _b.sent(); ++ return [3 /*break*/, 9]; ++ case 5: ++ e_20 = _b.sent(); ++ env_20.error = e_20; ++ env_20.hasError = true; ++ return [3 /*break*/, 9]; ++ case 6: ++ result_20 = __disposeResources(env_20); ++ if (!result_20) return [3 /*break*/, 8]; ++ return [4 /*yield*/, __await(result_20)]; ++ case 7: ++ _b.sent(); ++ _b.label = 8; ++ case 8: return [7 /*endfinally*/]; ++ case 9: return [2 /*return*/]; ++ } ++ }); ++ }); ++ }; ++ return C1; ++ }()); ++ { ++ var env_3 = { stack: [], error: void 0, hasError: false }; ++ try { ++ var d19 = __addDisposableResource(env_3, (_b = {}, _b[Symbol.asyncDispose] = function () { ++ return __awaiter(this, void 0, void 0, function () { return __generator(this, function (_a) { ++ return [2 /*return*/]; ++ }); }); ++ }, _b), true); ++ } ++ catch (e_1) { ++ env_3.error = e_1; ++ env_3.hasError = true; ++ } ++ finally { ++ var result_1 = __disposeResources(env_3); ++ if (result_1) ++ await result_1; ++ } ++ } ++ env_1 = { stack: [], error: void 0, hasError: false }; ++ try { ++ switch (Math.random()) { ++ case 0: ++ var d20 = __addDisposableResource(env_1, (_c = {}, _c[Symbol.asyncDispose] = function () { ++ return __awaiter(this, void 0, void 0, function () { return __generator(this, function (_a) { ++ return [2 /*return*/]; ++ }); }); ++ }, _c), true); ++ break; ++ case 1: ++ var d21 = __addDisposableResource(env_1, (_d = {}, _d[Symbol.asyncDispose] = function () { ++ return __awaiter(this, void 0, void 0, function () { return __generator(this, function (_a) { ++ return [2 /*return*/]; ++ }); }); ++ }, _d), true); ++ break; ++ } ++ } ++ catch (e_2) { ++ env_1.error = e_2; ++ env_1.hasError = true; ++ } ++ finally { ++ var result_2 = __disposeResources(env_1); ++ if (result_2) ++ await result_2; ++ } ++ if (true) { ++ var env_4 = { stack: [], error: void 0, hasError: false }; ++ try { ++ switch (0) { ++ case 0: ++ var d22 = __addDisposableResource(env_4, (_e = {}, _e[Symbol.asyncDispose] = function () { ++ return __awaiter(this, void 0, void 0, function () { return __generator(this, function (_a) { ++ return [2 /*return*/]; ++ }); }); ++ }, _e), true); ++ break; ++ } ++ } ++ catch (e_3) { ++ env_4.error = e_3; ++ env_4.hasError = true; ++ } ++ finally { ++ var result_3 = __disposeResources(env_4); ++ if (result_3) ++ await result_3; ++ } ++ } ++ try { ++ var env_5 = { stack: [], error: void 0, hasError: false }; ++ try { ++ var d23 = __addDisposableResource(env_5, (_f = {}, _f[Symbol.asyncDispose] = function () { ++ return __awaiter(this, void 0, void 0, function () { return __generator(this, function (_a) { ++ return [2 /*return*/]; ++ }); }); ++ }, _f), true); ++ } ++ catch (e_4) { ++ env_5.error = e_4; ++ env_5.hasError = true; ++ } ++ finally { ++ var result_4 = __disposeResources(env_5); ++ if (result_4) ++ await result_4; ++ } ++ } ++ catch (_r) { ++ var env_6 = { stack: [], error: void 0, hasError: false }; ++ try { ++ var d24 = __addDisposableResource(env_6, (_g = {}, _g[Symbol.asyncDispose] = function () { ++ return __awaiter(this, void 0, void 0, function () { return __generator(this, function (_a) { ++ return [2 /*return*/]; ++ }); }); ++ }, _g), true); ++ } ++ catch (e_5) { ++ env_6.error = e_5; ++ env_6.hasError = true; ++ } ++ finally { ++ var result_5 = __disposeResources(env_6); ++ if (result_5) ++ await result_5; ++ } ++ } ++ finally { ++ var env_7 = { stack: [], error: void 0, hasError: false }; ++ try { ++ var d25 = __addDisposableResource(env_7, (_h = {}, _h[Symbol.asyncDispose] = function () { ++ return __awaiter(this, void 0, void 0, function () { return __generator(this, function (_a) { ++ return [2 /*return*/]; ++ }); }); ++ }, _h), true); ++ } ++ catch (e_6) { ++ env_7.error = e_6; ++ env_7.hasError = true; ++ } ++ finally { ++ var result_6 = __disposeResources(env_7); ++ if (result_6) ++ await result_6; ++ } ++ } ++ if (true) { ++ var env_8 = { stack: [], error: void 0, hasError: false }; ++ try { ++ var d26 = __addDisposableResource(env_8, (_j = {}, _j[Symbol.asyncDispose] = function () { ++ return __awaiter(this, void 0, void 0, function () { return __generator(this, function (_a) { ++ return [2 /*return*/]; ++ }); }); ++ }, _j), true); ++ } ++ catch (e_7) { ++ env_8.error = e_7; ++ env_8.hasError = true; ++ } ++ finally { ++ var result_7 = __disposeResources(env_8); ++ if (result_7) ++ await result_7; ++ } ++ } ++ else { ++ var env_9 = { stack: [], error: void 0, hasError: false }; ++ try { ++ var d27 = __addDisposableResource(env_9, (_k = {}, _k[Symbol.asyncDispose] = function () { ++ return __awaiter(this, void 0, void 0, function () { return __generator(this, function (_a) { ++ return [2 /*return*/]; ++ }); }); ++ }, _k), true); ++ } ++ catch (e_8) { ++ env_9.error = e_8; ++ env_9.hasError = true; ++ } ++ finally { ++ var result_8 = __disposeResources(env_9); ++ if (result_8) ++ await result_8; ++ } ++ } ++ while (true) { ++ var env_10 = { stack: [], error: void 0, hasError: false }; ++ try { ++ var d28 = __addDisposableResource(env_10, (_l = {}, _l[Symbol.asyncDispose] = function () { ++ return __awaiter(this, void 0, void 0, function () { return __generator(this, function (_a) { ++ return [2 /*return*/]; ++ }); }); ++ }, _l), true); ++ break; ++ } ++ catch (e_9) { ++ env_10.error = e_9; ++ env_10.hasError = true; ++ } ++ finally { ++ var result_9 = __disposeResources(env_10); ++ if (result_9) ++ await result_9; ++ } ++ } ++ do { ++ var env_11 = { stack: [], error: void 0, hasError: false }; ++ try { ++ var d29 = __addDisposableResource(env_11, (_m = {}, _m[Symbol.asyncDispose] = function () { ++ return __awaiter(this, void 0, void 0, function () { return __generator(this, function (_a) { ++ return [2 /*return*/]; ++ }); }); ++ }, _m), true); ++ break; ++ } ++ catch (e_10) { ++ env_11.error = e_10; ++ env_11.hasError = true; ++ } ++ finally { ++ var result_10 = __disposeResources(env_11); ++ if (result_10) ++ await result_10; ++ } ++ } while (true); ++ for (;;) { ++ var env_12 = { stack: [], error: void 0, hasError: false }; ++ try { ++ var d30 = __addDisposableResource(env_12, (_o = {}, _o[Symbol.asyncDispose] = function () { ++ return __awaiter(this, void 0, void 0, function () { return __generator(this, function (_a) { ++ return [2 /*return*/]; ++ }); }); ++ }, _o), true); ++ break; ++ } ++ catch (e_11) { ++ env_12.error = e_11; ++ env_12.hasError = true; ++ } ++ finally { ++ var result_11 = __disposeResources(env_12); ++ if (result_11) ++ await result_11; ++ } ++ } ++ for (var x in {}) { ++ var env_13 = { stack: [], error: void 0, hasError: false }; ++ try { ++ var d31 = __addDisposableResource(env_13, (_p = {}, _p[Symbol.asyncDispose] = function () { ++ return __awaiter(this, void 0, void 0, function () { return __generator(this, function (_a) { ++ return [2 /*return*/]; ++ }); }); ++ }, _p), true); ++ } ++ catch (e_12) { ++ env_13.error = e_12; ++ env_13.hasError = true; ++ } ++ finally { ++ var result_12 = __disposeResources(env_13); ++ if (result_12) ++ await result_12; ++ } ++ } ++ for (var _i = 0, _s = []; _i < _s.length; _i++) { ++ var x = _s[_i]; ++ var env_14 = { stack: [], error: void 0, hasError: false }; ++ try { ++ var d32 = __addDisposableResource(env_14, (_q = {}, _q[Symbol.asyncDispose] = function () { ++ return __awaiter(this, void 0, void 0, function () { return __generator(this, function (_a) { ++ return [2 /*return*/]; ++ }); }); ++ }, _q), true); ++ } ++ catch (e_13) { ++ env_14.error = e_13; ++ env_14.hasError = true; ++ } ++ finally { ++ var result_13 = __disposeResources(env_14); ++ if (result_13) ++ await result_13; ++ } ++ } ++} ++catch (e_14) { ++ env_2.error = e_14; ++ env_2.hasError = true; ++} ++finally { ++ var result_14 = __disposeResources(env_2); ++ if (result_14) ++ await result_14; ++} ++export {}; +diff --git a/tests/baselines/reference/awaitUsingDeclarations.1(target=esnext).js b/tests/baselines/reference/awaitUsingDeclarations.1(target=esnext).js +new file mode 100644 +index 000000000..66107e393 +--- /dev/null ++++ b/tests/baselines/reference/awaitUsingDeclarations.1(target=esnext).js +@@ -0,0 +1,180 @@ ++//// [tests/cases/conformance/statements/VariableStatements/usingDeclarations/awaitUsingDeclarations.1.ts] //// ++ ++//// [awaitUsingDeclarations.1.ts] ++await using d1 = { async [Symbol.asyncDispose]() {} }; ++ ++async function af() { ++ await using d3 = { async [Symbol.asyncDispose]() {} }; ++ await null; ++} ++ ++async function * ag() { ++ await using d5 = { async [Symbol.asyncDispose]() {} }; ++ yield; ++ await null; ++} ++ ++const a = async () => { ++ await using d6 = { async [Symbol.asyncDispose]() {} }; ++}; ++ ++class C1 { ++ a = async () => { ++ await using d7 = { async [Symbol.asyncDispose]() {} }; ++ }; ++ ++ async am() { ++ await using d13 = { async [Symbol.asyncDispose]() {} }; ++ await null; ++ } ++ ++ async * ag() { ++ await using d15 = { async [Symbol.asyncDispose]() {} }; ++ yield; ++ await null; ++ } ++} ++ ++{ ++ await using d19 = { async [Symbol.asyncDispose]() {} }; ++} ++ ++switch (Math.random()) { ++ case 0: ++ await using d20 = { async [Symbol.asyncDispose]() {} }; ++ break; ++ ++ case 1: ++ await using d21 = { async [Symbol.asyncDispose]() {} }; ++ break; ++} ++ ++if (true) ++ switch (0) { ++ case 0: ++ await using d22 = { async [Symbol.asyncDispose]() {} }; ++ break; ++ } ++ ++try { ++ await using d23 = { async [Symbol.asyncDispose]() {} }; ++} ++catch { ++ await using d24 = { async [Symbol.asyncDispose]() {} }; ++} ++finally { ++ await using d25 = { async [Symbol.asyncDispose]() {} }; ++} ++ ++if (true) { ++ await using d26 = { async [Symbol.asyncDispose]() {} }; ++} ++else { ++ await using d27 = { async [Symbol.asyncDispose]() {} }; ++} ++ ++while (true) { ++ await using d28 = { async [Symbol.asyncDispose]() {} }; ++ break; ++} ++ ++do { ++ await using d29 = { async [Symbol.asyncDispose]() {} }; ++ break; ++} ++while (true); ++ ++for (;;) { ++ await using d30 = { async [Symbol.asyncDispose]() {} }; ++ break; ++} ++ ++for (const x in {}) { ++ await using d31 = { async [Symbol.asyncDispose]() {} }; ++} ++ ++for (const x of []) { ++ await using d32 = { async [Symbol.asyncDispose]() {} }; ++} ++ ++export {}; ++ ++//// [awaitUsingDeclarations.1.js] ++await using d1 = { async [Symbol.asyncDispose]() { } }; ++async function af() { ++ await using d3 = { async [Symbol.asyncDispose]() { } }; ++ await null; ++} ++async function* ag() { ++ await using d5 = { async [Symbol.asyncDispose]() { } }; ++ yield; ++ await null; ++} ++const a = async () => { ++ await using d6 = { async [Symbol.asyncDispose]() { } }; ++}; ++class C1 { ++ a = async () => { ++ await using d7 = { async [Symbol.asyncDispose]() { } }; ++ }; ++ async am() { ++ await using d13 = { async [Symbol.asyncDispose]() { } }; ++ await null; ++ } ++ async *ag() { ++ await using d15 = { async [Symbol.asyncDispose]() { } }; ++ yield; ++ await null; ++ } ++} ++{ ++ await using d19 = { async [Symbol.asyncDispose]() { } }; ++} ++switch (Math.random()) { ++ case 0: ++ await using d20 = { async [Symbol.asyncDispose]() { } }; ++ break; ++ case 1: ++ await using d21 = { async [Symbol.asyncDispose]() { } }; ++ break; ++} ++if (true) ++ switch (0) { ++ case 0: ++ await using d22 = { async [Symbol.asyncDispose]() { } }; ++ break; ++ } ++try { ++ await using d23 = { async [Symbol.asyncDispose]() { } }; ++} ++catch { ++ await using d24 = { async [Symbol.asyncDispose]() { } }; ++} ++finally { ++ await using d25 = { async [Symbol.asyncDispose]() { } }; ++} ++if (true) { ++ await using d26 = { async [Symbol.asyncDispose]() { } }; ++} ++else { ++ await using d27 = { async [Symbol.asyncDispose]() { } }; ++} ++while (true) { ++ await using d28 = { async [Symbol.asyncDispose]() { } }; ++ break; ++} ++do { ++ await using d29 = { async [Symbol.asyncDispose]() { } }; ++ break; ++} while (true); ++for (;;) { ++ await using d30 = { async [Symbol.asyncDispose]() { } }; ++ break; ++} ++for (const x in {}) { ++ await using d31 = { async [Symbol.asyncDispose]() { } }; ++} ++for (const x of []) { ++ await using d32 = { async [Symbol.asyncDispose]() { } }; ++} ++export {}; +diff --git a/tests/baselines/reference/awaitUsingDeclarations.10.errors.txt b/tests/baselines/reference/awaitUsingDeclarations.10.errors.txt +new file mode 100644 +index 000000000..897a5a03a +--- /dev/null ++++ b/tests/baselines/reference/awaitUsingDeclarations.10.errors.txt +@@ -0,0 +1,12 @@ ++awaitUsingDeclarations.10.ts(5,12): error TS1156: 'await using' declarations can only be declared inside a block. ++ ++ ++==== awaitUsingDeclarations.10.ts (1 errors) ==== ++ export {}; ++ ++ declare var x: any; ++ async function f() { ++ if (x) await using a = null; ++ ~~~~~~~~~~~~~~~~~~~~~ ++!!! error TS1156: 'await using' declarations can only be declared inside a block. ++ } +\ No newline at end of file +diff --git a/tests/baselines/reference/awaitUsingDeclarations.10.js b/tests/baselines/reference/awaitUsingDeclarations.10.js +new file mode 100644 +index 000000000..6ddcffab8 +--- /dev/null ++++ b/tests/baselines/reference/awaitUsingDeclarations.10.js +@@ -0,0 +1,16 @@ ++//// [tests/cases/conformance/statements/VariableStatements/usingDeclarations/awaitUsingDeclarations.10.ts] //// ++ ++//// [awaitUsingDeclarations.10.ts] ++export {}; ++ ++declare var x: any; ++async function f() { ++ if (x) await using a = null; ++} ++ ++//// [awaitUsingDeclarations.10.js] ++async function f() { ++ if (x) ++ await using a = null; ++} ++export {}; +diff --git a/tests/baselines/reference/awaitUsingDeclarations.11.errors.txt b/tests/baselines/reference/awaitUsingDeclarations.11.errors.txt +new file mode 100644 +index 000000000..51de3ea07 +--- /dev/null ++++ b/tests/baselines/reference/awaitUsingDeclarations.11.errors.txt +@@ -0,0 +1,12 @@ ++awaitUsingDeclarations.11.ts(1,1): error TS1495: 'export' modifier cannot appear on an 'await using' declaration. ++awaitUsingDeclarations.11.ts(2,1): error TS1495: 'declare' modifier cannot appear on an 'await using' declaration. ++ ++ ++==== awaitUsingDeclarations.11.ts (2 errors) ==== ++ export await using x = null; ++ ~~~~~~ ++!!! error TS1495: 'export' modifier cannot appear on an 'await using' declaration. ++ declare await using y: null; ++ ~~~~~~~ ++!!! error TS1495: 'declare' modifier cannot appear on an 'await using' declaration. ++ +\ No newline at end of file +diff --git a/tests/baselines/reference/awaitUsingDeclarations.11.js b/tests/baselines/reference/awaitUsingDeclarations.11.js +new file mode 100644 +index 000000000..76087f4f9 +--- /dev/null ++++ b/tests/baselines/reference/awaitUsingDeclarations.11.js +@@ -0,0 +1,9 @@ ++//// [tests/cases/conformance/statements/VariableStatements/usingDeclarations/awaitUsingDeclarations.11.ts] //// ++ ++//// [awaitUsingDeclarations.11.ts] ++export await using x = null; ++declare await using y: null; ++ ++ ++//// [awaitUsingDeclarations.11.js] ++export await using x = null; +diff --git a/tests/baselines/reference/awaitUsingDeclarations.12.errors.txt b/tests/baselines/reference/awaitUsingDeclarations.12.errors.txt +new file mode 100644 +index 000000000..623aecbad +--- /dev/null ++++ b/tests/baselines/reference/awaitUsingDeclarations.12.errors.txt +@@ -0,0 +1,9 @@ ++awaitUsingDeclarations.12.ts(2,21): error TS2851: The initializer of an 'await using' declaration must be either an object with a '[Symbol.asyncDispose]()' or '[Symbol.dispose]()' method, or be 'null' or 'undefined'. ++ ++ ++==== awaitUsingDeclarations.12.ts (1 errors) ==== ++ async function f() { ++ await using x = {}; ++ ~~ ++!!! error TS2851: The initializer of an 'await using' declaration must be either an object with a '[Symbol.asyncDispose]()' or '[Symbol.dispose]()' method, or be 'null' or 'undefined'. ++ } +\ No newline at end of file +diff --git a/tests/baselines/reference/awaitUsingDeclarations.12.js b/tests/baselines/reference/awaitUsingDeclarations.12.js +new file mode 100644 +index 000000000..32de98938 +--- /dev/null ++++ b/tests/baselines/reference/awaitUsingDeclarations.12.js +@@ -0,0 +1,11 @@ ++//// [tests/cases/conformance/statements/VariableStatements/usingDeclarations/awaitUsingDeclarations.12.ts] //// ++ ++//// [awaitUsingDeclarations.12.ts] ++async function f() { ++ await using x = {}; ++} ++ ++//// [awaitUsingDeclarations.12.js] ++async function f() { ++ await using x = {}; ++} +diff --git a/tests/baselines/reference/awaitUsingDeclarations.13.errors.txt b/tests/baselines/reference/awaitUsingDeclarations.13.errors.txt +new file mode 100644 +index 000000000..abe9121a8 +--- /dev/null ++++ b/tests/baselines/reference/awaitUsingDeclarations.13.errors.txt +@@ -0,0 +1,15 @@ ++awaitUsingDeclarations.13.ts(1,1): error TS2853: 'await using' statements are only allowed at the top level of a file when that file is a module, but this file has no imports or exports. Consider adding an empty 'export {}' to make this file a module. ++awaitUsingDeclarations.13.ts(4,5): error TS2852: 'await using' statements are only allowed within async functions and at the top levels of modules. ++ ++ ++==== awaitUsingDeclarations.13.ts (2 errors) ==== ++ await using x = null; ++ ~~~~~ ++!!! error TS2853: 'await using' statements are only allowed at the top level of a file when that file is a module, but this file has no imports or exports. Consider adding an empty 'export {}' to make this file a module. ++ ++ function f() { ++ await using x = null; ++ ~~~~~ ++!!! error TS2852: 'await using' statements are only allowed within async functions and at the top levels of modules. ++!!! related TS1356 awaitUsingDeclarations.13.ts:3:10: Did you mean to mark this function as 'async'? ++ } +\ No newline at end of file +diff --git a/tests/baselines/reference/awaitUsingDeclarations.13.js b/tests/baselines/reference/awaitUsingDeclarations.13.js +new file mode 100644 +index 000000000..f8a1d89e9 +--- /dev/null ++++ b/tests/baselines/reference/awaitUsingDeclarations.13.js +@@ -0,0 +1,14 @@ ++//// [tests/cases/conformance/statements/VariableStatements/usingDeclarations/awaitUsingDeclarations.13.ts] //// ++ ++//// [awaitUsingDeclarations.13.ts] ++await using x = null; ++ ++function f() { ++ await using x = null; ++} ++ ++//// [awaitUsingDeclarations.13.js] ++await using x = null; ++function f() { ++ await using x = null; ++} +diff --git a/tests/baselines/reference/awaitUsingDeclarations.14.errors.txt b/tests/baselines/reference/awaitUsingDeclarations.14.errors.txt +new file mode 100644 +index 000000000..bffdf3a17 +--- /dev/null ++++ b/tests/baselines/reference/awaitUsingDeclarations.14.errors.txt +@@ -0,0 +1,18 @@ ++awaitUsingDeclarations.14.ts(3,9): error TS18054: 'await using' statements cannot be used inside a class static block. ++awaitUsingDeclarations.14.ts(5,13): error TS18054: 'await using' statements cannot be used inside a class static block. ++ ++ ++==== awaitUsingDeclarations.14.ts (2 errors) ==== ++ class C { ++ static { ++ await using x = null; ++ ~~~~~~~~~~~~~~~~~~~~ ++!!! error TS18054: 'await using' statements cannot be used inside a class static block. ++ { ++ await using y = null; ++ ~~~~~~~~~~~~~~~~~~~~ ++!!! error TS18054: 'await using' statements cannot be used inside a class static block. ++ } ++ } ++ } ++ +\ No newline at end of file +diff --git a/tests/baselines/reference/awaitUsingDeclarations.14.js b/tests/baselines/reference/awaitUsingDeclarations.14.js +new file mode 100644 +index 000000000..223c913e7 +--- /dev/null ++++ b/tests/baselines/reference/awaitUsingDeclarations.14.js +@@ -0,0 +1,22 @@ ++//// [tests/cases/conformance/statements/VariableStatements/usingDeclarations/awaitUsingDeclarations.14.ts] //// ++ ++//// [awaitUsingDeclarations.14.ts] ++class C { ++ static { ++ await using x = null; ++ { ++ await using y = null; ++ } ++ } ++} ++ ++ ++//// [awaitUsingDeclarations.14.js] ++class C { ++ static { ++ await using x = null; ++ { ++ await using y = null; ++ } ++ } ++} +diff --git a/tests/baselines/reference/awaitUsingDeclarations.15.js b/tests/baselines/reference/awaitUsingDeclarations.15.js +new file mode 100644 +index 000000000..af2051299 +--- /dev/null ++++ b/tests/baselines/reference/awaitUsingDeclarations.15.js +@@ -0,0 +1,11 @@ ++//// [tests/cases/conformance/statements/VariableStatements/usingDeclarations/awaitUsingDeclarations.15.ts] //// ++ ++//// [awaitUsingDeclarations.15.ts] ++async function f() { ++ await using _ = { async [Symbol.asyncDispose]() {} }; ++} ++ ++//// [awaitUsingDeclarations.15.js] ++async function f() { ++ await using _ = { async [Symbol.asyncDispose]() { } }; ++} +diff --git a/tests/baselines/reference/awaitUsingDeclarations.2(target=es2015).errors.txt b/tests/baselines/reference/awaitUsingDeclarations.2(target=es2015).errors.txt +new file mode 100644 +index 000000000..b6d2d529f +--- /dev/null ++++ b/tests/baselines/reference/awaitUsingDeclarations.2(target=es2015).errors.txt +@@ -0,0 +1,12 @@ ++awaitUsingDeclarations.2.ts(2,5): error TS2854: Top-level 'await using' statements are only allowed when the 'module' option is set to 'es2022', 'esnext', 'system', 'node16', or 'nodenext', and the 'target' option is set to 'es2017' or higher. ++ ++ ++==== awaitUsingDeclarations.2.ts (1 errors) ==== ++ { ++ await using d1 = { async [Symbol.asyncDispose]() {} }, ++ ~~~~~ ++!!! error TS2854: Top-level 'await using' statements are only allowed when the 'module' option is set to 'es2022', 'esnext', 'system', 'node16', or 'nodenext', and the 'target' option is set to 'es2017' or higher. ++ d2 = { async [Symbol.asyncDispose]() {} }; ++ } ++ ++ export {}; +\ No newline at end of file +diff --git a/tests/baselines/reference/awaitUsingDeclarations.2(target=es2015).js b/tests/baselines/reference/awaitUsingDeclarations.2(target=es2015).js +new file mode 100644 +index 000000000..03565e6b3 +--- /dev/null ++++ b/tests/baselines/reference/awaitUsingDeclarations.2(target=es2015).js +@@ -0,0 +1,85 @@ ++//// [tests/cases/conformance/statements/VariableStatements/usingDeclarations/awaitUsingDeclarations.2.ts] //// ++ ++//// [awaitUsingDeclarations.2.ts] ++{ ++ await using d1 = { async [Symbol.asyncDispose]() {} }, ++ d2 = { async [Symbol.asyncDispose]() {} }; ++} ++ ++export {}; ++ ++//// [awaitUsingDeclarations.2.js] ++var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { ++ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } ++ return new (P || (P = Promise))(function (resolve, reject) { ++ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } ++ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } ++ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } ++ step((generator = generator.apply(thisArg, _arguments || [])).next()); ++ }); ++}; ++var __addDisposableResource = (this && this.__addDisposableResource) || function (env, value, async) { ++ if (value !== null && value !== void 0) { ++ if (typeof value !== "object") throw new TypeError("Object expected."); ++ var dispose; ++ if (async) { ++ if (!Symbol.asyncDispose) throw new TypeError("Symbol.asyncDispose is not defined."); ++ dispose = value[Symbol.asyncDispose]; ++ } ++ if (dispose === void 0) { ++ if (!Symbol.dispose) throw new TypeError("Symbol.dispose is not defined."); ++ dispose = value[Symbol.dispose]; ++ } ++ if (typeof dispose !== "function") throw new TypeError("Object not disposable."); ++ env.stack.push({ value: value, dispose: dispose, async: async }); ++ } ++ else if (async) { ++ env.stack.push({ async: true }); ++ } ++ return value; ++}; ++var __disposeResources = (this && this.__disposeResources) || (function (SuppressedError) { ++ return function (env) { ++ function fail(e) { ++ env.error = env.hasError ? new SuppressedError(e, env.error, "An error was suppressed during disposal.") : e; ++ env.hasError = true; ++ } ++ function next() { ++ while (env.stack.length) { ++ var rec = env.stack.pop(); ++ try { ++ var result = rec.dispose && rec.dispose.call(rec.value); ++ if (rec.async) return Promise.resolve(result).then(next, function(e) { fail(e); return next(); }); ++ } ++ catch (e) { ++ fail(e); ++ } ++ } ++ if (env.hasError) throw env.error; ++ } ++ return next(); ++ }; ++})(typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) { ++ var e = new Error(message); ++ return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e; ++}); ++{ ++ const env_1 = { stack: [], error: void 0, hasError: false }; ++ try { ++ const d1 = __addDisposableResource(env_1, { [Symbol.asyncDispose]() { ++ return __awaiter(this, void 0, void 0, function* () { }); ++ } }, true), d2 = __addDisposableResource(env_1, { [Symbol.asyncDispose]() { ++ return __awaiter(this, void 0, void 0, function* () { }); ++ } }, true); ++ } ++ catch (e_1) { ++ env_1.error = e_1; ++ env_1.hasError = true; ++ } ++ finally { ++ const result_1 = __disposeResources(env_1); ++ if (result_1) ++ await result_1; ++ } ++} ++export {}; +diff --git a/tests/baselines/reference/awaitUsingDeclarations.2(target=es2017).js b/tests/baselines/reference/awaitUsingDeclarations.2(target=es2017).js +new file mode 100644 +index 000000000..ab37b86fc +--- /dev/null ++++ b/tests/baselines/reference/awaitUsingDeclarations.2(target=es2017).js +@@ -0,0 +1,72 @@ ++//// [tests/cases/conformance/statements/VariableStatements/usingDeclarations/awaitUsingDeclarations.2.ts] //// ++ ++//// [awaitUsingDeclarations.2.ts] ++{ ++ await using d1 = { async [Symbol.asyncDispose]() {} }, ++ d2 = { async [Symbol.asyncDispose]() {} }; ++} ++ ++export {}; ++ ++//// [awaitUsingDeclarations.2.js] ++var __addDisposableResource = (this && this.__addDisposableResource) || function (env, value, async) { ++ if (value !== null && value !== void 0) { ++ if (typeof value !== "object") throw new TypeError("Object expected."); ++ var dispose; ++ if (async) { ++ if (!Symbol.asyncDispose) throw new TypeError("Symbol.asyncDispose is not defined."); ++ dispose = value[Symbol.asyncDispose]; ++ } ++ if (dispose === void 0) { ++ if (!Symbol.dispose) throw new TypeError("Symbol.dispose is not defined."); ++ dispose = value[Symbol.dispose]; ++ } ++ if (typeof dispose !== "function") throw new TypeError("Object not disposable."); ++ env.stack.push({ value: value, dispose: dispose, async: async }); ++ } ++ else if (async) { ++ env.stack.push({ async: true }); ++ } ++ return value; ++}; ++var __disposeResources = (this && this.__disposeResources) || (function (SuppressedError) { ++ return function (env) { ++ function fail(e) { ++ env.error = env.hasError ? new SuppressedError(e, env.error, "An error was suppressed during disposal.") : e; ++ env.hasError = true; ++ } ++ function next() { ++ while (env.stack.length) { ++ var rec = env.stack.pop(); ++ try { ++ var result = rec.dispose && rec.dispose.call(rec.value); ++ if (rec.async) return Promise.resolve(result).then(next, function(e) { fail(e); return next(); }); ++ } ++ catch (e) { ++ fail(e); ++ } ++ } ++ if (env.hasError) throw env.error; ++ } ++ return next(); ++ }; ++})(typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) { ++ var e = new Error(message); ++ return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e; ++}); ++{ ++ const env_1 = { stack: [], error: void 0, hasError: false }; ++ try { ++ const d1 = __addDisposableResource(env_1, { async [Symbol.asyncDispose]() { } }, true), d2 = __addDisposableResource(env_1, { async [Symbol.asyncDispose]() { } }, true); ++ } ++ catch (e_1) { ++ env_1.error = e_1; ++ env_1.hasError = true; ++ } ++ finally { ++ const result_1 = __disposeResources(env_1); ++ if (result_1) ++ await result_1; ++ } ++} ++export {}; +diff --git a/tests/baselines/reference/awaitUsingDeclarations.2(target=es2022).js b/tests/baselines/reference/awaitUsingDeclarations.2(target=es2022).js +new file mode 100644 +index 000000000..ab37b86fc +--- /dev/null ++++ b/tests/baselines/reference/awaitUsingDeclarations.2(target=es2022).js +@@ -0,0 +1,72 @@ ++//// [tests/cases/conformance/statements/VariableStatements/usingDeclarations/awaitUsingDeclarations.2.ts] //// ++ ++//// [awaitUsingDeclarations.2.ts] ++{ ++ await using d1 = { async [Symbol.asyncDispose]() {} }, ++ d2 = { async [Symbol.asyncDispose]() {} }; ++} ++ ++export {}; ++ ++//// [awaitUsingDeclarations.2.js] ++var __addDisposableResource = (this && this.__addDisposableResource) || function (env, value, async) { ++ if (value !== null && value !== void 0) { ++ if (typeof value !== "object") throw new TypeError("Object expected."); ++ var dispose; ++ if (async) { ++ if (!Symbol.asyncDispose) throw new TypeError("Symbol.asyncDispose is not defined."); ++ dispose = value[Symbol.asyncDispose]; ++ } ++ if (dispose === void 0) { ++ if (!Symbol.dispose) throw new TypeError("Symbol.dispose is not defined."); ++ dispose = value[Symbol.dispose]; ++ } ++ if (typeof dispose !== "function") throw new TypeError("Object not disposable."); ++ env.stack.push({ value: value, dispose: dispose, async: async }); ++ } ++ else if (async) { ++ env.stack.push({ async: true }); ++ } ++ return value; ++}; ++var __disposeResources = (this && this.__disposeResources) || (function (SuppressedError) { ++ return function (env) { ++ function fail(e) { ++ env.error = env.hasError ? new SuppressedError(e, env.error, "An error was suppressed during disposal.") : e; ++ env.hasError = true; ++ } ++ function next() { ++ while (env.stack.length) { ++ var rec = env.stack.pop(); ++ try { ++ var result = rec.dispose && rec.dispose.call(rec.value); ++ if (rec.async) return Promise.resolve(result).then(next, function(e) { fail(e); return next(); }); ++ } ++ catch (e) { ++ fail(e); ++ } ++ } ++ if (env.hasError) throw env.error; ++ } ++ return next(); ++ }; ++})(typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) { ++ var e = new Error(message); ++ return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e; ++}); ++{ ++ const env_1 = { stack: [], error: void 0, hasError: false }; ++ try { ++ const d1 = __addDisposableResource(env_1, { async [Symbol.asyncDispose]() { } }, true), d2 = __addDisposableResource(env_1, { async [Symbol.asyncDispose]() { } }, true); ++ } ++ catch (e_1) { ++ env_1.error = e_1; ++ env_1.hasError = true; ++ } ++ finally { ++ const result_1 = __disposeResources(env_1); ++ if (result_1) ++ await result_1; ++ } ++} ++export {}; +diff --git a/tests/baselines/reference/awaitUsingDeclarations.2(target=es5).errors.txt b/tests/baselines/reference/awaitUsingDeclarations.2(target=es5).errors.txt +new file mode 100644 +index 000000000..b6d2d529f +--- /dev/null ++++ b/tests/baselines/reference/awaitUsingDeclarations.2(target=es5).errors.txt +@@ -0,0 +1,12 @@ ++awaitUsingDeclarations.2.ts(2,5): error TS2854: Top-level 'await using' statements are only allowed when the 'module' option is set to 'es2022', 'esnext', 'system', 'node16', or 'nodenext', and the 'target' option is set to 'es2017' or higher. ++ ++ ++==== awaitUsingDeclarations.2.ts (1 errors) ==== ++ { ++ await using d1 = { async [Symbol.asyncDispose]() {} }, ++ ~~~~~ ++!!! error TS2854: Top-level 'await using' statements are only allowed when the 'module' option is set to 'es2022', 'esnext', 'system', 'node16', or 'nodenext', and the 'target' option is set to 'es2017' or higher. ++ d2 = { async [Symbol.asyncDispose]() {} }; ++ } ++ ++ export {}; +\ No newline at end of file +diff --git a/tests/baselines/reference/awaitUsingDeclarations.2(target=es5).js b/tests/baselines/reference/awaitUsingDeclarations.2(target=es5).js +new file mode 100644 +index 000000000..e9a87c08a +--- /dev/null ++++ b/tests/baselines/reference/awaitUsingDeclarations.2(target=es5).js +@@ -0,0 +1,117 @@ ++//// [tests/cases/conformance/statements/VariableStatements/usingDeclarations/awaitUsingDeclarations.2.ts] //// ++ ++//// [awaitUsingDeclarations.2.ts] ++{ ++ await using d1 = { async [Symbol.asyncDispose]() {} }, ++ d2 = { async [Symbol.asyncDispose]() {} }; ++} ++ ++export {}; ++ ++//// [awaitUsingDeclarations.2.js] ++var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { ++ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } ++ return new (P || (P = Promise))(function (resolve, reject) { ++ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } ++ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } ++ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } ++ step((generator = generator.apply(thisArg, _arguments || [])).next()); ++ }); ++}; ++var __generator = (this && this.__generator) || function (thisArg, body) { ++ var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; ++ return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; ++ function verb(n) { return function (v) { return step([n, v]); }; } ++ function step(op) { ++ if (f) throw new TypeError("Generator is already executing."); ++ while (g && (g = 0, op[0] && (_ = 0)), _) try { ++ if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; ++ if (y = 0, t) op = [op[0] & 2, t.value]; ++ switch (op[0]) { ++ case 0: case 1: t = op; break; ++ case 4: _.label++; return { value: op[1], done: false }; ++ case 5: _.label++; y = op[1]; op = [0]; continue; ++ case 7: op = _.ops.pop(); _.trys.pop(); continue; ++ default: ++ if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } ++ if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } ++ if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } ++ if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } ++ if (t[2]) _.ops.pop(); ++ _.trys.pop(); continue; ++ } ++ op = body.call(thisArg, _); ++ } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } ++ if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; ++ } ++}; ++var __addDisposableResource = (this && this.__addDisposableResource) || function (env, value, async) { ++ if (value !== null && value !== void 0) { ++ if (typeof value !== "object") throw new TypeError("Object expected."); ++ var dispose; ++ if (async) { ++ if (!Symbol.asyncDispose) throw new TypeError("Symbol.asyncDispose is not defined."); ++ dispose = value[Symbol.asyncDispose]; ++ } ++ if (dispose === void 0) { ++ if (!Symbol.dispose) throw new TypeError("Symbol.dispose is not defined."); ++ dispose = value[Symbol.dispose]; ++ } ++ if (typeof dispose !== "function") throw new TypeError("Object not disposable."); ++ env.stack.push({ value: value, dispose: dispose, async: async }); ++ } ++ else if (async) { ++ env.stack.push({ async: true }); ++ } ++ return value; ++}; ++var __disposeResources = (this && this.__disposeResources) || (function (SuppressedError) { ++ return function (env) { ++ function fail(e) { ++ env.error = env.hasError ? new SuppressedError(e, env.error, "An error was suppressed during disposal.") : e; ++ env.hasError = true; ++ } ++ function next() { ++ while (env.stack.length) { ++ var rec = env.stack.pop(); ++ try { ++ var result = rec.dispose && rec.dispose.call(rec.value); ++ if (rec.async) return Promise.resolve(result).then(next, function(e) { fail(e); return next(); }); ++ } ++ catch (e) { ++ fail(e); ++ } ++ } ++ if (env.hasError) throw env.error; ++ } ++ return next(); ++ }; ++})(typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) { ++ var e = new Error(message); ++ return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e; ++}); ++var _a, _b; ++{ ++ var env_1 = { stack: [], error: void 0, hasError: false }; ++ try { ++ var d1 = __addDisposableResource(env_1, (_a = {}, _a[Symbol.asyncDispose] = function () { ++ return __awaiter(this, void 0, void 0, function () { return __generator(this, function (_a) { ++ return [2 /*return*/]; ++ }); }); ++ }, _a), true), d2 = __addDisposableResource(env_1, (_b = {}, _b[Symbol.asyncDispose] = function () { ++ return __awaiter(this, void 0, void 0, function () { return __generator(this, function (_a) { ++ return [2 /*return*/]; ++ }); }); ++ }, _b), true); ++ } ++ catch (e_1) { ++ env_1.error = e_1; ++ env_1.hasError = true; ++ } ++ finally { ++ var result_1 = __disposeResources(env_1); ++ if (result_1) ++ await result_1; ++ } ++} ++export {}; +diff --git a/tests/baselines/reference/awaitUsingDeclarations.2(target=esnext).js b/tests/baselines/reference/awaitUsingDeclarations.2(target=esnext).js +new file mode 100644 +index 000000000..081606105 +--- /dev/null ++++ b/tests/baselines/reference/awaitUsingDeclarations.2(target=esnext).js +@@ -0,0 +1,15 @@ ++//// [tests/cases/conformance/statements/VariableStatements/usingDeclarations/awaitUsingDeclarations.2.ts] //// ++ ++//// [awaitUsingDeclarations.2.ts] ++{ ++ await using d1 = { async [Symbol.asyncDispose]() {} }, ++ d2 = { async [Symbol.asyncDispose]() {} }; ++} ++ ++export {}; ++ ++//// [awaitUsingDeclarations.2.js] ++{ ++ await using d1 = { async [Symbol.asyncDispose]() { } }, d2 = { async [Symbol.asyncDispose]() { } }; ++} ++export {}; +diff --git a/tests/baselines/reference/awaitUsingDeclarations.3(target=es2015).errors.txt b/tests/baselines/reference/awaitUsingDeclarations.3(target=es2015).errors.txt +new file mode 100644 +index 000000000..955e5041b +--- /dev/null ++++ b/tests/baselines/reference/awaitUsingDeclarations.3(target=es2015).errors.txt +@@ -0,0 +1,14 @@ ++awaitUsingDeclarations.3.ts(2,5): error TS2854: Top-level 'await using' statements are only allowed when the 'module' option is set to 'es2022', 'esnext', 'system', 'node16', or 'nodenext', and the 'target' option is set to 'es2017' or higher. ++ ++ ++==== awaitUsingDeclarations.3.ts (1 errors) ==== ++ { ++ await using d1 = { async [Symbol.asyncDispose]() {} }, ++ ~~~~~ ++!!! error TS2854: Top-level 'await using' statements are only allowed when the 'module' option is set to 'es2022', 'esnext', 'system', 'node16', or 'nodenext', and the 'target' option is set to 'es2017' or higher. ++ d2 = null, ++ d3 = undefined, ++ d4 = { [Symbol.dispose]() {} }; ++ } ++ ++ export {}; +\ No newline at end of file +diff --git a/tests/baselines/reference/awaitUsingDeclarations.3(target=es2015).js b/tests/baselines/reference/awaitUsingDeclarations.3(target=es2015).js +new file mode 100644 +index 000000000..4b8939b21 +--- /dev/null ++++ b/tests/baselines/reference/awaitUsingDeclarations.3(target=es2015).js +@@ -0,0 +1,85 @@ ++//// [tests/cases/conformance/statements/VariableStatements/usingDeclarations/awaitUsingDeclarations.3.ts] //// ++ ++//// [awaitUsingDeclarations.3.ts] ++{ ++ await using d1 = { async [Symbol.asyncDispose]() {} }, ++ d2 = null, ++ d3 = undefined, ++ d4 = { [Symbol.dispose]() {} }; ++} ++ ++export {}; ++ ++//// [awaitUsingDeclarations.3.js] ++var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { ++ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } ++ return new (P || (P = Promise))(function (resolve, reject) { ++ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } ++ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } ++ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } ++ step((generator = generator.apply(thisArg, _arguments || [])).next()); ++ }); ++}; ++var __addDisposableResource = (this && this.__addDisposableResource) || function (env, value, async) { ++ if (value !== null && value !== void 0) { ++ if (typeof value !== "object") throw new TypeError("Object expected."); ++ var dispose; ++ if (async) { ++ if (!Symbol.asyncDispose) throw new TypeError("Symbol.asyncDispose is not defined."); ++ dispose = value[Symbol.asyncDispose]; ++ } ++ if (dispose === void 0) { ++ if (!Symbol.dispose) throw new TypeError("Symbol.dispose is not defined."); ++ dispose = value[Symbol.dispose]; ++ } ++ if (typeof dispose !== "function") throw new TypeError("Object not disposable."); ++ env.stack.push({ value: value, dispose: dispose, async: async }); ++ } ++ else if (async) { ++ env.stack.push({ async: true }); ++ } ++ return value; ++}; ++var __disposeResources = (this && this.__disposeResources) || (function (SuppressedError) { ++ return function (env) { ++ function fail(e) { ++ env.error = env.hasError ? new SuppressedError(e, env.error, "An error was suppressed during disposal.") : e; ++ env.hasError = true; ++ } ++ function next() { ++ while (env.stack.length) { ++ var rec = env.stack.pop(); ++ try { ++ var result = rec.dispose && rec.dispose.call(rec.value); ++ if (rec.async) return Promise.resolve(result).then(next, function(e) { fail(e); return next(); }); ++ } ++ catch (e) { ++ fail(e); ++ } ++ } ++ if (env.hasError) throw env.error; ++ } ++ return next(); ++ }; ++})(typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) { ++ var e = new Error(message); ++ return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e; ++}); ++{ ++ const env_1 = { stack: [], error: void 0, hasError: false }; ++ try { ++ const d1 = __addDisposableResource(env_1, { [Symbol.asyncDispose]() { ++ return __awaiter(this, void 0, void 0, function* () { }); ++ } }, true), d2 = __addDisposableResource(env_1, null, true), d3 = __addDisposableResource(env_1, undefined, true), d4 = __addDisposableResource(env_1, { [Symbol.dispose]() { } }, true); ++ } ++ catch (e_1) { ++ env_1.error = e_1; ++ env_1.hasError = true; ++ } ++ finally { ++ const result_1 = __disposeResources(env_1); ++ if (result_1) ++ await result_1; ++ } ++} ++export {}; +diff --git a/tests/baselines/reference/awaitUsingDeclarations.3(target=es2017).js b/tests/baselines/reference/awaitUsingDeclarations.3(target=es2017).js +new file mode 100644 +index 000000000..2edb5db73 +--- /dev/null ++++ b/tests/baselines/reference/awaitUsingDeclarations.3(target=es2017).js +@@ -0,0 +1,74 @@ ++//// [tests/cases/conformance/statements/VariableStatements/usingDeclarations/awaitUsingDeclarations.3.ts] //// ++ ++//// [awaitUsingDeclarations.3.ts] ++{ ++ await using d1 = { async [Symbol.asyncDispose]() {} }, ++ d2 = null, ++ d3 = undefined, ++ d4 = { [Symbol.dispose]() {} }; ++} ++ ++export {}; ++ ++//// [awaitUsingDeclarations.3.js] ++var __addDisposableResource = (this && this.__addDisposableResource) || function (env, value, async) { ++ if (value !== null && value !== void 0) { ++ if (typeof value !== "object") throw new TypeError("Object expected."); ++ var dispose; ++ if (async) { ++ if (!Symbol.asyncDispose) throw new TypeError("Symbol.asyncDispose is not defined."); ++ dispose = value[Symbol.asyncDispose]; ++ } ++ if (dispose === void 0) { ++ if (!Symbol.dispose) throw new TypeError("Symbol.dispose is not defined."); ++ dispose = value[Symbol.dispose]; ++ } ++ if (typeof dispose !== "function") throw new TypeError("Object not disposable."); ++ env.stack.push({ value: value, dispose: dispose, async: async }); ++ } ++ else if (async) { ++ env.stack.push({ async: true }); ++ } ++ return value; ++}; ++var __disposeResources = (this && this.__disposeResources) || (function (SuppressedError) { ++ return function (env) { ++ function fail(e) { ++ env.error = env.hasError ? new SuppressedError(e, env.error, "An error was suppressed during disposal.") : e; ++ env.hasError = true; ++ } ++ function next() { ++ while (env.stack.length) { ++ var rec = env.stack.pop(); ++ try { ++ var result = rec.dispose && rec.dispose.call(rec.value); ++ if (rec.async) return Promise.resolve(result).then(next, function(e) { fail(e); return next(); }); ++ } ++ catch (e) { ++ fail(e); ++ } ++ } ++ if (env.hasError) throw env.error; ++ } ++ return next(); ++ }; ++})(typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) { ++ var e = new Error(message); ++ return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e; ++}); ++{ ++ const env_1 = { stack: [], error: void 0, hasError: false }; ++ try { ++ const d1 = __addDisposableResource(env_1, { async [Symbol.asyncDispose]() { } }, true), d2 = __addDisposableResource(env_1, null, true), d3 = __addDisposableResource(env_1, undefined, true), d4 = __addDisposableResource(env_1, { [Symbol.dispose]() { } }, true); ++ } ++ catch (e_1) { ++ env_1.error = e_1; ++ env_1.hasError = true; ++ } ++ finally { ++ const result_1 = __disposeResources(env_1); ++ if (result_1) ++ await result_1; ++ } ++} ++export {}; +diff --git a/tests/baselines/reference/awaitUsingDeclarations.3(target=es2022).js b/tests/baselines/reference/awaitUsingDeclarations.3(target=es2022).js +new file mode 100644 +index 000000000..2edb5db73 +--- /dev/null ++++ b/tests/baselines/reference/awaitUsingDeclarations.3(target=es2022).js +@@ -0,0 +1,74 @@ ++//// [tests/cases/conformance/statements/VariableStatements/usingDeclarations/awaitUsingDeclarations.3.ts] //// ++ ++//// [awaitUsingDeclarations.3.ts] ++{ ++ await using d1 = { async [Symbol.asyncDispose]() {} }, ++ d2 = null, ++ d3 = undefined, ++ d4 = { [Symbol.dispose]() {} }; ++} ++ ++export {}; ++ ++//// [awaitUsingDeclarations.3.js] ++var __addDisposableResource = (this && this.__addDisposableResource) || function (env, value, async) { ++ if (value !== null && value !== void 0) { ++ if (typeof value !== "object") throw new TypeError("Object expected."); ++ var dispose; ++ if (async) { ++ if (!Symbol.asyncDispose) throw new TypeError("Symbol.asyncDispose is not defined."); ++ dispose = value[Symbol.asyncDispose]; ++ } ++ if (dispose === void 0) { ++ if (!Symbol.dispose) throw new TypeError("Symbol.dispose is not defined."); ++ dispose = value[Symbol.dispose]; ++ } ++ if (typeof dispose !== "function") throw new TypeError("Object not disposable."); ++ env.stack.push({ value: value, dispose: dispose, async: async }); ++ } ++ else if (async) { ++ env.stack.push({ async: true }); ++ } ++ return value; ++}; ++var __disposeResources = (this && this.__disposeResources) || (function (SuppressedError) { ++ return function (env) { ++ function fail(e) { ++ env.error = env.hasError ? new SuppressedError(e, env.error, "An error was suppressed during disposal.") : e; ++ env.hasError = true; ++ } ++ function next() { ++ while (env.stack.length) { ++ var rec = env.stack.pop(); ++ try { ++ var result = rec.dispose && rec.dispose.call(rec.value); ++ if (rec.async) return Promise.resolve(result).then(next, function(e) { fail(e); return next(); }); ++ } ++ catch (e) { ++ fail(e); ++ } ++ } ++ if (env.hasError) throw env.error; ++ } ++ return next(); ++ }; ++})(typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) { ++ var e = new Error(message); ++ return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e; ++}); ++{ ++ const env_1 = { stack: [], error: void 0, hasError: false }; ++ try { ++ const d1 = __addDisposableResource(env_1, { async [Symbol.asyncDispose]() { } }, true), d2 = __addDisposableResource(env_1, null, true), d3 = __addDisposableResource(env_1, undefined, true), d4 = __addDisposableResource(env_1, { [Symbol.dispose]() { } }, true); ++ } ++ catch (e_1) { ++ env_1.error = e_1; ++ env_1.hasError = true; ++ } ++ finally { ++ const result_1 = __disposeResources(env_1); ++ if (result_1) ++ await result_1; ++ } ++} ++export {}; +diff --git a/tests/baselines/reference/awaitUsingDeclarations.3(target=es5).errors.txt b/tests/baselines/reference/awaitUsingDeclarations.3(target=es5).errors.txt +new file mode 100644 +index 000000000..955e5041b +--- /dev/null ++++ b/tests/baselines/reference/awaitUsingDeclarations.3(target=es5).errors.txt +@@ -0,0 +1,14 @@ ++awaitUsingDeclarations.3.ts(2,5): error TS2854: Top-level 'await using' statements are only allowed when the 'module' option is set to 'es2022', 'esnext', 'system', 'node16', or 'nodenext', and the 'target' option is set to 'es2017' or higher. ++ ++ ++==== awaitUsingDeclarations.3.ts (1 errors) ==== ++ { ++ await using d1 = { async [Symbol.asyncDispose]() {} }, ++ ~~~~~ ++!!! error TS2854: Top-level 'await using' statements are only allowed when the 'module' option is set to 'es2022', 'esnext', 'system', 'node16', or 'nodenext', and the 'target' option is set to 'es2017' or higher. ++ d2 = null, ++ d3 = undefined, ++ d4 = { [Symbol.dispose]() {} }; ++ } ++ ++ export {}; +\ No newline at end of file +diff --git a/tests/baselines/reference/awaitUsingDeclarations.3(target=es5).js b/tests/baselines/reference/awaitUsingDeclarations.3(target=es5).js +new file mode 100644 +index 000000000..2cc2c25f5 +--- /dev/null ++++ b/tests/baselines/reference/awaitUsingDeclarations.3(target=es5).js +@@ -0,0 +1,115 @@ ++//// [tests/cases/conformance/statements/VariableStatements/usingDeclarations/awaitUsingDeclarations.3.ts] //// ++ ++//// [awaitUsingDeclarations.3.ts] ++{ ++ await using d1 = { async [Symbol.asyncDispose]() {} }, ++ d2 = null, ++ d3 = undefined, ++ d4 = { [Symbol.dispose]() {} }; ++} ++ ++export {}; ++ ++//// [awaitUsingDeclarations.3.js] ++var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { ++ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } ++ return new (P || (P = Promise))(function (resolve, reject) { ++ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } ++ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } ++ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } ++ step((generator = generator.apply(thisArg, _arguments || [])).next()); ++ }); ++}; ++var __generator = (this && this.__generator) || function (thisArg, body) { ++ var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; ++ return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; ++ function verb(n) { return function (v) { return step([n, v]); }; } ++ function step(op) { ++ if (f) throw new TypeError("Generator is already executing."); ++ while (g && (g = 0, op[0] && (_ = 0)), _) try { ++ if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; ++ if (y = 0, t) op = [op[0] & 2, t.value]; ++ switch (op[0]) { ++ case 0: case 1: t = op; break; ++ case 4: _.label++; return { value: op[1], done: false }; ++ case 5: _.label++; y = op[1]; op = [0]; continue; ++ case 7: op = _.ops.pop(); _.trys.pop(); continue; ++ default: ++ if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } ++ if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } ++ if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } ++ if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } ++ if (t[2]) _.ops.pop(); ++ _.trys.pop(); continue; ++ } ++ op = body.call(thisArg, _); ++ } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } ++ if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; ++ } ++}; ++var __addDisposableResource = (this && this.__addDisposableResource) || function (env, value, async) { ++ if (value !== null && value !== void 0) { ++ if (typeof value !== "object") throw new TypeError("Object expected."); ++ var dispose; ++ if (async) { ++ if (!Symbol.asyncDispose) throw new TypeError("Symbol.asyncDispose is not defined."); ++ dispose = value[Symbol.asyncDispose]; ++ } ++ if (dispose === void 0) { ++ if (!Symbol.dispose) throw new TypeError("Symbol.dispose is not defined."); ++ dispose = value[Symbol.dispose]; ++ } ++ if (typeof dispose !== "function") throw new TypeError("Object not disposable."); ++ env.stack.push({ value: value, dispose: dispose, async: async }); ++ } ++ else if (async) { ++ env.stack.push({ async: true }); ++ } ++ return value; ++}; ++var __disposeResources = (this && this.__disposeResources) || (function (SuppressedError) { ++ return function (env) { ++ function fail(e) { ++ env.error = env.hasError ? new SuppressedError(e, env.error, "An error was suppressed during disposal.") : e; ++ env.hasError = true; ++ } ++ function next() { ++ while (env.stack.length) { ++ var rec = env.stack.pop(); ++ try { ++ var result = rec.dispose && rec.dispose.call(rec.value); ++ if (rec.async) return Promise.resolve(result).then(next, function(e) { fail(e); return next(); }); ++ } ++ catch (e) { ++ fail(e); ++ } ++ } ++ if (env.hasError) throw env.error; ++ } ++ return next(); ++ }; ++})(typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) { ++ var e = new Error(message); ++ return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e; ++}); ++var _a, _b; ++{ ++ var env_1 = { stack: [], error: void 0, hasError: false }; ++ try { ++ var d1 = __addDisposableResource(env_1, (_a = {}, _a[Symbol.asyncDispose] = function () { ++ return __awaiter(this, void 0, void 0, function () { return __generator(this, function (_a) { ++ return [2 /*return*/]; ++ }); }); ++ }, _a), true), d2 = __addDisposableResource(env_1, null, true), d3 = __addDisposableResource(env_1, undefined, true), d4 = __addDisposableResource(env_1, (_b = {}, _b[Symbol.dispose] = function () { }, _b), true); ++ } ++ catch (e_1) { ++ env_1.error = e_1; ++ env_1.hasError = true; ++ } ++ finally { ++ var result_1 = __disposeResources(env_1); ++ if (result_1) ++ await result_1; ++ } ++} ++export {}; +diff --git a/tests/baselines/reference/awaitUsingDeclarations.3(target=esnext).js b/tests/baselines/reference/awaitUsingDeclarations.3(target=esnext).js +new file mode 100644 +index 000000000..fa149c697 +--- /dev/null ++++ b/tests/baselines/reference/awaitUsingDeclarations.3(target=esnext).js +@@ -0,0 +1,17 @@ ++//// [tests/cases/conformance/statements/VariableStatements/usingDeclarations/awaitUsingDeclarations.3.ts] //// ++ ++//// [awaitUsingDeclarations.3.ts] ++{ ++ await using d1 = { async [Symbol.asyncDispose]() {} }, ++ d2 = null, ++ d3 = undefined, ++ d4 = { [Symbol.dispose]() {} }; ++} ++ ++export {}; ++ ++//// [awaitUsingDeclarations.3.js] ++{ ++ await using d1 = { async [Symbol.asyncDispose]() { } }, d2 = null, d3 = undefined, d4 = { [Symbol.dispose]() { } }; ++} ++export {}; +diff --git a/tests/baselines/reference/awaitUsingDeclarations.4.errors.txt b/tests/baselines/reference/awaitUsingDeclarations.4.errors.txt +new file mode 100644 +index 000000000..7fb618271 +--- /dev/null ++++ b/tests/baselines/reference/awaitUsingDeclarations.4.errors.txt +@@ -0,0 +1,17 @@ ++awaitUsingDeclarations.4.ts(2,11): error TS2304: Cannot find name 'using'. ++awaitUsingDeclarations.4.ts(2,18): error TS2304: Cannot find name 'a'. ++awaitUsingDeclarations.4.ts(2,21): error TS1005: ';' expected. ++ ++ ++==== awaitUsingDeclarations.4.ts (3 errors) ==== ++ { ++ await using [a] = null; ++ ~~~~~ ++!!! error TS2304: Cannot find name 'using'. ++ ~ ++!!! error TS2304: Cannot find name 'a'. ++ ~ ++!!! error TS1005: ';' expected. ++ } ++ ++ export {}; +\ No newline at end of file +diff --git a/tests/baselines/reference/awaitUsingDeclarations.4.js b/tests/baselines/reference/awaitUsingDeclarations.4.js +new file mode 100644 +index 000000000..887cb629e +--- /dev/null ++++ b/tests/baselines/reference/awaitUsingDeclarations.4.js +@@ -0,0 +1,15 @@ ++//// [tests/cases/conformance/statements/VariableStatements/usingDeclarations/awaitUsingDeclarations.4.ts] //// ++ ++//// [awaitUsingDeclarations.4.ts] ++{ ++ await using [a] = null; ++} ++ ++export {}; ++ ++//// [awaitUsingDeclarations.4.js] ++{ ++ await using[a]; ++ null; ++} ++export {}; +diff --git a/tests/baselines/reference/awaitUsingDeclarations.5.errors.txt b/tests/baselines/reference/awaitUsingDeclarations.5.errors.txt +new file mode 100644 +index 000000000..370cc3a6c +--- /dev/null ++++ b/tests/baselines/reference/awaitUsingDeclarations.5.errors.txt +@@ -0,0 +1,16 @@ ++awaitUsingDeclarations.5.ts(3,17): error TS1492: 'await using' declarations may not have binding patterns. ++awaitUsingDeclarations.5.ts(3,17): error TS2488: Type 'null' must have a '[Symbol.iterator]()' method that returns an iterator. ++ ++ ++==== awaitUsingDeclarations.5.ts (2 errors) ==== ++ { ++ await using a = null, ++ [b] = null, ++ ~~~ ++!!! error TS1492: 'await using' declarations may not have binding patterns. ++ ~~~ ++!!! error TS2488: Type 'null' must have a '[Symbol.iterator]()' method that returns an iterator. ++ c = null; ++ } ++ ++ export {}; +\ No newline at end of file +diff --git a/tests/baselines/reference/awaitUsingDeclarations.5.js b/tests/baselines/reference/awaitUsingDeclarations.5.js +new file mode 100644 +index 000000000..8a436907c +--- /dev/null ++++ b/tests/baselines/reference/awaitUsingDeclarations.5.js +@@ -0,0 +1,16 @@ ++//// [tests/cases/conformance/statements/VariableStatements/usingDeclarations/awaitUsingDeclarations.5.ts] //// ++ ++//// [awaitUsingDeclarations.5.ts] ++{ ++ await using a = null, ++ [b] = null, ++ c = null; ++} ++ ++export {}; ++ ++//// [awaitUsingDeclarations.5.js] ++{ ++ await using a = null, [b] = null, c = null; ++} ++export {}; +diff --git a/tests/baselines/reference/awaitUsingDeclarations.6.errors.txt b/tests/baselines/reference/awaitUsingDeclarations.6.errors.txt +new file mode 100644 +index 000000000..7f471afa2 +--- /dev/null ++++ b/tests/baselines/reference/awaitUsingDeclarations.6.errors.txt +@@ -0,0 +1,15 @@ ++awaitUsingDeclarations.6.ts(2,17): error TS1492: 'await using' declarations may not have binding patterns. ++awaitUsingDeclarations.6.ts(2,18): error TS2339: Property 'a' does not exist on type 'null'. ++ ++ ++==== awaitUsingDeclarations.6.ts (2 errors) ==== ++ { ++ await using {a} = null; ++ ~~~ ++!!! error TS1492: 'await using' declarations may not have binding patterns. ++ ~ ++!!! error TS2339: Property 'a' does not exist on type 'null'. ++ } ++ ++ ++ export {}; +\ No newline at end of file +diff --git a/tests/baselines/reference/awaitUsingDeclarations.6.js b/tests/baselines/reference/awaitUsingDeclarations.6.js +new file mode 100644 +index 000000000..56ee8073b +--- /dev/null ++++ b/tests/baselines/reference/awaitUsingDeclarations.6.js +@@ -0,0 +1,15 @@ ++//// [tests/cases/conformance/statements/VariableStatements/usingDeclarations/awaitUsingDeclarations.6.ts] //// ++ ++//// [awaitUsingDeclarations.6.ts] ++{ ++ await using {a} = null; ++} ++ ++ ++export {}; ++ ++//// [awaitUsingDeclarations.6.js] ++{ ++ await using { a } = null; ++} ++export {}; +diff --git a/tests/baselines/reference/awaitUsingDeclarations.7.errors.txt b/tests/baselines/reference/awaitUsingDeclarations.7.errors.txt +new file mode 100644 +index 000000000..c3061741e +--- /dev/null ++++ b/tests/baselines/reference/awaitUsingDeclarations.7.errors.txt +@@ -0,0 +1,17 @@ ++awaitUsingDeclarations.7.ts(2,5): error TS2853: 'await using' statements are only allowed at the top level of a file when that file is a module, but this file has no imports or exports. Consider adding an empty 'export {}' to make this file a module. ++awaitUsingDeclarations.7.ts(3,17): error TS1492: 'await using' declarations may not have binding patterns. ++awaitUsingDeclarations.7.ts(3,18): error TS2339: Property 'b' does not exist on type 'null'. ++ ++ ++==== awaitUsingDeclarations.7.ts (3 errors) ==== ++ { ++ await using a = null, ++ ~~~~~ ++!!! error TS2853: 'await using' statements are only allowed at the top level of a file when that file is a module, but this file has no imports or exports. Consider adding an empty 'export {}' to make this file a module. ++ {b} = null, ++ ~~~ ++!!! error TS1492: 'await using' declarations may not have binding patterns. ++ ~ ++!!! error TS2339: Property 'b' does not exist on type 'null'. ++ c = null; ++ } +\ No newline at end of file +diff --git a/tests/baselines/reference/awaitUsingDeclarations.7.js b/tests/baselines/reference/awaitUsingDeclarations.7.js +new file mode 100644 +index 000000000..c409558f3 +--- /dev/null ++++ b/tests/baselines/reference/awaitUsingDeclarations.7.js +@@ -0,0 +1,13 @@ ++//// [tests/cases/conformance/statements/VariableStatements/usingDeclarations/awaitUsingDeclarations.7.ts] //// ++ ++//// [awaitUsingDeclarations.7.ts] ++{ ++ await using a = null, ++ {b} = null, ++ c = null; ++} ++ ++//// [awaitUsingDeclarations.7.js] ++{ ++ await using a = null, { b } = null, c = null; ++} +diff --git a/tests/baselines/reference/awaitUsingDeclarations.8.errors.txt b/tests/baselines/reference/awaitUsingDeclarations.8.errors.txt +new file mode 100644 +index 000000000..f564b8c30 +--- /dev/null ++++ b/tests/baselines/reference/awaitUsingDeclarations.8.errors.txt +@@ -0,0 +1,11 @@ ++awaitUsingDeclarations.8.ts(2,17): error TS1155: 'await using' declarations must be initialized. ++ ++ ++==== awaitUsingDeclarations.8.ts (1 errors) ==== ++ { ++ await using a; ++ ~ ++!!! error TS1155: 'await using' declarations must be initialized. ++ } ++ ++ export {}; +\ No newline at end of file +diff --git a/tests/baselines/reference/awaitUsingDeclarations.8.js b/tests/baselines/reference/awaitUsingDeclarations.8.js +new file mode 100644 +index 000000000..5e42d69e7 +--- /dev/null ++++ b/tests/baselines/reference/awaitUsingDeclarations.8.js +@@ -0,0 +1,14 @@ ++//// [tests/cases/conformance/statements/VariableStatements/usingDeclarations/awaitUsingDeclarations.8.ts] //// ++ ++//// [awaitUsingDeclarations.8.ts] ++{ ++ await using a; ++} ++ ++export {}; ++ ++//// [awaitUsingDeclarations.8.js] ++{ ++ await using a; ++} ++export {}; +diff --git a/tests/baselines/reference/awaitUsingDeclarations.9.errors.txt b/tests/baselines/reference/awaitUsingDeclarations.9.errors.txt +new file mode 100644 +index 000000000..51b6a5e7d +--- /dev/null ++++ b/tests/baselines/reference/awaitUsingDeclarations.9.errors.txt +@@ -0,0 +1,12 @@ ++error TS2318: Cannot find global type 'AsyncDisposable'. ++error TS2318: Cannot find global type 'Disposable'. ++ ++ ++!!! error TS2318: Cannot find global type 'AsyncDisposable'. ++!!! error TS2318: Cannot find global type 'Disposable'. ++==== awaitUsingDeclarations.9.ts (0 errors) ==== ++ { ++ await using a = null; ++ } ++ ++ export {}; +\ No newline at end of file +diff --git a/tests/baselines/reference/awaitUsingDeclarations.9.js b/tests/baselines/reference/awaitUsingDeclarations.9.js +new file mode 100644 +index 000000000..291c6d133 +--- /dev/null ++++ b/tests/baselines/reference/awaitUsingDeclarations.9.js +@@ -0,0 +1,14 @@ ++//// [tests/cases/conformance/statements/VariableStatements/usingDeclarations/awaitUsingDeclarations.9.ts] //// ++ ++//// [awaitUsingDeclarations.9.ts] ++{ ++ await using a = null; ++} ++ ++export {}; ++ ++//// [awaitUsingDeclarations.9.js] ++{ ++ await using a = null; ++} ++export {}; +diff --git a/tests/baselines/reference/awaitUsingDeclarationsInFor(target=es2015).js b/tests/baselines/reference/awaitUsingDeclarationsInFor(target=es2015).js +new file mode 100644 +index 000000000..53a07f960 +--- /dev/null ++++ b/tests/baselines/reference/awaitUsingDeclarationsInFor(target=es2015).js +@@ -0,0 +1,89 @@ ++//// [tests/cases/conformance/statements/VariableStatements/usingDeclarations/awaitUsingDeclarationsInFor.ts] //// ++ ++//// [awaitUsingDeclarationsInFor.ts] ++async function main() { ++ for (await using d1 = { [Symbol.dispose]() {} }, ++ d2 = { async [Symbol.asyncDispose]() {} }, ++ d3 = null, ++ d4 = undefined;;) { ++ } ++} ++ ++//// [awaitUsingDeclarationsInFor.js] ++var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { ++ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } ++ return new (P || (P = Promise))(function (resolve, reject) { ++ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } ++ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } ++ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } ++ step((generator = generator.apply(thisArg, _arguments || [])).next()); ++ }); ++}; ++var __addDisposableResource = (this && this.__addDisposableResource) || function (env, value, async) { ++ if (value !== null && value !== void 0) { ++ if (typeof value !== "object") throw new TypeError("Object expected."); ++ var dispose; ++ if (async) { ++ if (!Symbol.asyncDispose) throw new TypeError("Symbol.asyncDispose is not defined."); ++ dispose = value[Symbol.asyncDispose]; ++ } ++ if (dispose === void 0) { ++ if (!Symbol.dispose) throw new TypeError("Symbol.dispose is not defined."); ++ dispose = value[Symbol.dispose]; ++ } ++ if (typeof dispose !== "function") throw new TypeError("Object not disposable."); ++ env.stack.push({ value: value, dispose: dispose, async: async }); ++ } ++ else if (async) { ++ env.stack.push({ async: true }); ++ } ++ return value; ++}; ++var __disposeResources = (this && this.__disposeResources) || (function (SuppressedError) { ++ return function (env) { ++ function fail(e) { ++ env.error = env.hasError ? new SuppressedError(e, env.error, "An error was suppressed during disposal.") : e; ++ env.hasError = true; ++ } ++ function next() { ++ while (env.stack.length) { ++ var rec = env.stack.pop(); ++ try { ++ var result = rec.dispose && rec.dispose.call(rec.value); ++ if (rec.async) return Promise.resolve(result).then(next, function(e) { fail(e); return next(); }); ++ } ++ catch (e) { ++ fail(e); ++ } ++ } ++ if (env.hasError) throw env.error; ++ } ++ return next(); ++ }; ++})(typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) { ++ var e = new Error(message); ++ return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e; ++}); ++function main() { ++ return __awaiter(this, void 0, void 0, function* () { ++ { ++ const env_1 = { stack: [], error: void 0, hasError: false }; ++ try { ++ const d1 = __addDisposableResource(env_1, { [Symbol.dispose]() { } }, true), d2 = __addDisposableResource(env_1, { [Symbol.asyncDispose]() { ++ return __awaiter(this, void 0, void 0, function* () { }); ++ } }, true), d3 = __addDisposableResource(env_1, null, true), d4 = __addDisposableResource(env_1, undefined, true); ++ for (;;) { ++ } ++ } ++ catch (e_1) { ++ env_1.error = e_1; ++ env_1.hasError = true; ++ } ++ finally { ++ const result_1 = __disposeResources(env_1); ++ if (result_1) ++ yield result_1; ++ } ++ } ++ }); ++} +diff --git a/tests/baselines/reference/awaitUsingDeclarationsInFor(target=es2017).js b/tests/baselines/reference/awaitUsingDeclarationsInFor(target=es2017).js +new file mode 100644 +index 000000000..bbfca93a9 +--- /dev/null ++++ b/tests/baselines/reference/awaitUsingDeclarationsInFor(target=es2017).js +@@ -0,0 +1,76 @@ ++//// [tests/cases/conformance/statements/VariableStatements/usingDeclarations/awaitUsingDeclarationsInFor.ts] //// ++ ++//// [awaitUsingDeclarationsInFor.ts] ++async function main() { ++ for (await using d1 = { [Symbol.dispose]() {} }, ++ d2 = { async [Symbol.asyncDispose]() {} }, ++ d3 = null, ++ d4 = undefined;;) { ++ } ++} ++ ++//// [awaitUsingDeclarationsInFor.js] ++var __addDisposableResource = (this && this.__addDisposableResource) || function (env, value, async) { ++ if (value !== null && value !== void 0) { ++ if (typeof value !== "object") throw new TypeError("Object expected."); ++ var dispose; ++ if (async) { ++ if (!Symbol.asyncDispose) throw new TypeError("Symbol.asyncDispose is not defined."); ++ dispose = value[Symbol.asyncDispose]; ++ } ++ if (dispose === void 0) { ++ if (!Symbol.dispose) throw new TypeError("Symbol.dispose is not defined."); ++ dispose = value[Symbol.dispose]; ++ } ++ if (typeof dispose !== "function") throw new TypeError("Object not disposable."); ++ env.stack.push({ value: value, dispose: dispose, async: async }); ++ } ++ else if (async) { ++ env.stack.push({ async: true }); ++ } ++ return value; ++}; ++var __disposeResources = (this && this.__disposeResources) || (function (SuppressedError) { ++ return function (env) { ++ function fail(e) { ++ env.error = env.hasError ? new SuppressedError(e, env.error, "An error was suppressed during disposal.") : e; ++ env.hasError = true; ++ } ++ function next() { ++ while (env.stack.length) { ++ var rec = env.stack.pop(); ++ try { ++ var result = rec.dispose && rec.dispose.call(rec.value); ++ if (rec.async) return Promise.resolve(result).then(next, function(e) { fail(e); return next(); }); ++ } ++ catch (e) { ++ fail(e); ++ } ++ } ++ if (env.hasError) throw env.error; ++ } ++ return next(); ++ }; ++})(typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) { ++ var e = new Error(message); ++ return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e; ++}); ++async function main() { ++ { ++ const env_1 = { stack: [], error: void 0, hasError: false }; ++ try { ++ const d1 = __addDisposableResource(env_1, { [Symbol.dispose]() { } }, true), d2 = __addDisposableResource(env_1, { async [Symbol.asyncDispose]() { } }, true), d3 = __addDisposableResource(env_1, null, true), d4 = __addDisposableResource(env_1, undefined, true); ++ for (;;) { ++ } ++ } ++ catch (e_1) { ++ env_1.error = e_1; ++ env_1.hasError = true; ++ } ++ finally { ++ const result_1 = __disposeResources(env_1); ++ if (result_1) ++ await result_1; ++ } ++ } ++} +diff --git a/tests/baselines/reference/awaitUsingDeclarationsInFor(target=es2022).js b/tests/baselines/reference/awaitUsingDeclarationsInFor(target=es2022).js +new file mode 100644 +index 000000000..bbfca93a9 +--- /dev/null ++++ b/tests/baselines/reference/awaitUsingDeclarationsInFor(target=es2022).js +@@ -0,0 +1,76 @@ ++//// [tests/cases/conformance/statements/VariableStatements/usingDeclarations/awaitUsingDeclarationsInFor.ts] //// ++ ++//// [awaitUsingDeclarationsInFor.ts] ++async function main() { ++ for (await using d1 = { [Symbol.dispose]() {} }, ++ d2 = { async [Symbol.asyncDispose]() {} }, ++ d3 = null, ++ d4 = undefined;;) { ++ } ++} ++ ++//// [awaitUsingDeclarationsInFor.js] ++var __addDisposableResource = (this && this.__addDisposableResource) || function (env, value, async) { ++ if (value !== null && value !== void 0) { ++ if (typeof value !== "object") throw new TypeError("Object expected."); ++ var dispose; ++ if (async) { ++ if (!Symbol.asyncDispose) throw new TypeError("Symbol.asyncDispose is not defined."); ++ dispose = value[Symbol.asyncDispose]; ++ } ++ if (dispose === void 0) { ++ if (!Symbol.dispose) throw new TypeError("Symbol.dispose is not defined."); ++ dispose = value[Symbol.dispose]; ++ } ++ if (typeof dispose !== "function") throw new TypeError("Object not disposable."); ++ env.stack.push({ value: value, dispose: dispose, async: async }); ++ } ++ else if (async) { ++ env.stack.push({ async: true }); ++ } ++ return value; ++}; ++var __disposeResources = (this && this.__disposeResources) || (function (SuppressedError) { ++ return function (env) { ++ function fail(e) { ++ env.error = env.hasError ? new SuppressedError(e, env.error, "An error was suppressed during disposal.") : e; ++ env.hasError = true; ++ } ++ function next() { ++ while (env.stack.length) { ++ var rec = env.stack.pop(); ++ try { ++ var result = rec.dispose && rec.dispose.call(rec.value); ++ if (rec.async) return Promise.resolve(result).then(next, function(e) { fail(e); return next(); }); ++ } ++ catch (e) { ++ fail(e); ++ } ++ } ++ if (env.hasError) throw env.error; ++ } ++ return next(); ++ }; ++})(typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) { ++ var e = new Error(message); ++ return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e; ++}); ++async function main() { ++ { ++ const env_1 = { stack: [], error: void 0, hasError: false }; ++ try { ++ const d1 = __addDisposableResource(env_1, { [Symbol.dispose]() { } }, true), d2 = __addDisposableResource(env_1, { async [Symbol.asyncDispose]() { } }, true), d3 = __addDisposableResource(env_1, null, true), d4 = __addDisposableResource(env_1, undefined, true); ++ for (;;) { ++ } ++ } ++ catch (e_1) { ++ env_1.error = e_1; ++ env_1.hasError = true; ++ } ++ finally { ++ const result_1 = __disposeResources(env_1); ++ if (result_1) ++ await result_1; ++ } ++ } ++} +diff --git a/tests/baselines/reference/awaitUsingDeclarationsInFor(target=es5).js b/tests/baselines/reference/awaitUsingDeclarationsInFor(target=es5).js +new file mode 100644 +index 000000000..1ba3ab31d +--- /dev/null ++++ b/tests/baselines/reference/awaitUsingDeclarationsInFor(target=es5).js +@@ -0,0 +1,130 @@ ++//// [tests/cases/conformance/statements/VariableStatements/usingDeclarations/awaitUsingDeclarationsInFor.ts] //// ++ ++//// [awaitUsingDeclarationsInFor.ts] ++async function main() { ++ for (await using d1 = { [Symbol.dispose]() {} }, ++ d2 = { async [Symbol.asyncDispose]() {} }, ++ d3 = null, ++ d4 = undefined;;) { ++ } ++} ++ ++//// [awaitUsingDeclarationsInFor.js] ++var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { ++ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } ++ return new (P || (P = Promise))(function (resolve, reject) { ++ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } ++ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } ++ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } ++ step((generator = generator.apply(thisArg, _arguments || [])).next()); ++ }); ++}; ++var __generator = (this && this.__generator) || function (thisArg, body) { ++ var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; ++ return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; ++ function verb(n) { return function (v) { return step([n, v]); }; } ++ function step(op) { ++ if (f) throw new TypeError("Generator is already executing."); ++ while (g && (g = 0, op[0] && (_ = 0)), _) try { ++ if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; ++ if (y = 0, t) op = [op[0] & 2, t.value]; ++ switch (op[0]) { ++ case 0: case 1: t = op; break; ++ case 4: _.label++; return { value: op[1], done: false }; ++ case 5: _.label++; y = op[1]; op = [0]; continue; ++ case 7: op = _.ops.pop(); _.trys.pop(); continue; ++ default: ++ if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } ++ if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } ++ if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } ++ if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } ++ if (t[2]) _.ops.pop(); ++ _.trys.pop(); continue; ++ } ++ op = body.call(thisArg, _); ++ } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } ++ if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; ++ } ++}; ++var __addDisposableResource = (this && this.__addDisposableResource) || function (env, value, async) { ++ if (value !== null && value !== void 0) { ++ if (typeof value !== "object") throw new TypeError("Object expected."); ++ var dispose; ++ if (async) { ++ if (!Symbol.asyncDispose) throw new TypeError("Symbol.asyncDispose is not defined."); ++ dispose = value[Symbol.asyncDispose]; ++ } ++ if (dispose === void 0) { ++ if (!Symbol.dispose) throw new TypeError("Symbol.dispose is not defined."); ++ dispose = value[Symbol.dispose]; ++ } ++ if (typeof dispose !== "function") throw new TypeError("Object not disposable."); ++ env.stack.push({ value: value, dispose: dispose, async: async }); ++ } ++ else if (async) { ++ env.stack.push({ async: true }); ++ } ++ return value; ++}; ++var __disposeResources = (this && this.__disposeResources) || (function (SuppressedError) { ++ return function (env) { ++ function fail(e) { ++ env.error = env.hasError ? new SuppressedError(e, env.error, "An error was suppressed during disposal.") : e; ++ env.hasError = true; ++ } ++ function next() { ++ while (env.stack.length) { ++ var rec = env.stack.pop(); ++ try { ++ var result = rec.dispose && rec.dispose.call(rec.value); ++ if (rec.async) return Promise.resolve(result).then(next, function(e) { fail(e); return next(); }); ++ } ++ catch (e) { ++ fail(e); ++ } ++ } ++ if (env.hasError) throw env.error; ++ } ++ return next(); ++ }; ++})(typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) { ++ var e = new Error(message); ++ return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e; ++}); ++function main() { ++ return __awaiter(this, void 0, void 0, function () { ++ var env_1, d1, d2, d3, d4, e_1, result_1; ++ var _a, _b; ++ return __generator(this, function (_c) { ++ switch (_c.label) { ++ case 0: ++ env_1 = { stack: [], error: void 0, hasError: false }; ++ _c.label = 1; ++ case 1: ++ _c.trys.push([1, 2, 3, 6]); ++ d1 = __addDisposableResource(env_1, (_a = {}, _a[Symbol.dispose] = function () { }, _a), true), d2 = __addDisposableResource(env_1, (_b = {}, _b[Symbol.asyncDispose] = function () { ++ return __awaiter(this, void 0, void 0, function () { return __generator(this, function (_a) { ++ return [2 /*return*/]; ++ }); }); ++ }, _b), true), d3 = __addDisposableResource(env_1, null, true), d4 = __addDisposableResource(env_1, undefined, true); ++ for (;;) { ++ } ++ return [3 /*break*/, 6]; ++ case 2: ++ e_1 = _c.sent(); ++ env_1.error = e_1; ++ env_1.hasError = true; ++ return [3 /*break*/, 6]; ++ case 3: ++ result_1 = __disposeResources(env_1); ++ if (!result_1) return [3 /*break*/, 5]; ++ return [4 /*yield*/, result_1]; ++ case 4: ++ _c.sent(); ++ _c.label = 5; ++ case 5: return [7 /*endfinally*/]; ++ case 6: return [2 /*return*/]; ++ } ++ }); ++ }); ++} +diff --git a/tests/baselines/reference/awaitUsingDeclarationsInFor(target=esnext).js b/tests/baselines/reference/awaitUsingDeclarationsInFor(target=esnext).js +new file mode 100644 +index 000000000..d7e96493e +--- /dev/null ++++ b/tests/baselines/reference/awaitUsingDeclarationsInFor(target=esnext).js +@@ -0,0 +1,16 @@ ++//// [tests/cases/conformance/statements/VariableStatements/usingDeclarations/awaitUsingDeclarationsInFor.ts] //// ++ ++//// [awaitUsingDeclarationsInFor.ts] ++async function main() { ++ for (await using d1 = { [Symbol.dispose]() {} }, ++ d2 = { async [Symbol.asyncDispose]() {} }, ++ d3 = null, ++ d4 = undefined;;) { ++ } ++} ++ ++//// [awaitUsingDeclarationsInFor.js] ++async function main() { ++ for (await using d1 = { [Symbol.dispose]() { } }, d2 = { async [Symbol.asyncDispose]() { } }, d3 = null, d4 = undefined;;) { ++ } ++} +diff --git a/tests/baselines/reference/awaitUsingDeclarationsInForAwaitOf(target=es2015).js b/tests/baselines/reference/awaitUsingDeclarationsInForAwaitOf(target=es2015).js +new file mode 100644 +index 000000000..187f098c8 +--- /dev/null ++++ b/tests/baselines/reference/awaitUsingDeclarationsInForAwaitOf(target=es2015).js +@@ -0,0 +1,104 @@ ++//// [tests/cases/conformance/statements/VariableStatements/usingDeclarations/awaitUsingDeclarationsInForAwaitOf.ts] //// ++ ++//// [awaitUsingDeclarationsInForAwaitOf.ts] ++async function main() { ++ for await (await using d1 of [{ async [Symbol.asyncDispose]() {} }, { [Symbol.dispose]() {} }, null, undefined]) { ++ } ++} ++ ++//// [awaitUsingDeclarationsInForAwaitOf.js] ++var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { ++ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } ++ return new (P || (P = Promise))(function (resolve, reject) { ++ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } ++ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } ++ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } ++ step((generator = generator.apply(thisArg, _arguments || [])).next()); ++ }); ++}; ++var __addDisposableResource = (this && this.__addDisposableResource) || function (env, value, async) { ++ if (value !== null && value !== void 0) { ++ if (typeof value !== "object") throw new TypeError("Object expected."); ++ var dispose; ++ if (async) { ++ if (!Symbol.asyncDispose) throw new TypeError("Symbol.asyncDispose is not defined."); ++ dispose = value[Symbol.asyncDispose]; ++ } ++ if (dispose === void 0) { ++ if (!Symbol.dispose) throw new TypeError("Symbol.dispose is not defined."); ++ dispose = value[Symbol.dispose]; ++ } ++ if (typeof dispose !== "function") throw new TypeError("Object not disposable."); ++ env.stack.push({ value: value, dispose: dispose, async: async }); ++ } ++ else if (async) { ++ env.stack.push({ async: true }); ++ } ++ return value; ++}; ++var __disposeResources = (this && this.__disposeResources) || (function (SuppressedError) { ++ return function (env) { ++ function fail(e) { ++ env.error = env.hasError ? new SuppressedError(e, env.error, "An error was suppressed during disposal.") : e; ++ env.hasError = true; ++ } ++ function next() { ++ while (env.stack.length) { ++ var rec = env.stack.pop(); ++ try { ++ var result = rec.dispose && rec.dispose.call(rec.value); ++ if (rec.async) return Promise.resolve(result).then(next, function(e) { fail(e); return next(); }); ++ } ++ catch (e) { ++ fail(e); ++ } ++ } ++ if (env.hasError) throw env.error; ++ } ++ return next(); ++ }; ++})(typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) { ++ var e = new Error(message); ++ return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e; ++}); ++var __asyncValues = (this && this.__asyncValues) || function (o) { ++ if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); ++ var m = o[Symbol.asyncIterator], i; ++ return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i); ++ function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; } ++ function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); } ++}; ++function main() { ++ var _a, e_1, _b, _c; ++ return __awaiter(this, void 0, void 0, function* () { ++ try { ++ for (var _d = true, _e = __asyncValues([{ [Symbol.asyncDispose]() { ++ return __awaiter(this, void 0, void 0, function* () { }); ++ } }, { [Symbol.dispose]() { } }, null, undefined]), _f; _f = yield _e.next(), _a = _f.done, !_a; _d = true) { ++ _c = _f.value; ++ _d = false; ++ const d1_1 = _c; ++ const env_1 = { stack: [], error: void 0, hasError: false }; ++ try { ++ const d1 = __addDisposableResource(env_1, d1_1, true); ++ } ++ catch (e_2) { ++ env_1.error = e_2; ++ env_1.hasError = true; ++ } ++ finally { ++ const result_1 = __disposeResources(env_1); ++ if (result_1) ++ yield result_1; ++ } ++ } ++ } ++ catch (e_1_1) { e_1 = { error: e_1_1 }; } ++ finally { ++ try { ++ if (!_d && !_a && (_b = _e.return)) yield _b.call(_e); ++ } ++ finally { if (e_1) throw e_1.error; } ++ } ++ }); ++} +diff --git a/tests/baselines/reference/awaitUsingDeclarationsInForAwaitOf(target=es2017).js b/tests/baselines/reference/awaitUsingDeclarationsInForAwaitOf(target=es2017).js +new file mode 100644 +index 000000000..845789f9a +--- /dev/null ++++ b/tests/baselines/reference/awaitUsingDeclarationsInForAwaitOf(target=es2017).js +@@ -0,0 +1,91 @@ ++//// [tests/cases/conformance/statements/VariableStatements/usingDeclarations/awaitUsingDeclarationsInForAwaitOf.ts] //// ++ ++//// [awaitUsingDeclarationsInForAwaitOf.ts] ++async function main() { ++ for await (await using d1 of [{ async [Symbol.asyncDispose]() {} }, { [Symbol.dispose]() {} }, null, undefined]) { ++ } ++} ++ ++//// [awaitUsingDeclarationsInForAwaitOf.js] ++var __addDisposableResource = (this && this.__addDisposableResource) || function (env, value, async) { ++ if (value !== null && value !== void 0) { ++ if (typeof value !== "object") throw new TypeError("Object expected."); ++ var dispose; ++ if (async) { ++ if (!Symbol.asyncDispose) throw new TypeError("Symbol.asyncDispose is not defined."); ++ dispose = value[Symbol.asyncDispose]; ++ } ++ if (dispose === void 0) { ++ if (!Symbol.dispose) throw new TypeError("Symbol.dispose is not defined."); ++ dispose = value[Symbol.dispose]; ++ } ++ if (typeof dispose !== "function") throw new TypeError("Object not disposable."); ++ env.stack.push({ value: value, dispose: dispose, async: async }); ++ } ++ else if (async) { ++ env.stack.push({ async: true }); ++ } ++ return value; ++}; ++var __disposeResources = (this && this.__disposeResources) || (function (SuppressedError) { ++ return function (env) { ++ function fail(e) { ++ env.error = env.hasError ? new SuppressedError(e, env.error, "An error was suppressed during disposal.") : e; ++ env.hasError = true; ++ } ++ function next() { ++ while (env.stack.length) { ++ var rec = env.stack.pop(); ++ try { ++ var result = rec.dispose && rec.dispose.call(rec.value); ++ if (rec.async) return Promise.resolve(result).then(next, function(e) { fail(e); return next(); }); ++ } ++ catch (e) { ++ fail(e); ++ } ++ } ++ if (env.hasError) throw env.error; ++ } ++ return next(); ++ }; ++})(typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) { ++ var e = new Error(message); ++ return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e; ++}); ++var __asyncValues = (this && this.__asyncValues) || function (o) { ++ if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); ++ var m = o[Symbol.asyncIterator], i; ++ return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i); ++ function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; } ++ function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); } ++}; ++async function main() { ++ var _a, e_1, _b, _c; ++ try { ++ for (var _d = true, _e = __asyncValues([{ async [Symbol.asyncDispose]() { } }, { [Symbol.dispose]() { } }, null, undefined]), _f; _f = await _e.next(), _a = _f.done, !_a; _d = true) { ++ _c = _f.value; ++ _d = false; ++ const d1_1 = _c; ++ const env_1 = { stack: [], error: void 0, hasError: false }; ++ try { ++ const d1 = __addDisposableResource(env_1, d1_1, true); ++ } ++ catch (e_2) { ++ env_1.error = e_2; ++ env_1.hasError = true; ++ } ++ finally { ++ const result_1 = __disposeResources(env_1); ++ if (result_1) ++ await result_1; ++ } ++ } ++ } ++ catch (e_1_1) { e_1 = { error: e_1_1 }; } ++ finally { ++ try { ++ if (!_d && !_a && (_b = _e.return)) await _b.call(_e); ++ } ++ finally { if (e_1) throw e_1.error; } ++ } ++} +diff --git a/tests/baselines/reference/awaitUsingDeclarationsInForAwaitOf(target=es2022).js b/tests/baselines/reference/awaitUsingDeclarationsInForAwaitOf(target=es2022).js +new file mode 100644 +index 000000000..1d6ca04cd +--- /dev/null ++++ b/tests/baselines/reference/awaitUsingDeclarationsInForAwaitOf(target=es2022).js +@@ -0,0 +1,71 @@ ++//// [tests/cases/conformance/statements/VariableStatements/usingDeclarations/awaitUsingDeclarationsInForAwaitOf.ts] //// ++ ++//// [awaitUsingDeclarationsInForAwaitOf.ts] ++async function main() { ++ for await (await using d1 of [{ async [Symbol.asyncDispose]() {} }, { [Symbol.dispose]() {} }, null, undefined]) { ++ } ++} ++ ++//// [awaitUsingDeclarationsInForAwaitOf.js] ++var __addDisposableResource = (this && this.__addDisposableResource) || function (env, value, async) { ++ if (value !== null && value !== void 0) { ++ if (typeof value !== "object") throw new TypeError("Object expected."); ++ var dispose; ++ if (async) { ++ if (!Symbol.asyncDispose) throw new TypeError("Symbol.asyncDispose is not defined."); ++ dispose = value[Symbol.asyncDispose]; ++ } ++ if (dispose === void 0) { ++ if (!Symbol.dispose) throw new TypeError("Symbol.dispose is not defined."); ++ dispose = value[Symbol.dispose]; ++ } ++ if (typeof dispose !== "function") throw new TypeError("Object not disposable."); ++ env.stack.push({ value: value, dispose: dispose, async: async }); ++ } ++ else if (async) { ++ env.stack.push({ async: true }); ++ } ++ return value; ++}; ++var __disposeResources = (this && this.__disposeResources) || (function (SuppressedError) { ++ return function (env) { ++ function fail(e) { ++ env.error = env.hasError ? new SuppressedError(e, env.error, "An error was suppressed during disposal.") : e; ++ env.hasError = true; ++ } ++ function next() { ++ while (env.stack.length) { ++ var rec = env.stack.pop(); ++ try { ++ var result = rec.dispose && rec.dispose.call(rec.value); ++ if (rec.async) return Promise.resolve(result).then(next, function(e) { fail(e); return next(); }); ++ } ++ catch (e) { ++ fail(e); ++ } ++ } ++ if (env.hasError) throw env.error; ++ } ++ return next(); ++ }; ++})(typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) { ++ var e = new Error(message); ++ return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e; ++}); ++async function main() { ++ for await (const d1_1 of [{ async [Symbol.asyncDispose]() { } }, { [Symbol.dispose]() { } }, null, undefined]) { ++ const env_1 = { stack: [], error: void 0, hasError: false }; ++ try { ++ const d1 = __addDisposableResource(env_1, d1_1, true); ++ } ++ catch (e_1) { ++ env_1.error = e_1; ++ env_1.hasError = true; ++ } ++ finally { ++ const result_1 = __disposeResources(env_1); ++ if (result_1) ++ await result_1; ++ } ++ } ++} +diff --git a/tests/baselines/reference/awaitUsingDeclarationsInForAwaitOf(target=es5).js b/tests/baselines/reference/awaitUsingDeclarationsInForAwaitOf(target=es5).js +new file mode 100644 +index 000000000..070dfbd44 +--- /dev/null ++++ b/tests/baselines/reference/awaitUsingDeclarationsInForAwaitOf(target=es5).js +@@ -0,0 +1,162 @@ ++//// [tests/cases/conformance/statements/VariableStatements/usingDeclarations/awaitUsingDeclarationsInForAwaitOf.ts] //// ++ ++//// [awaitUsingDeclarationsInForAwaitOf.ts] ++async function main() { ++ for await (await using d1 of [{ async [Symbol.asyncDispose]() {} }, { [Symbol.dispose]() {} }, null, undefined]) { ++ } ++} ++ ++//// [awaitUsingDeclarationsInForAwaitOf.js] ++var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { ++ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } ++ return new (P || (P = Promise))(function (resolve, reject) { ++ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } ++ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } ++ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } ++ step((generator = generator.apply(thisArg, _arguments || [])).next()); ++ }); ++}; ++var __generator = (this && this.__generator) || function (thisArg, body) { ++ var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; ++ return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; ++ function verb(n) { return function (v) { return step([n, v]); }; } ++ function step(op) { ++ if (f) throw new TypeError("Generator is already executing."); ++ while (g && (g = 0, op[0] && (_ = 0)), _) try { ++ if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; ++ if (y = 0, t) op = [op[0] & 2, t.value]; ++ switch (op[0]) { ++ case 0: case 1: t = op; break; ++ case 4: _.label++; return { value: op[1], done: false }; ++ case 5: _.label++; y = op[1]; op = [0]; continue; ++ case 7: op = _.ops.pop(); _.trys.pop(); continue; ++ default: ++ if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } ++ if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } ++ if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } ++ if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } ++ if (t[2]) _.ops.pop(); ++ _.trys.pop(); continue; ++ } ++ op = body.call(thisArg, _); ++ } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } ++ if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; ++ } ++}; ++var __addDisposableResource = (this && this.__addDisposableResource) || function (env, value, async) { ++ if (value !== null && value !== void 0) { ++ if (typeof value !== "object") throw new TypeError("Object expected."); ++ var dispose; ++ if (async) { ++ if (!Symbol.asyncDispose) throw new TypeError("Symbol.asyncDispose is not defined."); ++ dispose = value[Symbol.asyncDispose]; ++ } ++ if (dispose === void 0) { ++ if (!Symbol.dispose) throw new TypeError("Symbol.dispose is not defined."); ++ dispose = value[Symbol.dispose]; ++ } ++ if (typeof dispose !== "function") throw new TypeError("Object not disposable."); ++ env.stack.push({ value: value, dispose: dispose, async: async }); ++ } ++ else if (async) { ++ env.stack.push({ async: true }); ++ } ++ return value; ++}; ++var __disposeResources = (this && this.__disposeResources) || (function (SuppressedError) { ++ return function (env) { ++ function fail(e) { ++ env.error = env.hasError ? new SuppressedError(e, env.error, "An error was suppressed during disposal.") : e; ++ env.hasError = true; ++ } ++ function next() { ++ while (env.stack.length) { ++ var rec = env.stack.pop(); ++ try { ++ var result = rec.dispose && rec.dispose.call(rec.value); ++ if (rec.async) return Promise.resolve(result).then(next, function(e) { fail(e); return next(); }); ++ } ++ catch (e) { ++ fail(e); ++ } ++ } ++ if (env.hasError) throw env.error; ++ } ++ return next(); ++ }; ++})(typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) { ++ var e = new Error(message); ++ return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e; ++}); ++var __asyncValues = (this && this.__asyncValues) || function (o) { ++ if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); ++ var m = o[Symbol.asyncIterator], i; ++ return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i); ++ function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; } ++ function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); } ++}; ++function main() { ++ var _a, e_1, _b, _c; ++ return __awaiter(this, void 0, void 0, function () { ++ var _d, _e, _f, d1_1, env_1, d1, e_2, result_1, e_1_1; ++ var _g, _h; ++ return __generator(this, function (_j) { ++ switch (_j.label) { ++ case 0: ++ _j.trys.push([0, 10, 11, 16]); ++ _d = true, _e = __asyncValues([(_g = {}, _g[Symbol.asyncDispose] = function () { ++ return __awaiter(this, void 0, void 0, function () { return __generator(this, function (_a) { ++ return [2 /*return*/]; ++ }); }); ++ }, _g), (_h = {}, _h[Symbol.dispose] = function () { }, _h), null, undefined]); ++ _j.label = 1; ++ case 1: return [4 /*yield*/, _e.next()]; ++ case 2: ++ if (!(_f = _j.sent(), _a = _f.done, !_a)) return [3 /*break*/, 9]; ++ _c = _f.value; ++ _d = false; ++ d1_1 = _c; ++ env_1 = { stack: [], error: void 0, hasError: false }; ++ _j.label = 3; ++ case 3: ++ _j.trys.push([3, 4, 5, 8]); ++ d1 = __addDisposableResource(env_1, d1_1, true); ++ return [3 /*break*/, 8]; ++ case 4: ++ e_2 = _j.sent(); ++ env_1.error = e_2; ++ env_1.hasError = true; ++ return [3 /*break*/, 8]; ++ case 5: ++ result_1 = __disposeResources(env_1); ++ if (!result_1) return [3 /*break*/, 7]; ++ return [4 /*yield*/, result_1]; ++ case 6: ++ _j.sent(); ++ _j.label = 7; ++ case 7: return [7 /*endfinally*/]; ++ case 8: ++ _d = true; ++ return [3 /*break*/, 1]; ++ case 9: return [3 /*break*/, 16]; ++ case 10: ++ e_1_1 = _j.sent(); ++ e_1 = { error: e_1_1 }; ++ return [3 /*break*/, 16]; ++ case 11: ++ _j.trys.push([11, , 14, 15]); ++ if (!(!_d && !_a && (_b = _e.return))) return [3 /*break*/, 13]; ++ return [4 /*yield*/, _b.call(_e)]; ++ case 12: ++ _j.sent(); ++ _j.label = 13; ++ case 13: return [3 /*break*/, 15]; ++ case 14: ++ if (e_1) throw e_1.error; ++ return [7 /*endfinally*/]; ++ case 15: return [7 /*endfinally*/]; ++ case 16: return [2 /*return*/]; ++ } ++ }); ++ }); ++} +diff --git a/tests/baselines/reference/awaitUsingDeclarationsInForAwaitOf(target=esnext).js b/tests/baselines/reference/awaitUsingDeclarationsInForAwaitOf(target=esnext).js +new file mode 100644 +index 000000000..454e99531 +--- /dev/null ++++ b/tests/baselines/reference/awaitUsingDeclarationsInForAwaitOf(target=esnext).js +@@ -0,0 +1,13 @@ ++//// [tests/cases/conformance/statements/VariableStatements/usingDeclarations/awaitUsingDeclarationsInForAwaitOf.ts] //// ++ ++//// [awaitUsingDeclarationsInForAwaitOf.ts] ++async function main() { ++ for await (await using d1 of [{ async [Symbol.asyncDispose]() {} }, { [Symbol.dispose]() {} }, null, undefined]) { ++ } ++} ++ ++//// [awaitUsingDeclarationsInForAwaitOf.js] ++async function main() { ++ for await (await using d1 of [{ async [Symbol.asyncDispose]() { } }, { [Symbol.dispose]() { } }, null, undefined]) { ++ } ++} +diff --git a/tests/baselines/reference/awaitUsingDeclarationsInForIn.errors.txt b/tests/baselines/reference/awaitUsingDeclarationsInForIn.errors.txt +new file mode 100644 +index 000000000..50f340e64 +--- /dev/null ++++ b/tests/baselines/reference/awaitUsingDeclarationsInForIn.errors.txt +@@ -0,0 +1,11 @@ ++awaitUsingDeclarationsInForIn.ts(2,10): error TS1494: The left-hand side of a 'for...in' statement cannot be an 'await using' declaration. ++ ++ ++==== awaitUsingDeclarationsInForIn.ts (1 errors) ==== ++ async function main() { ++ for (await using x in {}) { ++ ~~~~~~~~~~~~~ ++!!! error TS1494: The left-hand side of a 'for...in' statement cannot be an 'await using' declaration. ++ } ++ } ++ +\ No newline at end of file +diff --git a/tests/baselines/reference/awaitUsingDeclarationsInForIn.js b/tests/baselines/reference/awaitUsingDeclarationsInForIn.js +new file mode 100644 +index 000000000..60b8eecfd +--- /dev/null ++++ b/tests/baselines/reference/awaitUsingDeclarationsInForIn.js +@@ -0,0 +1,14 @@ ++//// [tests/cases/conformance/statements/VariableStatements/usingDeclarations/awaitUsingDeclarationsInForIn.ts] //// ++ ++//// [awaitUsingDeclarationsInForIn.ts] ++async function main() { ++ for (await using x in {}) { ++ } ++} ++ ++ ++//// [awaitUsingDeclarationsInForIn.js] ++async function main() { ++ for (await using x in {}) { ++ } ++} +diff --git a/tests/baselines/reference/awaitUsingDeclarationsInForOf.1(target=es2015).js b/tests/baselines/reference/awaitUsingDeclarationsInForOf.1(target=es2015).js +new file mode 100644 +index 000000000..3f34c4582 +--- /dev/null ++++ b/tests/baselines/reference/awaitUsingDeclarationsInForOf.1(target=es2015).js +@@ -0,0 +1,85 @@ ++//// [tests/cases/conformance/statements/VariableStatements/usingDeclarations/awaitUsingDeclarationsInForOf.1.ts] //// ++ ++//// [awaitUsingDeclarationsInForOf.1.ts] ++async function main() { ++ for (await using d1 of [{ async [Symbol.asyncDispose]() {} }, { [Symbol.dispose]() {} }, null, undefined]) { ++ } ++} ++ ++ ++//// [awaitUsingDeclarationsInForOf.1.js] ++var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { ++ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } ++ return new (P || (P = Promise))(function (resolve, reject) { ++ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } ++ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } ++ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } ++ step((generator = generator.apply(thisArg, _arguments || [])).next()); ++ }); ++}; ++var __addDisposableResource = (this && this.__addDisposableResource) || function (env, value, async) { ++ if (value !== null && value !== void 0) { ++ if (typeof value !== "object") throw new TypeError("Object expected."); ++ var dispose; ++ if (async) { ++ if (!Symbol.asyncDispose) throw new TypeError("Symbol.asyncDispose is not defined."); ++ dispose = value[Symbol.asyncDispose]; ++ } ++ if (dispose === void 0) { ++ if (!Symbol.dispose) throw new TypeError("Symbol.dispose is not defined."); ++ dispose = value[Symbol.dispose]; ++ } ++ if (typeof dispose !== "function") throw new TypeError("Object not disposable."); ++ env.stack.push({ value: value, dispose: dispose, async: async }); ++ } ++ else if (async) { ++ env.stack.push({ async: true }); ++ } ++ return value; ++}; ++var __disposeResources = (this && this.__disposeResources) || (function (SuppressedError) { ++ return function (env) { ++ function fail(e) { ++ env.error = env.hasError ? new SuppressedError(e, env.error, "An error was suppressed during disposal.") : e; ++ env.hasError = true; ++ } ++ function next() { ++ while (env.stack.length) { ++ var rec = env.stack.pop(); ++ try { ++ var result = rec.dispose && rec.dispose.call(rec.value); ++ if (rec.async) return Promise.resolve(result).then(next, function(e) { fail(e); return next(); }); ++ } ++ catch (e) { ++ fail(e); ++ } ++ } ++ if (env.hasError) throw env.error; ++ } ++ return next(); ++ }; ++})(typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) { ++ var e = new Error(message); ++ return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e; ++}); ++function main() { ++ return __awaiter(this, void 0, void 0, function* () { ++ for (const d1_1 of [{ [Symbol.asyncDispose]() { ++ return __awaiter(this, void 0, void 0, function* () { }); ++ } }, { [Symbol.dispose]() { } }, null, undefined]) { ++ const env_1 = { stack: [], error: void 0, hasError: false }; ++ try { ++ const d1 = __addDisposableResource(env_1, d1_1, true); ++ } ++ catch (e_1) { ++ env_1.error = e_1; ++ env_1.hasError = true; ++ } ++ finally { ++ const result_1 = __disposeResources(env_1); ++ if (result_1) ++ yield result_1; ++ } ++ } ++ }); ++} +diff --git a/tests/baselines/reference/awaitUsingDeclarationsInForOf.1(target=es2017).js b/tests/baselines/reference/awaitUsingDeclarationsInForOf.1(target=es2017).js +new file mode 100644 +index 000000000..a9555cf3f +--- /dev/null ++++ b/tests/baselines/reference/awaitUsingDeclarationsInForOf.1(target=es2017).js +@@ -0,0 +1,72 @@ ++//// [tests/cases/conformance/statements/VariableStatements/usingDeclarations/awaitUsingDeclarationsInForOf.1.ts] //// ++ ++//// [awaitUsingDeclarationsInForOf.1.ts] ++async function main() { ++ for (await using d1 of [{ async [Symbol.asyncDispose]() {} }, { [Symbol.dispose]() {} }, null, undefined]) { ++ } ++} ++ ++ ++//// [awaitUsingDeclarationsInForOf.1.js] ++var __addDisposableResource = (this && this.__addDisposableResource) || function (env, value, async) { ++ if (value !== null && value !== void 0) { ++ if (typeof value !== "object") throw new TypeError("Object expected."); ++ var dispose; ++ if (async) { ++ if (!Symbol.asyncDispose) throw new TypeError("Symbol.asyncDispose is not defined."); ++ dispose = value[Symbol.asyncDispose]; ++ } ++ if (dispose === void 0) { ++ if (!Symbol.dispose) throw new TypeError("Symbol.dispose is not defined."); ++ dispose = value[Symbol.dispose]; ++ } ++ if (typeof dispose !== "function") throw new TypeError("Object not disposable."); ++ env.stack.push({ value: value, dispose: dispose, async: async }); ++ } ++ else if (async) { ++ env.stack.push({ async: true }); ++ } ++ return value; ++}; ++var __disposeResources = (this && this.__disposeResources) || (function (SuppressedError) { ++ return function (env) { ++ function fail(e) { ++ env.error = env.hasError ? new SuppressedError(e, env.error, "An error was suppressed during disposal.") : e; ++ env.hasError = true; ++ } ++ function next() { ++ while (env.stack.length) { ++ var rec = env.stack.pop(); ++ try { ++ var result = rec.dispose && rec.dispose.call(rec.value); ++ if (rec.async) return Promise.resolve(result).then(next, function(e) { fail(e); return next(); }); ++ } ++ catch (e) { ++ fail(e); ++ } ++ } ++ if (env.hasError) throw env.error; ++ } ++ return next(); ++ }; ++})(typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) { ++ var e = new Error(message); ++ return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e; ++}); ++async function main() { ++ for (const d1_1 of [{ async [Symbol.asyncDispose]() { } }, { [Symbol.dispose]() { } }, null, undefined]) { ++ const env_1 = { stack: [], error: void 0, hasError: false }; ++ try { ++ const d1 = __addDisposableResource(env_1, d1_1, true); ++ } ++ catch (e_1) { ++ env_1.error = e_1; ++ env_1.hasError = true; ++ } ++ finally { ++ const result_1 = __disposeResources(env_1); ++ if (result_1) ++ await result_1; ++ } ++ } ++} +diff --git a/tests/baselines/reference/awaitUsingDeclarationsInForOf.1(target=es2022).js b/tests/baselines/reference/awaitUsingDeclarationsInForOf.1(target=es2022).js +new file mode 100644 +index 000000000..a9555cf3f +--- /dev/null ++++ b/tests/baselines/reference/awaitUsingDeclarationsInForOf.1(target=es2022).js +@@ -0,0 +1,72 @@ ++//// [tests/cases/conformance/statements/VariableStatements/usingDeclarations/awaitUsingDeclarationsInForOf.1.ts] //// ++ ++//// [awaitUsingDeclarationsInForOf.1.ts] ++async function main() { ++ for (await using d1 of [{ async [Symbol.asyncDispose]() {} }, { [Symbol.dispose]() {} }, null, undefined]) { ++ } ++} ++ ++ ++//// [awaitUsingDeclarationsInForOf.1.js] ++var __addDisposableResource = (this && this.__addDisposableResource) || function (env, value, async) { ++ if (value !== null && value !== void 0) { ++ if (typeof value !== "object") throw new TypeError("Object expected."); ++ var dispose; ++ if (async) { ++ if (!Symbol.asyncDispose) throw new TypeError("Symbol.asyncDispose is not defined."); ++ dispose = value[Symbol.asyncDispose]; ++ } ++ if (dispose === void 0) { ++ if (!Symbol.dispose) throw new TypeError("Symbol.dispose is not defined."); ++ dispose = value[Symbol.dispose]; ++ } ++ if (typeof dispose !== "function") throw new TypeError("Object not disposable."); ++ env.stack.push({ value: value, dispose: dispose, async: async }); ++ } ++ else if (async) { ++ env.stack.push({ async: true }); ++ } ++ return value; ++}; ++var __disposeResources = (this && this.__disposeResources) || (function (SuppressedError) { ++ return function (env) { ++ function fail(e) { ++ env.error = env.hasError ? new SuppressedError(e, env.error, "An error was suppressed during disposal.") : e; ++ env.hasError = true; ++ } ++ function next() { ++ while (env.stack.length) { ++ var rec = env.stack.pop(); ++ try { ++ var result = rec.dispose && rec.dispose.call(rec.value); ++ if (rec.async) return Promise.resolve(result).then(next, function(e) { fail(e); return next(); }); ++ } ++ catch (e) { ++ fail(e); ++ } ++ } ++ if (env.hasError) throw env.error; ++ } ++ return next(); ++ }; ++})(typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) { ++ var e = new Error(message); ++ return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e; ++}); ++async function main() { ++ for (const d1_1 of [{ async [Symbol.asyncDispose]() { } }, { [Symbol.dispose]() { } }, null, undefined]) { ++ const env_1 = { stack: [], error: void 0, hasError: false }; ++ try { ++ const d1 = __addDisposableResource(env_1, d1_1, true); ++ } ++ catch (e_1) { ++ env_1.error = e_1; ++ env_1.hasError = true; ++ } ++ finally { ++ const result_1 = __disposeResources(env_1); ++ if (result_1) ++ await result_1; ++ } ++ } ++} +diff --git a/tests/baselines/reference/awaitUsingDeclarationsInForOf.1(target=es5).js b/tests/baselines/reference/awaitUsingDeclarationsInForOf.1(target=es5).js +new file mode 100644 +index 000000000..d9514c078 +--- /dev/null ++++ b/tests/baselines/reference/awaitUsingDeclarationsInForOf.1(target=es5).js +@@ -0,0 +1,134 @@ ++//// [tests/cases/conformance/statements/VariableStatements/usingDeclarations/awaitUsingDeclarationsInForOf.1.ts] //// ++ ++//// [awaitUsingDeclarationsInForOf.1.ts] ++async function main() { ++ for (await using d1 of [{ async [Symbol.asyncDispose]() {} }, { [Symbol.dispose]() {} }, null, undefined]) { ++ } ++} ++ ++ ++//// [awaitUsingDeclarationsInForOf.1.js] ++var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { ++ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } ++ return new (P || (P = Promise))(function (resolve, reject) { ++ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } ++ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } ++ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } ++ step((generator = generator.apply(thisArg, _arguments || [])).next()); ++ }); ++}; ++var __generator = (this && this.__generator) || function (thisArg, body) { ++ var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; ++ return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; ++ function verb(n) { return function (v) { return step([n, v]); }; } ++ function step(op) { ++ if (f) throw new TypeError("Generator is already executing."); ++ while (g && (g = 0, op[0] && (_ = 0)), _) try { ++ if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; ++ if (y = 0, t) op = [op[0] & 2, t.value]; ++ switch (op[0]) { ++ case 0: case 1: t = op; break; ++ case 4: _.label++; return { value: op[1], done: false }; ++ case 5: _.label++; y = op[1]; op = [0]; continue; ++ case 7: op = _.ops.pop(); _.trys.pop(); continue; ++ default: ++ if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } ++ if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } ++ if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } ++ if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } ++ if (t[2]) _.ops.pop(); ++ _.trys.pop(); continue; ++ } ++ op = body.call(thisArg, _); ++ } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } ++ if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; ++ } ++}; ++var __addDisposableResource = (this && this.__addDisposableResource) || function (env, value, async) { ++ if (value !== null && value !== void 0) { ++ if (typeof value !== "object") throw new TypeError("Object expected."); ++ var dispose; ++ if (async) { ++ if (!Symbol.asyncDispose) throw new TypeError("Symbol.asyncDispose is not defined."); ++ dispose = value[Symbol.asyncDispose]; ++ } ++ if (dispose === void 0) { ++ if (!Symbol.dispose) throw new TypeError("Symbol.dispose is not defined."); ++ dispose = value[Symbol.dispose]; ++ } ++ if (typeof dispose !== "function") throw new TypeError("Object not disposable."); ++ env.stack.push({ value: value, dispose: dispose, async: async }); ++ } ++ else if (async) { ++ env.stack.push({ async: true }); ++ } ++ return value; ++}; ++var __disposeResources = (this && this.__disposeResources) || (function (SuppressedError) { ++ return function (env) { ++ function fail(e) { ++ env.error = env.hasError ? new SuppressedError(e, env.error, "An error was suppressed during disposal.") : e; ++ env.hasError = true; ++ } ++ function next() { ++ while (env.stack.length) { ++ var rec = env.stack.pop(); ++ try { ++ var result = rec.dispose && rec.dispose.call(rec.value); ++ if (rec.async) return Promise.resolve(result).then(next, function(e) { fail(e); return next(); }); ++ } ++ catch (e) { ++ fail(e); ++ } ++ } ++ if (env.hasError) throw env.error; ++ } ++ return next(); ++ }; ++})(typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) { ++ var e = new Error(message); ++ return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e; ++}); ++function main() { ++ return __awaiter(this, void 0, void 0, function () { ++ var _i, _a, d1_1, env_1, d1, e_1, result_1; ++ var _b, _c; ++ return __generator(this, function (_d) { ++ switch (_d.label) { ++ case 0: ++ _i = 0, _a = [(_b = {}, _b[Symbol.asyncDispose] = function () { ++ return __awaiter(this, void 0, void 0, function () { return __generator(this, function (_a) { ++ return [2 /*return*/]; ++ }); }); ++ }, _b), (_c = {}, _c[Symbol.dispose] = function () { }, _c), null, undefined]; ++ _d.label = 1; ++ case 1: ++ if (!(_i < _a.length)) return [3 /*break*/, 8]; ++ d1_1 = _a[_i]; ++ env_1 = { stack: [], error: void 0, hasError: false }; ++ _d.label = 2; ++ case 2: ++ _d.trys.push([2, 3, 4, 7]); ++ d1 = __addDisposableResource(env_1, d1_1, true); ++ return [3 /*break*/, 7]; ++ case 3: ++ e_1 = _d.sent(); ++ env_1.error = e_1; ++ env_1.hasError = true; ++ return [3 /*break*/, 7]; ++ case 4: ++ result_1 = __disposeResources(env_1); ++ if (!result_1) return [3 /*break*/, 6]; ++ return [4 /*yield*/, result_1]; ++ case 5: ++ _d.sent(); ++ _d.label = 6; ++ case 6: return [7 /*endfinally*/]; ++ case 7: ++ _i++; ++ return [3 /*break*/, 1]; ++ case 8: return [2 /*return*/]; ++ } ++ }); ++ }); ++} +diff --git a/tests/baselines/reference/awaitUsingDeclarationsInForOf.1(target=esnext).js b/tests/baselines/reference/awaitUsingDeclarationsInForOf.1(target=esnext).js +new file mode 100644 +index 000000000..28c6d451b +--- /dev/null ++++ b/tests/baselines/reference/awaitUsingDeclarationsInForOf.1(target=esnext).js +@@ -0,0 +1,14 @@ ++//// [tests/cases/conformance/statements/VariableStatements/usingDeclarations/awaitUsingDeclarationsInForOf.1.ts] //// ++ ++//// [awaitUsingDeclarationsInForOf.1.ts] ++async function main() { ++ for (await using d1 of [{ async [Symbol.asyncDispose]() {} }, { [Symbol.dispose]() {} }, null, undefined]) { ++ } ++} ++ ++ ++//// [awaitUsingDeclarationsInForOf.1.js] ++async function main() { ++ for (await using d1 of [{ async [Symbol.asyncDispose]() { } }, { [Symbol.dispose]() { } }, null, undefined]) { ++ } ++} +diff --git a/tests/baselines/reference/awaitUsingDeclarationsInForOf.2.errors.txt b/tests/baselines/reference/awaitUsingDeclarationsInForOf.2.errors.txt +new file mode 100644 +index 000000000..2fd471769 +--- /dev/null ++++ b/tests/baselines/reference/awaitUsingDeclarationsInForOf.2.errors.txt +@@ -0,0 +1,20 @@ ++awaitUsingDeclarationsInForOf.2.ts(2,10): error TS2487: The left-hand side of a 'for...of' statement must be a variable or a property access. ++awaitUsingDeclarationsInForOf.2.ts(2,16): error TS2304: Cannot find name 'using'. ++awaitUsingDeclarationsInForOf.2.ts(2,25): error TS2304: Cannot find name 'of'. ++awaitUsingDeclarationsInForOf.2.ts(2,29): error TS1011: An element access expression should take an argument. ++ ++ ++==== awaitUsingDeclarationsInForOf.2.ts (4 errors) ==== ++ async function main() { ++ for (await using of of []) { ++ ~~~~~~~~~~~ ++!!! error TS2487: The left-hand side of a 'for...of' statement must be a variable or a property access. ++ ~~~~~ ++!!! error TS2304: Cannot find name 'using'. ++ ~~ ++!!! error TS2304: Cannot find name 'of'. ++ ++!!! error TS1011: An element access expression should take an argument. ++ } ++ } ++ +\ No newline at end of file +diff --git a/tests/baselines/reference/awaitUsingDeclarationsInForOf.2.js b/tests/baselines/reference/awaitUsingDeclarationsInForOf.2.js +new file mode 100644 +index 000000000..19d7b7d57 +--- /dev/null ++++ b/tests/baselines/reference/awaitUsingDeclarationsInForOf.2.js +@@ -0,0 +1,14 @@ ++//// [tests/cases/conformance/statements/VariableStatements/usingDeclarations/awaitUsingDeclarationsInForOf.2.ts] //// ++ ++//// [awaitUsingDeclarationsInForOf.2.ts] ++async function main() { ++ for (await using of of []) { ++ } ++} ++ ++ ++//// [awaitUsingDeclarationsInForOf.2.js] ++async function main() { ++ for (await using of of[]) { ++ } ++} +diff --git a/tests/baselines/reference/awaitUsingDeclarationsInForOf.3.errors.txt b/tests/baselines/reference/awaitUsingDeclarationsInForOf.3.errors.txt +new file mode 100644 +index 000000000..1379bfb71 +--- /dev/null ++++ b/tests/baselines/reference/awaitUsingDeclarationsInForOf.3.errors.txt +@@ -0,0 +1,11 @@ ++awaitUsingDeclarationsInForOf.3.ts(2,22): error TS1492: 'await using' declarations may not have binding patterns. ++ ++ ++==== awaitUsingDeclarationsInForOf.3.ts (1 errors) ==== ++ async function main() { ++ for (await using {} of []) { ++ ~~ ++!!! error TS1492: 'await using' declarations may not have binding patterns. ++ } ++ } ++ +\ No newline at end of file +diff --git a/tests/baselines/reference/awaitUsingDeclarationsInForOf.3.js b/tests/baselines/reference/awaitUsingDeclarationsInForOf.3.js +new file mode 100644 +index 000000000..0b25f1b2c +--- /dev/null ++++ b/tests/baselines/reference/awaitUsingDeclarationsInForOf.3.js +@@ -0,0 +1,14 @@ ++//// [tests/cases/conformance/statements/VariableStatements/usingDeclarations/awaitUsingDeclarationsInForOf.3.ts] //// ++ ++//// [awaitUsingDeclarationsInForOf.3.ts] ++async function main() { ++ for (await using {} of []) { ++ } ++} ++ ++ ++//// [awaitUsingDeclarationsInForOf.3.js] ++async function main() { ++ for (await using {} of []) { ++ } ++} +diff --git a/tests/baselines/reference/awaitUsingDeclarationsTopLevelOfModule.1(module=esnext).js b/tests/baselines/reference/awaitUsingDeclarationsTopLevelOfModule.1(module=esnext).js +new file mode 100644 +index 000000000..6d86c80c6 +--- /dev/null ++++ b/tests/baselines/reference/awaitUsingDeclarationsTopLevelOfModule.1(module=esnext).js +@@ -0,0 +1,40 @@ ++//// [tests/cases/conformance/statements/VariableStatements/usingDeclarations/awaitUsingDeclarationsTopLevelOfModule.1.ts] //// ++ ++//// [awaitUsingDeclarationsTopLevelOfModule.1.ts] ++export const x = 1; ++export { y }; ++ ++await using z = { async [Symbol.asyncDispose]() {} }; ++ ++const y = 2; ++ ++export const w = 3; ++ ++export default 4; ++ ++console.log(w, x, y, z); ++ ++ ++//// [awaitUsingDeclarationsTopLevelOfModule.1.js] ++export const x = 1; ++export { y }; ++export { _default as default }; ++var z, y, _default; ++export let w; ++const env_1 = { stack: [], error: void 0, hasError: false }; ++try { ++ z = __addDisposableResource(env_1, { async [Symbol.asyncDispose]() { } }, true); ++ y = 2; ++ w = 3; ++ _default = 4; ++ console.log(w, x, y, z); ++} ++catch (e_1) { ++ env_1.error = e_1; ++ env_1.hasError = true; ++} ++finally { ++ const result_1 = __disposeResources(env_1); ++ if (result_1) ++ await result_1; ++} +diff --git a/tests/baselines/reference/awaitUsingDeclarationsTopLevelOfModule.1(module=system).js b/tests/baselines/reference/awaitUsingDeclarationsTopLevelOfModule.1(module=system).js +new file mode 100644 +index 000000000..f321eda5e +--- /dev/null ++++ b/tests/baselines/reference/awaitUsingDeclarationsTopLevelOfModule.1(module=system).js +@@ -0,0 +1,46 @@ ++//// [tests/cases/conformance/statements/VariableStatements/usingDeclarations/awaitUsingDeclarationsTopLevelOfModule.1.ts] //// ++ ++//// [awaitUsingDeclarationsTopLevelOfModule.1.ts] ++export const x = 1; ++export { y }; ++ ++await using z = { async [Symbol.asyncDispose]() {} }; ++ ++const y = 2; ++ ++export const w = 3; ++ ++export default 4; ++ ++console.log(w, x, y, z); ++ ++ ++//// [awaitUsingDeclarationsTopLevelOfModule.1.js] ++System.register([], function (exports_1, context_1) { ++ "use strict"; ++ var x, z, y, _default, w, env_1; ++ var __moduleName = context_1 && context_1.id; ++ return { ++ setters: [], ++ execute: async function () { ++ exports_1("x", x = 1); ++ env_1 = { stack: [], error: void 0, hasError: false }; ++ try { ++ z = __addDisposableResource(env_1, { async [Symbol.asyncDispose]() { } }, true); ++ exports_1("y", y = 2); ++ exports_1("w", w = 3); ++ exports_1("default", _default = 4); ++ console.log(w, x, y, z); ++ } ++ catch (e_1) { ++ env_1.error = e_1; ++ env_1.hasError = true; ++ } ++ finally { ++ const result_1 = __disposeResources(env_1); ++ if (result_1) ++ await result_1; ++ } ++ } ++ }; ++}); +diff --git a/tests/baselines/reference/awaitUsingDeclarationsWithImportHelpers.errors.txt b/tests/baselines/reference/awaitUsingDeclarationsWithImportHelpers.errors.txt +new file mode 100644 +index 000000000..42a94f772 +--- /dev/null ++++ b/tests/baselines/reference/awaitUsingDeclarationsWithImportHelpers.errors.txt +@@ -0,0 +1,11 @@ ++awaitUsingDeclarationsWithImportHelpers.ts(4,5): error TS2354: This syntax requires an imported helper but module 'tslib' cannot be found. ++ ++ ++==== awaitUsingDeclarationsWithImportHelpers.ts (1 errors) ==== ++ export {}; ++ ++ async function f() { ++ await using a = null; ++ ~~~~~~~~~~~~~~~~~~~~ ++!!! error TS2354: This syntax requires an imported helper but module 'tslib' cannot be found. ++ } +\ No newline at end of file +diff --git a/tests/baselines/reference/awaitUsingDeclarationsWithImportHelpers.js b/tests/baselines/reference/awaitUsingDeclarationsWithImportHelpers.js +new file mode 100644 +index 000000000..fcc0a66c4 +--- /dev/null ++++ b/tests/baselines/reference/awaitUsingDeclarationsWithImportHelpers.js +@@ -0,0 +1,14 @@ ++//// [tests/cases/conformance/statements/VariableStatements/usingDeclarations/awaitUsingDeclarationsWithImportHelpers.ts] //// ++ ++//// [awaitUsingDeclarationsWithImportHelpers.ts] ++export {}; ++ ++async function f() { ++ await using a = null; ++} ++ ++//// [awaitUsingDeclarationsWithImportHelpers.js] ++async function f() { ++ await using a = null; ++} ++export {}; +diff --git a/tests/baselines/reference/classStaticBlock23(target=es2022).errors.txt b/tests/baselines/reference/classStaticBlock23(target=es2022).errors.txt +index de958d062..6868d85c1 100644 +--- a/tests/baselines/reference/classStaticBlock23(target=es2022).errors.txt ++++ b/tests/baselines/reference/classStaticBlock23(target=es2022).errors.txt +@@ -1,5 +1,5 @@ +-classStaticBlock23.ts(5,9): error TS18038: 'For await' loops cannot be used inside a class static block. +-classStaticBlock23.ts(14,11): error TS18038: 'For await' loops cannot be used inside a class static block. ++classStaticBlock23.ts(5,9): error TS18038: 'for await' loops cannot be used inside a class static block. ++classStaticBlock23.ts(14,11): error TS18038: 'for await' loops cannot be used inside a class static block. + + + ==== classStaticBlock23.ts (2 errors) ==== +@@ -9,7 +9,7 @@ classStaticBlock23.ts(14,11): error TS18038: 'For await' loops cannot be used in + static { + for await (const nn of nums) { + ~~~~~ +-!!! error TS18038: 'For await' loops cannot be used inside a class static block. ++!!! error TS18038: 'for await' loops cannot be used inside a class static block. + console.log(nn) + } + } +@@ -20,7 +20,7 @@ classStaticBlock23.ts(14,11): error TS18038: 'For await' loops cannot be used in + static { + for await (const nn of nums) { + ~~~~~ +-!!! error TS18038: 'For await' loops cannot be used inside a class static block. ++!!! error TS18038: 'for await' loops cannot be used inside a class static block. + console.log(nn) + } + } +diff --git a/tests/baselines/reference/classStaticBlock23(target=esnext).errors.txt b/tests/baselines/reference/classStaticBlock23(target=esnext).errors.txt +index de958d062..6868d85c1 100644 +--- a/tests/baselines/reference/classStaticBlock23(target=esnext).errors.txt ++++ b/tests/baselines/reference/classStaticBlock23(target=esnext).errors.txt +@@ -1,5 +1,5 @@ +-classStaticBlock23.ts(5,9): error TS18038: 'For await' loops cannot be used inside a class static block. +-classStaticBlock23.ts(14,11): error TS18038: 'For await' loops cannot be used inside a class static block. ++classStaticBlock23.ts(5,9): error TS18038: 'for await' loops cannot be used inside a class static block. ++classStaticBlock23.ts(14,11): error TS18038: 'for await' loops cannot be used inside a class static block. + + + ==== classStaticBlock23.ts (2 errors) ==== +@@ -9,7 +9,7 @@ classStaticBlock23.ts(14,11): error TS18038: 'For await' loops cannot be used in + static { + for await (const nn of nums) { + ~~~~~ +-!!! error TS18038: 'For await' loops cannot be used inside a class static block. ++!!! error TS18038: 'for await' loops cannot be used inside a class static block. + console.log(nn) + } + } +@@ -20,7 +20,7 @@ classStaticBlock23.ts(14,11): error TS18038: 'For await' loops cannot be used in + static { + for await (const nn of nums) { + ~~~~~ +-!!! error TS18038: 'For await' loops cannot be used inside a class static block. ++!!! error TS18038: 'for await' loops cannot be used inside a class static block. + console.log(nn) + } + } +diff --git a/tests/baselines/reference/classStaticBlock26(target=es2022).errors.txt b/tests/baselines/reference/classStaticBlock26(target=es2022).errors.txt +index 841adafab..108e2368d 100644 +--- a/tests/baselines/reference/classStaticBlock26(target=es2022).errors.txt ++++ b/tests/baselines/reference/classStaticBlock26(target=es2022).errors.txt +@@ -1,20 +1,20 @@ +-classStaticBlock26.ts(3,9): error TS18037: Await expression cannot be used inside a class static block. ++classStaticBlock26.ts(3,9): error TS18037: 'await' expression cannot be used inside a class static block. + classStaticBlock26.ts(3,14): error TS1109: Expression expected. +-classStaticBlock26.ts(6,9): error TS18037: Await expression cannot be used inside a class static block. +-classStaticBlock26.ts(9,13): error TS18037: Await expression cannot be used inside a class static block. ++classStaticBlock26.ts(6,9): error TS18037: 'await' expression cannot be used inside a class static block. ++classStaticBlock26.ts(9,13): error TS18037: 'await' expression cannot be used inside a class static block. + classStaticBlock26.ts(9,18): error TS1109: Expression expected. +-classStaticBlock26.ts(13,14): error TS18037: Await expression cannot be used inside a class static block. ++classStaticBlock26.ts(13,14): error TS18037: 'await' expression cannot be used inside a class static block. + classStaticBlock26.ts(13,19): error TS1109: Expression expected. + classStaticBlock26.ts(17,18): error TS1005: ':' expected. +-classStaticBlock26.ts(20,9): error TS18037: Await expression cannot be used inside a class static block. ++classStaticBlock26.ts(20,9): error TS18037: 'await' expression cannot be used inside a class static block. + classStaticBlock26.ts(20,14): error TS1109: Expression expected. + classStaticBlock26.ts(21,15): error TS1003: Identifier expected. +-classStaticBlock26.ts(21,15): error TS18037: Await expression cannot be used inside a class static block. ++classStaticBlock26.ts(21,15): error TS18037: 'await' expression cannot be used inside a class static block. + classStaticBlock26.ts(21,20): error TS1109: Expression expected. +-classStaticBlock26.ts(25,21): error TS18037: Await expression cannot be used inside a class static block. ++classStaticBlock26.ts(25,21): error TS18037: 'await' expression cannot be used inside a class static block. + classStaticBlock26.ts(25,26): error TS1109: Expression expected. + classStaticBlock26.ts(25,28): error TS1005: ';' expected. +-classStaticBlock26.ts(26,21): error TS18037: Await expression cannot be used inside a class static block. ++classStaticBlock26.ts(26,21): error TS18037: 'await' expression cannot be used inside a class static block. + classStaticBlock26.ts(26,27): error TS1109: Expression expected. + + +@@ -23,19 +23,19 @@ classStaticBlock26.ts(26,27): error TS1109: Expression expected. + static { + await; // illegal + ~~~~~ +-!!! error TS18037: Await expression cannot be used inside a class static block. ++!!! error TS18037: 'await' expression cannot be used inside a class static block. + ~ + !!! error TS1109: Expression expected. + } + static { + await (1); // illegal + ~~~~~~~~~ +-!!! error TS18037: Await expression cannot be used inside a class static block. ++!!! error TS18037: 'await' expression cannot be used inside a class static block. + } + static { + ({ [await]: 1 }); // illegal + ~~~~~ +-!!! error TS18037: Await expression cannot be used inside a class static block. ++!!! error TS18037: 'await' expression cannot be used inside a class static block. + ~ + !!! error TS1109: Expression expected. + } +@@ -43,7 +43,7 @@ classStaticBlock26.ts(26,27): error TS1109: Expression expected. + class D { + [await] = 1; // illegal (computed property names are evaluated outside of a class body + ~~~~~ +-!!! error TS18037: Await expression cannot be used inside a class static block. ++!!! error TS18037: 'await' expression cannot be used inside a class static block. + ~ + !!! error TS1109: Expression expected. + }; +@@ -56,14 +56,14 @@ classStaticBlock26.ts(26,27): error TS1109: Expression expected. + static { + await: // illegal, 'await' cannot be used as a label + ~~~~~ +-!!! error TS18037: Await expression cannot be used inside a class static block. ++!!! error TS18037: 'await' expression cannot be used inside a class static block. + ~ + !!! error TS1109: Expression expected. + break await; // illegal, 'await' cannot be used as a label + ~~~~~ + !!! error TS1003: Identifier expected. + ~~~~~ +-!!! error TS18037: Await expression cannot be used inside a class static block. ++!!! error TS18037: 'await' expression cannot be used inside a class static block. + ~ + !!! error TS1109: Expression expected. + } +@@ -71,14 +71,14 @@ classStaticBlock26.ts(26,27): error TS1109: Expression expected. + function f(await) { } + const ff = (await) => { } + ~~~~~ +-!!! error TS18037: Await expression cannot be used inside a class static block. ++!!! error TS18037: 'await' expression cannot be used inside a class static block. + ~ + !!! error TS1109: Expression expected. + ~~ + !!! error TS1005: ';' expected. + const fff = await => { } + ~~~~~ +-!!! error TS18037: Await expression cannot be used inside a class static block. ++!!! error TS18037: 'await' expression cannot be used inside a class static block. + ~~ + !!! error TS1109: Expression expected. + } +diff --git a/tests/baselines/reference/classStaticBlock26(target=esnext).errors.txt b/tests/baselines/reference/classStaticBlock26(target=esnext).errors.txt +index 841adafab..108e2368d 100644 +--- a/tests/baselines/reference/classStaticBlock26(target=esnext).errors.txt ++++ b/tests/baselines/reference/classStaticBlock26(target=esnext).errors.txt +@@ -1,20 +1,20 @@ +-classStaticBlock26.ts(3,9): error TS18037: Await expression cannot be used inside a class static block. ++classStaticBlock26.ts(3,9): error TS18037: 'await' expression cannot be used inside a class static block. + classStaticBlock26.ts(3,14): error TS1109: Expression expected. +-classStaticBlock26.ts(6,9): error TS18037: Await expression cannot be used inside a class static block. +-classStaticBlock26.ts(9,13): error TS18037: Await expression cannot be used inside a class static block. ++classStaticBlock26.ts(6,9): error TS18037: 'await' expression cannot be used inside a class static block. ++classStaticBlock26.ts(9,13): error TS18037: 'await' expression cannot be used inside a class static block. + classStaticBlock26.ts(9,18): error TS1109: Expression expected. +-classStaticBlock26.ts(13,14): error TS18037: Await expression cannot be used inside a class static block. ++classStaticBlock26.ts(13,14): error TS18037: 'await' expression cannot be used inside a class static block. + classStaticBlock26.ts(13,19): error TS1109: Expression expected. + classStaticBlock26.ts(17,18): error TS1005: ':' expected. +-classStaticBlock26.ts(20,9): error TS18037: Await expression cannot be used inside a class static block. ++classStaticBlock26.ts(20,9): error TS18037: 'await' expression cannot be used inside a class static block. + classStaticBlock26.ts(20,14): error TS1109: Expression expected. + classStaticBlock26.ts(21,15): error TS1003: Identifier expected. +-classStaticBlock26.ts(21,15): error TS18037: Await expression cannot be used inside a class static block. ++classStaticBlock26.ts(21,15): error TS18037: 'await' expression cannot be used inside a class static block. + classStaticBlock26.ts(21,20): error TS1109: Expression expected. +-classStaticBlock26.ts(25,21): error TS18037: Await expression cannot be used inside a class static block. ++classStaticBlock26.ts(25,21): error TS18037: 'await' expression cannot be used inside a class static block. + classStaticBlock26.ts(25,26): error TS1109: Expression expected. + classStaticBlock26.ts(25,28): error TS1005: ';' expected. +-classStaticBlock26.ts(26,21): error TS18037: Await expression cannot be used inside a class static block. ++classStaticBlock26.ts(26,21): error TS18037: 'await' expression cannot be used inside a class static block. + classStaticBlock26.ts(26,27): error TS1109: Expression expected. + + +@@ -23,19 +23,19 @@ classStaticBlock26.ts(26,27): error TS1109: Expression expected. + static { + await; // illegal + ~~~~~ +-!!! error TS18037: Await expression cannot be used inside a class static block. ++!!! error TS18037: 'await' expression cannot be used inside a class static block. + ~ + !!! error TS1109: Expression expected. + } + static { + await (1); // illegal + ~~~~~~~~~ +-!!! error TS18037: Await expression cannot be used inside a class static block. ++!!! error TS18037: 'await' expression cannot be used inside a class static block. + } + static { + ({ [await]: 1 }); // illegal + ~~~~~ +-!!! error TS18037: Await expression cannot be used inside a class static block. ++!!! error TS18037: 'await' expression cannot be used inside a class static block. + ~ + !!! error TS1109: Expression expected. + } +@@ -43,7 +43,7 @@ classStaticBlock26.ts(26,27): error TS1109: Expression expected. + class D { + [await] = 1; // illegal (computed property names are evaluated outside of a class body + ~~~~~ +-!!! error TS18037: Await expression cannot be used inside a class static block. ++!!! error TS18037: 'await' expression cannot be used inside a class static block. + ~ + !!! error TS1109: Expression expected. + }; +@@ -56,14 +56,14 @@ classStaticBlock26.ts(26,27): error TS1109: Expression expected. + static { + await: // illegal, 'await' cannot be used as a label + ~~~~~ +-!!! error TS18037: Await expression cannot be used inside a class static block. ++!!! error TS18037: 'await' expression cannot be used inside a class static block. + ~ + !!! error TS1109: Expression expected. + break await; // illegal, 'await' cannot be used as a label + ~~~~~ + !!! error TS1003: Identifier expected. + ~~~~~ +-!!! error TS18037: Await expression cannot be used inside a class static block. ++!!! error TS18037: 'await' expression cannot be used inside a class static block. + ~ + !!! error TS1109: Expression expected. + } +@@ -71,14 +71,14 @@ classStaticBlock26.ts(26,27): error TS1109: Expression expected. + function f(await) { } + const ff = (await) => { } + ~~~~~ +-!!! error TS18037: Await expression cannot be used inside a class static block. ++!!! error TS18037: 'await' expression cannot be used inside a class static block. + ~ + !!! error TS1109: Expression expected. + ~~ + !!! error TS1005: ';' expected. + const fff = await => { } + ~~~~~ +-!!! error TS18037: Await expression cannot be used inside a class static block. ++!!! error TS18037: 'await' expression cannot be used inside a class static block. + ~~ + !!! error TS1109: Expression expected. + } +diff --git a/tests/baselines/reference/classStaticBlock5(target=es5).js b/tests/baselines/reference/classStaticBlock5(target=es5).js +index b514bcbae..e12b8213a 100644 +--- a/tests/baselines/reference/classStaticBlock5(target=es5).js ++++ b/tests/baselines/reference/classStaticBlock5(target=es5).js +@@ -34,7 +34,6 @@ var __extends = (this && this.__extends) || (function () { + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; + })(); +-var _this = this; + var B = /** @class */ (function () { + function B() { + } +diff --git a/tests/baselines/reference/classStaticBlock6.errors.txt b/tests/baselines/reference/classStaticBlock6.errors.txt +index 899187fc6..fad78cc7d 100644 +--- a/tests/baselines/reference/classStaticBlock6.errors.txt ++++ b/tests/baselines/reference/classStaticBlock6.errors.txt +@@ -1,14 +1,14 @@ + classStaticBlock6.ts(8,13): error TS1210: Code contained in a class is evaluated in JavaScript's strict mode which does not allow this use of 'arguments'. For more information, see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Strict_mode. + classStaticBlock6.ts(9,13): error TS1210: Code contained in a class is evaluated in JavaScript's strict mode which does not allow this use of 'eval'. For more information, see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Strict_mode. +-classStaticBlock6.ts(13,9): error TS18037: Await expression cannot be used inside a class static block. ++classStaticBlock6.ts(13,9): error TS18037: 'await' expression cannot be used inside a class static block. + classStaticBlock6.ts(13,14): error TS1109: Expression expected. + classStaticBlock6.ts(17,9): error TS2662: Cannot find name 'arguments'. Did you mean the static member 'C.arguments'? +-classStaticBlock6.ts(18,9): error TS18037: Await expression cannot be used inside a class static block. ++classStaticBlock6.ts(18,9): error TS18037: 'await' expression cannot be used inside a class static block. + classStaticBlock6.ts(18,14): error TS1109: Expression expected. + classStaticBlock6.ts(19,9): error TS2337: Super calls are not permitted outside constructors or in nested functions inside constructors. + classStaticBlock6.ts(32,17): error TS2337: Super calls are not permitted outside constructors or in nested functions inside constructors. + classStaticBlock6.ts(41,13): error TS2815: 'arguments' cannot be referenced in property initializers. +-classStaticBlock6.ts(42,13): error TS18037: Await expression cannot be used inside a class static block. ++classStaticBlock6.ts(42,13): error TS18037: 'await' expression cannot be used inside a class static block. + classStaticBlock6.ts(42,18): error TS1109: Expression expected. + classStaticBlock6.ts(45,17): error TS2522: The 'arguments' object cannot be referenced in an async function or method in ES3 and ES5. Consider using a standard function or method. + classStaticBlock6.ts(46,22): error TS1109: Expression expected. +@@ -34,7 +34,7 @@ classStaticBlock6.ts(55,13): error TS2815: 'arguments' cannot be referenced in p + static { + await: if (true) { + ~~~~~ +-!!! error TS18037: Await expression cannot be used inside a class static block. ++!!! error TS18037: 'await' expression cannot be used inside a class static block. + ~ + !!! error TS1109: Expression expected. + +@@ -45,7 +45,7 @@ classStaticBlock6.ts(55,13): error TS2815: 'arguments' cannot be referenced in p + !!! error TS2662: Cannot find name 'arguments'. Did you mean the static member 'C.arguments'? + await; + ~~~~~ +-!!! error TS18037: Await expression cannot be used inside a class static block. ++!!! error TS18037: 'await' expression cannot be used inside a class static block. + ~ + !!! error TS1109: Expression expected. + super(); +@@ -79,7 +79,7 @@ classStaticBlock6.ts(55,13): error TS2815: 'arguments' cannot be referenced in p + !!! error TS2815: 'arguments' cannot be referenced in property initializers. + await; + ~~~~~ +-!!! error TS18037: Await expression cannot be used inside a class static block. ++!!! error TS18037: 'await' expression cannot be used inside a class static block. + ~ + !!! error TS1109: Expression expected. + +diff --git a/tests/baselines/reference/classStaticBlock7.errors.txt b/tests/baselines/reference/classStaticBlock7.errors.txt +index 89dabc6e0..d149e5bfa 100644 +--- a/tests/baselines/reference/classStaticBlock7.errors.txt ++++ b/tests/baselines/reference/classStaticBlock7.errors.txt +@@ -1,8 +1,8 @@ + error TS2318: Cannot find global type 'IterableIterator'. +-classStaticBlock7.ts(3,9): error TS18037: Await expression cannot be used inside a class static block. ++classStaticBlock7.ts(3,9): error TS18037: 'await' expression cannot be used inside a class static block. + classStaticBlock7.ts(4,9): error TS1163: A 'yield' expression is only allowed in a generator body. + classStaticBlock7.ts(5,9): error TS18041: A 'return' statement cannot be used inside a class static block. +-classStaticBlock7.ts(12,13): error TS18037: Await expression cannot be used inside a class static block. ++classStaticBlock7.ts(12,13): error TS18037: 'await' expression cannot be used inside a class static block. + classStaticBlock7.ts(24,13): error TS1163: A 'yield' expression is only allowed in a generator body. + classStaticBlock7.ts(36,13): error TS18041: A 'return' statement cannot be used inside a class static block. + +@@ -13,7 +13,7 @@ classStaticBlock7.ts(36,13): error TS18041: A 'return' statement cannot be used + static { + await 1; + ~~~~~~~ +-!!! error TS18037: Await expression cannot be used inside a class static block. ++!!! error TS18037: 'await' expression cannot be used inside a class static block. + yield 1; + ~~~~~ + !!! error TS1163: A 'yield' expression is only allowed in a generator body. +@@ -28,7 +28,7 @@ classStaticBlock7.ts(36,13): error TS18041: A 'return' statement cannot be used + static { + await 1; + ~~~~~~~ +-!!! error TS18037: Await expression cannot be used inside a class static block. ++!!! error TS18037: 'await' expression cannot be used inside a class static block. + + async function ff () { + await 1; +diff --git a/tests/baselines/reference/commonJSImportAsPrimaryExpression.js b/tests/baselines/reference/commonJSImportAsPrimaryExpression.js +index 566de0776..a02e7388f 100644 +--- a/tests/baselines/reference/commonJSImportAsPrimaryExpression.js ++++ b/tests/baselines/reference/commonJSImportAsPrimaryExpression.js +@@ -17,13 +17,14 @@ if(foo.C1.s1){ + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.C1 = void 0; +-var C1 = exports.C1 = /** @class */ (function () { ++var C1 = /** @class */ (function () { + function C1() { + this.m1 = 42; + } + C1.s1 = true; + return C1; + }()); ++exports.C1 = C1; + //// [foo_1.js] + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); +diff --git a/tests/baselines/reference/commonJSImportNotAsPrimaryExpression.js b/tests/baselines/reference/commonJSImportNotAsPrimaryExpression.js +index d569a47d3..8ce80ce2d 100644 +--- a/tests/baselines/reference/commonJSImportNotAsPrimaryExpression.js ++++ b/tests/baselines/reference/commonJSImportNotAsPrimaryExpression.js +@@ -35,13 +35,14 @@ var e: number = 0; + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.E1 = exports.C1 = void 0; +-var C1 = exports.C1 = /** @class */ (function () { ++var C1 = /** @class */ (function () { + function C1() { + this.m1 = 42; + } + C1.s1 = true; + return C1; + }()); ++exports.C1 = C1; + var E1; + (function (E1) { + E1[E1["A"] = 0] = "A"; +diff --git a/tests/baselines/reference/compoundExponentiationAssignmentLHSIsValue.js b/tests/baselines/reference/compoundExponentiationAssignmentLHSIsValue.js +index 6b9c08c23..b6b07e6b0 100644 +--- a/tests/baselines/reference/compoundExponentiationAssignmentLHSIsValue.js ++++ b/tests/baselines/reference/compoundExponentiationAssignmentLHSIsValue.js +@@ -152,9 +152,8 @@ _a = Math.pow(['', ''], value), '' = _a[0], '' = _a[1]; + var Derived = /** @class */ (function (_super) { + __extends(Derived, _super); + function Derived() { +- var _this = this; + var _a; +- _this = _super.call(this) || this; ++ var _this = _super.call(this) || this; + (_a = _super.prototype). = Math.pow(_a., value); + return _this; + } +diff --git a/tests/baselines/reference/config/commandLineParsing/parseCommandLine/Parse --lib option with extra comma.js b/tests/baselines/reference/config/commandLineParsing/parseCommandLine/Parse --lib option with extra comma.js +index 59c64e4c7..8a71d8443 100644 +--- a/tests/baselines/reference/config/commandLineParsing/parseCommandLine/Parse --lib option with extra comma.js ++++ b/tests/baselines/reference/config/commandLineParsing/parseCommandLine/Parse --lib option with extra comma.js +@@ -10,4 +10,4 @@ WatchOptions:: + FileNames:: + es7,0.ts + Errors:: +-error TS6046: Argument for '--lib' option must be: 'es5', 'es6', 'es2015', 'es7', 'es2016', 'es2017', 'es2018', 'es2019', 'es2020', 'es2021', 'es2022', 'es2023', 'esnext', 'dom', 'dom.iterable', 'webworker', 'webworker.importscripts', 'webworker.iterable', 'scripthost', 'es2015.core', 'es2015.collection', 'es2015.generator', 'es2015.iterable', 'es2015.promise', 'es2015.proxy', 'es2015.reflect', 'es2015.symbol', 'es2015.symbol.wellknown', 'es2016.array.include', 'es2017.date', 'es2017.object', 'es2017.sharedmemory', 'es2017.string', 'es2017.intl', 'es2017.typedarrays', 'es2018.asyncgenerator', 'es2018.asynciterable', 'es2018.intl', 'es2018.promise', 'es2018.regexp', 'es2019.array', 'es2019.object', 'es2019.string', 'es2019.symbol', 'es2019.intl', 'es2020.bigint', 'es2020.date', 'es2020.promise', 'es2020.sharedmemory', 'es2020.string', 'es2020.symbol.wellknown', 'es2020.intl', 'es2020.number', 'es2021.promise', 'es2021.string', 'es2021.weakref', 'es2021.intl', 'es2022.array', 'es2022.error', 'es2022.intl', 'es2022.object', 'es2022.sharedmemory', 'es2022.string', 'es2022.regexp', 'es2023.array', 'es2023.collection', 'esnext.array', 'esnext.collection', 'esnext.symbol', 'esnext.asynciterable', 'esnext.intl', 'esnext.bigint', 'esnext.string', 'esnext.promise', 'esnext.weakref', 'decorators', 'decorators.legacy'. ++error TS6046: Argument for '--lib' option must be: 'es5', 'es6', 'es2015', 'es7', 'es2016', 'es2017', 'es2018', 'es2019', 'es2020', 'es2021', 'es2022', 'es2023', 'esnext', 'dom', 'dom.iterable', 'webworker', 'webworker.importscripts', 'webworker.iterable', 'scripthost', 'es2015.core', 'es2015.collection', 'es2015.generator', 'es2015.iterable', 'es2015.promise', 'es2015.proxy', 'es2015.reflect', 'es2015.symbol', 'es2015.symbol.wellknown', 'es2016.array.include', 'es2017.date', 'es2017.object', 'es2017.sharedmemory', 'es2017.string', 'es2017.intl', 'es2017.typedarrays', 'es2018.asyncgenerator', 'es2018.asynciterable', 'es2018.intl', 'es2018.promise', 'es2018.regexp', 'es2019.array', 'es2019.object', 'es2019.string', 'es2019.symbol', 'es2019.intl', 'es2020.bigint', 'es2020.date', 'es2020.promise', 'es2020.sharedmemory', 'es2020.string', 'es2020.symbol.wellknown', 'es2020.intl', 'es2020.number', 'es2021.promise', 'es2021.string', 'es2021.weakref', 'es2021.intl', 'es2022.array', 'es2022.error', 'es2022.intl', 'es2022.object', 'es2022.sharedmemory', 'es2022.string', 'es2022.regexp', 'es2023.array', 'es2023.collection', 'esnext.array', 'esnext.collection', 'esnext.symbol', 'esnext.asynciterable', 'esnext.intl', 'esnext.disposable', 'esnext.bigint', 'esnext.string', 'esnext.promise', 'esnext.weakref', 'decorators', 'decorators.legacy'. +diff --git a/tests/baselines/reference/config/commandLineParsing/parseCommandLine/Parse --lib option with trailing white-space.js b/tests/baselines/reference/config/commandLineParsing/parseCommandLine/Parse --lib option with trailing white-space.js +index c51ff3925..ec3c309cd 100644 +--- a/tests/baselines/reference/config/commandLineParsing/parseCommandLine/Parse --lib option with trailing white-space.js ++++ b/tests/baselines/reference/config/commandLineParsing/parseCommandLine/Parse --lib option with trailing white-space.js +@@ -10,4 +10,4 @@ WatchOptions:: + FileNames:: + es7,0.ts + Errors:: +-error TS6046: Argument for '--lib' option must be: 'es5', 'es6', 'es2015', 'es7', 'es2016', 'es2017', 'es2018', 'es2019', 'es2020', 'es2021', 'es2022', 'es2023', 'esnext', 'dom', 'dom.iterable', 'webworker', 'webworker.importscripts', 'webworker.iterable', 'scripthost', 'es2015.core', 'es2015.collection', 'es2015.generator', 'es2015.iterable', 'es2015.promise', 'es2015.proxy', 'es2015.reflect', 'es2015.symbol', 'es2015.symbol.wellknown', 'es2016.array.include', 'es2017.date', 'es2017.object', 'es2017.sharedmemory', 'es2017.string', 'es2017.intl', 'es2017.typedarrays', 'es2018.asyncgenerator', 'es2018.asynciterable', 'es2018.intl', 'es2018.promise', 'es2018.regexp', 'es2019.array', 'es2019.object', 'es2019.string', 'es2019.symbol', 'es2019.intl', 'es2020.bigint', 'es2020.date', 'es2020.promise', 'es2020.sharedmemory', 'es2020.string', 'es2020.symbol.wellknown', 'es2020.intl', 'es2020.number', 'es2021.promise', 'es2021.string', 'es2021.weakref', 'es2021.intl', 'es2022.array', 'es2022.error', 'es2022.intl', 'es2022.object', 'es2022.sharedmemory', 'es2022.string', 'es2022.regexp', 'es2023.array', 'es2023.collection', 'esnext.array', 'esnext.collection', 'esnext.symbol', 'esnext.asynciterable', 'esnext.intl', 'esnext.bigint', 'esnext.string', 'esnext.promise', 'esnext.weakref', 'decorators', 'decorators.legacy'. ++error TS6046: Argument for '--lib' option must be: 'es5', 'es6', 'es2015', 'es7', 'es2016', 'es2017', 'es2018', 'es2019', 'es2020', 'es2021', 'es2022', 'es2023', 'esnext', 'dom', 'dom.iterable', 'webworker', 'webworker.importscripts', 'webworker.iterable', 'scripthost', 'es2015.core', 'es2015.collection', 'es2015.generator', 'es2015.iterable', 'es2015.promise', 'es2015.proxy', 'es2015.reflect', 'es2015.symbol', 'es2015.symbol.wellknown', 'es2016.array.include', 'es2017.date', 'es2017.object', 'es2017.sharedmemory', 'es2017.string', 'es2017.intl', 'es2017.typedarrays', 'es2018.asyncgenerator', 'es2018.asynciterable', 'es2018.intl', 'es2018.promise', 'es2018.regexp', 'es2019.array', 'es2019.object', 'es2019.string', 'es2019.symbol', 'es2019.intl', 'es2020.bigint', 'es2020.date', 'es2020.promise', 'es2020.sharedmemory', 'es2020.string', 'es2020.symbol.wellknown', 'es2020.intl', 'es2020.number', 'es2021.promise', 'es2021.string', 'es2021.weakref', 'es2021.intl', 'es2022.array', 'es2022.error', 'es2022.intl', 'es2022.object', 'es2022.sharedmemory', 'es2022.string', 'es2022.regexp', 'es2023.array', 'es2023.collection', 'esnext.array', 'esnext.collection', 'esnext.symbol', 'esnext.asynciterable', 'esnext.intl', 'esnext.disposable', 'esnext.bigint', 'esnext.string', 'esnext.promise', 'esnext.weakref', 'decorators', 'decorators.legacy'. +diff --git a/tests/baselines/reference/config/commandLineParsing/parseCommandLine/Parse invalid option of library flags.js b/tests/baselines/reference/config/commandLineParsing/parseCommandLine/Parse invalid option of library flags.js +index b4473aa3f..2fcb1cb1d 100644 +--- a/tests/baselines/reference/config/commandLineParsing/parseCommandLine/Parse invalid option of library flags.js ++++ b/tests/baselines/reference/config/commandLineParsing/parseCommandLine/Parse invalid option of library flags.js +@@ -10,4 +10,4 @@ WatchOptions:: + FileNames:: + 0.ts + Errors:: +-error TS6046: Argument for '--lib' option must be: 'es5', 'es6', 'es2015', 'es7', 'es2016', 'es2017', 'es2018', 'es2019', 'es2020', 'es2021', 'es2022', 'es2023', 'esnext', 'dom', 'dom.iterable', 'webworker', 'webworker.importscripts', 'webworker.iterable', 'scripthost', 'es2015.core', 'es2015.collection', 'es2015.generator', 'es2015.iterable', 'es2015.promise', 'es2015.proxy', 'es2015.reflect', 'es2015.symbol', 'es2015.symbol.wellknown', 'es2016.array.include', 'es2017.date', 'es2017.object', 'es2017.sharedmemory', 'es2017.string', 'es2017.intl', 'es2017.typedarrays', 'es2018.asyncgenerator', 'es2018.asynciterable', 'es2018.intl', 'es2018.promise', 'es2018.regexp', 'es2019.array', 'es2019.object', 'es2019.string', 'es2019.symbol', 'es2019.intl', 'es2020.bigint', 'es2020.date', 'es2020.promise', 'es2020.sharedmemory', 'es2020.string', 'es2020.symbol.wellknown', 'es2020.intl', 'es2020.number', 'es2021.promise', 'es2021.string', 'es2021.weakref', 'es2021.intl', 'es2022.array', 'es2022.error', 'es2022.intl', 'es2022.object', 'es2022.sharedmemory', 'es2022.string', 'es2022.regexp', 'es2023.array', 'es2023.collection', 'esnext.array', 'esnext.collection', 'esnext.symbol', 'esnext.asynciterable', 'esnext.intl', 'esnext.bigint', 'esnext.string', 'esnext.promise', 'esnext.weakref', 'decorators', 'decorators.legacy'. ++error TS6046: Argument for '--lib' option must be: 'es5', 'es6', 'es2015', 'es7', 'es2016', 'es2017', 'es2018', 'es2019', 'es2020', 'es2021', 'es2022', 'es2023', 'esnext', 'dom', 'dom.iterable', 'webworker', 'webworker.importscripts', 'webworker.iterable', 'scripthost', 'es2015.core', 'es2015.collection', 'es2015.generator', 'es2015.iterable', 'es2015.promise', 'es2015.proxy', 'es2015.reflect', 'es2015.symbol', 'es2015.symbol.wellknown', 'es2016.array.include', 'es2017.date', 'es2017.object', 'es2017.sharedmemory', 'es2017.string', 'es2017.intl', 'es2017.typedarrays', 'es2018.asyncgenerator', 'es2018.asynciterable', 'es2018.intl', 'es2018.promise', 'es2018.regexp', 'es2019.array', 'es2019.object', 'es2019.string', 'es2019.symbol', 'es2019.intl', 'es2020.bigint', 'es2020.date', 'es2020.promise', 'es2020.sharedmemory', 'es2020.string', 'es2020.symbol.wellknown', 'es2020.intl', 'es2020.number', 'es2021.promise', 'es2021.string', 'es2021.weakref', 'es2021.intl', 'es2022.array', 'es2022.error', 'es2022.intl', 'es2022.object', 'es2022.sharedmemory', 'es2022.string', 'es2022.regexp', 'es2023.array', 'es2023.collection', 'esnext.array', 'esnext.collection', 'esnext.symbol', 'esnext.asynciterable', 'esnext.intl', 'esnext.disposable', 'esnext.bigint', 'esnext.string', 'esnext.promise', 'esnext.weakref', 'decorators', 'decorators.legacy'. +diff --git a/tests/baselines/reference/config/convertCompilerOptionsFromJson/Convert empty string option of libs array to compiler-options with json api.js b/tests/baselines/reference/config/convertCompilerOptionsFromJson/Convert empty string option of libs array to compiler-options with json api.js +index 5844a15bc..36276be01 100644 +--- a/tests/baselines/reference/config/convertCompilerOptionsFromJson/Convert empty string option of libs array to compiler-options with json api.js ++++ b/tests/baselines/reference/config/convertCompilerOptionsFromJson/Convert empty string option of libs array to compiler-options with json api.js +@@ -30,5 +30,5 @@ CompilerOptions:: + "configFilePath": "tsconfig.json" + } + Errors:: +-error TS6046: Argument for '--lib' option must be: 'es5', 'es6', 'es2015', 'es7', 'es2016', 'es2017', 'es2018', 'es2019', 'es2020', 'es2021', 'es2022', 'es2023', 'esnext', 'dom', 'dom.iterable', 'webworker', 'webworker.importscripts', 'webworker.iterable', 'scripthost', 'es2015.core', 'es2015.collection', 'es2015.generator', 'es2015.iterable', 'es2015.promise', 'es2015.proxy', 'es2015.reflect', 'es2015.symbol', 'es2015.symbol.wellknown', 'es2016.array.include', 'es2017.date', 'es2017.object', 'es2017.sharedmemory', 'es2017.string', 'es2017.intl', 'es2017.typedarrays', 'es2018.asyncgenerator', 'es2018.asynciterable', 'es2018.intl', 'es2018.promise', 'es2018.regexp', 'es2019.array', 'es2019.object', 'es2019.string', 'es2019.symbol', 'es2019.intl', 'es2020.bigint', 'es2020.date', 'es2020.promise', 'es2020.sharedmemory', 'es2020.string', 'es2020.symbol.wellknown', 'es2020.intl', 'es2020.number', 'es2021.promise', 'es2021.string', 'es2021.weakref', 'es2021.intl', 'es2022.array', 'es2022.error', 'es2022.intl', 'es2022.object', 'es2022.sharedmemory', 'es2022.string', 'es2022.regexp', 'es2023.array', 'es2023.collection', 'esnext.array', 'esnext.collection', 'esnext.symbol', 'esnext.asynciterable', 'esnext.intl', 'esnext.bigint', 'esnext.string', 'esnext.promise', 'esnext.weakref', 'decorators', 'decorators.legacy'. ++error TS6046: Argument for '--lib' option must be: 'es5', 'es6', 'es2015', 'es7', 'es2016', 'es2017', 'es2018', 'es2019', 'es2020', 'es2021', 'es2022', 'es2023', 'esnext', 'dom', 'dom.iterable', 'webworker', 'webworker.importscripts', 'webworker.iterable', 'scripthost', 'es2015.core', 'es2015.collection', 'es2015.generator', 'es2015.iterable', 'es2015.promise', 'es2015.proxy', 'es2015.reflect', 'es2015.symbol', 'es2015.symbol.wellknown', 'es2016.array.include', 'es2017.date', 'es2017.object', 'es2017.sharedmemory', 'es2017.string', 'es2017.intl', 'es2017.typedarrays', 'es2018.asyncgenerator', 'es2018.asynciterable', 'es2018.intl', 'es2018.promise', 'es2018.regexp', 'es2019.array', 'es2019.object', 'es2019.string', 'es2019.symbol', 'es2019.intl', 'es2020.bigint', 'es2020.date', 'es2020.promise', 'es2020.sharedmemory', 'es2020.string', 'es2020.symbol.wellknown', 'es2020.intl', 'es2020.number', 'es2021.promise', 'es2021.string', 'es2021.weakref', 'es2021.intl', 'es2022.array', 'es2022.error', 'es2022.intl', 'es2022.object', 'es2022.sharedmemory', 'es2022.string', 'es2022.regexp', 'es2023.array', 'es2023.collection', 'esnext.array', 'esnext.collection', 'esnext.symbol', 'esnext.asynciterable', 'esnext.intl', 'esnext.disposable', 'esnext.bigint', 'esnext.string', 'esnext.promise', 'esnext.weakref', 'decorators', 'decorators.legacy'. + +diff --git a/tests/baselines/reference/config/convertCompilerOptionsFromJson/Convert empty string option of libs array to compiler-options with jsonSourceFile api.js b/tests/baselines/reference/config/convertCompilerOptionsFromJson/Convert empty string option of libs array to compiler-options with jsonSourceFile api.js +index 6122b2440..1519a6255 100644 +--- a/tests/baselines/reference/config/convertCompilerOptionsFromJson/Convert empty string option of libs array to compiler-options with jsonSourceFile api.js ++++ b/tests/baselines/reference/config/convertCompilerOptionsFromJson/Convert empty string option of libs array to compiler-options with jsonSourceFile api.js +@@ -30,7 +30,7 @@ CompilerOptions:: + "configFilePath": "tsconfig.json" + } + Errors:: +-tsconfig.json:8:4 - error TS6046: Argument for '--lib' option must be: 'es5', 'es6', 'es2015', 'es7', 'es2016', 'es2017', 'es2018', 'es2019', 'es2020', 'es2021', 'es2022', 'es2023', 'esnext', 'dom', 'dom.iterable', 'webworker', 'webworker.importscripts', 'webworker.iterable', 'scripthost', 'es2015.core', 'es2015.collection', 'es2015.generator', 'es2015.iterable', 'es2015.promise', 'es2015.proxy', 'es2015.reflect', 'es2015.symbol', 'es2015.symbol.wellknown', 'es2016.array.include', 'es2017.date', 'es2017.object', 'es2017.sharedmemory', 'es2017.string', 'es2017.intl', 'es2017.typedarrays', 'es2018.asyncgenerator', 'es2018.asynciterable', 'es2018.intl', 'es2018.promise', 'es2018.regexp', 'es2019.array', 'es2019.object', 'es2019.string', 'es2019.symbol', 'es2019.intl', 'es2020.bigint', 'es2020.date', 'es2020.promise', 'es2020.sharedmemory', 'es2020.string', 'es2020.symbol.wellknown', 'es2020.intl', 'es2020.number', 'es2021.promise', 'es2021.string', 'es2021.weakref', 'es2021.intl', 'es2022.array', 'es2022.error', 'es2022.intl', 'es2022.object', 'es2022.sharedmemory', 'es2022.string', 'es2022.regexp', 'es2023.array', 'es2023.collection', 'esnext.array', 'esnext.collection', 'esnext.symbol', 'esnext.asynciterable', 'esnext.intl', 'esnext.bigint', 'esnext.string', 'esnext.promise', 'esnext.weakref', 'decorators', 'decorators.legacy'. ++tsconfig.json:8:4 - error TS6046: Argument for '--lib' option must be: 'es5', 'es6', 'es2015', 'es7', 'es2016', 'es2017', 'es2018', 'es2019', 'es2020', 'es2021', 'es2022', 'es2023', 'esnext', 'dom', 'dom.iterable', 'webworker', 'webworker.importscripts', 'webworker.iterable', 'scripthost', 'es2015.core', 'es2015.collection', 'es2015.generator', 'es2015.iterable', 'es2015.promise', 'es2015.proxy', 'es2015.reflect', 'es2015.symbol', 'es2015.symbol.wellknown', 'es2016.array.include', 'es2017.date', 'es2017.object', 'es2017.sharedmemory', 'es2017.string', 'es2017.intl', 'es2017.typedarrays', 'es2018.asyncgenerator', 'es2018.asynciterable', 'es2018.intl', 'es2018.promise', 'es2018.regexp', 'es2019.array', 'es2019.object', 'es2019.string', 'es2019.symbol', 'es2019.intl', 'es2020.bigint', 'es2020.date', 'es2020.promise', 'es2020.sharedmemory', 'es2020.string', 'es2020.symbol.wellknown', 'es2020.intl', 'es2020.number', 'es2021.promise', 'es2021.string', 'es2021.weakref', 'es2021.intl', 'es2022.array', 'es2022.error', 'es2022.intl', 'es2022.object', 'es2022.sharedmemory', 'es2022.string', 'es2022.regexp', 'es2023.array', 'es2023.collection', 'esnext.array', 'esnext.collection', 'esnext.symbol', 'esnext.asynciterable', 'esnext.intl', 'esnext.disposable', 'esnext.bigint', 'esnext.string', 'esnext.promise', 'esnext.weakref', 'decorators', 'decorators.legacy'. + + 8 "" +    ~~ +diff --git a/tests/baselines/reference/config/convertCompilerOptionsFromJson/Convert empty string option of libs to compiler-options with json api.js b/tests/baselines/reference/config/convertCompilerOptionsFromJson/Convert empty string option of libs to compiler-options with json api.js +index f089381ab..f6aec65ca 100644 +--- a/tests/baselines/reference/config/convertCompilerOptionsFromJson/Convert empty string option of libs to compiler-options with json api.js ++++ b/tests/baselines/reference/config/convertCompilerOptionsFromJson/Convert empty string option of libs to compiler-options with json api.js +@@ -33,5 +33,5 @@ CompilerOptions:: + "configFilePath": "tsconfig.json" + } + Errors:: +-error TS6046: Argument for '--lib' option must be: 'es5', 'es6', 'es2015', 'es7', 'es2016', 'es2017', 'es2018', 'es2019', 'es2020', 'es2021', 'es2022', 'es2023', 'esnext', 'dom', 'dom.iterable', 'webworker', 'webworker.importscripts', 'webworker.iterable', 'scripthost', 'es2015.core', 'es2015.collection', 'es2015.generator', 'es2015.iterable', 'es2015.promise', 'es2015.proxy', 'es2015.reflect', 'es2015.symbol', 'es2015.symbol.wellknown', 'es2016.array.include', 'es2017.date', 'es2017.object', 'es2017.sharedmemory', 'es2017.string', 'es2017.intl', 'es2017.typedarrays', 'es2018.asyncgenerator', 'es2018.asynciterable', 'es2018.intl', 'es2018.promise', 'es2018.regexp', 'es2019.array', 'es2019.object', 'es2019.string', 'es2019.symbol', 'es2019.intl', 'es2020.bigint', 'es2020.date', 'es2020.promise', 'es2020.sharedmemory', 'es2020.string', 'es2020.symbol.wellknown', 'es2020.intl', 'es2020.number', 'es2021.promise', 'es2021.string', 'es2021.weakref', 'es2021.intl', 'es2022.array', 'es2022.error', 'es2022.intl', 'es2022.object', 'es2022.sharedmemory', 'es2022.string', 'es2022.regexp', 'es2023.array', 'es2023.collection', 'esnext.array', 'esnext.collection', 'esnext.symbol', 'esnext.asynciterable', 'esnext.intl', 'esnext.bigint', 'esnext.string', 'esnext.promise', 'esnext.weakref', 'decorators', 'decorators.legacy'. ++error TS6046: Argument for '--lib' option must be: 'es5', 'es6', 'es2015', 'es7', 'es2016', 'es2017', 'es2018', 'es2019', 'es2020', 'es2021', 'es2022', 'es2023', 'esnext', 'dom', 'dom.iterable', 'webworker', 'webworker.importscripts', 'webworker.iterable', 'scripthost', 'es2015.core', 'es2015.collection', 'es2015.generator', 'es2015.iterable', 'es2015.promise', 'es2015.proxy', 'es2015.reflect', 'es2015.symbol', 'es2015.symbol.wellknown', 'es2016.array.include', 'es2017.date', 'es2017.object', 'es2017.sharedmemory', 'es2017.string', 'es2017.intl', 'es2017.typedarrays', 'es2018.asyncgenerator', 'es2018.asynciterable', 'es2018.intl', 'es2018.promise', 'es2018.regexp', 'es2019.array', 'es2019.object', 'es2019.string', 'es2019.symbol', 'es2019.intl', 'es2020.bigint', 'es2020.date', 'es2020.promise', 'es2020.sharedmemory', 'es2020.string', 'es2020.symbol.wellknown', 'es2020.intl', 'es2020.number', 'es2021.promise', 'es2021.string', 'es2021.weakref', 'es2021.intl', 'es2022.array', 'es2022.error', 'es2022.intl', 'es2022.object', 'es2022.sharedmemory', 'es2022.string', 'es2022.regexp', 'es2023.array', 'es2023.collection', 'esnext.array', 'esnext.collection', 'esnext.symbol', 'esnext.asynciterable', 'esnext.intl', 'esnext.disposable', 'esnext.bigint', 'esnext.string', 'esnext.promise', 'esnext.weakref', 'decorators', 'decorators.legacy'. + +diff --git a/tests/baselines/reference/config/convertCompilerOptionsFromJson/Convert empty string option of libs to compiler-options with jsonSourceFile api.js b/tests/baselines/reference/config/convertCompilerOptionsFromJson/Convert empty string option of libs to compiler-options with jsonSourceFile api.js +index 6a996e3a8..66b7ccff8 100644 +--- a/tests/baselines/reference/config/convertCompilerOptionsFromJson/Convert empty string option of libs to compiler-options with jsonSourceFile api.js ++++ b/tests/baselines/reference/config/convertCompilerOptionsFromJson/Convert empty string option of libs to compiler-options with jsonSourceFile api.js +@@ -33,7 +33,7 @@ CompilerOptions:: + "configFilePath": "tsconfig.json" + } + Errors:: +-tsconfig.json:9:4 - error TS6046: Argument for '--lib' option must be: 'es5', 'es6', 'es2015', 'es7', 'es2016', 'es2017', 'es2018', 'es2019', 'es2020', 'es2021', 'es2022', 'es2023', 'esnext', 'dom', 'dom.iterable', 'webworker', 'webworker.importscripts', 'webworker.iterable', 'scripthost', 'es2015.core', 'es2015.collection', 'es2015.generator', 'es2015.iterable', 'es2015.promise', 'es2015.proxy', 'es2015.reflect', 'es2015.symbol', 'es2015.symbol.wellknown', 'es2016.array.include', 'es2017.date', 'es2017.object', 'es2017.sharedmemory', 'es2017.string', 'es2017.intl', 'es2017.typedarrays', 'es2018.asyncgenerator', 'es2018.asynciterable', 'es2018.intl', 'es2018.promise', 'es2018.regexp', 'es2019.array', 'es2019.object', 'es2019.string', 'es2019.symbol', 'es2019.intl', 'es2020.bigint', 'es2020.date', 'es2020.promise', 'es2020.sharedmemory', 'es2020.string', 'es2020.symbol.wellknown', 'es2020.intl', 'es2020.number', 'es2021.promise', 'es2021.string', 'es2021.weakref', 'es2021.intl', 'es2022.array', 'es2022.error', 'es2022.intl', 'es2022.object', 'es2022.sharedmemory', 'es2022.string', 'es2022.regexp', 'es2023.array', 'es2023.collection', 'esnext.array', 'esnext.collection', 'esnext.symbol', 'esnext.asynciterable', 'esnext.intl', 'esnext.bigint', 'esnext.string', 'esnext.promise', 'esnext.weakref', 'decorators', 'decorators.legacy'. ++tsconfig.json:9:4 - error TS6046: Argument for '--lib' option must be: 'es5', 'es6', 'es2015', 'es7', 'es2016', 'es2017', 'es2018', 'es2019', 'es2020', 'es2021', 'es2022', 'es2023', 'esnext', 'dom', 'dom.iterable', 'webworker', 'webworker.importscripts', 'webworker.iterable', 'scripthost', 'es2015.core', 'es2015.collection', 'es2015.generator', 'es2015.iterable', 'es2015.promise', 'es2015.proxy', 'es2015.reflect', 'es2015.symbol', 'es2015.symbol.wellknown', 'es2016.array.include', 'es2017.date', 'es2017.object', 'es2017.sharedmemory', 'es2017.string', 'es2017.intl', 'es2017.typedarrays', 'es2018.asyncgenerator', 'es2018.asynciterable', 'es2018.intl', 'es2018.promise', 'es2018.regexp', 'es2019.array', 'es2019.object', 'es2019.string', 'es2019.symbol', 'es2019.intl', 'es2020.bigint', 'es2020.date', 'es2020.promise', 'es2020.sharedmemory', 'es2020.string', 'es2020.symbol.wellknown', 'es2020.intl', 'es2020.number', 'es2021.promise', 'es2021.string', 'es2021.weakref', 'es2021.intl', 'es2022.array', 'es2022.error', 'es2022.intl', 'es2022.object', 'es2022.sharedmemory', 'es2022.string', 'es2022.regexp', 'es2023.array', 'es2023.collection', 'esnext.array', 'esnext.collection', 'esnext.symbol', 'esnext.asynciterable', 'esnext.intl', 'esnext.disposable', 'esnext.bigint', 'esnext.string', 'esnext.promise', 'esnext.weakref', 'decorators', 'decorators.legacy'. + + 9 "" +    ~~ +diff --git a/tests/baselines/reference/config/convertCompilerOptionsFromJson/Convert incorrect option of libs to compiler-options with json api.js b/tests/baselines/reference/config/convertCompilerOptionsFromJson/Convert incorrect option of libs to compiler-options with json api.js +index 0aea5a2fe..16074f275 100644 +--- a/tests/baselines/reference/config/convertCompilerOptionsFromJson/Convert incorrect option of libs to compiler-options with json api.js ++++ b/tests/baselines/reference/config/convertCompilerOptionsFromJson/Convert incorrect option of libs to compiler-options with json api.js +@@ -35,5 +35,5 @@ CompilerOptions:: + "configFilePath": "tsconfig.json" + } + Errors:: +-error TS6046: Argument for '--lib' option must be: 'es5', 'es6', 'es2015', 'es7', 'es2016', 'es2017', 'es2018', 'es2019', 'es2020', 'es2021', 'es2022', 'es2023', 'esnext', 'dom', 'dom.iterable', 'webworker', 'webworker.importscripts', 'webworker.iterable', 'scripthost', 'es2015.core', 'es2015.collection', 'es2015.generator', 'es2015.iterable', 'es2015.promise', 'es2015.proxy', 'es2015.reflect', 'es2015.symbol', 'es2015.symbol.wellknown', 'es2016.array.include', 'es2017.date', 'es2017.object', 'es2017.sharedmemory', 'es2017.string', 'es2017.intl', 'es2017.typedarrays', 'es2018.asyncgenerator', 'es2018.asynciterable', 'es2018.intl', 'es2018.promise', 'es2018.regexp', 'es2019.array', 'es2019.object', 'es2019.string', 'es2019.symbol', 'es2019.intl', 'es2020.bigint', 'es2020.date', 'es2020.promise', 'es2020.sharedmemory', 'es2020.string', 'es2020.symbol.wellknown', 'es2020.intl', 'es2020.number', 'es2021.promise', 'es2021.string', 'es2021.weakref', 'es2021.intl', 'es2022.array', 'es2022.error', 'es2022.intl', 'es2022.object', 'es2022.sharedmemory', 'es2022.string', 'es2022.regexp', 'es2023.array', 'es2023.collection', 'esnext.array', 'esnext.collection', 'esnext.symbol', 'esnext.asynciterable', 'esnext.intl', 'esnext.bigint', 'esnext.string', 'esnext.promise', 'esnext.weakref', 'decorators', 'decorators.legacy'. ++error TS6046: Argument for '--lib' option must be: 'es5', 'es6', 'es2015', 'es7', 'es2016', 'es2017', 'es2018', 'es2019', 'es2020', 'es2021', 'es2022', 'es2023', 'esnext', 'dom', 'dom.iterable', 'webworker', 'webworker.importscripts', 'webworker.iterable', 'scripthost', 'es2015.core', 'es2015.collection', 'es2015.generator', 'es2015.iterable', 'es2015.promise', 'es2015.proxy', 'es2015.reflect', 'es2015.symbol', 'es2015.symbol.wellknown', 'es2016.array.include', 'es2017.date', 'es2017.object', 'es2017.sharedmemory', 'es2017.string', 'es2017.intl', 'es2017.typedarrays', 'es2018.asyncgenerator', 'es2018.asynciterable', 'es2018.intl', 'es2018.promise', 'es2018.regexp', 'es2019.array', 'es2019.object', 'es2019.string', 'es2019.symbol', 'es2019.intl', 'es2020.bigint', 'es2020.date', 'es2020.promise', 'es2020.sharedmemory', 'es2020.string', 'es2020.symbol.wellknown', 'es2020.intl', 'es2020.number', 'es2021.promise', 'es2021.string', 'es2021.weakref', 'es2021.intl', 'es2022.array', 'es2022.error', 'es2022.intl', 'es2022.object', 'es2022.sharedmemory', 'es2022.string', 'es2022.regexp', 'es2023.array', 'es2023.collection', 'esnext.array', 'esnext.collection', 'esnext.symbol', 'esnext.asynciterable', 'esnext.intl', 'esnext.disposable', 'esnext.bigint', 'esnext.string', 'esnext.promise', 'esnext.weakref', 'decorators', 'decorators.legacy'. + +diff --git a/tests/baselines/reference/config/convertCompilerOptionsFromJson/Convert incorrect option of libs to compiler-options with jsonSourceFile api.js b/tests/baselines/reference/config/convertCompilerOptionsFromJson/Convert incorrect option of libs to compiler-options with jsonSourceFile api.js +index bdaa64c07..72c476e7e 100644 +--- a/tests/baselines/reference/config/convertCompilerOptionsFromJson/Convert incorrect option of libs to compiler-options with jsonSourceFile api.js ++++ b/tests/baselines/reference/config/convertCompilerOptionsFromJson/Convert incorrect option of libs to compiler-options with jsonSourceFile api.js +@@ -35,7 +35,7 @@ CompilerOptions:: + "configFilePath": "tsconfig.json" + } + Errors:: +-tsconfig.json:10:4 - error TS6046: Argument for '--lib' option must be: 'es5', 'es6', 'es2015', 'es7', 'es2016', 'es2017', 'es2018', 'es2019', 'es2020', 'es2021', 'es2022', 'es2023', 'esnext', 'dom', 'dom.iterable', 'webworker', 'webworker.importscripts', 'webworker.iterable', 'scripthost', 'es2015.core', 'es2015.collection', 'es2015.generator', 'es2015.iterable', 'es2015.promise', 'es2015.proxy', 'es2015.reflect', 'es2015.symbol', 'es2015.symbol.wellknown', 'es2016.array.include', 'es2017.date', 'es2017.object', 'es2017.sharedmemory', 'es2017.string', 'es2017.intl', 'es2017.typedarrays', 'es2018.asyncgenerator', 'es2018.asynciterable', 'es2018.intl', 'es2018.promise', 'es2018.regexp', 'es2019.array', 'es2019.object', 'es2019.string', 'es2019.symbol', 'es2019.intl', 'es2020.bigint', 'es2020.date', 'es2020.promise', 'es2020.sharedmemory', 'es2020.string', 'es2020.symbol.wellknown', 'es2020.intl', 'es2020.number', 'es2021.promise', 'es2021.string', 'es2021.weakref', 'es2021.intl', 'es2022.array', 'es2022.error', 'es2022.intl', 'es2022.object', 'es2022.sharedmemory', 'es2022.string', 'es2022.regexp', 'es2023.array', 'es2023.collection', 'esnext.array', 'esnext.collection', 'esnext.symbol', 'esnext.asynciterable', 'esnext.intl', 'esnext.bigint', 'esnext.string', 'esnext.promise', 'esnext.weakref', 'decorators', 'decorators.legacy'. ++tsconfig.json:10:4 - error TS6046: Argument for '--lib' option must be: 'es5', 'es6', 'es2015', 'es7', 'es2016', 'es2017', 'es2018', 'es2019', 'es2020', 'es2021', 'es2022', 'es2023', 'esnext', 'dom', 'dom.iterable', 'webworker', 'webworker.importscripts', 'webworker.iterable', 'scripthost', 'es2015.core', 'es2015.collection', 'es2015.generator', 'es2015.iterable', 'es2015.promise', 'es2015.proxy', 'es2015.reflect', 'es2015.symbol', 'es2015.symbol.wellknown', 'es2016.array.include', 'es2017.date', 'es2017.object', 'es2017.sharedmemory', 'es2017.string', 'es2017.intl', 'es2017.typedarrays', 'es2018.asyncgenerator', 'es2018.asynciterable', 'es2018.intl', 'es2018.promise', 'es2018.regexp', 'es2019.array', 'es2019.object', 'es2019.string', 'es2019.symbol', 'es2019.intl', 'es2020.bigint', 'es2020.date', 'es2020.promise', 'es2020.sharedmemory', 'es2020.string', 'es2020.symbol.wellknown', 'es2020.intl', 'es2020.number', 'es2021.promise', 'es2021.string', 'es2021.weakref', 'es2021.intl', 'es2022.array', 'es2022.error', 'es2022.intl', 'es2022.object', 'es2022.sharedmemory', 'es2022.string', 'es2022.regexp', 'es2023.array', 'es2023.collection', 'esnext.array', 'esnext.collection', 'esnext.symbol', 'esnext.asynciterable', 'esnext.intl', 'esnext.disposable', 'esnext.bigint', 'esnext.string', 'esnext.promise', 'esnext.weakref', 'decorators', 'decorators.legacy'. + + 10 "incorrectLib" +    ~~~~~~~~~~~~~~ +diff --git a/tests/baselines/reference/config/convertCompilerOptionsFromJson/Convert trailing-whitespace string option of libs to compiler-options with json api.js b/tests/baselines/reference/config/convertCompilerOptionsFromJson/Convert trailing-whitespace string option of libs to compiler-options with json api.js +index 7722a1dc4..55d1a73bf 100644 +--- a/tests/baselines/reference/config/convertCompilerOptionsFromJson/Convert trailing-whitespace string option of libs to compiler-options with json api.js ++++ b/tests/baselines/reference/config/convertCompilerOptionsFromJson/Convert trailing-whitespace string option of libs to compiler-options with json api.js +@@ -30,5 +30,5 @@ CompilerOptions:: + "configFilePath": "tsconfig.json" + } + Errors:: +-error TS6046: Argument for '--lib' option must be: 'es5', 'es6', 'es2015', 'es7', 'es2016', 'es2017', 'es2018', 'es2019', 'es2020', 'es2021', 'es2022', 'es2023', 'esnext', 'dom', 'dom.iterable', 'webworker', 'webworker.importscripts', 'webworker.iterable', 'scripthost', 'es2015.core', 'es2015.collection', 'es2015.generator', 'es2015.iterable', 'es2015.promise', 'es2015.proxy', 'es2015.reflect', 'es2015.symbol', 'es2015.symbol.wellknown', 'es2016.array.include', 'es2017.date', 'es2017.object', 'es2017.sharedmemory', 'es2017.string', 'es2017.intl', 'es2017.typedarrays', 'es2018.asyncgenerator', 'es2018.asynciterable', 'es2018.intl', 'es2018.promise', 'es2018.regexp', 'es2019.array', 'es2019.object', 'es2019.string', 'es2019.symbol', 'es2019.intl', 'es2020.bigint', 'es2020.date', 'es2020.promise', 'es2020.sharedmemory', 'es2020.string', 'es2020.symbol.wellknown', 'es2020.intl', 'es2020.number', 'es2021.promise', 'es2021.string', 'es2021.weakref', 'es2021.intl', 'es2022.array', 'es2022.error', 'es2022.intl', 'es2022.object', 'es2022.sharedmemory', 'es2022.string', 'es2022.regexp', 'es2023.array', 'es2023.collection', 'esnext.array', 'esnext.collection', 'esnext.symbol', 'esnext.asynciterable', 'esnext.intl', 'esnext.bigint', 'esnext.string', 'esnext.promise', 'esnext.weakref', 'decorators', 'decorators.legacy'. ++error TS6046: Argument for '--lib' option must be: 'es5', 'es6', 'es2015', 'es7', 'es2016', 'es2017', 'es2018', 'es2019', 'es2020', 'es2021', 'es2022', 'es2023', 'esnext', 'dom', 'dom.iterable', 'webworker', 'webworker.importscripts', 'webworker.iterable', 'scripthost', 'es2015.core', 'es2015.collection', 'es2015.generator', 'es2015.iterable', 'es2015.promise', 'es2015.proxy', 'es2015.reflect', 'es2015.symbol', 'es2015.symbol.wellknown', 'es2016.array.include', 'es2017.date', 'es2017.object', 'es2017.sharedmemory', 'es2017.string', 'es2017.intl', 'es2017.typedarrays', 'es2018.asyncgenerator', 'es2018.asynciterable', 'es2018.intl', 'es2018.promise', 'es2018.regexp', 'es2019.array', 'es2019.object', 'es2019.string', 'es2019.symbol', 'es2019.intl', 'es2020.bigint', 'es2020.date', 'es2020.promise', 'es2020.sharedmemory', 'es2020.string', 'es2020.symbol.wellknown', 'es2020.intl', 'es2020.number', 'es2021.promise', 'es2021.string', 'es2021.weakref', 'es2021.intl', 'es2022.array', 'es2022.error', 'es2022.intl', 'es2022.object', 'es2022.sharedmemory', 'es2022.string', 'es2022.regexp', 'es2023.array', 'es2023.collection', 'esnext.array', 'esnext.collection', 'esnext.symbol', 'esnext.asynciterable', 'esnext.intl', 'esnext.disposable', 'esnext.bigint', 'esnext.string', 'esnext.promise', 'esnext.weakref', 'decorators', 'decorators.legacy'. + +diff --git a/tests/baselines/reference/config/convertCompilerOptionsFromJson/Convert trailing-whitespace string option of libs to compiler-options with jsonSourceFile api.js b/tests/baselines/reference/config/convertCompilerOptionsFromJson/Convert trailing-whitespace string option of libs to compiler-options with jsonSourceFile api.js +index 10f48ec0d..015e00b37 100644 +--- a/tests/baselines/reference/config/convertCompilerOptionsFromJson/Convert trailing-whitespace string option of libs to compiler-options with jsonSourceFile api.js ++++ b/tests/baselines/reference/config/convertCompilerOptionsFromJson/Convert trailing-whitespace string option of libs to compiler-options with jsonSourceFile api.js +@@ -30,7 +30,7 @@ CompilerOptions:: + "configFilePath": "tsconfig.json" + } + Errors:: +-tsconfig.json:8:4 - error TS6046: Argument for '--lib' option must be: 'es5', 'es6', 'es2015', 'es7', 'es2016', 'es2017', 'es2018', 'es2019', 'es2020', 'es2021', 'es2022', 'es2023', 'esnext', 'dom', 'dom.iterable', 'webworker', 'webworker.importscripts', 'webworker.iterable', 'scripthost', 'es2015.core', 'es2015.collection', 'es2015.generator', 'es2015.iterable', 'es2015.promise', 'es2015.proxy', 'es2015.reflect', 'es2015.symbol', 'es2015.symbol.wellknown', 'es2016.array.include', 'es2017.date', 'es2017.object', 'es2017.sharedmemory', 'es2017.string', 'es2017.intl', 'es2017.typedarrays', 'es2018.asyncgenerator', 'es2018.asynciterable', 'es2018.intl', 'es2018.promise', 'es2018.regexp', 'es2019.array', 'es2019.object', 'es2019.string', 'es2019.symbol', 'es2019.intl', 'es2020.bigint', 'es2020.date', 'es2020.promise', 'es2020.sharedmemory', 'es2020.string', 'es2020.symbol.wellknown', 'es2020.intl', 'es2020.number', 'es2021.promise', 'es2021.string', 'es2021.weakref', 'es2021.intl', 'es2022.array', 'es2022.error', 'es2022.intl', 'es2022.object', 'es2022.sharedmemory', 'es2022.string', 'es2022.regexp', 'es2023.array', 'es2023.collection', 'esnext.array', 'esnext.collection', 'esnext.symbol', 'esnext.asynciterable', 'esnext.intl', 'esnext.bigint', 'esnext.string', 'esnext.promise', 'esnext.weakref', 'decorators', 'decorators.legacy'. ++tsconfig.json:8:4 - error TS6046: Argument for '--lib' option must be: 'es5', 'es6', 'es2015', 'es7', 'es2016', 'es2017', 'es2018', 'es2019', 'es2020', 'es2021', 'es2022', 'es2023', 'esnext', 'dom', 'dom.iterable', 'webworker', 'webworker.importscripts', 'webworker.iterable', 'scripthost', 'es2015.core', 'es2015.collection', 'es2015.generator', 'es2015.iterable', 'es2015.promise', 'es2015.proxy', 'es2015.reflect', 'es2015.symbol', 'es2015.symbol.wellknown', 'es2016.array.include', 'es2017.date', 'es2017.object', 'es2017.sharedmemory', 'es2017.string', 'es2017.intl', 'es2017.typedarrays', 'es2018.asyncgenerator', 'es2018.asynciterable', 'es2018.intl', 'es2018.promise', 'es2018.regexp', 'es2019.array', 'es2019.object', 'es2019.string', 'es2019.symbol', 'es2019.intl', 'es2020.bigint', 'es2020.date', 'es2020.promise', 'es2020.sharedmemory', 'es2020.string', 'es2020.symbol.wellknown', 'es2020.intl', 'es2020.number', 'es2021.promise', 'es2021.string', 'es2021.weakref', 'es2021.intl', 'es2022.array', 'es2022.error', 'es2022.intl', 'es2022.object', 'es2022.sharedmemory', 'es2022.string', 'es2022.regexp', 'es2023.array', 'es2023.collection', 'esnext.array', 'esnext.collection', 'esnext.symbol', 'esnext.asynciterable', 'esnext.intl', 'esnext.disposable', 'esnext.bigint', 'esnext.string', 'esnext.promise', 'esnext.weakref', 'decorators', 'decorators.legacy'. + + 8 " " +    ~~~~~ +diff --git a/tests/baselines/reference/customTransforms/before+decorators.js b/tests/baselines/reference/customTransforms/before+decorators.js +index 7901f9846..ef705f0c9 100644 +--- a/tests/baselines/reference/customTransforms/before+decorators.js ++++ b/tests/baselines/reference/customTransforms/before+decorators.js +@@ -13,7 +13,7 @@ var B = /** @class */ (function () { + } + return B; + }()); +-export var C = /** @class */ (function () { ++var C = /** @class */ (function () { + function C(b) { + } + C = __decorate([ +@@ -22,4 +22,5 @@ export var C = /** @class */ (function () { + ], C); + return C; + }()); ++export { C }; + "changed"; +diff --git a/tests/baselines/reference/declarationEmitLocalClassHasRequiredDeclare.js b/tests/baselines/reference/declarationEmitLocalClassHasRequiredDeclare.js +index c2cd9b491..e0379df80 100644 +--- a/tests/baselines/reference/declarationEmitLocalClassHasRequiredDeclare.js ++++ b/tests/baselines/reference/declarationEmitLocalClassHasRequiredDeclare.js +@@ -26,12 +26,13 @@ var X = /** @class */ (function () { + } + return X; + }()); +-var A = exports.A = /** @class */ (function () { ++var A = /** @class */ (function () { + function A() { + } + A.X = X; + return A; + }()); ++exports.A = A; + var Y = /** @class */ (function () { + function Y() { + } +diff --git a/tests/baselines/reference/decoratedClassExportsCommonJS1.js b/tests/baselines/reference/decoratedClassExportsCommonJS1.js +index 11842c166..0cb283c09 100644 +--- a/tests/baselines/reference/decoratedClassExportsCommonJS1.js ++++ b/tests/baselines/reference/decoratedClassExportsCommonJS1.js +@@ -19,8 +19,9 @@ var __decorate = (this && this.__decorate) || function (decorators, target, key, + var Testing123_1; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.Testing123 = void 0; +-let Testing123 = exports.Testing123 = Testing123_1 = class Testing123 { ++let Testing123 = Testing123_1 = class Testing123 { + }; ++exports.Testing123 = Testing123; + Testing123.prop1 = Testing123_1.prop0; + exports.Testing123 = Testing123 = Testing123_1 = __decorate([ + Something({ v: () => Testing123_1 }) +diff --git a/tests/baselines/reference/decoratedClassExportsCommonJS2.js b/tests/baselines/reference/decoratedClassExportsCommonJS2.js +index 8751b844e..6d9ba9cc9 100644 +--- a/tests/baselines/reference/decoratedClassExportsCommonJS2.js ++++ b/tests/baselines/reference/decoratedClassExportsCommonJS2.js +@@ -17,8 +17,9 @@ var __decorate = (this && this.__decorate) || function (decorators, target, key, + var Testing123_1; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.Testing123 = void 0; +-let Testing123 = exports.Testing123 = Testing123_1 = class Testing123 { ++let Testing123 = Testing123_1 = class Testing123 { + }; ++exports.Testing123 = Testing123; + exports.Testing123 = Testing123 = Testing123_1 = __decorate([ + Something({ v: () => Testing123_1 }) + ], Testing123); +diff --git a/tests/baselines/reference/decoratedClassExportsSystem1.js b/tests/baselines/reference/decoratedClassExportsSystem1.js +index 9d552b38a..1ed6fa3da 100644 +--- a/tests/baselines/reference/decoratedClassExportsSystem1.js ++++ b/tests/baselines/reference/decoratedClassExportsSystem1.js +@@ -23,8 +23,9 @@ System.register([], function (exports_1, context_1) { + return { + setters: [], + execute: function () { +- exports_1("Testing123", Testing123 = Testing123_1 = class Testing123 { +- }); ++ Testing123 = Testing123_1 = class Testing123 { ++ }; ++ exports_1("Testing123", Testing123); + Testing123.prop1 = Testing123_1.prop0; + exports_1("Testing123", Testing123 = Testing123_1 = __decorate([ + Something({ v: () => Testing123_1 }) +diff --git a/tests/baselines/reference/decoratedClassExportsSystem2.js b/tests/baselines/reference/decoratedClassExportsSystem2.js +index 19724806e..321aa309b 100644 +--- a/tests/baselines/reference/decoratedClassExportsSystem2.js ++++ b/tests/baselines/reference/decoratedClassExportsSystem2.js +@@ -20,8 +20,9 @@ System.register([], function (exports_1, context_1) { + return { + setters: [], + execute: function () { +- exports_1("Testing123", Testing123 = Testing123_1 = class Testing123 { +- }); ++ Testing123 = Testing123_1 = class Testing123 { ++ }; ++ exports_1("Testing123", Testing123); + exports_1("Testing123", Testing123 = Testing123_1 = __decorate([ + Something({ v: () => Testing123_1 }) + ], Testing123)); +diff --git a/tests/baselines/reference/decoratorMetadataGenericTypeVariable.js b/tests/baselines/reference/decoratorMetadataGenericTypeVariable.js +index 6660ebe04..fd751b3a1 100644 +--- a/tests/baselines/reference/decoratorMetadataGenericTypeVariable.js ++++ b/tests/baselines/reference/decoratorMetadataGenericTypeVariable.js +@@ -20,7 +20,7 @@ var __metadata = (this && this.__metadata) || function (k, v) { + }; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.C = void 0; +-var C = exports.C = /** @class */ (function () { ++var C = /** @class */ (function () { + function C() { + } + __decorate([ +@@ -29,3 +29,4 @@ var C = exports.C = /** @class */ (function () { + ], C.prototype, "member", void 0); + return C; + }()); ++exports.C = C; +diff --git a/tests/baselines/reference/decoratorMetadataGenericTypeVariableDefault.js b/tests/baselines/reference/decoratorMetadataGenericTypeVariableDefault.js +index 8a64577cb..ad13025fb 100644 +--- a/tests/baselines/reference/decoratorMetadataGenericTypeVariableDefault.js ++++ b/tests/baselines/reference/decoratorMetadataGenericTypeVariableDefault.js +@@ -20,7 +20,7 @@ var __metadata = (this && this.__metadata) || function (k, v) { + }; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.C = void 0; +-var C = exports.C = /** @class */ (function () { ++var C = /** @class */ (function () { + function C() { + } + __decorate([ +@@ -29,3 +29,4 @@ var C = exports.C = /** @class */ (function () { + ], C.prototype, "member", void 0); + return C; + }()); ++exports.C = C; +diff --git a/tests/baselines/reference/decoratorMetadataGenericTypeVariableInScope.js b/tests/baselines/reference/decoratorMetadataGenericTypeVariableInScope.js +index 9505b27f3..dafb8244c 100644 +--- a/tests/baselines/reference/decoratorMetadataGenericTypeVariableInScope.js ++++ b/tests/baselines/reference/decoratorMetadataGenericTypeVariableInScope.js +@@ -29,7 +29,7 @@ var TypeVariable = /** @class */ (function () { + } + return TypeVariable; + }()); +-var C = exports.C = /** @class */ (function () { ++var C = /** @class */ (function () { + function C() { + } + __decorate([ +@@ -38,3 +38,4 @@ var C = exports.C = /** @class */ (function () { + ], C.prototype, "member", void 0); + return C; + }()); ++exports.C = C; +diff --git a/tests/baselines/reference/decoratorMetadataNoLibIsolatedModulesTypes.js b/tests/baselines/reference/decoratorMetadataNoLibIsolatedModulesTypes.js +index 21af819a2..b09ce5b6c 100644 +--- a/tests/baselines/reference/decoratorMetadataNoLibIsolatedModulesTypes.js ++++ b/tests/baselines/reference/decoratorMetadataNoLibIsolatedModulesTypes.js +@@ -20,7 +20,7 @@ var __metadata = (this && this.__metadata) || function (k, v) { + }; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.B = void 0; +-var B = exports.B = /** @class */ (function () { ++var B = /** @class */ (function () { + function B() { + } + var _a; +@@ -30,3 +30,4 @@ var B = exports.B = /** @class */ (function () { + ], B.prototype, "member", void 0); + return B; + }()); ++exports.B = B; +diff --git a/tests/baselines/reference/decoratorMetadataOnInferredType.js b/tests/baselines/reference/decoratorMetadataOnInferredType.js +index fdf12d9a4..6a5152b5e 100644 +--- a/tests/baselines/reference/decoratorMetadataOnInferredType.js ++++ b/tests/baselines/reference/decoratorMetadataOnInferredType.js +@@ -30,7 +30,7 @@ var A = /** @class */ (function () { + }()); + function decorator(target, propertyKey) { + } +-var B = exports.B = /** @class */ (function () { ++var B = /** @class */ (function () { + function B() { + this.x = new A(); + } +@@ -40,3 +40,4 @@ var B = exports.B = /** @class */ (function () { + ], B.prototype, "x", void 0); + return B; + }()); ++exports.B = B; +diff --git a/tests/baselines/reference/decoratorMetadataRestParameterWithImportedType.js b/tests/baselines/reference/decoratorMetadataRestParameterWithImportedType.js +index ddb84dfe4..c42cb65fa 100644 +--- a/tests/baselines/reference/decoratorMetadataRestParameterWithImportedType.js ++++ b/tests/baselines/reference/decoratorMetadataRestParameterWithImportedType.js +@@ -90,7 +90,7 @@ function annotation() { + function annotation1() { + return function (target) { }; + } +-var ClassA = exports.ClassA = /** @class */ (function () { ++var ClassA = /** @class */ (function () { + function ClassA() { + var init = []; + for (var _i = 0; _i < arguments.length; _i++) { +@@ -116,3 +116,4 @@ var ClassA = exports.ClassA = /** @class */ (function () { + ], ClassA); + return ClassA; + }()); ++exports.ClassA = ClassA; +diff --git a/tests/baselines/reference/decoratorMetadataWithConstructorType.js b/tests/baselines/reference/decoratorMetadataWithConstructorType.js +index 6c48ec6f0..b9de65b0a 100644 +--- a/tests/baselines/reference/decoratorMetadataWithConstructorType.js ++++ b/tests/baselines/reference/decoratorMetadataWithConstructorType.js +@@ -30,7 +30,7 @@ var A = /** @class */ (function () { + }()); + function decorator(target, propertyKey) { + } +-var B = exports.B = /** @class */ (function () { ++var B = /** @class */ (function () { + function B() { + this.x = new A(); + } +@@ -40,3 +40,4 @@ var B = exports.B = /** @class */ (function () { + ], B.prototype, "x", void 0); + return B; + }()); ++exports.B = B; +diff --git a/tests/baselines/reference/decoratorMetadataWithTypeOnlyImport2.js b/tests/baselines/reference/decoratorMetadataWithTypeOnlyImport2.js +index de8f0aef7..1f55126d1 100644 +--- a/tests/baselines/reference/decoratorMetadataWithTypeOnlyImport2.js ++++ b/tests/baselines/reference/decoratorMetadataWithTypeOnlyImport2.js +@@ -41,7 +41,7 @@ var __metadata = (this && this.__metadata) || function (k, v) { + }; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.Main = void 0; +-var Main = exports.Main = /** @class */ (function () { ++var Main = /** @class */ (function () { + function Main() { + } + __decorate([ +@@ -50,3 +50,4 @@ var Main = exports.Main = /** @class */ (function () { + ], Main.prototype, "field", void 0); + return Main; + }()); ++exports.Main = Main; +diff --git a/tests/baselines/reference/decoratorOnClass2.es6.js b/tests/baselines/reference/decoratorOnClass2.es6.js +index 59dec2f5a..608d98270 100644 +--- a/tests/baselines/reference/decoratorOnClass2.es6.js ++++ b/tests/baselines/reference/decoratorOnClass2.es6.js +@@ -16,9 +16,10 @@ var __decorate = (this && this.__decorate) || function (decorators, target, key, + else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; + return c > 3 && r && Object.defineProperty(target, key, r), r; + }; +-export let C = class C { ++let C = class C { + }; + C = __decorate([ + dec + ], C); ++export { C }; + let c = new C(); +diff --git a/tests/baselines/reference/decoratorOnClass2.js b/tests/baselines/reference/decoratorOnClass2.js +index 649c3e9b0..a86c5a411 100644 +--- a/tests/baselines/reference/decoratorOnClass2.js ++++ b/tests/baselines/reference/decoratorOnClass2.js +@@ -17,7 +17,7 @@ var __decorate = (this && this.__decorate) || function (decorators, target, key, + }; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.C = void 0; +-var C = exports.C = /** @class */ (function () { ++var C = /** @class */ (function () { + function C() { + } + C = __decorate([ +@@ -25,3 +25,4 @@ var C = exports.C = /** @class */ (function () { + ], C); + return C; + }()); ++exports.C = C; +diff --git a/tests/baselines/reference/decoratorOnClass3.js b/tests/baselines/reference/decoratorOnClass3.js +index 28a7f2221..ffb602784 100644 +--- a/tests/baselines/reference/decoratorOnClass3.js ++++ b/tests/baselines/reference/decoratorOnClass3.js +@@ -18,7 +18,7 @@ var __decorate = (this && this.__decorate) || function (decorators, target, key, + }; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.C = void 0; +-var C = exports.C = /** @class */ (function () { ++var C = /** @class */ (function () { + function C() { + } + C = __decorate([ +@@ -26,3 +26,4 @@ var C = exports.C = /** @class */ (function () { + ], C); + return C; + }()); ++exports.C = C; +diff --git a/tests/baselines/reference/decoratorOnClass6.es6.js b/tests/baselines/reference/decoratorOnClass6.es6.js +index 079578f49..cf9238b9c 100644 +--- a/tests/baselines/reference/decoratorOnClass6.es6.js ++++ b/tests/baselines/reference/decoratorOnClass6.es6.js +@@ -19,11 +19,12 @@ var __decorate = (this && this.__decorate) || function (decorators, target, key, + return c > 3 && r && Object.defineProperty(target, key, r), r; + }; + var C_1; +-export let C = C_1 = class C { ++let C = C_1 = class C { + static x() { return C_1.y; } + }; + C.y = 1; + C = C_1 = __decorate([ + dec + ], C); ++export { C }; + let c = new C(); +diff --git a/tests/baselines/reference/decoratorOnClass8.es6.js b/tests/baselines/reference/decoratorOnClass8.es6.js +index 65733d82e..629737f99 100644 +--- a/tests/baselines/reference/decoratorOnClass8.es6.js ++++ b/tests/baselines/reference/decoratorOnClass8.es6.js +@@ -19,9 +19,10 @@ var __setFunctionName = (this && this.__setFunctionName) || function (f, name, p + if (typeof name === "symbol") name = name.description ? "[".concat(name.description, "]") : ""; + return Object.defineProperty(f, "name", { configurable: true, value: prefix ? "".concat(prefix, " ", name) : name }); + }; +-let default_1 = class { ++var _a; ++let default_1 = _a = class { + }; +-__setFunctionName(default_1, "default"); ++__setFunctionName(_a, "default"); + default_1.y = 1; + default_1 = __decorate([ + dec +diff --git a/tests/baselines/reference/decoratorOnClassConstructor2.js b/tests/baselines/reference/decoratorOnClassConstructor2.js +index dff6101a9..23dbbf690 100644 +--- a/tests/baselines/reference/decoratorOnClassConstructor2.js ++++ b/tests/baselines/reference/decoratorOnClassConstructor2.js +@@ -55,7 +55,7 @@ Object.defineProperty(exports, "__esModule", { value: true }); + exports.C = void 0; + var _0_ts_1 = require("./0.ts"); + var _0_ts_2 = require("./0.ts"); +-var C = exports.C = /** @class */ (function (_super) { ++var C = /** @class */ (function (_super) { + __extends(C, _super); + function C(prop) { + return _super.call(this) || this; +@@ -65,3 +65,4 @@ var C = exports.C = /** @class */ (function (_super) { + ], C); + return C; + }(_0_ts_1.base)); ++exports.C = C; +diff --git a/tests/baselines/reference/decoratorOnClassConstructor3.js b/tests/baselines/reference/decoratorOnClassConstructor3.js +index c81f6d873..ff584adb5 100644 +--- a/tests/baselines/reference/decoratorOnClassConstructor3.js ++++ b/tests/baselines/reference/decoratorOnClassConstructor3.js +@@ -58,7 +58,7 @@ exports.C = void 0; + var _0_1 = require("./0"); + var _0_2 = require("./0"); + /* Comment on the Class Declaration */ +-var C = exports.C = /** @class */ (function (_super) { ++var C = /** @class */ (function (_super) { + __extends(C, _super); + function C(prop) { + return _super.call(this) || this; +@@ -68,3 +68,4 @@ var C = exports.C = /** @class */ (function (_super) { + ], C); + return C; + }(_0_1.base)); ++exports.C = C; +diff --git a/tests/baselines/reference/derivedClassSuperProperties.js b/tests/baselines/reference/derivedClassSuperProperties.js +index b76dd2286..e87fd91b7 100644 +--- a/tests/baselines/reference/derivedClassSuperProperties.js ++++ b/tests/baselines/reference/derivedClassSuperProperties.js +@@ -814,9 +814,9 @@ var DerivedWithObjectAccessors = /** @class */ (function (_super) { + return DerivedWithObjectAccessors; + }(Base)); + var DerivedWithObjectAccessorsUsingThisInKeys = /** @class */ (function (_super) { +- var _a; + __extends(DerivedWithObjectAccessorsUsingThisInKeys, _super); + function DerivedWithObjectAccessorsUsingThisInKeys() { ++ var _a; + var _this = this; + var obj = (_a = { + _prop: "prop" +@@ -875,13 +875,13 @@ var DerivedWithObjectComputedPropertyBody = /** @class */ (function (_super) { + return DerivedWithObjectComputedPropertyBody; + }(Base)); + var DerivedWithObjectComputedPropertyName = /** @class */ (function (_super) { +- var _b; + __extends(DerivedWithObjectComputedPropertyName, _super); + function DerivedWithObjectComputedPropertyName() { ++ var _a; + var _this = this; +- var obj = (_b = {}, +- _b[_this.propName] = true, +- _b); ++ var obj = (_a = {}, ++ _a[_this.propName] = true, ++ _a); + _this = _super.call(this) || this; + _this.propName = "prop"; + return _this; +diff --git a/tests/baselines/reference/derivedClassSuperStatementPosition.js b/tests/baselines/reference/derivedClassSuperStatementPosition.js +index dcbfd4dd7..dccc2730c 100644 +--- a/tests/baselines/reference/derivedClassSuperStatementPosition.js ++++ b/tests/baselines/reference/derivedClassSuperStatementPosition.js +@@ -126,8 +126,8 @@ var DerivedBasic = /** @class */ (function (_super) { + var DerivedAfterParameterDefault = /** @class */ (function (_super) { + __extends(DerivedAfterParameterDefault, _super); + function DerivedAfterParameterDefault(x) { +- if (x === void 0) { x = false; } + var _this = this; ++ if (x === void 0) { x = false; } + _this.x1 = x; + _this = _super.call(this, x) || this; + _this.x2 = x; +@@ -138,11 +138,11 @@ var DerivedAfterParameterDefault = /** @class */ (function (_super) { + var DerivedAfterRestParameter = /** @class */ (function (_super) { + __extends(DerivedAfterRestParameter, _super); + function DerivedAfterRestParameter() { ++ var _this = this; + var x = []; + for (var _i = 0; _i < arguments.length; _i++) { + x[_i] = arguments[_i]; + } +- var _this = this; + _this.x1 = x; + _this = _super.call(this, x) || this; + _this.x2 = x; +diff --git a/tests/baselines/reference/emitHelpersWithLocalCollisions(module=amd).js b/tests/baselines/reference/emitHelpersWithLocalCollisions(module=amd).js +index bc2b95802..84f85ae58 100644 +--- a/tests/baselines/reference/emitHelpersWithLocalCollisions(module=amd).js ++++ b/tests/baselines/reference/emitHelpersWithLocalCollisions(module=amd).js +@@ -20,8 +20,9 @@ define(["require", "exports"], function (require, exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.A = void 0; +- let A = exports.A = class A { ++ let A = class A { + }; ++ exports.A = A; + exports.A = A = __decorate([ + dec + ], A); +diff --git a/tests/baselines/reference/emitHelpersWithLocalCollisions(module=commonjs).js b/tests/baselines/reference/emitHelpersWithLocalCollisions(module=commonjs).js +index 18f8435b4..2bf5641f4 100644 +--- a/tests/baselines/reference/emitHelpersWithLocalCollisions(module=commonjs).js ++++ b/tests/baselines/reference/emitHelpersWithLocalCollisions(module=commonjs).js +@@ -19,8 +19,9 @@ var __decorate = (this && this.__decorate) || function (decorators, target, key, + }; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.A = void 0; +-let A = exports.A = class A { ++let A = class A { + }; ++exports.A = A; + exports.A = A = __decorate([ + dec + ], A); +diff --git a/tests/baselines/reference/emitHelpersWithLocalCollisions(module=es2020).js b/tests/baselines/reference/emitHelpersWithLocalCollisions(module=es2020).js +index f66b39136..47204b7a7 100644 +--- a/tests/baselines/reference/emitHelpersWithLocalCollisions(module=es2020).js ++++ b/tests/baselines/reference/emitHelpersWithLocalCollisions(module=es2020).js +@@ -16,10 +16,11 @@ var __decorate = (this && this.__decorate) || function (decorators, target, key, + else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; + return c > 3 && r && Object.defineProperty(target, key, r), r; + }; +-export let A = class A { ++let A = class A { + }; + A = __decorate([ + dec + ], A); ++export { A }; + const o = { a: 1 }; + const y = Object.assign({}, o); +diff --git a/tests/baselines/reference/emitHelpersWithLocalCollisions(module=es2022).js b/tests/baselines/reference/emitHelpersWithLocalCollisions(module=es2022).js +index f66b39136..47204b7a7 100644 +--- a/tests/baselines/reference/emitHelpersWithLocalCollisions(module=es2022).js ++++ b/tests/baselines/reference/emitHelpersWithLocalCollisions(module=es2022).js +@@ -16,10 +16,11 @@ var __decorate = (this && this.__decorate) || function (decorators, target, key, + else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; + return c > 3 && r && Object.defineProperty(target, key, r), r; + }; +-export let A = class A { ++let A = class A { + }; + A = __decorate([ + dec + ], A); ++export { A }; + const o = { a: 1 }; + const y = Object.assign({}, o); +diff --git a/tests/baselines/reference/emitHelpersWithLocalCollisions(module=es6).js b/tests/baselines/reference/emitHelpersWithLocalCollisions(module=es6).js +index f66b39136..47204b7a7 100644 +--- a/tests/baselines/reference/emitHelpersWithLocalCollisions(module=es6).js ++++ b/tests/baselines/reference/emitHelpersWithLocalCollisions(module=es6).js +@@ -16,10 +16,11 @@ var __decorate = (this && this.__decorate) || function (decorators, target, key, + else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; + return c > 3 && r && Object.defineProperty(target, key, r), r; + }; +-export let A = class A { ++let A = class A { + }; + A = __decorate([ + dec + ], A); ++export { A }; + const o = { a: 1 }; + const y = Object.assign({}, o); +diff --git a/tests/baselines/reference/emitHelpersWithLocalCollisions(module=esnext).js b/tests/baselines/reference/emitHelpersWithLocalCollisions(module=esnext).js +index f66b39136..47204b7a7 100644 +--- a/tests/baselines/reference/emitHelpersWithLocalCollisions(module=esnext).js ++++ b/tests/baselines/reference/emitHelpersWithLocalCollisions(module=esnext).js +@@ -16,10 +16,11 @@ var __decorate = (this && this.__decorate) || function (decorators, target, key, + else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; + return c > 3 && r && Object.defineProperty(target, key, r), r; + }; +-export let A = class A { ++let A = class A { + }; + A = __decorate([ + dec + ], A); ++export { A }; + const o = { a: 1 }; + const y = Object.assign({}, o); +diff --git a/tests/baselines/reference/emitHelpersWithLocalCollisions(module=node16).js b/tests/baselines/reference/emitHelpersWithLocalCollisions(module=node16).js +index 18f8435b4..2bf5641f4 100644 +--- a/tests/baselines/reference/emitHelpersWithLocalCollisions(module=node16).js ++++ b/tests/baselines/reference/emitHelpersWithLocalCollisions(module=node16).js +@@ -19,8 +19,9 @@ var __decorate = (this && this.__decorate) || function (decorators, target, key, + }; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.A = void 0; +-let A = exports.A = class A { ++let A = class A { + }; ++exports.A = A; + exports.A = A = __decorate([ + dec + ], A); +diff --git a/tests/baselines/reference/emitHelpersWithLocalCollisions(module=nodenext).js b/tests/baselines/reference/emitHelpersWithLocalCollisions(module=nodenext).js +index 18f8435b4..2bf5641f4 100644 +--- a/tests/baselines/reference/emitHelpersWithLocalCollisions(module=nodenext).js ++++ b/tests/baselines/reference/emitHelpersWithLocalCollisions(module=nodenext).js +@@ -19,8 +19,9 @@ var __decorate = (this && this.__decorate) || function (decorators, target, key, + }; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.A = void 0; +-let A = exports.A = class A { ++let A = class A { + }; ++exports.A = A; + exports.A = A = __decorate([ + dec + ], A); +diff --git a/tests/baselines/reference/emitHelpersWithLocalCollisions(module=none).js b/tests/baselines/reference/emitHelpersWithLocalCollisions(module=none).js +index 18f8435b4..2bf5641f4 100644 +--- a/tests/baselines/reference/emitHelpersWithLocalCollisions(module=none).js ++++ b/tests/baselines/reference/emitHelpersWithLocalCollisions(module=none).js +@@ -19,8 +19,9 @@ var __decorate = (this && this.__decorate) || function (decorators, target, key, + }; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.A = void 0; +-let A = exports.A = class A { ++let A = class A { + }; ++exports.A = A; + exports.A = A = __decorate([ + dec + ], A); +diff --git a/tests/baselines/reference/emitHelpersWithLocalCollisions(module=system).js b/tests/baselines/reference/emitHelpersWithLocalCollisions(module=system).js +index 541e086b2..bc2a54a45 100644 +--- a/tests/baselines/reference/emitHelpersWithLocalCollisions(module=system).js ++++ b/tests/baselines/reference/emitHelpersWithLocalCollisions(module=system).js +@@ -23,8 +23,9 @@ System.register([], function (exports_1, context_1) { + return { + setters: [], + execute: function () { +- exports_1("A", A = class A { +- }); ++ A = class A { ++ }; ++ exports_1("A", A); + exports_1("A", A = __decorate([ + dec + ], A)); +diff --git a/tests/baselines/reference/emitHelpersWithLocalCollisions(module=umd).js b/tests/baselines/reference/emitHelpersWithLocalCollisions(module=umd).js +index 451d285e6..19538ce4e 100644 +--- a/tests/baselines/reference/emitHelpersWithLocalCollisions(module=umd).js ++++ b/tests/baselines/reference/emitHelpersWithLocalCollisions(module=umd).js +@@ -28,8 +28,9 @@ var __decorate = (this && this.__decorate) || function (decorators, target, key, + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.A = void 0; +- let A = exports.A = class A { ++ let A = class A { + }; ++ exports.A = A; + exports.A = A = __decorate([ + dec + ], A); +diff --git a/tests/baselines/reference/es3defaultAliasIsQuoted.js b/tests/baselines/reference/es3defaultAliasIsQuoted.js +index c8ae85c5b..a486ad614 100644 +--- a/tests/baselines/reference/es3defaultAliasIsQuoted.js ++++ b/tests/baselines/reference/es3defaultAliasIsQuoted.js +@@ -17,12 +17,13 @@ assert(Foo.CONSTANT === "Foo"); + "use strict"; + exports.__esModule = true; + exports.Foo = void 0; +-var Foo = exports.Foo = /** @class */ (function () { ++var Foo = /** @class */ (function () { + function Foo() { + } + Foo.CONSTANT = "Foo"; + return Foo; + }()); ++exports.Foo = Foo; + function assert(value) { + if (!value) + throw new Error("Assertion failed!"); +diff --git a/tests/baselines/reference/es6modulekindWithES5Target.js b/tests/baselines/reference/es6modulekindWithES5Target.js +index d1930d6b2..cf06a98bd 100644 +--- a/tests/baselines/reference/es6modulekindWithES5Target.js ++++ b/tests/baselines/reference/es6modulekindWithES5Target.js +@@ -28,7 +28,7 @@ var __decorate = (this && this.__decorate) || function (decorators, target, key, + else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; + return c > 3 && r && Object.defineProperty(target, key, r), r; + }; +-export var C = /** @class */ (function () { ++var C = /** @class */ (function () { + function C() { + this.p = 1; + } +@@ -36,8 +36,9 @@ export var C = /** @class */ (function () { + C.s = 0; + return C; + }()); ++export { C }; + export { C as C2 }; +-export var D = /** @class */ (function () { ++var D = /** @class */ (function () { + function D() { + this.p = 1; + } +@@ -48,6 +49,7 @@ export var D = /** @class */ (function () { + ], D); + return D; + }()); ++export { D }; + export { D as D2 }; + var E = /** @class */ (function () { + function E() { +diff --git a/tests/baselines/reference/esDecorators-classDeclaration-accessors-nonStatic(target=es5).js b/tests/baselines/reference/esDecorators-classDeclaration-accessors-nonStatic(target=es5).js +index 2a06295af..84e8663f0 100644 +--- a/tests/baselines/reference/esDecorators-classDeclaration-accessors-nonStatic(target=es5).js ++++ b/tests/baselines/reference/esDecorators-classDeclaration-accessors-nonStatic(target=es5).js +@@ -16,7 +16,6 @@ class C { + + + //// [esDecorators-classDeclaration-accessors-nonStatic.js] +-var _this = this; + var method3 = "method3"; + var C = function () { + var _a; +diff --git a/tests/baselines/reference/esDecorators-classDeclaration-accessors-static(target=es5).js b/tests/baselines/reference/esDecorators-classDeclaration-accessors-static(target=es5).js +index 4b2145d6f..e4a789cc1 100644 +--- a/tests/baselines/reference/esDecorators-classDeclaration-accessors-static(target=es5).js ++++ b/tests/baselines/reference/esDecorators-classDeclaration-accessors-static(target=es5).js +@@ -16,7 +16,6 @@ class C { + + + //// [esDecorators-classDeclaration-accessors-static.js] +-var _this = this; + var method3 = "method3"; + var C = function () { + var _a; +diff --git a/tests/baselines/reference/esDecorators-classDeclaration-accessors-staticPrivate(target=es2015).js b/tests/baselines/reference/esDecorators-classDeclaration-accessors-staticPrivate(target=es2015).js +index 99000eedb..6cc43a114 100644 +--- a/tests/baselines/reference/esDecorators-classDeclaration-accessors-staticPrivate(target=es2015).js ++++ b/tests/baselines/reference/esDecorators-classDeclaration-accessors-staticPrivate(target=es2015).js +@@ -41,23 +41,23 @@ let C = (() => { + _a; + })(); + let D = (() => { +- var _method1_get, _method1_set; ++ var _D_method1_get, _D_method1_set; + let _classDecorators = [dec]; + let _classDescriptor; + let _classExtraInitializers = []; + let _classThis; + var D = _classThis = class { + }; +- _method1_get = function _method1_get() { return 0; }; +- _method1_set = function _method1_set(value) { }; ++ _D_method1_get = function _D_method1_get() { return 0; }; ++ _D_method1_set = function _D_method1_set(value) { }; + __setFunctionName(_classThis, "D"); + (() => { + __esDecorate(null, _classDescriptor = { value: _classThis }, _classDecorators, { kind: "class", name: _classThis.name }, null, _classExtraInitializers); + D = _classThis = _classDescriptor.value; + })(); + (() => { +- __classPrivateFieldGet(_classThis, _classThis, "a", _method1_get); +- __classPrivateFieldSet(_classThis, _classThis, 1, "a", _method1_set); ++ __classPrivateFieldGet(_classThis, _classThis, "a", _D_method1_get); ++ __classPrivateFieldSet(_classThis, _classThis, 1, "a", _D_method1_set); + })(); + (() => { + __runInitializers(_classThis, _classExtraInitializers); +diff --git a/tests/baselines/reference/esDecorators-classDeclaration-accessors-staticPrivate(target=es2022).js b/tests/baselines/reference/esDecorators-classDeclaration-accessors-staticPrivate(target=es2022).js +index 9c6884476..11ec07623 100644 +--- a/tests/baselines/reference/esDecorators-classDeclaration-accessors-staticPrivate(target=es2022).js ++++ b/tests/baselines/reference/esDecorators-classDeclaration-accessors-staticPrivate(target=es2022).js +@@ -39,21 +39,22 @@ let C = (() => { + }; + })(); + let D = (() => { +- var _method1_get, _method1_set; ++ var _D_method1_get, _D_method1_set; + let _classDecorators = [dec]; + let _classDescriptor; + let _classExtraInitializers = []; + let _classThis; + var D = class { ++ static { _classThis = this; } + static { __setFunctionName(this, "D"); } +- static { _method1_get = function _method1_get() { return 0; }, _method1_set = function _method1_set(value) { }; } ++ static { _D_method1_get = function _D_method1_get() { return 0; }, _D_method1_set = function _D_method1_set(value) { }; } + static { +- __esDecorate(null, _classDescriptor = { value: this }, _classDecorators, { kind: "class", name: this.name }, null, _classExtraInitializers); ++ __esDecorate(null, _classDescriptor = { value: _classThis }, _classDecorators, { kind: "class", name: _classThis.name }, null, _classExtraInitializers); + D = _classThis = _classDescriptor.value; + } + static { +- __classPrivateFieldGet(_classThis, _classThis, "a", _method1_get); +- __classPrivateFieldSet(_classThis, _classThis, 1, "a", _method1_set); ++ __classPrivateFieldGet(_classThis, _classThis, "a", _D_method1_get); ++ __classPrivateFieldSet(_classThis, _classThis, 1, "a", _D_method1_set); + } + static { + __runInitializers(_classThis, _classExtraInitializers); +diff --git a/tests/baselines/reference/esDecorators-classDeclaration-classSuper.1.js b/tests/baselines/reference/esDecorators-classDeclaration-classSuper.1.js +index 9c19a1b1c..9eca68691 100644 +--- a/tests/baselines/reference/esDecorators-classDeclaration-classSuper.1.js ++++ b/tests/baselines/reference/esDecorators-classDeclaration-classSuper.1.js +@@ -32,8 +32,9 @@ let C = (() => { + let _classThis; + let _classSuper = Base; + var C = class extends _classSuper { ++ static { _classThis = this; } + static { +- __esDecorate(null, _classDescriptor = { value: this }, _classDecorators, { kind: "class", name: this.name }, null, _classExtraInitializers); ++ __esDecorate(null, _classDescriptor = { value: _classThis }, _classDecorators, { kind: "class", name: _classThis.name }, null, _classExtraInitializers); + C = _classThis = _classDescriptor.value; + } + static { +diff --git a/tests/baselines/reference/esDecorators-classDeclaration-classSuper.2.js b/tests/baselines/reference/esDecorators-classDeclaration-classSuper.2.js +index 09a3a34b0..489e29eb0 100644 +--- a/tests/baselines/reference/esDecorators-classDeclaration-classSuper.2.js ++++ b/tests/baselines/reference/esDecorators-classDeclaration-classSuper.2.js +@@ -38,8 +38,9 @@ let C1 = (() => { + let _classSuper = (0, class { + }); + var C1 = class extends _classSuper { ++ static { _classThis = this; } + static { +- __esDecorate(null, _classDescriptor = { value: this }, _classDecorators, { kind: "class", name: this.name }, null, _classExtraInitializers); ++ __esDecorate(null, _classDescriptor = { value: _classThis }, _classDecorators, { kind: "class", name: _classThis.name }, null, _classExtraInitializers); + C1 = _classThis = _classDescriptor.value; + } + static { +@@ -53,43 +54,45 @@ let C1 = (() => { + })(); + // function expression in extends should not get an assigned name + let C2 = (() => { +- let _classDecorators_1 = [dec]; +- let _classDescriptor_1; +- let _classExtraInitializers_1 = []; +- let _classThis_1; +- let _classSuper_1 = (0, function () { }); +- var C2 = class extends _classSuper_1 { ++ let _classDecorators = [dec]; ++ let _classDescriptor; ++ let _classExtraInitializers = []; ++ let _classThis; ++ let _classSuper = (0, function () { }); ++ var C2 = class extends _classSuper { ++ static { _classThis = this; } + static { +- __esDecorate(null, _classDescriptor_1 = { value: this }, _classDecorators_1, { kind: "class", name: this.name }, null, _classExtraInitializers_1); +- C2 = _classThis_1 = _classDescriptor_1.value; ++ __esDecorate(null, _classDescriptor = { value: _classThis }, _classDecorators, { kind: "class", name: _classThis.name }, null, _classExtraInitializers); ++ C2 = _classThis = _classDescriptor.value; + } + static { +- Reflect.get(_classSuper_1, "name", _classThis_1); ++ Reflect.get(_classSuper, "name", _classThis); + } + static { +- __runInitializers(_classThis_1, _classExtraInitializers_1); ++ __runInitializers(_classThis, _classExtraInitializers); + } + }; +- return C2 = _classThis_1; ++ return C2 = _classThis; + })(); + // arrow function in extends should not get an assigned name + let C3 = (() => { +- let _classDecorators_2 = [dec]; +- let _classDescriptor_2; +- let _classExtraInitializers_2 = []; +- let _classThis_2; +- let _classSuper_2 = (0, (() => { })); +- var C3 = class extends _classSuper_2 { ++ let _classDecorators = [dec]; ++ let _classDescriptor; ++ let _classExtraInitializers = []; ++ let _classThis; ++ let _classSuper = (0, (() => { })); ++ var C3 = class extends _classSuper { ++ static { _classThis = this; } + static { +- __esDecorate(null, _classDescriptor_2 = { value: this }, _classDecorators_2, { kind: "class", name: this.name }, null, _classExtraInitializers_2); +- C3 = _classThis_2 = _classDescriptor_2.value; ++ __esDecorate(null, _classDescriptor = { value: _classThis }, _classDecorators, { kind: "class", name: _classThis.name }, null, _classExtraInitializers); ++ C3 = _classThis = _classDescriptor.value; + } + static { +- Reflect.get(_classSuper_2, "name", _classThis_2); ++ Reflect.get(_classSuper, "name", _classThis); + } + static { +- __runInitializers(_classThis_2, _classExtraInitializers_2); ++ __runInitializers(_classThis, _classExtraInitializers); + } + }; +- return C3 = _classThis_2; ++ return C3 = _classThis; + })(); +diff --git a/tests/baselines/reference/esDecorators-classDeclaration-classSuper.3.js b/tests/baselines/reference/esDecorators-classDeclaration-classSuper.3.js +index bb7b5c389..17b21ab7c 100644 +--- a/tests/baselines/reference/esDecorators-classDeclaration-classSuper.3.js ++++ b/tests/baselines/reference/esDecorators-classDeclaration-classSuper.3.js +@@ -54,8 +54,9 @@ let C = (() => { + let _classThis; + let _classSuper = Base; + var C = class extends _classSuper { ++ static { _classThis = this; } + static { +- __esDecorate(null, _classDescriptor = { value: this }, _classDecorators, { kind: "class", name: this.name }, null, _classExtraInitializers); ++ __esDecorate(null, _classDescriptor = { value: _classThis }, _classDecorators, { kind: "class", name: _classThis.name }, null, _classExtraInitializers); + C = _classThis = _classDescriptor.value; + } + static { +diff --git a/tests/baselines/reference/esDecorators-classDeclaration-classSuper.4.js b/tests/baselines/reference/esDecorators-classDeclaration-classSuper.4.js +index 7f79fba31..8a3503ccd 100644 +--- a/tests/baselines/reference/esDecorators-classDeclaration-classSuper.4.js ++++ b/tests/baselines/reference/esDecorators-classDeclaration-classSuper.4.js +@@ -29,8 +29,9 @@ let C = (() => { + let _classThis; + let _classSuper = Base; + var C = class extends _classSuper { ++ static { _classThis = this; } + static { +- __esDecorate(null, _classDescriptor = { value: this }, _classDecorators, { kind: "class", name: this.name }, null, _classExtraInitializers); ++ __esDecorate(null, _classDescriptor = { value: _classThis }, _classDecorators, { kind: "class", name: _classThis.name }, null, _classExtraInitializers); + C = _classThis = _classDescriptor.value; + } + static a = Reflect.get(_classSuper, "method", _classThis).call(_classThis); +diff --git a/tests/baselines/reference/esDecorators-classDeclaration-classSuper.5.js b/tests/baselines/reference/esDecorators-classDeclaration-classSuper.5.js +index 7bcc60744..f32ee7620 100644 +--- a/tests/baselines/reference/esDecorators-classDeclaration-classSuper.5.js ++++ b/tests/baselines/reference/esDecorators-classDeclaration-classSuper.5.js +@@ -58,8 +58,9 @@ let C1 = (() => { + let _classThis; + let _classSuper = Base; + var C1 = class extends _classSuper { ++ static { _classThis = this; } + static { +- __esDecorate(null, _classDescriptor = { value: this }, _classDecorators, { kind: "class", name: this.name }, null, _classExtraInitializers); ++ __esDecorate(null, _classDescriptor = { value: _classThis }, _classDecorators, { kind: "class", name: _classThis.name }, null, _classExtraInitializers); + C1 = _classThis = _classDescriptor.value; + } + static a = Reflect.get(_classSuper, "x", _classThis); +@@ -96,90 +97,92 @@ let C1 = (() => { + return C1 = _classThis; + })(); + let C2 = (() => { +- let _classDecorators_1 = [dec]; +- let _classDescriptor_1; +- let _classExtraInitializers_1 = []; +- let _classThis_1; +- let _classSuper_1 = Base; +- var C2 = class extends _classSuper_1 { ++ let _classDecorators = [dec]; ++ let _classDescriptor; ++ let _classExtraInitializers = []; ++ let _classThis; ++ let _classSuper = Base; ++ var C2 = class extends _classSuper { ++ static { _classThis = this; } + static { +- __esDecorate(null, _classDescriptor_1 = { value: this }, _classDecorators_1, { kind: "class", name: this.name }, null, _classExtraInitializers_1); +- C2 = _classThis_1 = _classDescriptor_1.value; ++ __esDecorate(null, _classDescriptor = { value: _classThis }, _classDecorators, { kind: "class", name: _classThis.name }, null, _classExtraInitializers); ++ C2 = _classThis = _classDescriptor.value; + } +- static a = Reflect.get(_classSuper_1, "x", _classThis_1); ++ static a = Reflect.get(_classSuper, "x", _classThis); + static b = (() => { + var _a; +- return Reflect.set(_classSuper_1, "x", _a = 1, _classThis_1), _a; ++ return Reflect.set(_classSuper, "x", _a = 1, _classThis), _a; + })(); + static c = (() => { + var _a; +- return Reflect.set(_classSuper_1, "x", _a = Reflect.get(_classSuper_1, "x", _classThis_1) + 1, _classThis_1), _a; ++ return Reflect.set(_classSuper, "x", _a = Reflect.get(_classSuper, "x", _classThis) + 1, _classThis), _a; + })(); + static d = (() => { + var _a, _b; +- return Reflect.set(_classSuper_1, "x", (_b = Reflect.get(_classSuper_1, "x", _classThis_1), _a = _b++, _b), _classThis_1), _a; ++ return Reflect.set(_classSuper, "x", (_b = Reflect.get(_classSuper, "x", _classThis), _a = _b++, _b), _classThis), _a; + })(); + static e = (() => { + var _a, _b; +- return Reflect.set(_classSuper_1, "x", (_b = Reflect.get(_classSuper_1, "x", _classThis_1), _a = _b--, _b), _classThis_1), _a; ++ return Reflect.set(_classSuper, "x", (_b = Reflect.get(_classSuper, "x", _classThis), _a = _b--, _b), _classThis), _a; + })(); + static f = (() => { + var _a, _b; +- return Reflect.set(_classSuper_1, "x", (_b = Reflect.get(_classSuper_1, "x", _classThis_1), _a = ++_b), _classThis_1), _a; ++ return Reflect.set(_classSuper, "x", (_b = Reflect.get(_classSuper, "x", _classThis), _a = ++_b), _classThis), _a; + })(); + static g = (() => { + var _a, _b; +- return Reflect.set(_classSuper_1, "x", (_b = Reflect.get(_classSuper_1, "x", _classThis_1), _a = --_b), _classThis_1), _a; ++ return Reflect.set(_classSuper, "x", (_b = Reflect.get(_classSuper, "x", _classThis), _a = --_b), _classThis), _a; + })(); +- static h = ({ x: ({ set value(_a) { Reflect.set(_classSuper_1, "x", _a, _classThis_1); } }).value } = { x: 1 }); +- static i = [({ set value(_a) { Reflect.set(_classSuper_1, "x", _a, _classThis_1); } }).value] = [1]; ++ static h = ({ x: ({ set value(_a) { Reflect.set(_classSuper, "x", _a, _classThis); } }).value } = { x: 1 }); ++ static i = [({ set value(_a) { Reflect.set(_classSuper, "x", _a, _classThis); } }).value] = [1]; + static { +- __runInitializers(_classThis_1, _classExtraInitializers_1); ++ __runInitializers(_classThis, _classExtraInitializers); + } + }; +- return C2 = _classThis_1; ++ return C2 = _classThis; + })(); + let C3 = (() => { +- let _classDecorators_2 = [dec]; +- let _classDescriptor_2; +- let _classExtraInitializers_2 = []; +- let _classThis_2; +- let _classSuper_2 = Base; +- var C3 = class extends _classSuper_2 { ++ let _classDecorators = [dec]; ++ let _classDescriptor; ++ let _classExtraInitializers = []; ++ let _classThis; ++ let _classSuper = Base; ++ var C3 = class extends _classSuper { ++ static { _classThis = this; } + static { +- __esDecorate(null, _classDescriptor_2 = { value: this }, _classDecorators_2, { kind: "class", name: this.name }, null, _classExtraInitializers_2); +- C3 = _classThis_2 = _classDescriptor_2.value; ++ __esDecorate(null, _classDescriptor = { value: _classThis }, _classDecorators, { kind: "class", name: _classThis.name }, null, _classExtraInitializers); ++ C3 = _classThis = _classDescriptor.value; + } +- static a = Reflect.get(_classSuper_2, x, _classThis_2); ++ static a = Reflect.get(_classSuper, x, _classThis); + static b = (() => { + var _a; +- return Reflect.set(_classSuper_2, x, _a = 1, _classThis_2), _a; ++ return Reflect.set(_classSuper, x, _a = 1, _classThis), _a; + })(); + static c = (() => { + var _a, _b; +- return Reflect.set(_classSuper_2, _a = x, _b = Reflect.get(_classSuper_2, _a, _classThis_2) + 1, _classThis_2), _b; ++ return Reflect.set(_classSuper, _a = x, _b = Reflect.get(_classSuper, _a, _classThis) + 1, _classThis), _b; + })(); + static d = (() => { + var _a, _b, _c; +- return Reflect.set(_classSuper_2, _a = x, (_c = Reflect.get(_classSuper_2, _a, _classThis_2), _b = _c++, _c), _classThis_2), _b; ++ return Reflect.set(_classSuper, _a = x, (_c = Reflect.get(_classSuper, _a, _classThis), _b = _c++, _c), _classThis), _b; + })(); + static e = (() => { + var _a, _b, _c; +- return Reflect.set(_classSuper_2, _a = x, (_c = Reflect.get(_classSuper_2, _a, _classThis_2), _b = _c--, _c), _classThis_2), _b; ++ return Reflect.set(_classSuper, _a = x, (_c = Reflect.get(_classSuper, _a, _classThis), _b = _c--, _c), _classThis), _b; + })(); + static f = (() => { + var _a, _b, _c; +- return Reflect.set(_classSuper_2, _a = x, (_c = Reflect.get(_classSuper_2, _a, _classThis_2), _b = ++_c), _classThis_2), _b; ++ return Reflect.set(_classSuper, _a = x, (_c = Reflect.get(_classSuper, _a, _classThis), _b = ++_c), _classThis), _b; + })(); + static g = (() => { + var _a, _b, _c; +- return Reflect.set(_classSuper_2, _a = x, (_c = Reflect.get(_classSuper_2, _a, _classThis_2), _b = --_c), _classThis_2), _b; ++ return Reflect.set(_classSuper, _a = x, (_c = Reflect.get(_classSuper, _a, _classThis), _b = --_c), _classThis), _b; + })(); +- static h = ({ x: ({ set value(_a) { Reflect.set(_classSuper_2, x, _a, _classThis_2); } }).value } = { x: 1 }); +- static i = [({ set value(_a) { Reflect.set(_classSuper_2, x, _a, _classThis_2); } }).value] = [1]; ++ static h = ({ x: ({ set value(_a) { Reflect.set(_classSuper, x, _a, _classThis); } }).value } = { x: 1 }); ++ static i = [({ set value(_a) { Reflect.set(_classSuper, x, _a, _classThis); } }).value] = [1]; + static { +- __runInitializers(_classThis_2, _classExtraInitializers_2); ++ __runInitializers(_classThis, _classExtraInitializers); + } + }; +- return C3 = _classThis_2; ++ return C3 = _classThis; + })(); +diff --git a/tests/baselines/reference/esDecorators-classDeclaration-classSuper.6.js b/tests/baselines/reference/esDecorators-classDeclaration-classSuper.6.js +index def3ef120..ec4181df8 100644 +--- a/tests/baselines/reference/esDecorators-classDeclaration-classSuper.6.js ++++ b/tests/baselines/reference/esDecorators-classDeclaration-classSuper.6.js +@@ -35,8 +35,9 @@ let C = (() => { + let _classExtraInitializers = []; + let _classThis; + var C = class extends Base { ++ static { _classThis = this; } + static { +- __esDecorate(null, _classDescriptor = { value: this }, _classDecorators, { kind: "class", name: this.name }, null, _classExtraInitializers); ++ __esDecorate(null, _classDescriptor = { value: _classThis }, _classDecorators, { kind: "class", name: _classThis.name }, null, _classExtraInitializers); + C = _classThis = _classDescriptor.value; + __runInitializers(_classThis, _classExtraInitializers); + } +diff --git a/tests/baselines/reference/esDecorators-classDeclaration-classSuper.7.js b/tests/baselines/reference/esDecorators-classDeclaration-classSuper.7.js +index 0072e7150..a10338a6a 100644 +--- a/tests/baselines/reference/esDecorators-classDeclaration-classSuper.7.js ++++ b/tests/baselines/reference/esDecorators-classDeclaration-classSuper.7.js +@@ -71,31 +71,31 @@ function foo(method, _context) { + new B(); + // https://github.com/microsoft/TypeScript/issues/53448 + let C = (() => { +- let _instanceExtraInitializers_1 = []; ++ let _instanceExtraInitializers = []; + let _get_val_decorators; + return class C { + static { + _get_val_decorators = [foo]; +- __esDecorate(this, null, _get_val_decorators, { kind: "getter", name: "val", static: false, private: false, access: { has: obj => "val" in obj, get: obj => obj.val } }, null, _instanceExtraInitializers_1); ++ __esDecorate(this, null, _get_val_decorators, { kind: "getter", name: "val", static: false, private: false, access: { has: obj => "val" in obj, get: obj => obj.val } }, null, _instanceExtraInitializers); + } + constructor() { +- __runInitializers(this, _instanceExtraInitializers_1); ++ __runInitializers(this, _instanceExtraInitializers); + this.val; + } + get val() { return 3; } + }; + })(); + let D = (() => { +- let _instanceExtraInitializers_2 = []; ++ let _instanceExtraInitializers = []; + let _get_val_decorators; + return class D extends A { + static { + _get_val_decorators = [foo]; +- __esDecorate(this, null, _get_val_decorators, { kind: "getter", name: "val", static: false, private: false, access: { has: obj => "val" in obj, get: obj => obj.val } }, null, _instanceExtraInitializers_2); ++ __esDecorate(this, null, _get_val_decorators, { kind: "getter", name: "val", static: false, private: false, access: { has: obj => "val" in obj, get: obj => obj.val } }, null, _instanceExtraInitializers); + } + constructor() { + super(); +- __runInitializers(this, _instanceExtraInitializers_2); ++ __runInitializers(this, _instanceExtraInitializers); + this.val; + } + get val() { return 3; } +diff --git a/tests/baselines/reference/esDecorators-classDeclaration-classThisReference(target=es2015).js b/tests/baselines/reference/esDecorators-classDeclaration-classThisReference(target=es2015).js +index ec04ba624..3438801f4 100644 +--- a/tests/baselines/reference/esDecorators-classDeclaration-classThisReference(target=es2015).js ++++ b/tests/baselines/reference/esDecorators-classDeclaration-classThisReference(target=es2015).js +@@ -15,14 +15,14 @@ class C { + + //// [esDecorators-classDeclaration-classThisReference.js] + let C = (() => { +- var _a_accessor_storage; ++ var _C_a_accessor_storage; + let _classDecorators = [dec]; + let _classDescriptor; + let _classExtraInitializers = []; + let _classThis; + var C = _classThis = class { +- static get a() { return __classPrivateFieldGet(this, _classThis, "f", _a_accessor_storage); } +- static set a(value) { __classPrivateFieldSet(this, _classThis, value, "f", _a_accessor_storage); } ++ static get a() { return __classPrivateFieldGet(this, _classThis, "f", _C_a_accessor_storage); } ++ static set a(value) { __classPrivateFieldSet(this, _classThis, value, "f", _C_a_accessor_storage); } + static m() { this; } + static get g() { return this; } + }; +@@ -35,7 +35,7 @@ let C = (() => { + _classThis; + })(); + _classThis.x = _classThis; +- _a_accessor_storage = { value: _classThis }; ++ _C_a_accessor_storage = { value: _classThis }; + (() => { + __runInitializers(_classThis, _classExtraInitializers); + })(); +diff --git a/tests/baselines/reference/esDecorators-classDeclaration-classThisReference(target=es2022).js b/tests/baselines/reference/esDecorators-classDeclaration-classThisReference(target=es2022).js +index 616b3afdf..18a9b11fb 100644 +--- a/tests/baselines/reference/esDecorators-classDeclaration-classThisReference(target=es2022).js ++++ b/tests/baselines/reference/esDecorators-classDeclaration-classThisReference(target=es2022).js +@@ -15,24 +15,25 @@ class C { + + //// [esDecorators-classDeclaration-classThisReference.js] + let C = (() => { +- var _a_accessor_storage; ++ var _C_a_accessor_storage; + let _classDecorators = [dec]; + let _classDescriptor; + let _classExtraInitializers = []; + let _classThis; + var C = class { ++ static { _classThis = this; } + static { __setFunctionName(this, "C"); } + static { +- __esDecorate(null, _classDescriptor = { value: this }, _classDecorators, { kind: "class", name: this.name }, null, _classExtraInitializers); ++ __esDecorate(null, _classDescriptor = { value: _classThis }, _classDecorators, { kind: "class", name: _classThis.name }, null, _classExtraInitializers); + C = _classThis = _classDescriptor.value; + } + static { _classThis; } + static x = _classThis; + static { +- _a_accessor_storage = { value: _classThis }; ++ _C_a_accessor_storage = { value: _classThis }; + } +- static get a() { return __classPrivateFieldGet(this, _classThis, "f", _a_accessor_storage); } +- static set a(value) { __classPrivateFieldSet(this, _classThis, value, "f", _a_accessor_storage); } ++ static get a() { return __classPrivateFieldGet(this, _classThis, "f", _C_a_accessor_storage); } ++ static set a(value) { __classPrivateFieldSet(this, _classThis, value, "f", _C_a_accessor_storage); } + static m() { this; } + static get g() { return this; } + static { +diff --git a/tests/baselines/reference/esDecorators-classDeclaration-classThisReference.es5.js b/tests/baselines/reference/esDecorators-classDeclaration-classThisReference.es5.js +index 8e7ed7b65..29c1235e7 100644 +--- a/tests/baselines/reference/esDecorators-classDeclaration-classThisReference.es5.js ++++ b/tests/baselines/reference/esDecorators-classDeclaration-classThisReference.es5.js +@@ -13,7 +13,6 @@ class C { + + + //// [esDecorators-classDeclaration-classThisReference.es5.js] +-var _this = this; + var C = function () { + var _classDecorators = [dec]; + var _classDescriptor; +diff --git a/tests/baselines/reference/esDecorators-classDeclaration-commentPreservation(module=commonjs,target=es2015).js b/tests/baselines/reference/esDecorators-classDeclaration-commentPreservation(module=commonjs,target=es2015).js +index bc92f15ec..152531f27 100644 +--- a/tests/baselines/reference/esDecorators-classDeclaration-commentPreservation(module=commonjs,target=es2015).js ++++ b/tests/baselines/reference/esDecorators-classDeclaration-commentPreservation(module=commonjs,target=es2015).js +@@ -122,7 +122,7 @@ class G { + //// [file1.js] + /*1*/ + let C = (() => { +- var _method_get, _x_get, _x_set, _y, _z_accessor_storage, _z_get, _z_set, _z_1_accessor_storage; ++ var _C_method_get, _C_x_get, _C_x_set, _C_y, _C_z_accessor_storage, _C_z_get, _C_z_set, _C_z_1_accessor_storage; + let _classDecorators = [dec, dec]; + let _classDescriptor; + let _classExtraInitializers = []; +@@ -151,7 +151,7 @@ let C = (() => { + constructor() { + /*13*/ + this.y = (__runInitializers(this, _instanceExtraInitializers), __runInitializers(this, _y_initializers, 1)); +- _z_1_accessor_storage.set(this, __runInitializers(this, _z_initializers, 1)); ++ _C_z_1_accessor_storage.set(this, __runInitializers(this, _z_initializers, 1)); + } + /*4*/ + method() { } +@@ -160,15 +160,15 @@ let C = (() => { + /*10*/ + set x(value) { } + /*16*/ +- get z() { return __classPrivateFieldGet(this, _z_1_accessor_storage, "f"); } +- set z(value) { __classPrivateFieldSet(this, _z_1_accessor_storage, value, "f"); } ++ get z() { return __classPrivateFieldGet(this, _C_z_1_accessor_storage, "f"); } ++ set z(value) { __classPrivateFieldSet(this, _C_z_1_accessor_storage, value, "f"); } + }; +- _z_1_accessor_storage = new WeakMap(); +- _method_get = function _method_get() { return _static_private_method_descriptor.value; }; +- _x_get = function _x_get() { return _static_private_get_x_descriptor.get.call(this); }; +- _x_set = function _x_set(value) { return _static_private_set_x_descriptor.set.call(this, value); }; +- _z_get = function _z_get() { return _static_private_z_descriptor.get.call(this); }; +- _z_set = function _z_set(value) { return _static_private_z_descriptor.set.call(this, value); }; ++ _C_z_1_accessor_storage = new WeakMap(); ++ _C_method_get = function _C_method_get() { return _static_private_method_descriptor.value; }; ++ _C_x_get = function _C_x_get() { return _static_private_get_x_descriptor.get.call(this); }; ++ _C_x_set = function _C_x_set(value) { return _static_private_set_x_descriptor.set.call(this, value); }; ++ _C_z_get = function _C_z_get() { return _static_private_z_descriptor.get.call(this); }; ++ _C_z_set = function _C_z_set(value) { return _static_private_z_descriptor.set.call(this, value); }; + __setFunctionName(_classThis, "C"); + (() => { + _method_decorators = [dec, dec]; +@@ -181,23 +181,23 @@ let C = (() => { + _static_private_set_x_decorators = [dec, dec]; + _static_private_y_decorators = [dec, dec]; + _static_private_z_decorators = [dec, dec]; +- __esDecorate(_classThis, _static_private_method_descriptor = { value: __setFunctionName(function () { }, "#method") }, _static_private_method_decorators, { kind: "method", name: "#method", static: true, private: true, access: { has: obj => __classPrivateFieldIn(_classThis, obj), get: obj => __classPrivateFieldGet(obj, _classThis, "a", _method_get) } }, null, _staticExtraInitializers); +- __esDecorate(_classThis, _static_private_get_x_descriptor = { get: __setFunctionName(function () { return 1; }, "#x", "get") }, _static_private_get_x_decorators, { kind: "getter", name: "#x", static: true, private: true, access: { has: obj => __classPrivateFieldIn(_classThis, obj), get: obj => __classPrivateFieldGet(obj, _classThis, "a", _x_get) } }, null, _staticExtraInitializers); +- __esDecorate(_classThis, _static_private_set_x_descriptor = { set: __setFunctionName(function (value) { }, "#x", "set") }, _static_private_set_x_decorators, { kind: "setter", name: "#x", static: true, private: true, access: { has: obj => __classPrivateFieldIn(_classThis, obj), set: (obj, value) => { __classPrivateFieldSet(obj, _classThis, value, "a", _x_set); } } }, null, _staticExtraInitializers); +- __esDecorate(_classThis, _static_private_z_descriptor = { get: __setFunctionName(function () { return __classPrivateFieldGet(_classThis, _classThis, "f", _z_accessor_storage); }, "#z", "get"), set: __setFunctionName(function (value) { __classPrivateFieldSet(_classThis, _classThis, value, "f", _z_accessor_storage); }, "#z", "set") }, _static_private_z_decorators, { kind: "accessor", name: "#z", static: true, private: true, access: { has: obj => __classPrivateFieldIn(_classThis, obj), get: obj => __classPrivateFieldGet(obj, _classThis, "a", _z_get), set: (obj, value) => { __classPrivateFieldSet(obj, _classThis, value, "a", _z_set); } } }, _static_private_z_initializers, _staticExtraInitializers); ++ __esDecorate(_classThis, _static_private_method_descriptor = { value: __setFunctionName(function () { }, "#method") }, _static_private_method_decorators, { kind: "method", name: "#method", static: true, private: true, access: { has: obj => __classPrivateFieldIn(_classThis, obj), get: obj => __classPrivateFieldGet(obj, _classThis, "a", _C_method_get) } }, null, _staticExtraInitializers); ++ __esDecorate(_classThis, _static_private_get_x_descriptor = { get: __setFunctionName(function () { return 1; }, "#x", "get") }, _static_private_get_x_decorators, { kind: "getter", name: "#x", static: true, private: true, access: { has: obj => __classPrivateFieldIn(_classThis, obj), get: obj => __classPrivateFieldGet(obj, _classThis, "a", _C_x_get) } }, null, _staticExtraInitializers); ++ __esDecorate(_classThis, _static_private_set_x_descriptor = { set: __setFunctionName(function (value) { }, "#x", "set") }, _static_private_set_x_decorators, { kind: "setter", name: "#x", static: true, private: true, access: { has: obj => __classPrivateFieldIn(_classThis, obj), set: (obj, value) => { __classPrivateFieldSet(obj, _classThis, value, "a", _C_x_set); } } }, null, _staticExtraInitializers); ++ __esDecorate(_classThis, _static_private_z_descriptor = { get: __setFunctionName(function () { return __classPrivateFieldGet(_classThis, _classThis, "f", _C_z_accessor_storage); }, "#z", "get"), set: __setFunctionName(function (value) { __classPrivateFieldSet(_classThis, _classThis, value, "f", _C_z_accessor_storage); }, "#z", "set") }, _static_private_z_decorators, { kind: "accessor", name: "#z", static: true, private: true, access: { has: obj => __classPrivateFieldIn(_classThis, obj), get: obj => __classPrivateFieldGet(obj, _classThis, "a", _C_z_get), set: (obj, value) => { __classPrivateFieldSet(obj, _classThis, value, "a", _C_z_set); } } }, _static_private_z_initializers, _staticExtraInitializers); + __esDecorate(_classThis, null, _method_decorators, { kind: "method", name: "method", static: false, private: false, access: { has: obj => "method" in obj, get: obj => obj.method } }, null, _instanceExtraInitializers); + __esDecorate(_classThis, null, _get_x_decorators, { kind: "getter", name: "x", static: false, private: false, access: { has: obj => "x" in obj, get: obj => obj.x } }, null, _instanceExtraInitializers); + __esDecorate(_classThis, null, _set_x_decorators, { kind: "setter", name: "x", static: false, private: false, access: { has: obj => "x" in obj, set: (obj, value) => { obj.x = value; } } }, null, _instanceExtraInitializers); + __esDecorate(_classThis, null, _z_decorators, { kind: "accessor", name: "z", static: false, private: false, access: { has: obj => "z" in obj, get: obj => obj.z, set: (obj, value) => { obj.z = value; } } }, _z_initializers, _instanceExtraInitializers); +- __esDecorate(null, null, _static_private_y_decorators, { kind: "field", name: "#y", static: true, private: true, access: { has: obj => __classPrivateFieldIn(_classThis, obj), get: obj => __classPrivateFieldGet(obj, _classThis, "f", _y), set: (obj, value) => { __classPrivateFieldSet(obj, _classThis, value, "f", _y); } } }, _static_private_y_initializers, _staticExtraInitializers); ++ __esDecorate(null, null, _static_private_y_decorators, { kind: "field", name: "#y", static: true, private: true, access: { has: obj => __classPrivateFieldIn(_classThis, obj), get: obj => __classPrivateFieldGet(obj, _classThis, "f", _C_y), set: (obj, value) => { __classPrivateFieldSet(obj, _classThis, value, "f", _C_y); } } }, _static_private_y_initializers, _staticExtraInitializers); + __esDecorate(null, null, _y_decorators, { kind: "field", name: "y", static: false, private: false, access: { has: obj => "y" in obj, get: obj => obj.y, set: (obj, value) => { obj.y = value; } } }, _y_initializers, _instanceExtraInitializers); + __esDecorate(null, _classDescriptor = { value: _classThis }, _classDecorators, { kind: "class", name: _classThis.name }, null, _classExtraInitializers); + C = _classThis = _classDescriptor.value; + __runInitializers(_classThis, _staticExtraInitializers); + })(); + /*28*/ +- _y = { value: __runInitializers(_classThis, _static_private_y_initializers, 1) }; +- _z_accessor_storage = { value: __runInitializers(_classThis, _static_private_z_initializers, 1) }; ++ _C_y = { value: __runInitializers(_classThis, _static_private_y_initializers, 1) }; ++ _C_z_accessor_storage = { value: __runInitializers(_classThis, _static_private_z_initializers, 1) }; + (() => { + __runInitializers(_classThis, _classExtraInitializers); + })(); +@@ -208,7 +208,7 @@ let C = (() => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.D = void 0; + /*34*/ +-let D = exports.D = (() => { ++let D = (() => { + let _classDecorators = [dec, dec]; + let _classDescriptor; + let _classExtraInitializers = []; +@@ -223,27 +223,29 @@ let D = exports.D = (() => { + })(); + return D = _classThis; + })(); +-exports.default = (() => { +- let _classDecorators_1 = [dec, dec]; +- let _classDescriptor_1; +- let _classExtraInitializers_1 = []; +- let _classThis_1; +- var E = _classThis_1 = class { ++exports.D = D; ++let E = (() => { ++ let _classDecorators = [dec, dec]; ++ let _classDescriptor; ++ let _classExtraInitializers = []; ++ let _classThis; ++ var E = _classThis = class { + }; +- __setFunctionName(_classThis_1, "E"); ++ __setFunctionName(_classThis, "E"); + (() => { +- __esDecorate(null, _classDescriptor_1 = { value: _classThis_1 }, _classDecorators_1, { kind: "class", name: _classThis_1.name }, null, _classExtraInitializers_1); +- E = _classThis_1 = _classDescriptor_1.value; +- __runInitializers(_classThis_1, _classExtraInitializers_1); ++ __esDecorate(null, _classDescriptor = { value: _classThis }, _classDecorators, { kind: "class", name: _classThis.name }, null, _classExtraInitializers); ++ E = _classThis = _classDescriptor.value; ++ __runInitializers(_classThis, _classExtraInitializers); + })(); +- return E = _classThis_1; ++ return E = _classThis; + })(); ++exports.default = E; + //// [file3.js] + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.F = void 0; + /*40*/ +-let F = exports.F = (() => { ++let F = (() => { + let _classDecorators = [dec, dec]; + let _classDescriptor; + let _classExtraInitializers = []; +@@ -258,18 +260,20 @@ let F = exports.F = (() => { + })(); + return F = _classThis; + })(); +-exports.default = (() => { +- let _classDecorators_1 = [dec, dec]; +- let _classDescriptor_1; +- let _classExtraInitializers_1 = []; +- let _classThis_1; +- var G = _classThis_1 = class { ++exports.F = F; ++let G = (() => { ++ let _classDecorators = [dec, dec]; ++ let _classDescriptor; ++ let _classExtraInitializers = []; ++ let _classThis; ++ var G = _classThis = class { + }; +- __setFunctionName(_classThis_1, "G"); ++ __setFunctionName(_classThis, "G"); + (() => { +- __esDecorate(null, _classDescriptor_1 = { value: _classThis_1 }, _classDecorators_1, { kind: "class", name: _classThis_1.name }, null, _classExtraInitializers_1); +- G = _classThis_1 = _classDescriptor_1.value; +- __runInitializers(_classThis_1, _classExtraInitializers_1); ++ __esDecorate(null, _classDescriptor = { value: _classThis }, _classDecorators, { kind: "class", name: _classThis.name }, null, _classExtraInitializers); ++ G = _classThis = _classDescriptor.value; ++ __runInitializers(_classThis, _classExtraInitializers); + })(); +- return G = _classThis_1; ++ return G = _classThis; + })(); ++exports.default = G; +diff --git a/tests/baselines/reference/esDecorators-classDeclaration-commentPreservation(module=commonjs,target=es2022).js b/tests/baselines/reference/esDecorators-classDeclaration-commentPreservation(module=commonjs,target=es2022).js +index 812dcb282..3d1ef041d 100644 +--- a/tests/baselines/reference/esDecorators-classDeclaration-commentPreservation(module=commonjs,target=es2022).js ++++ b/tests/baselines/reference/esDecorators-classDeclaration-commentPreservation(module=commonjs,target=es2022).js +@@ -122,7 +122,7 @@ class G { + //// [file1.js] + /*1*/ + let C = (() => { +- var _method_get, _x_get, _x_set, _y, _z_accessor_storage, _z_get, _z_set; ++ var _C_method_get, _C_x_get, _C_x_set, _C_y, _C_z_accessor_storage, _C_z_get, _C_z_set; + let _classDecorators = [dec, dec]; + let _classDescriptor; + let _classExtraInitializers = []; +@@ -148,8 +148,9 @@ let C = (() => { + let _z_decorators; + let _z_initializers = []; + var C = class { ++ static { _classThis = this; } + static { __setFunctionName(this, "C"); } +- static { _method_get = function _method_get() { return _static_private_method_descriptor.value; }, _x_get = function _x_get() { return _static_private_get_x_descriptor.get.call(this); }, _x_set = function _x_set(value) { return _static_private_set_x_descriptor.set.call(this, value); }, _z_get = function _z_get() { return _static_private_z_descriptor.get.call(this); }, _z_set = function _z_set(value) { return _static_private_z_descriptor.set.call(this, value); }; } ++ static { _C_method_get = function _C_method_get() { return _static_private_method_descriptor.value; }, _C_x_get = function _C_x_get() { return _static_private_get_x_descriptor.get.call(this); }, _C_x_set = function _C_x_set(value) { return _static_private_set_x_descriptor.set.call(this, value); }, _C_z_get = function _C_z_get() { return _static_private_z_descriptor.get.call(this); }, _C_z_set = function _C_z_set(value) { return _static_private_z_descriptor.set.call(this, value); }; } + static { + _method_decorators = [dec, dec]; + _get_x_decorators = [dec, dec]; +@@ -161,17 +162,17 @@ let C = (() => { + _static_private_set_x_decorators = [dec, dec]; + _static_private_y_decorators = [dec, dec]; + _static_private_z_decorators = [dec, dec]; +- __esDecorate(this, _static_private_method_descriptor = { value: __setFunctionName(function () { }, "#method") }, _static_private_method_decorators, { kind: "method", name: "#method", static: true, private: true, access: { has: obj => __classPrivateFieldIn(_classThis, obj), get: obj => __classPrivateFieldGet(obj, _classThis, "a", _method_get) } }, null, _staticExtraInitializers); +- __esDecorate(this, _static_private_get_x_descriptor = { get: __setFunctionName(function () { return 1; }, "#x", "get") }, _static_private_get_x_decorators, { kind: "getter", name: "#x", static: true, private: true, access: { has: obj => __classPrivateFieldIn(_classThis, obj), get: obj => __classPrivateFieldGet(obj, _classThis, "a", _x_get) } }, null, _staticExtraInitializers); +- __esDecorate(this, _static_private_set_x_descriptor = { set: __setFunctionName(function (value) { }, "#x", "set") }, _static_private_set_x_decorators, { kind: "setter", name: "#x", static: true, private: true, access: { has: obj => __classPrivateFieldIn(_classThis, obj), set: (obj, value) => { __classPrivateFieldSet(obj, _classThis, value, "a", _x_set); } } }, null, _staticExtraInitializers); +- __esDecorate(this, _static_private_z_descriptor = { get: __setFunctionName(function () { return __classPrivateFieldGet(this, _classThis, "f", _z_accessor_storage); }, "#z", "get"), set: __setFunctionName(function (value) { __classPrivateFieldSet(this, _classThis, value, "f", _z_accessor_storage); }, "#z", "set") }, _static_private_z_decorators, { kind: "accessor", name: "#z", static: true, private: true, access: { has: obj => __classPrivateFieldIn(_classThis, obj), get: obj => __classPrivateFieldGet(obj, _classThis, "a", _z_get), set: (obj, value) => { __classPrivateFieldSet(obj, _classThis, value, "a", _z_set); } } }, _static_private_z_initializers, _staticExtraInitializers); ++ __esDecorate(this, _static_private_method_descriptor = { value: __setFunctionName(function () { }, "#method") }, _static_private_method_decorators, { kind: "method", name: "#method", static: true, private: true, access: { has: obj => __classPrivateFieldIn(_classThis, obj), get: obj => __classPrivateFieldGet(obj, _classThis, "a", _C_method_get) } }, null, _staticExtraInitializers); ++ __esDecorate(this, _static_private_get_x_descriptor = { get: __setFunctionName(function () { return 1; }, "#x", "get") }, _static_private_get_x_decorators, { kind: "getter", name: "#x", static: true, private: true, access: { has: obj => __classPrivateFieldIn(_classThis, obj), get: obj => __classPrivateFieldGet(obj, _classThis, "a", _C_x_get) } }, null, _staticExtraInitializers); ++ __esDecorate(this, _static_private_set_x_descriptor = { set: __setFunctionName(function (value) { }, "#x", "set") }, _static_private_set_x_decorators, { kind: "setter", name: "#x", static: true, private: true, access: { has: obj => __classPrivateFieldIn(_classThis, obj), set: (obj, value) => { __classPrivateFieldSet(obj, _classThis, value, "a", _C_x_set); } } }, null, _staticExtraInitializers); ++ __esDecorate(this, _static_private_z_descriptor = { get: __setFunctionName(function () { return __classPrivateFieldGet(this, _classThis, "f", _C_z_accessor_storage); }, "#z", "get"), set: __setFunctionName(function (value) { __classPrivateFieldSet(this, _classThis, value, "f", _C_z_accessor_storage); }, "#z", "set") }, _static_private_z_decorators, { kind: "accessor", name: "#z", static: true, private: true, access: { has: obj => __classPrivateFieldIn(_classThis, obj), get: obj => __classPrivateFieldGet(obj, _classThis, "a", _C_z_get), set: (obj, value) => { __classPrivateFieldSet(obj, _classThis, value, "a", _C_z_set); } } }, _static_private_z_initializers, _staticExtraInitializers); + __esDecorate(this, null, _method_decorators, { kind: "method", name: "method", static: false, private: false, access: { has: obj => "method" in obj, get: obj => obj.method } }, null, _instanceExtraInitializers); + __esDecorate(this, null, _get_x_decorators, { kind: "getter", name: "x", static: false, private: false, access: { has: obj => "x" in obj, get: obj => obj.x } }, null, _instanceExtraInitializers); + __esDecorate(this, null, _set_x_decorators, { kind: "setter", name: "x", static: false, private: false, access: { has: obj => "x" in obj, set: (obj, value) => { obj.x = value; } } }, null, _instanceExtraInitializers); + __esDecorate(this, null, _z_decorators, { kind: "accessor", name: "z", static: false, private: false, access: { has: obj => "z" in obj, get: obj => obj.z, set: (obj, value) => { obj.z = value; } } }, _z_initializers, _instanceExtraInitializers); +- __esDecorate(null, null, _static_private_y_decorators, { kind: "field", name: "#y", static: true, private: true, access: { has: obj => __classPrivateFieldIn(_classThis, obj), get: obj => __classPrivateFieldGet(obj, _classThis, "f", _y), set: (obj, value) => { __classPrivateFieldSet(obj, _classThis, value, "f", _y); } } }, _static_private_y_initializers, _staticExtraInitializers); ++ __esDecorate(null, null, _static_private_y_decorators, { kind: "field", name: "#y", static: true, private: true, access: { has: obj => __classPrivateFieldIn(_classThis, obj), get: obj => __classPrivateFieldGet(obj, _classThis, "f", _C_y), set: (obj, value) => { __classPrivateFieldSet(obj, _classThis, value, "f", _C_y); } } }, _static_private_y_initializers, _staticExtraInitializers); + __esDecorate(null, null, _y_decorators, { kind: "field", name: "y", static: false, private: false, access: { has: obj => "y" in obj, get: obj => obj.y, set: (obj, value) => { obj.y = value; } } }, _y_initializers, _instanceExtraInitializers); +- __esDecorate(null, _classDescriptor = { value: this }, _classDecorators, { kind: "class", name: this.name }, null, _classExtraInitializers); ++ __esDecorate(null, _classDescriptor = { value: _classThis }, _classDecorators, { kind: "class", name: _classThis.name }, null, _classExtraInitializers); + C = _classThis = _classDescriptor.value; + __runInitializers(_classThis, _staticExtraInitializers); + } +@@ -189,10 +190,10 @@ let C = (() => { + set z(value) { this.#z_accessor_storage = value; } + static { + /*28*/ +- _y = { value: __runInitializers(_classThis, _static_private_y_initializers, 1) }; ++ _C_y = { value: __runInitializers(_classThis, _static_private_y_initializers, 1) }; + } + static { +- _z_accessor_storage = { value: __runInitializers(_classThis, _static_private_z_initializers, 1) }; ++ _C_z_accessor_storage = { value: __runInitializers(_classThis, _static_private_z_initializers, 1) }; + } + static { + __runInitializers(_classThis, _classExtraInitializers); +@@ -205,64 +206,72 @@ let C = (() => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.D = void 0; + /*34*/ +-let D = exports.D = (() => { ++let D = (() => { + let _classDecorators = [dec, dec]; + let _classDescriptor; + let _classExtraInitializers = []; + let _classThis; + var D = class { ++ static { _classThis = this; } + static { +- __esDecorate(null, _classDescriptor = { value: this }, _classDecorators, { kind: "class", name: this.name }, null, _classExtraInitializers); ++ __esDecorate(null, _classDescriptor = { value: _classThis }, _classDecorators, { kind: "class", name: _classThis.name }, null, _classExtraInitializers); + D = _classThis = _classDescriptor.value; + __runInitializers(_classThis, _classExtraInitializers); + } + }; + return D = _classThis; + })(); +-exports.default = (() => { +- let _classDecorators_1 = [dec, dec]; +- let _classDescriptor_1; +- let _classExtraInitializers_1 = []; +- let _classThis_1; ++exports.D = D; ++let E = (() => { ++ let _classDecorators = [dec, dec]; ++ let _classDescriptor; ++ let _classExtraInitializers = []; ++ let _classThis; + var E = class { ++ static { _classThis = this; } + static { +- __esDecorate(null, _classDescriptor_1 = { value: this }, _classDecorators_1, { kind: "class", name: this.name }, null, _classExtraInitializers_1); +- E = _classThis_1 = _classDescriptor_1.value; +- __runInitializers(_classThis_1, _classExtraInitializers_1); ++ __esDecorate(null, _classDescriptor = { value: _classThis }, _classDecorators, { kind: "class", name: _classThis.name }, null, _classExtraInitializers); ++ E = _classThis = _classDescriptor.value; ++ __runInitializers(_classThis, _classExtraInitializers); + } + }; +- return E = _classThis_1; ++ return E = _classThis; + })(); ++exports.default = E; + //// [file3.js] + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.F = void 0; + /*40*/ +-let F = exports.F = (() => { ++let F = (() => { + let _classDecorators = [dec, dec]; + let _classDescriptor; + let _classExtraInitializers = []; + let _classThis; + var F = class { ++ static { _classThis = this; } + static { +- __esDecorate(null, _classDescriptor = { value: this }, _classDecorators, { kind: "class", name: this.name }, null, _classExtraInitializers); ++ __esDecorate(null, _classDescriptor = { value: _classThis }, _classDecorators, { kind: "class", name: _classThis.name }, null, _classExtraInitializers); + F = _classThis = _classDescriptor.value; + __runInitializers(_classThis, _classExtraInitializers); + } + }; + return F = _classThis; + })(); +-exports.default = (() => { +- let _classDecorators_1 = [dec, dec]; +- let _classDescriptor_1; +- let _classExtraInitializers_1 = []; +- let _classThis_1; ++exports.F = F; ++let G = (() => { ++ let _classDecorators = [dec, dec]; ++ let _classDescriptor; ++ let _classExtraInitializers = []; ++ let _classThis; + var G = class { ++ static { _classThis = this; } + static { +- __esDecorate(null, _classDescriptor_1 = { value: this }, _classDecorators_1, { kind: "class", name: this.name }, null, _classExtraInitializers_1); +- G = _classThis_1 = _classDescriptor_1.value; +- __runInitializers(_classThis_1, _classExtraInitializers_1); ++ __esDecorate(null, _classDescriptor = { value: _classThis }, _classDecorators, { kind: "class", name: _classThis.name }, null, _classExtraInitializers); ++ G = _classThis = _classDescriptor.value; ++ __runInitializers(_classThis, _classExtraInitializers); + } + }; +- return G = _classThis_1; ++ return G = _classThis; + })(); ++exports.default = G; +diff --git a/tests/baselines/reference/esDecorators-classDeclaration-commentPreservation(module=esnext,target=es2015).js b/tests/baselines/reference/esDecorators-classDeclaration-commentPreservation(module=esnext,target=es2015).js +index 98eb2ad7a..7029ea115 100644 +--- a/tests/baselines/reference/esDecorators-classDeclaration-commentPreservation(module=esnext,target=es2015).js ++++ b/tests/baselines/reference/esDecorators-classDeclaration-commentPreservation(module=esnext,target=es2015).js +@@ -122,7 +122,7 @@ class G { + //// [file1.js] + /*1*/ + let C = (() => { +- var _method_get, _x_get, _x_set, _y, _z_accessor_storage, _z_get, _z_set, _z_1_accessor_storage; ++ var _C_method_get, _C_x_get, _C_x_set, _C_y, _C_z_accessor_storage, _C_z_get, _C_z_set, _C_z_1_accessor_storage; + let _classDecorators = [dec, dec]; + let _classDescriptor; + let _classExtraInitializers = []; +@@ -151,7 +151,7 @@ let C = (() => { + constructor() { + /*13*/ + this.y = (__runInitializers(this, _instanceExtraInitializers), __runInitializers(this, _y_initializers, 1)); +- _z_1_accessor_storage.set(this, __runInitializers(this, _z_initializers, 1)); ++ _C_z_1_accessor_storage.set(this, __runInitializers(this, _z_initializers, 1)); + } + /*4*/ + method() { } +@@ -160,15 +160,15 @@ let C = (() => { + /*10*/ + set x(value) { } + /*16*/ +- get z() { return __classPrivateFieldGet(this, _z_1_accessor_storage, "f"); } +- set z(value) { __classPrivateFieldSet(this, _z_1_accessor_storage, value, "f"); } ++ get z() { return __classPrivateFieldGet(this, _C_z_1_accessor_storage, "f"); } ++ set z(value) { __classPrivateFieldSet(this, _C_z_1_accessor_storage, value, "f"); } + }; +- _z_1_accessor_storage = new WeakMap(); +- _method_get = function _method_get() { return _static_private_method_descriptor.value; }; +- _x_get = function _x_get() { return _static_private_get_x_descriptor.get.call(this); }; +- _x_set = function _x_set(value) { return _static_private_set_x_descriptor.set.call(this, value); }; +- _z_get = function _z_get() { return _static_private_z_descriptor.get.call(this); }; +- _z_set = function _z_set(value) { return _static_private_z_descriptor.set.call(this, value); }; ++ _C_z_1_accessor_storage = new WeakMap(); ++ _C_method_get = function _C_method_get() { return _static_private_method_descriptor.value; }; ++ _C_x_get = function _C_x_get() { return _static_private_get_x_descriptor.get.call(this); }; ++ _C_x_set = function _C_x_set(value) { return _static_private_set_x_descriptor.set.call(this, value); }; ++ _C_z_get = function _C_z_get() { return _static_private_z_descriptor.get.call(this); }; ++ _C_z_set = function _C_z_set(value) { return _static_private_z_descriptor.set.call(this, value); }; + __setFunctionName(_classThis, "C"); + (() => { + _method_decorators = [dec, dec]; +@@ -181,23 +181,23 @@ let C = (() => { + _static_private_set_x_decorators = [dec, dec]; + _static_private_y_decorators = [dec, dec]; + _static_private_z_decorators = [dec, dec]; +- __esDecorate(_classThis, _static_private_method_descriptor = { value: __setFunctionName(function () { }, "#method") }, _static_private_method_decorators, { kind: "method", name: "#method", static: true, private: true, access: { has: obj => __classPrivateFieldIn(_classThis, obj), get: obj => __classPrivateFieldGet(obj, _classThis, "a", _method_get) } }, null, _staticExtraInitializers); +- __esDecorate(_classThis, _static_private_get_x_descriptor = { get: __setFunctionName(function () { return 1; }, "#x", "get") }, _static_private_get_x_decorators, { kind: "getter", name: "#x", static: true, private: true, access: { has: obj => __classPrivateFieldIn(_classThis, obj), get: obj => __classPrivateFieldGet(obj, _classThis, "a", _x_get) } }, null, _staticExtraInitializers); +- __esDecorate(_classThis, _static_private_set_x_descriptor = { set: __setFunctionName(function (value) { }, "#x", "set") }, _static_private_set_x_decorators, { kind: "setter", name: "#x", static: true, private: true, access: { has: obj => __classPrivateFieldIn(_classThis, obj), set: (obj, value) => { __classPrivateFieldSet(obj, _classThis, value, "a", _x_set); } } }, null, _staticExtraInitializers); +- __esDecorate(_classThis, _static_private_z_descriptor = { get: __setFunctionName(function () { return __classPrivateFieldGet(_classThis, _classThis, "f", _z_accessor_storage); }, "#z", "get"), set: __setFunctionName(function (value) { __classPrivateFieldSet(_classThis, _classThis, value, "f", _z_accessor_storage); }, "#z", "set") }, _static_private_z_decorators, { kind: "accessor", name: "#z", static: true, private: true, access: { has: obj => __classPrivateFieldIn(_classThis, obj), get: obj => __classPrivateFieldGet(obj, _classThis, "a", _z_get), set: (obj, value) => { __classPrivateFieldSet(obj, _classThis, value, "a", _z_set); } } }, _static_private_z_initializers, _staticExtraInitializers); ++ __esDecorate(_classThis, _static_private_method_descriptor = { value: __setFunctionName(function () { }, "#method") }, _static_private_method_decorators, { kind: "method", name: "#method", static: true, private: true, access: { has: obj => __classPrivateFieldIn(_classThis, obj), get: obj => __classPrivateFieldGet(obj, _classThis, "a", _C_method_get) } }, null, _staticExtraInitializers); ++ __esDecorate(_classThis, _static_private_get_x_descriptor = { get: __setFunctionName(function () { return 1; }, "#x", "get") }, _static_private_get_x_decorators, { kind: "getter", name: "#x", static: true, private: true, access: { has: obj => __classPrivateFieldIn(_classThis, obj), get: obj => __classPrivateFieldGet(obj, _classThis, "a", _C_x_get) } }, null, _staticExtraInitializers); ++ __esDecorate(_classThis, _static_private_set_x_descriptor = { set: __setFunctionName(function (value) { }, "#x", "set") }, _static_private_set_x_decorators, { kind: "setter", name: "#x", static: true, private: true, access: { has: obj => __classPrivateFieldIn(_classThis, obj), set: (obj, value) => { __classPrivateFieldSet(obj, _classThis, value, "a", _C_x_set); } } }, null, _staticExtraInitializers); ++ __esDecorate(_classThis, _static_private_z_descriptor = { get: __setFunctionName(function () { return __classPrivateFieldGet(_classThis, _classThis, "f", _C_z_accessor_storage); }, "#z", "get"), set: __setFunctionName(function (value) { __classPrivateFieldSet(_classThis, _classThis, value, "f", _C_z_accessor_storage); }, "#z", "set") }, _static_private_z_decorators, { kind: "accessor", name: "#z", static: true, private: true, access: { has: obj => __classPrivateFieldIn(_classThis, obj), get: obj => __classPrivateFieldGet(obj, _classThis, "a", _C_z_get), set: (obj, value) => { __classPrivateFieldSet(obj, _classThis, value, "a", _C_z_set); } } }, _static_private_z_initializers, _staticExtraInitializers); + __esDecorate(_classThis, null, _method_decorators, { kind: "method", name: "method", static: false, private: false, access: { has: obj => "method" in obj, get: obj => obj.method } }, null, _instanceExtraInitializers); + __esDecorate(_classThis, null, _get_x_decorators, { kind: "getter", name: "x", static: false, private: false, access: { has: obj => "x" in obj, get: obj => obj.x } }, null, _instanceExtraInitializers); + __esDecorate(_classThis, null, _set_x_decorators, { kind: "setter", name: "x", static: false, private: false, access: { has: obj => "x" in obj, set: (obj, value) => { obj.x = value; } } }, null, _instanceExtraInitializers); + __esDecorate(_classThis, null, _z_decorators, { kind: "accessor", name: "z", static: false, private: false, access: { has: obj => "z" in obj, get: obj => obj.z, set: (obj, value) => { obj.z = value; } } }, _z_initializers, _instanceExtraInitializers); +- __esDecorate(null, null, _static_private_y_decorators, { kind: "field", name: "#y", static: true, private: true, access: { has: obj => __classPrivateFieldIn(_classThis, obj), get: obj => __classPrivateFieldGet(obj, _classThis, "f", _y), set: (obj, value) => { __classPrivateFieldSet(obj, _classThis, value, "f", _y); } } }, _static_private_y_initializers, _staticExtraInitializers); ++ __esDecorate(null, null, _static_private_y_decorators, { kind: "field", name: "#y", static: true, private: true, access: { has: obj => __classPrivateFieldIn(_classThis, obj), get: obj => __classPrivateFieldGet(obj, _classThis, "f", _C_y), set: (obj, value) => { __classPrivateFieldSet(obj, _classThis, value, "f", _C_y); } } }, _static_private_y_initializers, _staticExtraInitializers); + __esDecorate(null, null, _y_decorators, { kind: "field", name: "y", static: false, private: false, access: { has: obj => "y" in obj, get: obj => obj.y, set: (obj, value) => { obj.y = value; } } }, _y_initializers, _instanceExtraInitializers); + __esDecorate(null, _classDescriptor = { value: _classThis }, _classDecorators, { kind: "class", name: _classThis.name }, null, _classExtraInitializers); + C = _classThis = _classDescriptor.value; + __runInitializers(_classThis, _staticExtraInitializers); + })(); + /*28*/ +- _y = { value: __runInitializers(_classThis, _static_private_y_initializers, 1) }; +- _z_accessor_storage = { value: __runInitializers(_classThis, _static_private_z_initializers, 1) }; ++ _C_y = { value: __runInitializers(_classThis, _static_private_y_initializers, 1) }; ++ _C_z_accessor_storage = { value: __runInitializers(_classThis, _static_private_z_initializers, 1) }; + (() => { + __runInitializers(_classThis, _classExtraInitializers); + })(); +@@ -205,8 +205,7 @@ let C = (() => { + })(); + //// [file2.js] + /*34*/ +-/*36*/ +-export let D = (() => { ++let D = (() => { + let _classDecorators = [dec, dec]; + let _classDescriptor; + let _classExtraInitializers = []; +@@ -221,25 +220,27 @@ export let D = (() => { + })(); + return D = _classThis; + })(); +-/*37*/ +-export default (() => { +- let _classDecorators_1 = [dec, dec]; +- let _classDescriptor_1; +- let _classExtraInitializers_1 = []; +- let _classThis_1; +- var E = _classThis_1 = class { ++export { D }; ++let E = (() => { ++ let _classDecorators = [dec, dec]; ++ let _classDescriptor; ++ let _classExtraInitializers = []; ++ let _classThis; ++ var E = _classThis = class { + }; +- __setFunctionName(_classThis_1, "E"); ++ __setFunctionName(_classThis, "E"); + (() => { +- __esDecorate(null, _classDescriptor_1 = { value: _classThis_1 }, _classDecorators_1, { kind: "class", name: _classThis_1.name }, null, _classExtraInitializers_1); +- E = _classThis_1 = _classDescriptor_1.value; +- __runInitializers(_classThis_1, _classExtraInitializers_1); ++ __esDecorate(null, _classDescriptor = { value: _classThis }, _classDecorators, { kind: "class", name: _classThis.name }, null, _classExtraInitializers); ++ E = _classThis = _classDescriptor.value; ++ __runInitializers(_classThis, _classExtraInitializers); + })(); +- return E = _classThis_1; ++ return E = _classThis; + })(); ++/*37*/ ++export default E; + //// [file3.js] + /*40*/ +-export let F = (() => { ++let F = (() => { + let _classDecorators = [dec, dec]; + let _classDescriptor; + let _classExtraInitializers = []; +@@ -254,19 +255,21 @@ export let F = (() => { + })(); + return F = _classThis; + })(); +-/*44*/ +-export default (() => { +- let _classDecorators_1 = [dec, dec]; +- let _classDescriptor_1; +- let _classExtraInitializers_1 = []; +- let _classThis_1; +- var G = _classThis_1 = class { ++export { F }; ++let G = (() => { ++ let _classDecorators = [dec, dec]; ++ let _classDescriptor; ++ let _classExtraInitializers = []; ++ let _classThis; ++ var G = _classThis = class { + }; +- __setFunctionName(_classThis_1, "G"); ++ __setFunctionName(_classThis, "G"); + (() => { +- __esDecorate(null, _classDescriptor_1 = { value: _classThis_1 }, _classDecorators_1, { kind: "class", name: _classThis_1.name }, null, _classExtraInitializers_1); +- G = _classThis_1 = _classDescriptor_1.value; +- __runInitializers(_classThis_1, _classExtraInitializers_1); ++ __esDecorate(null, _classDescriptor = { value: _classThis }, _classDecorators, { kind: "class", name: _classThis.name }, null, _classExtraInitializers); ++ G = _classThis = _classDescriptor.value; ++ __runInitializers(_classThis, _classExtraInitializers); + })(); +- return G = _classThis_1; ++ return G = _classThis; + })(); ++/*44*/ ++export default G; +diff --git a/tests/baselines/reference/esDecorators-classDeclaration-commentPreservation(module=esnext,target=es2022).js b/tests/baselines/reference/esDecorators-classDeclaration-commentPreservation(module=esnext,target=es2022).js +index fb04f31ae..cdd455b4f 100644 +--- a/tests/baselines/reference/esDecorators-classDeclaration-commentPreservation(module=esnext,target=es2022).js ++++ b/tests/baselines/reference/esDecorators-classDeclaration-commentPreservation(module=esnext,target=es2022).js +@@ -122,7 +122,7 @@ class G { + //// [file1.js] + /*1*/ + let C = (() => { +- var _method_get, _x_get, _x_set, _y, _z_accessor_storage, _z_get, _z_set; ++ var _C_method_get, _C_x_get, _C_x_set, _C_y, _C_z_accessor_storage, _C_z_get, _C_z_set; + let _classDecorators = [dec, dec]; + let _classDescriptor; + let _classExtraInitializers = []; +@@ -148,8 +148,9 @@ let C = (() => { + let _z_decorators; + let _z_initializers = []; + var C = class { ++ static { _classThis = this; } + static { __setFunctionName(this, "C"); } +- static { _method_get = function _method_get() { return _static_private_method_descriptor.value; }, _x_get = function _x_get() { return _static_private_get_x_descriptor.get.call(this); }, _x_set = function _x_set(value) { return _static_private_set_x_descriptor.set.call(this, value); }, _z_get = function _z_get() { return _static_private_z_descriptor.get.call(this); }, _z_set = function _z_set(value) { return _static_private_z_descriptor.set.call(this, value); }; } ++ static { _C_method_get = function _C_method_get() { return _static_private_method_descriptor.value; }, _C_x_get = function _C_x_get() { return _static_private_get_x_descriptor.get.call(this); }, _C_x_set = function _C_x_set(value) { return _static_private_set_x_descriptor.set.call(this, value); }, _C_z_get = function _C_z_get() { return _static_private_z_descriptor.get.call(this); }, _C_z_set = function _C_z_set(value) { return _static_private_z_descriptor.set.call(this, value); }; } + static { + _method_decorators = [dec, dec]; + _get_x_decorators = [dec, dec]; +@@ -161,17 +162,17 @@ let C = (() => { + _static_private_set_x_decorators = [dec, dec]; + _static_private_y_decorators = [dec, dec]; + _static_private_z_decorators = [dec, dec]; +- __esDecorate(this, _static_private_method_descriptor = { value: __setFunctionName(function () { }, "#method") }, _static_private_method_decorators, { kind: "method", name: "#method", static: true, private: true, access: { has: obj => __classPrivateFieldIn(_classThis, obj), get: obj => __classPrivateFieldGet(obj, _classThis, "a", _method_get) } }, null, _staticExtraInitializers); +- __esDecorate(this, _static_private_get_x_descriptor = { get: __setFunctionName(function () { return 1; }, "#x", "get") }, _static_private_get_x_decorators, { kind: "getter", name: "#x", static: true, private: true, access: { has: obj => __classPrivateFieldIn(_classThis, obj), get: obj => __classPrivateFieldGet(obj, _classThis, "a", _x_get) } }, null, _staticExtraInitializers); +- __esDecorate(this, _static_private_set_x_descriptor = { set: __setFunctionName(function (value) { }, "#x", "set") }, _static_private_set_x_decorators, { kind: "setter", name: "#x", static: true, private: true, access: { has: obj => __classPrivateFieldIn(_classThis, obj), set: (obj, value) => { __classPrivateFieldSet(obj, _classThis, value, "a", _x_set); } } }, null, _staticExtraInitializers); +- __esDecorate(this, _static_private_z_descriptor = { get: __setFunctionName(function () { return __classPrivateFieldGet(this, _classThis, "f", _z_accessor_storage); }, "#z", "get"), set: __setFunctionName(function (value) { __classPrivateFieldSet(this, _classThis, value, "f", _z_accessor_storage); }, "#z", "set") }, _static_private_z_decorators, { kind: "accessor", name: "#z", static: true, private: true, access: { has: obj => __classPrivateFieldIn(_classThis, obj), get: obj => __classPrivateFieldGet(obj, _classThis, "a", _z_get), set: (obj, value) => { __classPrivateFieldSet(obj, _classThis, value, "a", _z_set); } } }, _static_private_z_initializers, _staticExtraInitializers); ++ __esDecorate(this, _static_private_method_descriptor = { value: __setFunctionName(function () { }, "#method") }, _static_private_method_decorators, { kind: "method", name: "#method", static: true, private: true, access: { has: obj => __classPrivateFieldIn(_classThis, obj), get: obj => __classPrivateFieldGet(obj, _classThis, "a", _C_method_get) } }, null, _staticExtraInitializers); ++ __esDecorate(this, _static_private_get_x_descriptor = { get: __setFunctionName(function () { return 1; }, "#x", "get") }, _static_private_get_x_decorators, { kind: "getter", name: "#x", static: true, private: true, access: { has: obj => __classPrivateFieldIn(_classThis, obj), get: obj => __classPrivateFieldGet(obj, _classThis, "a", _C_x_get) } }, null, _staticExtraInitializers); ++ __esDecorate(this, _static_private_set_x_descriptor = { set: __setFunctionName(function (value) { }, "#x", "set") }, _static_private_set_x_decorators, { kind: "setter", name: "#x", static: true, private: true, access: { has: obj => __classPrivateFieldIn(_classThis, obj), set: (obj, value) => { __classPrivateFieldSet(obj, _classThis, value, "a", _C_x_set); } } }, null, _staticExtraInitializers); ++ __esDecorate(this, _static_private_z_descriptor = { get: __setFunctionName(function () { return __classPrivateFieldGet(this, _classThis, "f", _C_z_accessor_storage); }, "#z", "get"), set: __setFunctionName(function (value) { __classPrivateFieldSet(this, _classThis, value, "f", _C_z_accessor_storage); }, "#z", "set") }, _static_private_z_decorators, { kind: "accessor", name: "#z", static: true, private: true, access: { has: obj => __classPrivateFieldIn(_classThis, obj), get: obj => __classPrivateFieldGet(obj, _classThis, "a", _C_z_get), set: (obj, value) => { __classPrivateFieldSet(obj, _classThis, value, "a", _C_z_set); } } }, _static_private_z_initializers, _staticExtraInitializers); + __esDecorate(this, null, _method_decorators, { kind: "method", name: "method", static: false, private: false, access: { has: obj => "method" in obj, get: obj => obj.method } }, null, _instanceExtraInitializers); + __esDecorate(this, null, _get_x_decorators, { kind: "getter", name: "x", static: false, private: false, access: { has: obj => "x" in obj, get: obj => obj.x } }, null, _instanceExtraInitializers); + __esDecorate(this, null, _set_x_decorators, { kind: "setter", name: "x", static: false, private: false, access: { has: obj => "x" in obj, set: (obj, value) => { obj.x = value; } } }, null, _instanceExtraInitializers); + __esDecorate(this, null, _z_decorators, { kind: "accessor", name: "z", static: false, private: false, access: { has: obj => "z" in obj, get: obj => obj.z, set: (obj, value) => { obj.z = value; } } }, _z_initializers, _instanceExtraInitializers); +- __esDecorate(null, null, _static_private_y_decorators, { kind: "field", name: "#y", static: true, private: true, access: { has: obj => __classPrivateFieldIn(_classThis, obj), get: obj => __classPrivateFieldGet(obj, _classThis, "f", _y), set: (obj, value) => { __classPrivateFieldSet(obj, _classThis, value, "f", _y); } } }, _static_private_y_initializers, _staticExtraInitializers); ++ __esDecorate(null, null, _static_private_y_decorators, { kind: "field", name: "#y", static: true, private: true, access: { has: obj => __classPrivateFieldIn(_classThis, obj), get: obj => __classPrivateFieldGet(obj, _classThis, "f", _C_y), set: (obj, value) => { __classPrivateFieldSet(obj, _classThis, value, "f", _C_y); } } }, _static_private_y_initializers, _staticExtraInitializers); + __esDecorate(null, null, _y_decorators, { kind: "field", name: "y", static: false, private: false, access: { has: obj => "y" in obj, get: obj => obj.y, set: (obj, value) => { obj.y = value; } } }, _y_initializers, _instanceExtraInitializers); +- __esDecorate(null, _classDescriptor = { value: this }, _classDecorators, { kind: "class", name: this.name }, null, _classExtraInitializers); ++ __esDecorate(null, _classDescriptor = { value: _classThis }, _classDecorators, { kind: "class", name: _classThis.name }, null, _classExtraInitializers); + C = _classThis = _classDescriptor.value; + __runInitializers(_classThis, _staticExtraInitializers); + } +@@ -189,10 +190,10 @@ let C = (() => { + set z(value) { this.#z_accessor_storage = value; } + static { + /*28*/ +- _y = { value: __runInitializers(_classThis, _static_private_y_initializers, 1) }; ++ _C_y = { value: __runInitializers(_classThis, _static_private_y_initializers, 1) }; + } + static { +- _z_accessor_storage = { value: __runInitializers(_classThis, _static_private_z_initializers, 1) }; ++ _C_z_accessor_storage = { value: __runInitializers(_classThis, _static_private_z_initializers, 1) }; + } + static { + __runInitializers(_classThis, _classExtraInitializers); +@@ -202,64 +203,71 @@ let C = (() => { + })(); + //// [file2.js] + /*34*/ +-/*36*/ +-export let D = (() => { ++let D = (() => { + let _classDecorators = [dec, dec]; + let _classDescriptor; + let _classExtraInitializers = []; + let _classThis; + var D = class { ++ static { _classThis = this; } + static { +- __esDecorate(null, _classDescriptor = { value: this }, _classDecorators, { kind: "class", name: this.name }, null, _classExtraInitializers); ++ __esDecorate(null, _classDescriptor = { value: _classThis }, _classDecorators, { kind: "class", name: _classThis.name }, null, _classExtraInitializers); + D = _classThis = _classDescriptor.value; + __runInitializers(_classThis, _classExtraInitializers); + } + }; + return D = _classThis; + })(); +-/*37*/ +-export default (() => { +- let _classDecorators_1 = [dec, dec]; +- let _classDescriptor_1; +- let _classExtraInitializers_1 = []; +- let _classThis_1; ++export { D }; ++let E = (() => { ++ let _classDecorators = [dec, dec]; ++ let _classDescriptor; ++ let _classExtraInitializers = []; ++ let _classThis; + var E = class { ++ static { _classThis = this; } + static { +- __esDecorate(null, _classDescriptor_1 = { value: this }, _classDecorators_1, { kind: "class", name: this.name }, null, _classExtraInitializers_1); +- E = _classThis_1 = _classDescriptor_1.value; +- __runInitializers(_classThis_1, _classExtraInitializers_1); ++ __esDecorate(null, _classDescriptor = { value: _classThis }, _classDecorators, { kind: "class", name: _classThis.name }, null, _classExtraInitializers); ++ E = _classThis = _classDescriptor.value; ++ __runInitializers(_classThis, _classExtraInitializers); + } + }; +- return E = _classThis_1; ++ return E = _classThis; + })(); ++/*37*/ ++export default E; + //// [file3.js] + /*40*/ +-export let F = (() => { ++let F = (() => { + let _classDecorators = [dec, dec]; + let _classDescriptor; + let _classExtraInitializers = []; + let _classThis; + var F = class { ++ static { _classThis = this; } + static { +- __esDecorate(null, _classDescriptor = { value: this }, _classDecorators, { kind: "class", name: this.name }, null, _classExtraInitializers); ++ __esDecorate(null, _classDescriptor = { value: _classThis }, _classDecorators, { kind: "class", name: _classThis.name }, null, _classExtraInitializers); + F = _classThis = _classDescriptor.value; + __runInitializers(_classThis, _classExtraInitializers); + } + }; + return F = _classThis; + })(); +-/*44*/ +-export default (() => { +- let _classDecorators_1 = [dec, dec]; +- let _classDescriptor_1; +- let _classExtraInitializers_1 = []; +- let _classThis_1; ++export { F }; ++let G = (() => { ++ let _classDecorators = [dec, dec]; ++ let _classDescriptor; ++ let _classExtraInitializers = []; ++ let _classThis; + var G = class { ++ static { _classThis = this; } + static { +- __esDecorate(null, _classDescriptor_1 = { value: this }, _classDecorators_1, { kind: "class", name: this.name }, null, _classExtraInitializers_1); +- G = _classThis_1 = _classDescriptor_1.value; +- __runInitializers(_classThis_1, _classExtraInitializers_1); ++ __esDecorate(null, _classDescriptor = { value: _classThis }, _classDecorators, { kind: "class", name: _classThis.name }, null, _classExtraInitializers); ++ G = _classThis = _classDescriptor.value; ++ __runInitializers(_classThis, _classExtraInitializers); + } + }; +- return G = _classThis_1; ++ return G = _classThis; + })(); ++/*44*/ ++export default G; +diff --git a/tests/baselines/reference/esDecorators-classDeclaration-commonjs-classNamespaceMerge.js b/tests/baselines/reference/esDecorators-classDeclaration-commonjs-classNamespaceMerge.js +index 0d52e9f28..2d666b869 100644 +--- a/tests/baselines/reference/esDecorators-classDeclaration-commonjs-classNamespaceMerge.js ++++ b/tests/baselines/reference/esDecorators-classDeclaration-commonjs-classNamespaceMerge.js +@@ -52,14 +52,15 @@ var __runInitializers = (this && this.__runInitializers) || function (thisArg, i + }; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.Example = void 0; +-let Example = exports.Example = (() => { ++let Example = (() => { + let _classDecorators = [deco]; + let _classDescriptor; + let _classExtraInitializers = []; + let _classThis; + var Example = class { ++ static { _classThis = this; } + static { +- __esDecorate(null, _classDescriptor = { value: this }, _classDecorators, { kind: "class", name: this.name }, null, _classExtraInitializers); ++ __esDecorate(null, _classDescriptor = { value: _classThis }, _classDecorators, { kind: "class", name: _classThis.name }, null, _classExtraInitializers); + Example = _classThis = _classDescriptor.value; + __runInitializers(_classThis, _classExtraInitializers); + } +@@ -67,6 +68,7 @@ let Example = exports.Example = (() => { + }; + return Example = _classThis; + })(); ++exports.Example = Example; + (function (Example) { + Example.x = 1; + })(Example || (exports.Example = Example = {})); +diff --git a/tests/baselines/reference/esDecorators-classDeclaration-commonjs.js b/tests/baselines/reference/esDecorators-classDeclaration-commonjs.js +index d354b8480..aa5eda219 100644 +--- a/tests/baselines/reference/esDecorators-classDeclaration-commonjs.js ++++ b/tests/baselines/reference/esDecorators-classDeclaration-commonjs.js +@@ -48,14 +48,15 @@ var __runInitializers = (this && this.__runInitializers) || function (thisArg, i + }; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.Example = void 0; +-let Example = exports.Example = (() => { ++let Example = (() => { + let _classDecorators = [deco]; + let _classDescriptor; + let _classExtraInitializers = []; + let _classThis; + var Example = class { ++ static { _classThis = this; } + static { +- __esDecorate(null, _classDescriptor = { value: this }, _classDecorators, { kind: "class", name: this.name }, null, _classExtraInitializers); ++ __esDecorate(null, _classDescriptor = { value: _classThis }, _classDecorators, { kind: "class", name: _classThis.name }, null, _classExtraInitializers); + Example = _classThis = _classDescriptor.value; + __runInitializers(_classThis, _classExtraInitializers); + } +@@ -63,4 +64,5 @@ let Example = exports.Example = (() => { + }; + return Example = _classThis; + })(); ++exports.Example = Example; + Example.foo(); +diff --git a/tests/baselines/reference/esDecorators-classDeclaration-fields-staticAccessor(target=es2015).js b/tests/baselines/reference/esDecorators-classDeclaration-fields-staticAccessor(target=es2015).js +index a914c0d06..67795dc6b 100644 +--- a/tests/baselines/reference/esDecorators-classDeclaration-fields-staticAccessor(target=es2015).js ++++ b/tests/baselines/reference/esDecorators-classDeclaration-fields-staticAccessor(target=es2015).js +@@ -52,21 +52,21 @@ let C = (() => { + _a; + })(); + let D = (() => { +- var _field1_accessor_storage; ++ var _D_field1_accessor_storage; + let _classDecorators = [dec]; + let _classDescriptor; + let _classExtraInitializers = []; + let _classThis; + var D = _classThis = class { +- static get field1() { return __classPrivateFieldGet(this, _classThis, "f", _field1_accessor_storage); } +- static set field1(value) { __classPrivateFieldSet(this, _classThis, value, "f", _field1_accessor_storage); } ++ static get field1() { return __classPrivateFieldGet(this, _classThis, "f", _D_field1_accessor_storage); } ++ static set field1(value) { __classPrivateFieldSet(this, _classThis, value, "f", _D_field1_accessor_storage); } + }; + __setFunctionName(_classThis, "D"); + (() => { + __esDecorate(null, _classDescriptor = { value: _classThis }, _classDecorators, { kind: "class", name: _classThis.name }, null, _classExtraInitializers); + D = _classThis = _classDescriptor.value; + })(); +- _field1_accessor_storage = { value: 1 }; ++ _D_field1_accessor_storage = { value: 1 }; + (() => { + _classThis.field1; + _classThis.field1 = 1; +diff --git a/tests/baselines/reference/esDecorators-classDeclaration-fields-staticAccessor(target=es2022).js b/tests/baselines/reference/esDecorators-classDeclaration-fields-staticAccessor(target=es2022).js +index 15e126bf8..f0d99a239 100644 +--- a/tests/baselines/reference/esDecorators-classDeclaration-fields-staticAccessor(target=es2022).js ++++ b/tests/baselines/reference/esDecorators-classDeclaration-fields-staticAccessor(target=es2022).js +@@ -50,22 +50,23 @@ let C = (() => { + }; + })(); + let D = (() => { +- var _field1_accessor_storage; ++ var _D_field1_accessor_storage; + let _classDecorators = [dec]; + let _classDescriptor; + let _classExtraInitializers = []; + let _classThis; + var D = class { ++ static { _classThis = this; } + static { __setFunctionName(this, "D"); } + static { +- __esDecorate(null, _classDescriptor = { value: this }, _classDecorators, { kind: "class", name: this.name }, null, _classExtraInitializers); ++ __esDecorate(null, _classDescriptor = { value: _classThis }, _classDecorators, { kind: "class", name: _classThis.name }, null, _classExtraInitializers); + D = _classThis = _classDescriptor.value; + } + static { +- _field1_accessor_storage = { value: 1 }; ++ _D_field1_accessor_storage = { value: 1 }; + } +- static get field1() { return __classPrivateFieldGet(this, _classThis, "f", _field1_accessor_storage); } +- static set field1(value) { __classPrivateFieldSet(this, _classThis, value, "f", _field1_accessor_storage); } ++ static get field1() { return __classPrivateFieldGet(this, _classThis, "f", _D_field1_accessor_storage); } ++ static set field1(value) { __classPrivateFieldSet(this, _classThis, value, "f", _D_field1_accessor_storage); } + static { + _classThis.field1; + _classThis.field1 = 1; +diff --git a/tests/baselines/reference/esDecorators-classDeclaration-fields-staticPrivate(target=es2015).js b/tests/baselines/reference/esDecorators-classDeclaration-fields-staticPrivate(target=es2015).js +index 70c22ebd6..185fb761b 100644 +--- a/tests/baselines/reference/esDecorators-classDeclaration-fields-staticPrivate(target=es2015).js ++++ b/tests/baselines/reference/esDecorators-classDeclaration-fields-staticPrivate(target=es2015).js +@@ -34,7 +34,7 @@ let C = (() => { + _a; + })(); + let D = (() => { +- var _field1; ++ var _D_field1; + let _classDecorators = [dec]; + let _classDescriptor; + let _classExtraInitializers = []; +@@ -46,10 +46,10 @@ let D = (() => { + __esDecorate(null, _classDescriptor = { value: _classThis }, _classDecorators, { kind: "class", name: _classThis.name }, null, _classExtraInitializers); + D = _classThis = _classDescriptor.value; + })(); +- _field1 = { value: 0 }; ++ _D_field1 = { value: 0 }; + (() => { +- __classPrivateFieldGet(_classThis, _classThis, "f", _field1); +- __classPrivateFieldSet(_classThis, _classThis, 1, "f", _field1); ++ __classPrivateFieldGet(_classThis, _classThis, "f", _D_field1); ++ __classPrivateFieldSet(_classThis, _classThis, 1, "f", _D_field1); + })(); + (() => { + __runInitializers(_classThis, _classExtraInitializers); +diff --git a/tests/baselines/reference/esDecorators-classDeclaration-fields-staticPrivate(target=es2022).js b/tests/baselines/reference/esDecorators-classDeclaration-fields-staticPrivate(target=es2022).js +index cbb231f14..7aef10a84 100644 +--- a/tests/baselines/reference/esDecorators-classDeclaration-fields-staticPrivate(target=es2022).js ++++ b/tests/baselines/reference/esDecorators-classDeclaration-fields-staticPrivate(target=es2022).js +@@ -32,23 +32,24 @@ let C = (() => { + }; + })(); + let D = (() => { +- var _field1; ++ var _D_field1; + let _classDecorators = [dec]; + let _classDescriptor; + let _classExtraInitializers = []; + let _classThis; + var D = class { ++ static { _classThis = this; } + static { __setFunctionName(this, "D"); } + static { +- __esDecorate(null, _classDescriptor = { value: this }, _classDecorators, { kind: "class", name: this.name }, null, _classExtraInitializers); ++ __esDecorate(null, _classDescriptor = { value: _classThis }, _classDecorators, { kind: "class", name: _classThis.name }, null, _classExtraInitializers); + D = _classThis = _classDescriptor.value; + } + static { +- _field1 = { value: 0 }; ++ _D_field1 = { value: 0 }; + } + static { +- __classPrivateFieldGet(_classThis, _classThis, "f", _field1); +- __classPrivateFieldSet(_classThis, _classThis, 1, "f", _field1); ++ __classPrivateFieldGet(_classThis, _classThis, "f", _D_field1); ++ __classPrivateFieldSet(_classThis, _classThis, 1, "f", _D_field1); + } + static { + __runInitializers(_classThis, _classExtraInitializers); +diff --git a/tests/baselines/reference/esDecorators-classDeclaration-fields-staticPrivateAccessor(target=es2015).js b/tests/baselines/reference/esDecorators-classDeclaration-fields-staticPrivateAccessor(target=es2015).js +index 70faeb7de..032b59a41 100644 +--- a/tests/baselines/reference/esDecorators-classDeclaration-fields-staticPrivateAccessor(target=es2015).js ++++ b/tests/baselines/reference/esDecorators-classDeclaration-fields-staticPrivateAccessor(target=es2015).js +@@ -33,28 +33,28 @@ let C = (() => { + __esDecorate(_a, _static_private_field1_descriptor = { get: __setFunctionName(function () { return __classPrivateFieldGet(_a, _a, "f", _C_field1_accessor_storage); }, "#field1", "get"), set: __setFunctionName(function (value) { __classPrivateFieldSet(_a, _a, value, "f", _C_field1_accessor_storage); }, "#field1", "set") }, _static_private_field1_decorators, { kind: "accessor", name: "#field1", static: true, private: true, access: { has: obj => __classPrivateFieldIn(_a, obj), get: obj => __classPrivateFieldGet(obj, _a, "a", _C_field1_get), set: (obj, value) => { __classPrivateFieldSet(obj, _a, value, "a", _C_field1_set); } } }, _static_private_field1_initializers, _staticExtraInitializers); + __runInitializers(_a, _staticExtraInitializers); + })(), +- _C_field1_accessor_storage = { value: __runInitializers(this, _static_private_field1_initializers, 0) }, ++ _C_field1_accessor_storage = { value: __runInitializers(_a, _static_private_field1_initializers, 0) }, + _a; + })(); + let D = (() => { +- var _field1_get, _field1_set, _field1_accessor_storage; ++ var _D_field1_get, _D_field1_set, _D_field1_accessor_storage; + let _classDecorators = [dec]; + let _classDescriptor; + let _classExtraInitializers = []; + let _classThis; + var D = _classThis = class { + }; +- _field1_get = function _field1_get() { return __classPrivateFieldGet(this, _classThis, "f", _field1_accessor_storage); }; +- _field1_set = function _field1_set(value) { __classPrivateFieldSet(this, _classThis, value, "f", _field1_accessor_storage); }; ++ _D_field1_get = function _D_field1_get() { return __classPrivateFieldGet(this, _classThis, "f", _D_field1_accessor_storage); }; ++ _D_field1_set = function _D_field1_set(value) { __classPrivateFieldSet(this, _classThis, value, "f", _D_field1_accessor_storage); }; + __setFunctionName(_classThis, "D"); + (() => { + __esDecorate(null, _classDescriptor = { value: _classThis }, _classDecorators, { kind: "class", name: _classThis.name }, null, _classExtraInitializers); + D = _classThis = _classDescriptor.value; + })(); +- _field1_accessor_storage = { value: 0 }; ++ _D_field1_accessor_storage = { value: 0 }; + (() => { +- __classPrivateFieldGet(_classThis, _classThis, "a", _field1_get); +- __classPrivateFieldSet(_classThis, _classThis, 1, "a", _field1_set); ++ __classPrivateFieldGet(_classThis, _classThis, "a", _D_field1_get); ++ __classPrivateFieldSet(_classThis, _classThis, 1, "a", _D_field1_set); + })(); + (() => { + __runInitializers(_classThis, _classExtraInitializers); +diff --git a/tests/baselines/reference/esDecorators-classDeclaration-fields-staticPrivateAccessor(target=es2022).js b/tests/baselines/reference/esDecorators-classDeclaration-fields-staticPrivateAccessor(target=es2022).js +index 1337c1f57..0fd54651c 100644 +--- a/tests/baselines/reference/esDecorators-classDeclaration-fields-staticPrivateAccessor(target=es2022).js ++++ b/tests/baselines/reference/esDecorators-classDeclaration-fields-staticPrivateAccessor(target=es2022).js +@@ -35,24 +35,25 @@ let C = (() => { + }; + })(); + let D = (() => { +- var _field1_get, _field1_set, _field1_accessor_storage; ++ var _D_field1_get, _D_field1_set, _D_field1_accessor_storage; + let _classDecorators = [dec]; + let _classDescriptor; + let _classExtraInitializers = []; + let _classThis; + var D = class { ++ static { _classThis = this; } + static { __setFunctionName(this, "D"); } +- static { _field1_get = function _field1_get() { return __classPrivateFieldGet(this, _classThis, "f", _field1_accessor_storage); }, _field1_set = function _field1_set(value) { __classPrivateFieldSet(this, _classThis, value, "f", _field1_accessor_storage); }; } ++ static { _D_field1_get = function _D_field1_get() { return __classPrivateFieldGet(this, _classThis, "f", _D_field1_accessor_storage); }, _D_field1_set = function _D_field1_set(value) { __classPrivateFieldSet(this, _classThis, value, "f", _D_field1_accessor_storage); }; } + static { +- __esDecorate(null, _classDescriptor = { value: this }, _classDecorators, { kind: "class", name: this.name }, null, _classExtraInitializers); ++ __esDecorate(null, _classDescriptor = { value: _classThis }, _classDecorators, { kind: "class", name: _classThis.name }, null, _classExtraInitializers); + D = _classThis = _classDescriptor.value; + } + static { +- _field1_accessor_storage = { value: 0 }; ++ _D_field1_accessor_storage = { value: 0 }; + } + static { +- __classPrivateFieldGet(_classThis, _classThis, "a", _field1_get); +- __classPrivateFieldSet(_classThis, _classThis, 1, "a", _field1_set); ++ __classPrivateFieldGet(_classThis, _classThis, "a", _D_field1_get); ++ __classPrivateFieldSet(_classThis, _classThis, 1, "a", _D_field1_set); + } + static { + __runInitializers(_classThis, _classExtraInitializers); +diff --git a/tests/baselines/reference/esDecorators-classDeclaration-methods-nonStatic(target=es5).js b/tests/baselines/reference/esDecorators-classDeclaration-methods-nonStatic(target=es5).js +index ee0e92d45..e3e4ce19b 100644 +--- a/tests/baselines/reference/esDecorators-classDeclaration-methods-nonStatic(target=es5).js ++++ b/tests/baselines/reference/esDecorators-classDeclaration-methods-nonStatic(target=es5).js +@@ -13,7 +13,6 @@ class C { + + + //// [esDecorators-classDeclaration-methods-nonStatic.js] +-var _this = this; + var method3 = "method3"; + var C = function () { + var _a; +diff --git a/tests/baselines/reference/esDecorators-classDeclaration-methods-static(target=es5).js b/tests/baselines/reference/esDecorators-classDeclaration-methods-static(target=es5).js +index 301743dd2..e28c8eb99 100644 +--- a/tests/baselines/reference/esDecorators-classDeclaration-methods-static(target=es5).js ++++ b/tests/baselines/reference/esDecorators-classDeclaration-methods-static(target=es5).js +@@ -13,7 +13,6 @@ class C { + + + //// [esDecorators-classDeclaration-methods-static.js] +-var _this = this; + var method3 = "method3"; + var C = function () { + var _a; +diff --git a/tests/baselines/reference/esDecorators-classDeclaration-methods-staticPrivate(target=es2015).js b/tests/baselines/reference/esDecorators-classDeclaration-methods-staticPrivate(target=es2015).js +index 71a531d10..449a96263 100644 +--- a/tests/baselines/reference/esDecorators-classDeclaration-methods-staticPrivate(target=es2015).js ++++ b/tests/baselines/reference/esDecorators-classDeclaration-methods-staticPrivate(target=es2015).js +@@ -30,14 +30,14 @@ let C = (() => { + _a; + })(); + let D = (() => { +- var _method1; ++ var _D_method1; + let _classDecorators = [dec]; + let _classDescriptor; + let _classExtraInitializers = []; + let _classThis; + var D = _classThis = class { + }; +- _method1 = function _method1() { }; ++ _D_method1 = function _D_method1() { }; + __setFunctionName(_classThis, "D"); + (() => { + __esDecorate(null, _classDescriptor = { value: _classThis }, _classDecorators, { kind: "class", name: _classThis.name }, null, _classExtraInitializers); +diff --git a/tests/baselines/reference/esDecorators-classDeclaration-methods-staticPrivate(target=es2022).js b/tests/baselines/reference/esDecorators-classDeclaration-methods-staticPrivate(target=es2022).js +index efc4f2e83..d1516b157 100644 +--- a/tests/baselines/reference/esDecorators-classDeclaration-methods-staticPrivate(target=es2022).js ++++ b/tests/baselines/reference/esDecorators-classDeclaration-methods-staticPrivate(target=es2022).js +@@ -28,16 +28,17 @@ let C = (() => { + }; + })(); + let D = (() => { +- var _method1; ++ var _D_method1; + let _classDecorators = [dec]; + let _classDescriptor; + let _classExtraInitializers = []; + let _classThis; + var D = class { ++ static { _classThis = this; } + static { __setFunctionName(this, "D"); } +- static { _method1 = function _method1() { }; } ++ static { _D_method1 = function _D_method1() { }; } + static { +- __esDecorate(null, _classDescriptor = { value: this }, _classDecorators, { kind: "class", name: this.name }, null, _classExtraInitializers); ++ __esDecorate(null, _classDescriptor = { value: _classThis }, _classDecorators, { kind: "class", name: _classThis.name }, null, _classExtraInitializers); + D = _classThis = _classDescriptor.value; + __runInitializers(_classThis, _classExtraInitializers); + } +diff --git a/tests/baselines/reference/esDecorators-classDeclaration-missingEmitHelpers-classDecorator.1.js b/tests/baselines/reference/esDecorators-classDeclaration-missingEmitHelpers-classDecorator.1.js +index d5480454c..bffbb5a88 100644 +--- a/tests/baselines/reference/esDecorators-classDeclaration-missingEmitHelpers-classDecorator.1.js ++++ b/tests/baselines/reference/esDecorators-classDeclaration-missingEmitHelpers-classDecorator.1.js +@@ -23,8 +23,9 @@ let C = (() => { + let _classExtraInitializers = []; + let _classThis; + var C = class { ++ static { _classThis = this; } + static { +- tslib_1.__esDecorate(null, _classDescriptor = { value: this }, _classDecorators, { kind: "class", name: this.name }, null, _classExtraInitializers); ++ tslib_1.__esDecorate(null, _classDescriptor = { value: _classThis }, _classDecorators, { kind: "class", name: _classThis.name }, null, _classExtraInitializers); + C = _classThis = _classDescriptor.value; + tslib_1.__runInitializers(_classThis, _classExtraInitializers); + } +diff --git a/tests/baselines/reference/esDecorators-classDeclaration-missingEmitHelpers-classDecorator.2.js b/tests/baselines/reference/esDecorators-classDeclaration-missingEmitHelpers-classDecorator.2.js +index c39b9a4c0..cc5d12ea3 100644 +--- a/tests/baselines/reference/esDecorators-classDeclaration-missingEmitHelpers-classDecorator.2.js ++++ b/tests/baselines/reference/esDecorators-classDeclaration-missingEmitHelpers-classDecorator.2.js +@@ -22,9 +22,10 @@ exports.default = (() => { + let _classExtraInitializers = []; + let _classThis; + var default_1 = class { ++ static { _classThis = this; } ++ static { tslib_1.__setFunctionName(_classThis, "default"); } + static { +- tslib_1.__setFunctionName(this, "default"); +- tslib_1.__esDecorate(null, _classDescriptor = { value: this }, _classDecorators, { kind: "class", name: this.name }, null, _classExtraInitializers); ++ tslib_1.__esDecorate(null, _classDescriptor = { value: _classThis }, _classDecorators, { kind: "class", name: _classThis.name }, null, _classExtraInitializers); + default_1 = _classThis = _classDescriptor.value; + tslib_1.__runInitializers(_classThis, _classExtraInitializers); + } +diff --git a/tests/baselines/reference/esDecorators-classDeclaration-missingEmitHelpers-classDecorator.3.js b/tests/baselines/reference/esDecorators-classDeclaration-missingEmitHelpers-classDecorator.3.js +index 75f96af51..abbd3d0ab 100644 +--- a/tests/baselines/reference/esDecorators-classDeclaration-missingEmitHelpers-classDecorator.3.js ++++ b/tests/baselines/reference/esDecorators-classDeclaration-missingEmitHelpers-classDecorator.3.js +@@ -20,16 +20,17 @@ Object.defineProperty(exports, "__esModule", { value: true }); + const tslib_1 = require("tslib"); + // needs: __esDecorate, __runInitializers, __setFunctionName + let C = (() => { +- var _foo; ++ var _C_foo; + let _classDecorators = [dec]; + let _classDescriptor; + let _classExtraInitializers = []; + let _classThis; + var C = class { ++ static { _classThis = this; } + static { tslib_1.__setFunctionName(this, "C"); } +- static { _foo = function _foo() { }; } ++ static { _C_foo = function _C_foo() { }; } + static { +- tslib_1.__esDecorate(null, _classDescriptor = { value: this }, _classDecorators, { kind: "class", name: this.name }, null, _classExtraInitializers); ++ tslib_1.__esDecorate(null, _classDescriptor = { value: _classThis }, _classDecorators, { kind: "class", name: _classThis.name }, null, _classExtraInitializers); + C = _classThis = _classDescriptor.value; + tslib_1.__runInitializers(_classThis, _classExtraInitializers); + } +diff --git a/tests/baselines/reference/esDecorators-classDeclaration-multipleDecorators(target=es2022).js b/tests/baselines/reference/esDecorators-classDeclaration-multipleDecorators(target=es2022).js +index 7ee615b20..a1e83f6d1 100644 +--- a/tests/baselines/reference/esDecorators-classDeclaration-multipleDecorators(target=es2022).js ++++ b/tests/baselines/reference/esDecorators-classDeclaration-multipleDecorators(target=es2022).js +@@ -16,8 +16,9 @@ let C = (() => { + let _classExtraInitializers = []; + let _classThis; + var C = class { ++ static { _classThis = this; } + static { +- __esDecorate(null, _classDescriptor = { value: this }, _classDecorators, { kind: "class", name: this.name }, null, _classExtraInitializers); ++ __esDecorate(null, _classDescriptor = { value: _classThis }, _classDecorators, { kind: "class", name: _classThis.name }, null, _classExtraInitializers); + C = _classThis = _classDescriptor.value; + __runInitializers(_classThis, _classExtraInitializers); + } +diff --git a/tests/baselines/reference/esDecorators-classDeclaration-multipleDecorators(target=es5).js b/tests/baselines/reference/esDecorators-classDeclaration-multipleDecorators(target=es5).js +index 83e5ce848..54bf2f0b1 100644 +--- a/tests/baselines/reference/esDecorators-classDeclaration-multipleDecorators(target=es5).js ++++ b/tests/baselines/reference/esDecorators-classDeclaration-multipleDecorators(target=es5).js +@@ -10,7 +10,6 @@ class C { + + + //// [esDecorators-classDeclaration-multipleDecorators.js] +-var _this = this; + var C = function () { + var _classDecorators = [dec1, dec2]; + var _classDescriptor; +diff --git a/tests/baselines/reference/esDecorators-classDeclaration-outerThisReference(target=es2015).js b/tests/baselines/reference/esDecorators-classDeclaration-outerThisReference(target=es2015).js +index 4f67275e1..3b3d0e404 100644 +--- a/tests/baselines/reference/esDecorators-classDeclaration-outerThisReference(target=es2015).js ++++ b/tests/baselines/reference/esDecorators-classDeclaration-outerThisReference(target=es2015).js +@@ -67,17 +67,17 @@ let A = (() => { + // property names. + let B = (() => { + var _a, _b; +- let _classDecorators_1 = [dec(this)]; +- let _classDescriptor_1; +- let _classExtraInitializers_1 = []; +- let _classThis_1; +- let _instanceExtraInitializers_1 = []; ++ let _classDecorators = [dec(this)]; ++ let _classDescriptor; ++ let _classExtraInitializers = []; ++ let _classThis; ++ let _instanceExtraInitializers = []; + let _b_decorators; + let _b_initializers = []; +- var B = _classThis_1 = class { ++ var B = _classThis = class { + constructor() { + // @ts-ignore +- this[_a] = (__runInitializers(this, _instanceExtraInitializers_1), 1); ++ this[_a] = (__runInitializers(this, _instanceExtraInitializers), 1); + this.b = __runInitializers(this, _b_initializers, 2); + // @ts-ignore + this[_b] = 3; +@@ -85,41 +85,41 @@ let B = (() => { + }; + _a = f(this); + _b = (_b_decorators = [dec(this)], f(this)); +- __setFunctionName(_classThis_1, "B"); ++ __setFunctionName(_classThis, "B"); + (() => { +- __esDecorate(null, null, _b_decorators, { kind: "field", name: "b", static: false, private: false, access: { has: obj => "b" in obj, get: obj => obj.b, set: (obj, value) => { obj.b = value; } } }, _b_initializers, _instanceExtraInitializers_1); +- __esDecorate(null, _classDescriptor_1 = { value: _classThis_1 }, _classDecorators_1, { kind: "class", name: _classThis_1.name }, null, _classExtraInitializers_1); +- B = _classThis_1 = _classDescriptor_1.value; +- __runInitializers(_classThis_1, _classExtraInitializers_1); ++ __esDecorate(null, null, _b_decorators, { kind: "field", name: "b", static: false, private: false, access: { has: obj => "b" in obj, get: obj => obj.b, set: (obj, value) => { obj.b = value; } } }, _b_initializers, _instanceExtraInitializers); ++ __esDecorate(null, _classDescriptor = { value: _classThis }, _classDecorators, { kind: "class", name: _classThis.name }, null, _classExtraInitializers); ++ B = _classThis = _classDescriptor.value; ++ __runInitializers(_classThis, _classExtraInitializers); + })(); +- return B = _classThis_1; ++ return B = _classThis; + })(); + // The `this` transformation should ensure that decorators inside the class body have privileged access to + // private names. + let C = (() => { +- var _a; ++ var _C_a; + let _outerThis_1 = this; +- let _classDecorators_2 = [dec(this)]; +- let _classDescriptor_2; +- let _classExtraInitializers_2 = []; +- let _classThis_2; +- let _instanceExtraInitializers_2 = []; ++ let _classDecorators = [dec(this)]; ++ let _classDescriptor; ++ let _classExtraInitializers = []; ++ let _classThis; ++ let _instanceExtraInitializers = []; + let _b_decorators; + let _b_initializers = []; +- var C = _classThis_2 = class { ++ var C = _classThis = class { + constructor() { +- _a.set(this, (__runInitializers(this, _instanceExtraInitializers_2), 1)); ++ _C_a.set(this, (__runInitializers(this, _instanceExtraInitializers), 1)); + this.b = __runInitializers(this, _b_initializers, 2); + } + }; +- _a = new WeakMap(); +- __setFunctionName(_classThis_2, "C"); ++ _C_a = new WeakMap(); ++ __setFunctionName(_classThis, "C"); + (() => { +- _b_decorators = [dec(_outerThis_1, (x) => __classPrivateFieldGet(x, _a, "f"))]; +- __esDecorate(null, null, _b_decorators, { kind: "field", name: "b", static: false, private: false, access: { has: obj => "b" in obj, get: obj => obj.b, set: (obj, value) => { obj.b = value; } } }, _b_initializers, _instanceExtraInitializers_2); +- __esDecorate(null, _classDescriptor_2 = { value: _classThis_2 }, _classDecorators_2, { kind: "class", name: _classThis_2.name }, null, _classExtraInitializers_2); +- C = _classThis_2 = _classDescriptor_2.value; +- __runInitializers(_classThis_2, _classExtraInitializers_2); ++ _b_decorators = [dec(_outerThis_1, (x) => __classPrivateFieldGet(x, _C_a, "f"))]; ++ __esDecorate(null, null, _b_decorators, { kind: "field", name: "b", static: false, private: false, access: { has: obj => "b" in obj, get: obj => obj.b, set: (obj, value) => { obj.b = value; } } }, _b_initializers, _instanceExtraInitializers); ++ __esDecorate(null, _classDescriptor = { value: _classThis }, _classDecorators, { kind: "class", name: _classThis.name }, null, _classExtraInitializers); ++ C = _classThis = _classDescriptor.value; ++ __runInitializers(_classThis, _classExtraInitializers); + })(); +- return C = _classThis_2; ++ return C = _classThis; + })(); +diff --git a/tests/baselines/reference/esDecorators-classDeclaration-outerThisReference(target=es2021).js b/tests/baselines/reference/esDecorators-classDeclaration-outerThisReference(target=es2021).js +index 4f67275e1..3b3d0e404 100644 +--- a/tests/baselines/reference/esDecorators-classDeclaration-outerThisReference(target=es2021).js ++++ b/tests/baselines/reference/esDecorators-classDeclaration-outerThisReference(target=es2021).js +@@ -67,17 +67,17 @@ let A = (() => { + // property names. + let B = (() => { + var _a, _b; +- let _classDecorators_1 = [dec(this)]; +- let _classDescriptor_1; +- let _classExtraInitializers_1 = []; +- let _classThis_1; +- let _instanceExtraInitializers_1 = []; ++ let _classDecorators = [dec(this)]; ++ let _classDescriptor; ++ let _classExtraInitializers = []; ++ let _classThis; ++ let _instanceExtraInitializers = []; + let _b_decorators; + let _b_initializers = []; +- var B = _classThis_1 = class { ++ var B = _classThis = class { + constructor() { + // @ts-ignore +- this[_a] = (__runInitializers(this, _instanceExtraInitializers_1), 1); ++ this[_a] = (__runInitializers(this, _instanceExtraInitializers), 1); + this.b = __runInitializers(this, _b_initializers, 2); + // @ts-ignore + this[_b] = 3; +@@ -85,41 +85,41 @@ let B = (() => { + }; + _a = f(this); + _b = (_b_decorators = [dec(this)], f(this)); +- __setFunctionName(_classThis_1, "B"); ++ __setFunctionName(_classThis, "B"); + (() => { +- __esDecorate(null, null, _b_decorators, { kind: "field", name: "b", static: false, private: false, access: { has: obj => "b" in obj, get: obj => obj.b, set: (obj, value) => { obj.b = value; } } }, _b_initializers, _instanceExtraInitializers_1); +- __esDecorate(null, _classDescriptor_1 = { value: _classThis_1 }, _classDecorators_1, { kind: "class", name: _classThis_1.name }, null, _classExtraInitializers_1); +- B = _classThis_1 = _classDescriptor_1.value; +- __runInitializers(_classThis_1, _classExtraInitializers_1); ++ __esDecorate(null, null, _b_decorators, { kind: "field", name: "b", static: false, private: false, access: { has: obj => "b" in obj, get: obj => obj.b, set: (obj, value) => { obj.b = value; } } }, _b_initializers, _instanceExtraInitializers); ++ __esDecorate(null, _classDescriptor = { value: _classThis }, _classDecorators, { kind: "class", name: _classThis.name }, null, _classExtraInitializers); ++ B = _classThis = _classDescriptor.value; ++ __runInitializers(_classThis, _classExtraInitializers); + })(); +- return B = _classThis_1; ++ return B = _classThis; + })(); + // The `this` transformation should ensure that decorators inside the class body have privileged access to + // private names. + let C = (() => { +- var _a; ++ var _C_a; + let _outerThis_1 = this; +- let _classDecorators_2 = [dec(this)]; +- let _classDescriptor_2; +- let _classExtraInitializers_2 = []; +- let _classThis_2; +- let _instanceExtraInitializers_2 = []; ++ let _classDecorators = [dec(this)]; ++ let _classDescriptor; ++ let _classExtraInitializers = []; ++ let _classThis; ++ let _instanceExtraInitializers = []; + let _b_decorators; + let _b_initializers = []; +- var C = _classThis_2 = class { ++ var C = _classThis = class { + constructor() { +- _a.set(this, (__runInitializers(this, _instanceExtraInitializers_2), 1)); ++ _C_a.set(this, (__runInitializers(this, _instanceExtraInitializers), 1)); + this.b = __runInitializers(this, _b_initializers, 2); + } + }; +- _a = new WeakMap(); +- __setFunctionName(_classThis_2, "C"); ++ _C_a = new WeakMap(); ++ __setFunctionName(_classThis, "C"); + (() => { +- _b_decorators = [dec(_outerThis_1, (x) => __classPrivateFieldGet(x, _a, "f"))]; +- __esDecorate(null, null, _b_decorators, { kind: "field", name: "b", static: false, private: false, access: { has: obj => "b" in obj, get: obj => obj.b, set: (obj, value) => { obj.b = value; } } }, _b_initializers, _instanceExtraInitializers_2); +- __esDecorate(null, _classDescriptor_2 = { value: _classThis_2 }, _classDecorators_2, { kind: "class", name: _classThis_2.name }, null, _classExtraInitializers_2); +- C = _classThis_2 = _classDescriptor_2.value; +- __runInitializers(_classThis_2, _classExtraInitializers_2); ++ _b_decorators = [dec(_outerThis_1, (x) => __classPrivateFieldGet(x, _C_a, "f"))]; ++ __esDecorate(null, null, _b_decorators, { kind: "field", name: "b", static: false, private: false, access: { has: obj => "b" in obj, get: obj => obj.b, set: (obj, value) => { obj.b = value; } } }, _b_initializers, _instanceExtraInitializers); ++ __esDecorate(null, _classDescriptor = { value: _classThis }, _classDecorators, { kind: "class", name: _classThis.name }, null, _classExtraInitializers); ++ C = _classThis = _classDescriptor.value; ++ __runInitializers(_classThis, _classExtraInitializers); + })(); +- return C = _classThis_2; ++ return C = _classThis; + })(); +diff --git a/tests/baselines/reference/esDecorators-classDeclaration-outerThisReference(target=es2022).js b/tests/baselines/reference/esDecorators-classDeclaration-outerThisReference(target=es2022).js +index e23eb5b11..259bf471f 100644 +--- a/tests/baselines/reference/esDecorators-classDeclaration-outerThisReference(target=es2022).js ++++ b/tests/baselines/reference/esDecorators-classDeclaration-outerThisReference(target=es2022).js +@@ -49,10 +49,11 @@ let A = (() => { + let _b_decorators; + let _b_initializers = []; + var A = class { ++ static { _classThis = this; } + static { + _b_decorators = [dec(_outerThis)]; + __esDecorate(null, null, _b_decorators, { kind: "field", name: "b", static: false, private: false, access: { has: obj => "b" in obj, get: obj => obj.b, set: (obj, value) => { obj.b = value; } } }, _b_initializers, _instanceExtraInitializers); +- __esDecorate(null, _classDescriptor = { value: this }, _classDecorators, { kind: "class", name: this.name }, null, _classExtraInitializers); ++ __esDecorate(null, _classDescriptor = { value: _classThis }, _classDecorators, { kind: "class", name: _classThis.name }, null, _classExtraInitializers); + A = _classThis = _classDescriptor.value; + __runInitializers(_classThis, _classExtraInitializers); + } +@@ -63,49 +64,51 @@ let A = (() => { + // `this` should point to the outer `this`, and maintain the correct evaluation order with respect to computed + // property names. + let B = (() => { +- let _classDecorators_1 = [dec(this)]; +- let _classDescriptor_1; +- let _classExtraInitializers_1 = []; +- let _classThis_1; +- let _instanceExtraInitializers_1 = []; ++ let _classDecorators = [dec(this)]; ++ let _classDescriptor; ++ let _classExtraInitializers = []; ++ let _classThis; ++ let _instanceExtraInitializers = []; + let _b_decorators; + let _b_initializers = []; + var B = class { ++ static { _classThis = this; } + static { +- __esDecorate(null, null, _b_decorators, { kind: "field", name: "b", static: false, private: false, access: { has: obj => "b" in obj, get: obj => obj.b, set: (obj, value) => { obj.b = value; } } }, _b_initializers, _instanceExtraInitializers_1); +- __esDecorate(null, _classDescriptor_1 = { value: this }, _classDecorators_1, { kind: "class", name: this.name }, null, _classExtraInitializers_1); +- B = _classThis_1 = _classDescriptor_1.value; +- __runInitializers(_classThis_1, _classExtraInitializers_1); ++ __esDecorate(null, null, _b_decorators, { kind: "field", name: "b", static: false, private: false, access: { has: obj => "b" in obj, get: obj => obj.b, set: (obj, value) => { obj.b = value; } } }, _b_initializers, _instanceExtraInitializers); ++ __esDecorate(null, _classDescriptor = { value: _classThis }, _classDecorators, { kind: "class", name: _classThis.name }, null, _classExtraInitializers); ++ B = _classThis = _classDescriptor.value; ++ __runInitializers(_classThis, _classExtraInitializers); + } + // @ts-ignore +- [f(this)] = (__runInitializers(this, _instanceExtraInitializers_1), 1); ++ [f(this)] = (__runInitializers(this, _instanceExtraInitializers), 1); + b = __runInitializers(this, _b_initializers, 2); + // @ts-ignore + [(_b_decorators = [dec(this)], f(this))] = 3; + }; +- return B = _classThis_1; ++ return B = _classThis; + })(); + // The `this` transformation should ensure that decorators inside the class body have privileged access to + // private names. + let C = (() => { + let _outerThis_1 = this; +- let _classDecorators_2 = [dec(this)]; +- let _classDescriptor_2; +- let _classExtraInitializers_2 = []; +- let _classThis_2; +- let _instanceExtraInitializers_2 = []; ++ let _classDecorators = [dec(this)]; ++ let _classDescriptor; ++ let _classExtraInitializers = []; ++ let _classThis; ++ let _instanceExtraInitializers = []; + let _b_decorators; + let _b_initializers = []; + var C = class { ++ static { _classThis = this; } + static { + _b_decorators = [dec(_outerThis_1, (x) => x.#a)]; +- __esDecorate(null, null, _b_decorators, { kind: "field", name: "b", static: false, private: false, access: { has: obj => "b" in obj, get: obj => obj.b, set: (obj, value) => { obj.b = value; } } }, _b_initializers, _instanceExtraInitializers_2); +- __esDecorate(null, _classDescriptor_2 = { value: this }, _classDecorators_2, { kind: "class", name: this.name }, null, _classExtraInitializers_2); +- C = _classThis_2 = _classDescriptor_2.value; +- __runInitializers(_classThis_2, _classExtraInitializers_2); ++ __esDecorate(null, null, _b_decorators, { kind: "field", name: "b", static: false, private: false, access: { has: obj => "b" in obj, get: obj => obj.b, set: (obj, value) => { obj.b = value; } } }, _b_initializers, _instanceExtraInitializers); ++ __esDecorate(null, _classDescriptor = { value: _classThis }, _classDecorators, { kind: "class", name: _classThis.name }, null, _classExtraInitializers); ++ C = _classThis = _classDescriptor.value; ++ __runInitializers(_classThis, _classExtraInitializers); + } +- #a = (__runInitializers(this, _instanceExtraInitializers_2), 1); ++ #a = (__runInitializers(this, _instanceExtraInitializers), 1); + b = __runInitializers(this, _b_initializers, 2); + }; +- return C = _classThis_2; ++ return C = _classThis; + })(); +diff --git a/tests/baselines/reference/esDecorators-classDeclaration-parameterProperties(target=es5,usedefineforclassfields=false).js b/tests/baselines/reference/esDecorators-classDeclaration-parameterProperties(target=es5,usedefineforclassfields=false).js +index b00b1ac7f..f7505a503 100644 +--- a/tests/baselines/reference/esDecorators-classDeclaration-parameterProperties(target=es5,usedefineforclassfields=false).js ++++ b/tests/baselines/reference/esDecorators-classDeclaration-parameterProperties(target=es5,usedefineforclassfields=false).js +@@ -12,7 +12,6 @@ class C { + + + //// [esDecorators-classDeclaration-parameterProperties.js] +-var _this = this; + var C = function () { + var _a; + var _instanceExtraInitializers = []; +diff --git a/tests/baselines/reference/esDecorators-classDeclaration-parameterProperties(target=es5,usedefineforclassfields=true).js b/tests/baselines/reference/esDecorators-classDeclaration-parameterProperties(target=es5,usedefineforclassfields=true).js +index a798a3d24..b352efced 100644 +--- a/tests/baselines/reference/esDecorators-classDeclaration-parameterProperties(target=es5,usedefineforclassfields=true).js ++++ b/tests/baselines/reference/esDecorators-classDeclaration-parameterProperties(target=es5,usedefineforclassfields=true).js +@@ -12,7 +12,6 @@ class C { + + + //// [esDecorators-classDeclaration-parameterProperties.js] +-var _this = this; + var C = function () { + var _a; + var _instanceExtraInitializers = []; +diff --git a/tests/baselines/reference/esDecorators-classDeclaration-setFunctionName(target=es2015).js b/tests/baselines/reference/esDecorators-classDeclaration-setFunctionName(target=es2015).js +index 7702afec3..93e137a73 100644 +--- a/tests/baselines/reference/esDecorators-classDeclaration-setFunctionName(target=es2015).js ++++ b/tests/baselines/reference/esDecorators-classDeclaration-setFunctionName(target=es2015).js +@@ -41,7 +41,7 @@ let C = (() => { + })(); + export {}; + //// [b.js] +-export let C = (() => { ++let C = (() => { + let _classDecorators = [dec]; + let _classDescriptor; + let _classExtraInitializers = []; +@@ -56,6 +56,7 @@ export let C = (() => { + })(); + return C = _classThis; + })(); ++export { C }; + //// [c.js] + export default (() => { + let _classDecorators = [dec]; +@@ -64,8 +65,8 @@ export default (() => { + let _classThis; + var default_1 = _classThis = class { + }; ++ __setFunctionName(_classThis, "default"); + (() => { +- __setFunctionName(_classThis, "default"); + __esDecorate(null, _classDescriptor = { value: _classThis }, _classDecorators, { kind: "class", name: _classThis.name }, null, _classExtraInitializers); + default_1 = _classThis = _classDescriptor.value; + __runInitializers(_classThis, _classExtraInitializers); +diff --git a/tests/baselines/reference/esDecorators-classDeclaration-setFunctionName(target=es2022).js b/tests/baselines/reference/esDecorators-classDeclaration-setFunctionName(target=es2022).js +index 09eac0a5b..aa2e4099d 100644 +--- a/tests/baselines/reference/esDecorators-classDeclaration-setFunctionName(target=es2022).js ++++ b/tests/baselines/reference/esDecorators-classDeclaration-setFunctionName(target=es2022).js +@@ -30,8 +30,9 @@ let C = (() => { + let _classExtraInitializers = []; + let _classThis; + var C = class { ++ static { _classThis = this; } + static { +- __esDecorate(null, _classDescriptor = { value: this }, _classDecorators, { kind: "class", name: this.name }, null, _classExtraInitializers); ++ __esDecorate(null, _classDescriptor = { value: _classThis }, _classDecorators, { kind: "class", name: _classThis.name }, null, _classExtraInitializers); + C = _classThis = _classDescriptor.value; + __runInitializers(_classThis, _classExtraInitializers); + } +@@ -40,20 +41,22 @@ let C = (() => { + })(); + export {}; + //// [b.js] +-export let C = (() => { ++let C = (() => { + let _classDecorators = [dec]; + let _classDescriptor; + let _classExtraInitializers = []; + let _classThis; + var C = class { ++ static { _classThis = this; } + static { +- __esDecorate(null, _classDescriptor = { value: this }, _classDecorators, { kind: "class", name: this.name }, null, _classExtraInitializers); ++ __esDecorate(null, _classDescriptor = { value: _classThis }, _classDecorators, { kind: "class", name: _classThis.name }, null, _classExtraInitializers); + C = _classThis = _classDescriptor.value; + __runInitializers(_classThis, _classExtraInitializers); + } + }; + return C = _classThis; + })(); ++export { C }; + //// [c.js] + export default (() => { + let _classDecorators = [dec]; +@@ -61,9 +64,10 @@ export default (() => { + let _classExtraInitializers = []; + let _classThis; + var default_1 = class { ++ static { _classThis = this; } ++ static { __setFunctionName(_classThis, "default"); } + static { +- __setFunctionName(this, "default"); +- __esDecorate(null, _classDescriptor = { value: this }, _classDecorators, { kind: "class", name: this.name }, null, _classExtraInitializers); ++ __esDecorate(null, _classDescriptor = { value: _classThis }, _classDecorators, { kind: "class", name: _classThis.name }, null, _classExtraInitializers); + default_1 = _classThis = _classDescriptor.value; + __runInitializers(_classThis, _classExtraInitializers); + } +diff --git a/tests/baselines/reference/esDecorators-classDeclaration-setFunctionName(target=es5).js b/tests/baselines/reference/esDecorators-classDeclaration-setFunctionName(target=es5).js +index b574caffd..a0ef79023 100644 +--- a/tests/baselines/reference/esDecorators-classDeclaration-setFunctionName(target=es5).js ++++ b/tests/baselines/reference/esDecorators-classDeclaration-setFunctionName(target=es5).js +@@ -25,7 +25,6 @@ declare let dec: any; + + //// [a.js] + "use strict"; +-var _this = this; + Object.defineProperty(exports, "__esModule", { value: true }); + var C = function () { + var _classDecorators = [dec]; +@@ -47,10 +46,9 @@ var C = function () { + }(); + //// [b.js] + "use strict"; +-var _this = this; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.C = void 0; +-var C = exports.C = function () { ++var C = function () { + var _classDecorators = [dec]; + var _classDescriptor; + var _classExtraInitializers = []; +@@ -68,9 +66,9 @@ var C = exports.C = function () { + })(); + return C = _classThis; + }(); ++exports.C = C; + //// [c.js] + "use strict"; +-var _this = this; + Object.defineProperty(exports, "__esModule", { value: true }); + var default_1 = function () { + var _classDecorators = [dec]; +@@ -82,8 +80,8 @@ var default_1 = function () { + } + return default_1; + }()); ++ __setFunctionName(_classThis, "default"); + (function () { +- __setFunctionName(_classThis, "default_1"); + __esDecorate(null, _classDescriptor = { value: _classThis }, _classDecorators, { kind: "class", name: _classThis.name }, null, _classExtraInitializers); + default_1 = _classThis = _classDescriptor.value; + __runInitializers(_classThis, _classExtraInitializers); +diff --git a/tests/baselines/reference/esDecorators-classDeclaration-simpleTransformation(target=es2022).js b/tests/baselines/reference/esDecorators-classDeclaration-simpleTransformation(target=es2022).js +index f6d99dc42..8396a58f6 100644 +--- a/tests/baselines/reference/esDecorators-classDeclaration-simpleTransformation(target=es2022).js ++++ b/tests/baselines/reference/esDecorators-classDeclaration-simpleTransformation(target=es2022).js +@@ -15,8 +15,9 @@ let C = (() => { + let _classExtraInitializers = []; + let _classThis; + var C = class { ++ static { _classThis = this; } + static { +- __esDecorate(null, _classDescriptor = { value: this }, _classDecorators, { kind: "class", name: this.name }, null, _classExtraInitializers); ++ __esDecorate(null, _classDescriptor = { value: _classThis }, _classDecorators, { kind: "class", name: _classThis.name }, null, _classExtraInitializers); + C = _classThis = _classDescriptor.value; + __runInitializers(_classThis, _classExtraInitializers); + } +diff --git a/tests/baselines/reference/esDecorators-classDeclaration-simpleTransformation(target=es5).js b/tests/baselines/reference/esDecorators-classDeclaration-simpleTransformation(target=es5).js +index 6567b6fcd..89d9fea82 100644 +--- a/tests/baselines/reference/esDecorators-classDeclaration-simpleTransformation(target=es5).js ++++ b/tests/baselines/reference/esDecorators-classDeclaration-simpleTransformation(target=es5).js +@@ -9,7 +9,6 @@ class C { + + + //// [esDecorators-classDeclaration-simpleTransformation.js] +-var _this = this; + var C = function () { + var _classDecorators = [dec]; + var _classDescriptor; +diff --git a/tests/baselines/reference/esDecorators-classDeclaration-sourceMap(target=es2015).js b/tests/baselines/reference/esDecorators-classDeclaration-sourceMap(target=es2015).js +index d85f8dacc..c3cc0da41 100644 +--- a/tests/baselines/reference/esDecorators-classDeclaration-sourceMap(target=es2015).js ++++ b/tests/baselines/reference/esDecorators-classDeclaration-sourceMap(target=es2015).js +@@ -103,7 +103,7 @@ var __classPrivateFieldIn = (this && this.__classPrivateFieldIn) || function(sta + return typeof state === "function" ? receiver === state : state.has(receiver); + }; + let C = (() => { +- var _method_get, _x_get, _x_set, _y, _z_accessor_storage, _z_get, _z_set, _z_1_accessor_storage; ++ var _C_method_get, _C_x_get, _C_x_set, _C_y, _C_z_accessor_storage, _C_z_get, _C_z_set, _C_z_1_accessor_storage; + let _classDecorators = [dec, dec]; + let _classDescriptor; + let _classExtraInitializers = []; +@@ -131,20 +131,20 @@ let C = (() => { + var C = _classThis = class { + constructor() { + this.y = (__runInitializers(this, _instanceExtraInitializers), __runInitializers(this, _y_initializers, 1)); +- _z_1_accessor_storage.set(this, __runInitializers(this, _z_initializers, 1)); ++ _C_z_1_accessor_storage.set(this, __runInitializers(this, _z_initializers, 1)); + } + method() { } + get x() { return 1; } + set x(value) { } +- get z() { return __classPrivateFieldGet(this, _z_1_accessor_storage, "f"); } +- set z(value) { __classPrivateFieldSet(this, _z_1_accessor_storage, value, "f"); } ++ get z() { return __classPrivateFieldGet(this, _C_z_1_accessor_storage, "f"); } ++ set z(value) { __classPrivateFieldSet(this, _C_z_1_accessor_storage, value, "f"); } + }; +- _z_1_accessor_storage = new WeakMap(); +- _method_get = function _method_get() { return _static_private_method_descriptor.value; }; +- _x_get = function _x_get() { return _static_private_get_x_descriptor.get.call(this); }; +- _x_set = function _x_set(value) { return _static_private_set_x_descriptor.set.call(this, value); }; +- _z_get = function _z_get() { return _static_private_z_descriptor.get.call(this); }; +- _z_set = function _z_set(value) { return _static_private_z_descriptor.set.call(this, value); }; ++ _C_z_1_accessor_storage = new WeakMap(); ++ _C_method_get = function _C_method_get() { return _static_private_method_descriptor.value; }; ++ _C_x_get = function _C_x_get() { return _static_private_get_x_descriptor.get.call(this); }; ++ _C_x_set = function _C_x_set(value) { return _static_private_set_x_descriptor.set.call(this, value); }; ++ _C_z_get = function _C_z_get() { return _static_private_z_descriptor.get.call(this); }; ++ _C_z_set = function _C_z_set(value) { return _static_private_z_descriptor.set.call(this, value); }; + __setFunctionName(_classThis, "C"); + (() => { + _method_decorators = [dec, dec]; +@@ -157,22 +157,22 @@ let C = (() => { + _static_private_set_x_decorators = [dec, dec]; + _static_private_y_decorators = [dec, dec]; + _static_private_z_decorators = [dec, dec]; +- __esDecorate(_classThis, _static_private_method_descriptor = { value: __setFunctionName(function () { }, "#method") }, _static_private_method_decorators, { kind: "method", name: "#method", static: true, private: true, access: { has: obj => __classPrivateFieldIn(_classThis, obj), get: obj => __classPrivateFieldGet(obj, _classThis, "a", _method_get) } }, null, _staticExtraInitializers); +- __esDecorate(_classThis, _static_private_get_x_descriptor = { get: __setFunctionName(function () { return 1; }, "#x", "get") }, _static_private_get_x_decorators, { kind: "getter", name: "#x", static: true, private: true, access: { has: obj => __classPrivateFieldIn(_classThis, obj), get: obj => __classPrivateFieldGet(obj, _classThis, "a", _x_get) } }, null, _staticExtraInitializers); +- __esDecorate(_classThis, _static_private_set_x_descriptor = { set: __setFunctionName(function (value) { }, "#x", "set") }, _static_private_set_x_decorators, { kind: "setter", name: "#x", static: true, private: true, access: { has: obj => __classPrivateFieldIn(_classThis, obj), set: (obj, value) => { __classPrivateFieldSet(obj, _classThis, value, "a", _x_set); } } }, null, _staticExtraInitializers); +- __esDecorate(_classThis, _static_private_z_descriptor = { get: __setFunctionName(function () { return __classPrivateFieldGet(_classThis, _classThis, "f", _z_accessor_storage); }, "#z", "get"), set: __setFunctionName(function (value) { __classPrivateFieldSet(_classThis, _classThis, value, "f", _z_accessor_storage); }, "#z", "set") }, _static_private_z_decorators, { kind: "accessor", name: "#z", static: true, private: true, access: { has: obj => __classPrivateFieldIn(_classThis, obj), get: obj => __classPrivateFieldGet(obj, _classThis, "a", _z_get), set: (obj, value) => { __classPrivateFieldSet(obj, _classThis, value, "a", _z_set); } } }, _static_private_z_initializers, _staticExtraInitializers); ++ __esDecorate(_classThis, _static_private_method_descriptor = { value: __setFunctionName(function () { }, "#method") }, _static_private_method_decorators, { kind: "method", name: "#method", static: true, private: true, access: { has: obj => __classPrivateFieldIn(_classThis, obj), get: obj => __classPrivateFieldGet(obj, _classThis, "a", _C_method_get) } }, null, _staticExtraInitializers); ++ __esDecorate(_classThis, _static_private_get_x_descriptor = { get: __setFunctionName(function () { return 1; }, "#x", "get") }, _static_private_get_x_decorators, { kind: "getter", name: "#x", static: true, private: true, access: { has: obj => __classPrivateFieldIn(_classThis, obj), get: obj => __classPrivateFieldGet(obj, _classThis, "a", _C_x_get) } }, null, _staticExtraInitializers); ++ __esDecorate(_classThis, _static_private_set_x_descriptor = { set: __setFunctionName(function (value) { }, "#x", "set") }, _static_private_set_x_decorators, { kind: "setter", name: "#x", static: true, private: true, access: { has: obj => __classPrivateFieldIn(_classThis, obj), set: (obj, value) => { __classPrivateFieldSet(obj, _classThis, value, "a", _C_x_set); } } }, null, _staticExtraInitializers); ++ __esDecorate(_classThis, _static_private_z_descriptor = { get: __setFunctionName(function () { return __classPrivateFieldGet(_classThis, _classThis, "f", _C_z_accessor_storage); }, "#z", "get"), set: __setFunctionName(function (value) { __classPrivateFieldSet(_classThis, _classThis, value, "f", _C_z_accessor_storage); }, "#z", "set") }, _static_private_z_decorators, { kind: "accessor", name: "#z", static: true, private: true, access: { has: obj => __classPrivateFieldIn(_classThis, obj), get: obj => __classPrivateFieldGet(obj, _classThis, "a", _C_z_get), set: (obj, value) => { __classPrivateFieldSet(obj, _classThis, value, "a", _C_z_set); } } }, _static_private_z_initializers, _staticExtraInitializers); + __esDecorate(_classThis, null, _method_decorators, { kind: "method", name: "method", static: false, private: false, access: { has: obj => "method" in obj, get: obj => obj.method } }, null, _instanceExtraInitializers); + __esDecorate(_classThis, null, _get_x_decorators, { kind: "getter", name: "x", static: false, private: false, access: { has: obj => "x" in obj, get: obj => obj.x } }, null, _instanceExtraInitializers); + __esDecorate(_classThis, null, _set_x_decorators, { kind: "setter", name: "x", static: false, private: false, access: { has: obj => "x" in obj, set: (obj, value) => { obj.x = value; } } }, null, _instanceExtraInitializers); + __esDecorate(_classThis, null, _z_decorators, { kind: "accessor", name: "z", static: false, private: false, access: { has: obj => "z" in obj, get: obj => obj.z, set: (obj, value) => { obj.z = value; } } }, _z_initializers, _instanceExtraInitializers); +- __esDecorate(null, null, _static_private_y_decorators, { kind: "field", name: "#y", static: true, private: true, access: { has: obj => __classPrivateFieldIn(_classThis, obj), get: obj => __classPrivateFieldGet(obj, _classThis, "f", _y), set: (obj, value) => { __classPrivateFieldSet(obj, _classThis, value, "f", _y); } } }, _static_private_y_initializers, _staticExtraInitializers); ++ __esDecorate(null, null, _static_private_y_decorators, { kind: "field", name: "#y", static: true, private: true, access: { has: obj => __classPrivateFieldIn(_classThis, obj), get: obj => __classPrivateFieldGet(obj, _classThis, "f", _C_y), set: (obj, value) => { __classPrivateFieldSet(obj, _classThis, value, "f", _C_y); } } }, _static_private_y_initializers, _staticExtraInitializers); + __esDecorate(null, null, _y_decorators, { kind: "field", name: "y", static: false, private: false, access: { has: obj => "y" in obj, get: obj => obj.y, set: (obj, value) => { obj.y = value; } } }, _y_initializers, _instanceExtraInitializers); + __esDecorate(null, _classDescriptor = { value: _classThis }, _classDecorators, { kind: "class", name: _classThis.name }, null, _classExtraInitializers); + C = _classThis = _classDescriptor.value; + __runInitializers(_classThis, _staticExtraInitializers); + })(); +- _y = { value: __runInitializers(_classThis, _static_private_y_initializers, 1) }; +- _z_accessor_storage = { value: __runInitializers(_classThis, _static_private_z_initializers, 1) }; ++ _C_y = { value: __runInitializers(_classThis, _static_private_y_initializers, 1) }; ++ _C_z_accessor_storage = { value: __runInitializers(_classThis, _static_private_z_initializers, 1) }; + (() => { + __runInitializers(_classThis, _classExtraInitializers); + })(); +diff --git a/tests/baselines/reference/esDecorators-classDeclaration-sourceMap(target=es2015).js.map b/tests/baselines/reference/esDecorators-classDeclaration-sourceMap(target=es2015).js.map +index 25a35851e..095f55e5a 100644 +--- a/tests/baselines/reference/esDecorators-classDeclaration-sourceMap(target=es2015).js.map ++++ b/tests/baselines/reference/esDecorators-classDeclaration-sourceMap(target=es2015).js.map +@@ -1,6 +1,6 @@ + //// [esDecorators-classDeclaration-sourceMap.js.map] +-{"version":3,"file":"esDecorators-classDeclaration-sourceMap.js","sourceRoot":"","sources":["esDecorators-classDeclaration-sourceMap.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;IAIM,CAAC;;4BAFN,GAAG,EACH,GAAG;;;;;;;;;;;;;;;;;;;;;;;;;;YAgBA,MAAC,kGAAG,CAAC,GAAC;YAIG,yEAAI,CAAC,GAAC;QAqBnB,CAAC;QArCG,MAAM,KAAI,CAAC;QAIX,IAAI,CAAC,KAAK,OAAO,CAAC,CAAC,CAAC,CAAC;QAIrB,IAAI,CAAC,CAAC,KAAa,IAAI,CAAC;QAQxB,IAAS,CAAC,uEAAK;QAAf,IAAS,CAAC,4EAAK;;;;;;;;;;8BAlBd,GAAG,EACH,GAAG;6BAGH,GAAG,EACH,GAAG;6BAGH,GAAG,EACH,GAAG;yBAGH,GAAG,EACH,GAAG;yBAGH,GAAG,EACH,GAAG;6CAGH,GAAG,EACH,GAAG;4CAGH,GAAG,EACH,GAAG;4CAGH,GAAG,EACH,GAAG;wCAGH,GAAG,EACH,GAAG;wCAGH,GAAG,EACH,GAAG;QAfJ,+DAAA,yBAAA,cAAkB,CAAC,YAAA,gRAAA;QAInB,8DAAA,uBAAA,cAAkB,OAAO,CAAC,CAAC,CAAC,CAAC,cAAA,qQAAA;QAI7B,8DAAA,uBAAA,UAAc,KAAa,IAAI,CAAC,cAAA,0RAAA;QAQhC,0DAAA,uBAAA,gGAAuB,cAAA,EAAvB,uBAAA,qGAAuB,cAAA,oXAAA;QApCvB,2KAAA,MAAM,wCAAK;QAIX,gKAAI,CAAC,wCAAgB;QAIrB,2KAAI,CAAC,mDAAmB;QAQxB,8JAAS,CAAC,6BAAD,CAAC,8DAAK;QAgBf,8XAAc;QApBd,qJAAA,CAAC,6BAAD,CAAC,8DAAK;QAfV,wJAwCC;;QAxCK,wDAAC;;IAmCI,4EAAK,CAAC,GAAJ,CAAK;IAIE,6FAAK,CAAC,GAAJ,CAAK;;QAvCrB,uDAAC"} +-//// https://sokra.github.io/source-map-visualization#base64,dmFyIF9fZXNEZWNvcmF0ZSA9ICh0aGlzICYmIHRoaXMuX19lc0RlY29yYXRlKSB8fCBmdW5jdGlvbiAoY3RvciwgZGVzY3JpcHRvckluLCBkZWNvcmF0b3JzLCBjb250ZXh0SW4sIGluaXRpYWxpemVycywgZXh0cmFJbml0aWFsaXplcnMpIHsNCiAgICBmdW5jdGlvbiBhY2NlcHQoZikgeyBpZiAoZiAhPT0gdm9pZCAwICYmIHR5cGVvZiBmICE9PSAiZnVuY3Rpb24iKSB0aHJvdyBuZXcgVHlwZUVycm9yKCJGdW5jdGlvbiBleHBlY3RlZCIpOyByZXR1cm4gZjsgfQ0KICAgIHZhciBraW5kID0gY29udGV4dEluLmtpbmQsIGtleSA9IGtpbmQgPT09ICJnZXR0ZXIiID8gImdldCIgOiBraW5kID09PSAic2V0dGVyIiA/ICJzZXQiIDogInZhbHVlIjsNCiAgICB2YXIgdGFyZ2V0ID0gIWRlc2NyaXB0b3JJbiAmJiBjdG9yID8gY29udGV4dEluWyJzdGF0aWMiXSA/IGN0b3IgOiBjdG9yLnByb3RvdHlwZSA6IG51bGw7DQogICAgdmFyIGRlc2NyaXB0b3IgPSBkZXNjcmlwdG9ySW4gfHwgKHRhcmdldCA/IE9iamVjdC5nZXRPd25Qcm9wZXJ0eURlc2NyaXB0b3IodGFyZ2V0LCBjb250ZXh0SW4ubmFtZSkgOiB7fSk7DQogICAgdmFyIF8sIGRvbmUgPSBmYWxzZTsNCiAgICBmb3IgKHZhciBpID0gZGVjb3JhdG9ycy5sZW5ndGggLSAxOyBpID49IDA7IGktLSkgew0KICAgICAgICB2YXIgY29udGV4dCA9IHt9Ow0KICAgICAgICBmb3IgKHZhciBwIGluIGNvbnRleHRJbikgY29udGV4dFtwXSA9IHAgPT09ICJhY2Nlc3MiID8ge30gOiBjb250ZXh0SW5bcF07DQogICAgICAgIGZvciAodmFyIHAgaW4gY29udGV4dEluLmFjY2VzcykgY29udGV4dC5hY2Nlc3NbcF0gPSBjb250ZXh0SW4uYWNjZXNzW3BdOw0KICAgICAgICBjb250ZXh0LmFkZEluaXRpYWxpemVyID0gZnVuY3Rpb24gKGYpIHsgaWYgKGRvbmUpIHRocm93IG5ldyBUeXBlRXJyb3IoIkNhbm5vdCBhZGQgaW5pdGlhbGl6ZXJzIGFmdGVyIGRlY29yYXRpb24gaGFzIGNvbXBsZXRlZCIpOyBleHRyYUluaXRpYWxpemVycy5wdXNoKGFjY2VwdChmIHx8IG51bGwpKTsgfTsNCiAgICAgICAgdmFyIHJlc3VsdCA9ICgwLCBkZWNvcmF0b3JzW2ldKShraW5kID09PSAiYWNjZXNzb3IiID8geyBnZXQ6IGRlc2NyaXB0b3IuZ2V0LCBzZXQ6IGRlc2NyaXB0b3Iuc2V0IH0gOiBkZXNjcmlwdG9yW2tleV0sIGNvbnRleHQpOw0KICAgICAgICBpZiAoa2luZCA9PT0gImFjY2Vzc29yIikgew0KICAgICAgICAgICAgaWYgKHJlc3VsdCA9PT0gdm9pZCAwKSBjb250aW51ZTsNCiAgICAgICAgICAgIGlmIChyZXN1bHQgPT09IG51bGwgfHwgdHlwZW9mIHJlc3VsdCAhPT0gIm9iamVjdCIpIHRocm93IG5ldyBUeXBlRXJyb3IoIk9iamVjdCBleHBlY3RlZCIpOw0KICAgICAgICAgICAgaWYgKF8gPSBhY2NlcHQocmVzdWx0LmdldCkpIGRlc2NyaXB0b3IuZ2V0ID0gXzsNCiAgICAgICAgICAgIGlmIChfID0gYWNjZXB0KHJlc3VsdC5zZXQpKSBkZXNjcmlwdG9yLnNldCA9IF87DQogICAgICAgICAgICBpZiAoXyA9IGFjY2VwdChyZXN1bHQuaW5pdCkpIGluaXRpYWxpemVycy51bnNoaWZ0KF8pOw0KICAgICAgICB9DQogICAgICAgIGVsc2UgaWYgKF8gPSBhY2NlcHQocmVzdWx0KSkgew0KICAgICAgICAgICAgaWYgKGtpbmQgPT09ICJmaWVsZCIpIGluaXRpYWxpemVycy51bnNoaWZ0KF8pOw0KICAgICAgICAgICAgZWxzZSBkZXNjcmlwdG9yW2tleV0gPSBfOw0KICAgICAgICB9DQogICAgfQ0KICAgIGlmICh0YXJnZXQpIE9iamVjdC5kZWZpbmVQcm9wZXJ0eSh0YXJnZXQsIGNvbnRleHRJbi5uYW1lLCBkZXNjcmlwdG9yKTsNCiAgICBkb25lID0gdHJ1ZTsNCn07DQp2YXIgX19ydW5Jbml0aWFsaXplcnMgPSAodGhpcyAmJiB0aGlzLl9fcnVuSW5pdGlhbGl6ZXJzKSB8fCBmdW5jdGlvbiAodGhpc0FyZywgaW5pdGlhbGl6ZXJzLCB2YWx1ZSkgew0KICAgIHZhciB1c2VWYWx1ZSA9IGFyZ3VtZW50cy5sZW5ndGggPiAyOw0KICAgIGZvciAodmFyIGkgPSAwOyBpIDwgaW5pdGlhbGl6ZXJzLmxlbmd0aDsgaSsrKSB7DQogICAgICAgIHZhbHVlID0gdXNlVmFsdWUgPyBpbml0aWFsaXplcnNbaV0uY2FsbCh0aGlzQXJnLCB2YWx1ZSkgOiBpbml0aWFsaXplcnNbaV0uY2FsbCh0aGlzQXJnKTsNCiAgICB9DQogICAgcmV0dXJuIHVzZVZhbHVlID8gdmFsdWUgOiB2b2lkIDA7DQp9Ow0KdmFyIF9fc2V0RnVuY3Rpb25OYW1lID0gKHRoaXMgJiYgdGhpcy5fX3NldEZ1bmN0aW9uTmFtZSkgfHwgZnVuY3Rpb24gKGYsIG5hbWUsIHByZWZpeCkgew0KICAgIGlmICh0eXBlb2YgbmFtZSA9PT0gInN5bWJvbCIpIG5hbWUgPSBuYW1lLmRlc2NyaXB0aW9uID8gIlsiLmNvbmNhdChuYW1lLmRlc2NyaXB0aW9uLCAiXSIpIDogIiI7DQogICAgcmV0dXJuIE9iamVjdC5kZWZpbmVQcm9wZXJ0eShmLCAibmFtZSIsIHsgY29uZmlndXJhYmxlOiB0cnVlLCB2YWx1ZTogcHJlZml4ID8gIiIuY29uY2F0KHByZWZpeCwgIiAiLCBuYW1lKSA6IG5hbWUgfSk7DQp9Ow0KdmFyIF9fY2xhc3NQcml2YXRlRmllbGRHZXQgPSAodGhpcyAmJiB0aGlzLl9fY2xhc3NQcml2YXRlRmllbGRHZXQpIHx8IGZ1bmN0aW9uIChyZWNlaXZlciwgc3RhdGUsIGtpbmQsIGYpIHsNCiAgICBpZiAoa2luZCA9PT0gImEiICYmICFmKSB0aHJvdyBuZXcgVHlwZUVycm9yKCJQcml2YXRlIGFjY2Vzc29yIHdhcyBkZWZpbmVkIHdpdGhvdXQgYSBnZXR0ZXIiKTsNCiAgICBpZiAodHlwZW9mIHN0YXRlID09PSAiZnVuY3Rpb24iID8gcmVjZWl2ZXIgIT09IHN0YXRlIHx8ICFmIDogIXN0YXRlLmhhcyhyZWNlaXZlcikpIHRocm93IG5ldyBUeXBlRXJyb3IoIkNhbm5vdCByZWFkIHByaXZhdGUgbWVtYmVyIGZyb20gYW4gb2JqZWN0IHdob3NlIGNsYXNzIGRpZCBub3QgZGVjbGFyZSBpdCIpOw0KICAgIHJldHVybiBraW5kID09PSAibSIgPyBmIDoga2luZCA9PT0gImEiID8gZi5jYWxsKHJlY2VpdmVyKSA6IGYgPyBmLnZhbHVlIDogc3RhdGUuZ2V0KHJlY2VpdmVyKTsNCn07DQp2YXIgX19jbGFzc1ByaXZhdGVGaWVsZFNldCA9ICh0aGlzICYmIHRoaXMuX19jbGFzc1ByaXZhdGVGaWVsZFNldCkgfHwgZnVuY3Rpb24gKHJlY2VpdmVyLCBzdGF0ZSwgdmFsdWUsIGtpbmQsIGYpIHsNCiAgICBpZiAoa2luZCA9PT0gIm0iKSB0aHJvdyBuZXcgVHlwZUVycm9yKCJQcml2YXRlIG1ldGhvZCBpcyBub3Qgd3JpdGFibGUiKTsNCiAgICBpZiAoa2luZCA9PT0gImEiICYmICFmKSB0aHJvdyBuZXcgVHlwZUVycm9yKCJQcml2YXRlIGFjY2Vzc29yIHdhcyBkZWZpbmVkIHdpdGhvdXQgYSBzZXR0ZXIiKTsNCiAgICBpZiAodHlwZW9mIHN0YXRlID09PSAiZnVuY3Rpb24iID8gcmVjZWl2ZXIgIT09IHN0YXRlIHx8ICFmIDogIXN0YXRlLmhhcyhyZWNlaXZlcikpIHRocm93IG5ldyBUeXBlRXJyb3IoIkNhbm5vdCB3cml0ZSBwcml2YXRlIG1lbWJlciB0byBhbiBvYmplY3Qgd2hvc2UgY2xhc3MgZGlkIG5vdCBkZWNsYXJlIGl0Iik7DQogICAgcmV0dXJuIChraW5kID09PSAiYSIgPyBmLmNhbGwocmVjZWl2ZXIsIHZhbHVlKSA6IGYgPyBmLnZhbHVlID0gdmFsdWUgOiBzdGF0ZS5zZXQocmVjZWl2ZXIsIHZhbHVlKSksIHZhbHVlOw0KfTsNCnZhciBfX2NsYXNzUHJpdmF0ZUZpZWxkSW4gPSAodGhpcyAmJiB0aGlzLl9fY2xhc3NQcml2YXRlRmllbGRJbikgfHwgZnVuY3Rpb24oc3RhdGUsIHJlY2VpdmVyKSB7DQogICAgaWYgKHJlY2VpdmVyID09PSBudWxsIHx8ICh0eXBlb2YgcmVjZWl2ZXIgIT09ICJvYmplY3QiICYmIHR5cGVvZiByZWNlaXZlciAhPT0gImZ1bmN0aW9uIikpIHRocm93IG5ldyBUeXBlRXJyb3IoIkNhbm5vdCB1c2UgJ2luJyBvcGVyYXRvciBvbiBub24tb2JqZWN0Iik7DQogICAgcmV0dXJuIHR5cGVvZiBzdGF0ZSA9PT0gImZ1bmN0aW9uIiA/IHJlY2VpdmVyID09PSBzdGF0ZSA6IHN0YXRlLmhhcyhyZWNlaXZlcik7DQp9Ow0KbGV0IEMgPSAoKCkgPT4gew0KICAgIHZhciBfbWV0aG9kX2dldCwgX3hfZ2V0LCBfeF9zZXQsIF95LCBfel9hY2Nlc3Nvcl9zdG9yYWdlLCBfel9nZXQsIF96X3NldCwgX3pfMV9hY2Nlc3Nvcl9zdG9yYWdlOw0KICAgIGxldCBfY2xhc3NEZWNvcmF0b3JzID0gW2RlYywgZGVjXTsNCiAgICBsZXQgX2NsYXNzRGVzY3JpcHRvcjsNCiAgICBsZXQgX2NsYXNzRXh0cmFJbml0aWFsaXplcnMgPSBbXTsNCiAgICBsZXQgX2NsYXNzVGhpczsNCiAgICBsZXQgX3N0YXRpY0V4dHJhSW5pdGlhbGl6ZXJzID0gW107DQogICAgbGV0IF9pbnN0YW5jZUV4dHJhSW5pdGlhbGl6ZXJzID0gW107DQogICAgbGV0IF9zdGF0aWNfcHJpdmF0ZV9tZXRob2RfZGVjb3JhdG9yczsNCiAgICBsZXQgX3N0YXRpY19wcml2YXRlX21ldGhvZF9kZXNjcmlwdG9yOw0KICAgIGxldCBfc3RhdGljX3ByaXZhdGVfZ2V0X3hfZGVjb3JhdG9yczsNCiAgICBsZXQgX3N0YXRpY19wcml2YXRlX2dldF94X2Rlc2NyaXB0b3I7DQogICAgbGV0IF9zdGF0aWNfcHJpdmF0ZV9zZXRfeF9kZWNvcmF0b3JzOw0KICAgIGxldCBfc3RhdGljX3ByaXZhdGVfc2V0X3hfZGVzY3JpcHRvcjsNCiAgICBsZXQgX3N0YXRpY19wcml2YXRlX3lfZGVjb3JhdG9yczsNCiAgICBsZXQgX3N0YXRpY19wcml2YXRlX3lfaW5pdGlhbGl6ZXJzID0gW107DQogICAgbGV0IF9zdGF0aWNfcHJpdmF0ZV96X2RlY29yYXRvcnM7DQogICAgbGV0IF9zdGF0aWNfcHJpdmF0ZV96X2luaXRpYWxpemVycyA9IFtdOw0KICAgIGxldCBfc3RhdGljX3ByaXZhdGVfel9kZXNjcmlwdG9yOw0KICAgIGxldCBfbWV0aG9kX2RlY29yYXRvcnM7DQogICAgbGV0IF9nZXRfeF9kZWNvcmF0b3JzOw0KICAgIGxldCBfc2V0X3hfZGVjb3JhdG9yczsNCiAgICBsZXQgX3lfZGVjb3JhdG9yczsNCiAgICBsZXQgX3lfaW5pdGlhbGl6ZXJzID0gW107DQogICAgbGV0IF96X2RlY29yYXRvcnM7DQogICAgbGV0IF96X2luaXRpYWxpemVycyA9IFtdOw0KICAgIHZhciBDID0gX2NsYXNzVGhpcyA9IGNsYXNzIHsNCiAgICAgICAgY29uc3RydWN0b3IoKSB7DQogICAgICAgICAgICB0aGlzLnkgPSAoX19ydW5Jbml0aWFsaXplcnModGhpcywgX2luc3RhbmNlRXh0cmFJbml0aWFsaXplcnMpLCBfX3J1bkluaXRpYWxpemVycyh0aGlzLCBfeV9pbml0aWFsaXplcnMsIDEpKTsNCiAgICAgICAgICAgIF96XzFfYWNjZXNzb3Jfc3RvcmFnZS5zZXQodGhpcywgX19ydW5Jbml0aWFsaXplcnModGhpcywgX3pfaW5pdGlhbGl6ZXJzLCAxKSk7DQogICAgICAgIH0NCiAgICAgICAgbWV0aG9kKCkgeyB9DQogICAgICAgIGdldCB4KCkgeyByZXR1cm4gMTsgfQ0KICAgICAgICBzZXQgeCh2YWx1ZSkgeyB9DQogICAgICAgIGdldCB6KCkgeyByZXR1cm4gX19jbGFzc1ByaXZhdGVGaWVsZEdldCh0aGlzLCBfel8xX2FjY2Vzc29yX3N0b3JhZ2UsICJmIik7IH0NCiAgICAgICAgc2V0IHoodmFsdWUpIHsgX19jbGFzc1ByaXZhdGVGaWVsZFNldCh0aGlzLCBfel8xX2FjY2Vzc29yX3N0b3JhZ2UsIHZhbHVlLCAiZiIpOyB9DQogICAgfTsNCiAgICBfel8xX2FjY2Vzc29yX3N0b3JhZ2UgPSBuZXcgV2Vha01hcCgpOw0KICAgIF9tZXRob2RfZ2V0ID0gZnVuY3Rpb24gX21ldGhvZF9nZXQoKSB7IHJldHVybiBfc3RhdGljX3ByaXZhdGVfbWV0aG9kX2Rlc2NyaXB0b3IudmFsdWU7IH07DQogICAgX3hfZ2V0ID0gZnVuY3Rpb24gX3hfZ2V0KCkgeyByZXR1cm4gX3N0YXRpY19wcml2YXRlX2dldF94X2Rlc2NyaXB0b3IuZ2V0LmNhbGwodGhpcyk7IH07DQogICAgX3hfc2V0ID0gZnVuY3Rpb24gX3hfc2V0KHZhbHVlKSB7IHJldHVybiBfc3RhdGljX3ByaXZhdGVfc2V0X3hfZGVzY3JpcHRvci5zZXQuY2FsbCh0aGlzLCB2YWx1ZSk7IH07DQogICAgX3pfZ2V0ID0gZnVuY3Rpb24gX3pfZ2V0KCkgeyByZXR1cm4gX3N0YXRpY19wcml2YXRlX3pfZGVzY3JpcHRvci5nZXQuY2FsbCh0aGlzKTsgfTsNCiAgICBfel9zZXQgPSBmdW5jdGlvbiBfel9zZXQodmFsdWUpIHsgcmV0dXJuIF9zdGF0aWNfcHJpdmF0ZV96X2Rlc2NyaXB0b3Iuc2V0LmNhbGwodGhpcywgdmFsdWUpOyB9Ow0KICAgIF9fc2V0RnVuY3Rpb25OYW1lKF9jbGFzc1RoaXMsICJDIik7DQogICAgKCgpID0+IHsNCiAgICAgICAgX21ldGhvZF9kZWNvcmF0b3JzID0gW2RlYywgZGVjXTsNCiAgICAgICAgX2dldF94X2RlY29yYXRvcnMgPSBbZGVjLCBkZWNdOw0KICAgICAgICBfc2V0X3hfZGVjb3JhdG9ycyA9IFtkZWMsIGRlY107DQogICAgICAgIF95X2RlY29yYXRvcnMgPSBbZGVjLCBkZWNdOw0KICAgICAgICBfel9kZWNvcmF0b3JzID0gW2RlYywgZGVjXTsNCiAgICAgICAgX3N0YXRpY19wcml2YXRlX21ldGhvZF9kZWNvcmF0b3JzID0gW2RlYywgZGVjXTsNCiAgICAgICAgX3N0YXRpY19wcml2YXRlX2dldF94X2RlY29yYXRvcnMgPSBbZGVjLCBkZWNdOw0KICAgICAgICBfc3RhdGljX3ByaXZhdGVfc2V0X3hfZGVjb3JhdG9ycyA9IFtkZWMsIGRlY107DQogICAgICAgIF9zdGF0aWNfcHJpdmF0ZV95X2RlY29yYXRvcnMgPSBbZGVjLCBkZWNdOw0KICAgICAgICBfc3RhdGljX3ByaXZhdGVfel9kZWNvcmF0b3JzID0gW2RlYywgZGVjXTsNCiAgICAgICAgX19lc0RlY29yYXRlKF9jbGFzc1RoaXMsIF9zdGF0aWNfcHJpdmF0ZV9tZXRob2RfZGVzY3JpcHRvciA9IHsgdmFsdWU6IF9fc2V0RnVuY3Rpb25OYW1lKGZ1bmN0aW9uICgpIHsgfSwgIiNtZXRob2QiKSB9LCBfc3RhdGljX3ByaXZhdGVfbWV0aG9kX2RlY29yYXRvcnMsIHsga2luZDogIm1ldGhvZCIsIG5hbWU6ICIjbWV0aG9kIiwgc3RhdGljOiB0cnVlLCBwcml2YXRlOiB0cnVlLCBhY2Nlc3M6IHsgaGFzOiBvYmogPT4gX19jbGFzc1ByaXZhdGVGaWVsZEluKF9jbGFzc1RoaXMsIG9iaiksIGdldDogb2JqID0+IF9fY2xhc3NQcml2YXRlRmllbGRHZXQob2JqLCBfY2xhc3NUaGlzLCAiYSIsIF9tZXRob2RfZ2V0KSB9IH0sIG51bGwsIF9zdGF0aWNFeHRyYUluaXRpYWxpemVycyk7DQogICAgICAgIF9fZXNEZWNvcmF0ZShfY2xhc3NUaGlzLCBfc3RhdGljX3ByaXZhdGVfZ2V0X3hfZGVzY3JpcHRvciA9IHsgZ2V0OiBfX3NldEZ1bmN0aW9uTmFtZShmdW5jdGlvbiAoKSB7IHJldHVybiAxOyB9LCAiI3giLCAiZ2V0IikgfSwgX3N0YXRpY19wcml2YXRlX2dldF94X2RlY29yYXRvcnMsIHsga2luZDogImdldHRlciIsIG5hbWU6ICIjeCIsIHN0YXRpYzogdHJ1ZSwgcHJpdmF0ZTogdHJ1ZSwgYWNjZXNzOiB7IGhhczogb2JqID0+IF9fY2xhc3NQcml2YXRlRmllbGRJbihfY2xhc3NUaGlzLCBvYmopLCBnZXQ6IG9iaiA9PiBfX2NsYXNzUHJpdmF0ZUZpZWxkR2V0KG9iaiwgX2NsYXNzVGhpcywgImEiLCBfeF9nZXQpIH0gfSwgbnVsbCwgX3N0YXRpY0V4dHJhSW5pdGlhbGl6ZXJzKTsNCiAgICAgICAgX19lc0RlY29yYXRlKF9jbGFzc1RoaXMsIF9zdGF0aWNfcHJpdmF0ZV9zZXRfeF9kZXNjcmlwdG9yID0geyBzZXQ6IF9fc2V0RnVuY3Rpb25OYW1lKGZ1bmN0aW9uICh2YWx1ZSkgeyB9LCAiI3giLCAic2V0IikgfSwgX3N0YXRpY19wcml2YXRlX3NldF94X2RlY29yYXRvcnMsIHsga2luZDogInNldHRlciIsIG5hbWU6ICIjeCIsIHN0YXRpYzogdHJ1ZSwgcHJpdmF0ZTogdHJ1ZSwgYWNjZXNzOiB7IGhhczogb2JqID0+IF9fY2xhc3NQcml2YXRlRmllbGRJbihfY2xhc3NUaGlzLCBvYmopLCBzZXQ6IChvYmosIHZhbHVlKSA9PiB7IF9fY2xhc3NQcml2YXRlRmllbGRTZXQob2JqLCBfY2xhc3NUaGlzLCB2YWx1ZSwgImEiLCBfeF9zZXQpOyB9IH0gfSwgbnVsbCwgX3N0YXRpY0V4dHJhSW5pdGlhbGl6ZXJzKTsNCiAgICAgICAgX19lc0RlY29yYXRlKF9jbGFzc1RoaXMsIF9zdGF0aWNfcHJpdmF0ZV96X2Rlc2NyaXB0b3IgPSB7IGdldDogX19zZXRGdW5jdGlvbk5hbWUoZnVuY3Rpb24gKCkgeyByZXR1cm4gX19jbGFzc1ByaXZhdGVGaWVsZEdldChfY2xhc3NUaGlzLCBfY2xhc3NUaGlzLCAiZiIsIF96X2FjY2Vzc29yX3N0b3JhZ2UpOyB9LCAiI3oiLCAiZ2V0IiksIHNldDogX19zZXRGdW5jdGlvbk5hbWUoZnVuY3Rpb24gKHZhbHVlKSB7IF9fY2xhc3NQcml2YXRlRmllbGRTZXQoX2NsYXNzVGhpcywgX2NsYXNzVGhpcywgdmFsdWUsICJmIiwgX3pfYWNjZXNzb3Jfc3RvcmFnZSk7IH0sICIjeiIsICJzZXQiKSB9LCBfc3RhdGljX3ByaXZhdGVfel9kZWNvcmF0b3JzLCB7IGtpbmQ6ICJhY2Nlc3NvciIsIG5hbWU6ICIjeiIsIHN0YXRpYzogdHJ1ZSwgcHJpdmF0ZTogdHJ1ZSwgYWNjZXNzOiB7IGhhczogb2JqID0+IF9fY2xhc3NQcml2YXRlRmllbGRJbihfY2xhc3NUaGlzLCBvYmopLCBnZXQ6IG9iaiA9PiBfX2NsYXNzUHJpdmF0ZUZpZWxkR2V0KG9iaiwgX2NsYXNzVGhpcywgImEiLCBfel9nZXQpLCBzZXQ6IChvYmosIHZhbHVlKSA9PiB7IF9fY2xhc3NQcml2YXRlRmllbGRTZXQob2JqLCBfY2xhc3NUaGlzLCB2YWx1ZSwgImEiLCBfel9zZXQpOyB9IH0gfSwgX3N0YXRpY19wcml2YXRlX3pfaW5pdGlhbGl6ZXJzLCBfc3RhdGljRXh0cmFJbml0aWFsaXplcnMpOw0KICAgICAgICBfX2VzRGVjb3JhdGUoX2NsYXNzVGhpcywgbnVsbCwgX21ldGhvZF9kZWNvcmF0b3JzLCB7IGtpbmQ6ICJtZXRob2QiLCBuYW1lOiAibWV0aG9kIiwgc3RhdGljOiBmYWxzZSwgcHJpdmF0ZTogZmFsc2UsIGFjY2VzczogeyBoYXM6IG9iaiA9PiAibWV0aG9kIiBpbiBvYmosIGdldDogb2JqID0+IG9iai5tZXRob2QgfSB9LCBudWxsLCBfaW5zdGFuY2VFeHRyYUluaXRpYWxpemVycyk7DQogICAgICAgIF9fZXNEZWNvcmF0ZShfY2xhc3NUaGlzLCBudWxsLCBfZ2V0X3hfZGVjb3JhdG9ycywgeyBraW5kOiAiZ2V0dGVyIiwgbmFtZTogIngiLCBzdGF0aWM6IGZhbHNlLCBwcml2YXRlOiBmYWxzZSwgYWNjZXNzOiB7IGhhczogb2JqID0+ICJ4IiBpbiBvYmosIGdldDogb2JqID0+IG9iai54IH0gfSwgbnVsbCwgX2luc3RhbmNlRXh0cmFJbml0aWFsaXplcnMpOw0KICAgICAgICBfX2VzRGVjb3JhdGUoX2NsYXNzVGhpcywgbnVsbCwgX3NldF94X2RlY29yYXRvcnMsIHsga2luZDogInNldHRlciIsIG5hbWU6ICJ4Iiwgc3RhdGljOiBmYWxzZSwgcHJpdmF0ZTogZmFsc2UsIGFjY2VzczogeyBoYXM6IG9iaiA9PiAieCIgaW4gb2JqLCBzZXQ6IChvYmosIHZhbHVlKSA9PiB7IG9iai54ID0gdmFsdWU7IH0gfSB9LCBudWxsLCBfaW5zdGFuY2VFeHRyYUluaXRpYWxpemVycyk7DQogICAgICAgIF9fZXNEZWNvcmF0ZShfY2xhc3NUaGlzLCBudWxsLCBfel9kZWNvcmF0b3JzLCB7IGtpbmQ6ICJhY2Nlc3NvciIsIG5hbWU6ICJ6Iiwgc3RhdGljOiBmYWxzZSwgcHJpdmF0ZTogZmFsc2UsIGFjY2VzczogeyBoYXM6IG9iaiA9PiAieiIgaW4gb2JqLCBnZXQ6IG9iaiA9PiBvYmoueiwgc2V0OiAob2JqLCB2YWx1ZSkgPT4geyBvYmoueiA9IHZhbHVlOyB9IH0gfSwgX3pfaW5pdGlhbGl6ZXJzLCBfaW5zdGFuY2VFeHRyYUluaXRpYWxpemVycyk7DQogICAgICAgIF9fZXNEZWNvcmF0ZShudWxsLCBudWxsLCBfc3RhdGljX3ByaXZhdGVfeV9kZWNvcmF0b3JzLCB7IGtpbmQ6ICJmaWVsZCIsIG5hbWU6ICIjeSIsIHN0YXRpYzogdHJ1ZSwgcHJpdmF0ZTogdHJ1ZSwgYWNjZXNzOiB7IGhhczogb2JqID0+IF9fY2xhc3NQcml2YXRlRmllbGRJbihfY2xhc3NUaGlzLCBvYmopLCBnZXQ6IG9iaiA9PiBfX2NsYXNzUHJpdmF0ZUZpZWxkR2V0KG9iaiwgX2NsYXNzVGhpcywgImYiLCBfeSksIHNldDogKG9iaiwgdmFsdWUpID0+IHsgX19jbGFzc1ByaXZhdGVGaWVsZFNldChvYmosIF9jbGFzc1RoaXMsIHZhbHVlLCAiZiIsIF95KTsgfSB9IH0sIF9zdGF0aWNfcHJpdmF0ZV95X2luaXRpYWxpemVycywgX3N0YXRpY0V4dHJhSW5pdGlhbGl6ZXJzKTsNCiAgICAgICAgX19lc0RlY29yYXRlKG51bGwsIG51bGwsIF95X2RlY29yYXRvcnMsIHsga2luZDogImZpZWxkIiwgbmFtZTogInkiLCBzdGF0aWM6IGZhbHNlLCBwcml2YXRlOiBmYWxzZSwgYWNjZXNzOiB7IGhhczogb2JqID0+ICJ5IiBpbiBvYmosIGdldDogb2JqID0+IG9iai55LCBzZXQ6IChvYmosIHZhbHVlKSA9PiB7IG9iai55ID0gdmFsdWU7IH0gfSB9LCBfeV9pbml0aWFsaXplcnMsIF9pbnN0YW5jZUV4dHJhSW5pdGlhbGl6ZXJzKTsNCiAgICAgICAgX19lc0RlY29yYXRlKG51bGwsIF9jbGFzc0Rlc2NyaXB0b3IgPSB7IHZhbHVlOiBfY2xhc3NUaGlzIH0sIF9jbGFzc0RlY29yYXRvcnMsIHsga2luZDogImNsYXNzIiwgbmFtZTogX2NsYXNzVGhpcy5uYW1lIH0sIG51bGwsIF9jbGFzc0V4dHJhSW5pdGlhbGl6ZXJzKTsNCiAgICAgICAgQyA9IF9jbGFzc1RoaXMgPSBfY2xhc3NEZXNjcmlwdG9yLnZhbHVlOw0KICAgICAgICBfX3J1bkluaXRpYWxpemVycyhfY2xhc3NUaGlzLCBfc3RhdGljRXh0cmFJbml0aWFsaXplcnMpOw0KICAgIH0pKCk7DQogICAgX3kgPSB7IHZhbHVlOiBfX3J1bkluaXRpYWxpemVycyhfY2xhc3NUaGlzLCBfc3RhdGljX3ByaXZhdGVfeV9pbml0aWFsaXplcnMsIDEpIH07DQogICAgX3pfYWNjZXNzb3Jfc3RvcmFnZSA9IHsgdmFsdWU6IF9fcnVuSW5pdGlhbGl6ZXJzKF9jbGFzc1RoaXMsIF9zdGF0aWNfcHJpdmF0ZV96X2luaXRpYWxpemVycywgMSkgfTsNCiAgICAoKCkgPT4gew0KICAgICAgICBfX3J1bkluaXRpYWxpemVycyhfY2xhc3NUaGlzLCBfY2xhc3NFeHRyYUluaXRpYWxpemVycyk7DQogICAgfSkoKTsNCiAgICByZXR1cm4gQyA9IF9jbGFzc1RoaXM7DQp9KSgpOw0KLy8jIHNvdXJjZU1hcHBpbmdVUkw9ZXNEZWNvcmF0b3JzLWNsYXNzRGVjbGFyYXRpb24tc291cmNlTWFwLmpzLm1hcA==,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiZXNEZWNvcmF0b3JzLWNsYXNzRGVjbGFyYXRpb24tc291cmNlTWFwLmpzIiwic291cmNlUm9vdCI6IiIsInNvdXJjZXMiOlsiZXNEZWNvcmF0b3JzLWNsYXNzRGVjbGFyYXRpb24tc291cmNlTWFwLnRzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiI7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7O0lBSU0sQ0FBQzs7NEJBRk4sR0FBRyxFQUNILEdBQUc7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7O1lBZ0JBLE1BQUMsa0dBQUcsQ0FBQyxHQUFDO1lBSUcseUVBQUksQ0FBQyxHQUFDO1FBcUJuQixDQUFDO1FBckNHLE1BQU0sS0FBSSxDQUFDO1FBSVgsSUFBSSxDQUFDLEtBQUssT0FBTyxDQUFDLENBQUMsQ0FBQyxDQUFDO1FBSXJCLElBQUksQ0FBQyxDQUFDLEtBQWEsSUFBSSxDQUFDO1FBUXhCLElBQVMsQ0FBQyx1RUFBSztRQUFmLElBQVMsQ0FBQyw0RUFBSzs7Ozs7Ozs7Ozs4QkFsQmQsR0FBRyxFQUNILEdBQUc7NkJBR0gsR0FBRyxFQUNILEdBQUc7NkJBR0gsR0FBRyxFQUNILEdBQUc7eUJBR0gsR0FBRyxFQUNILEdBQUc7eUJBR0gsR0FBRyxFQUNILEdBQUc7NkNBR0gsR0FBRyxFQUNILEdBQUc7NENBR0gsR0FBRyxFQUNILEdBQUc7NENBR0gsR0FBRyxFQUNILEdBQUc7d0NBR0gsR0FBRyxFQUNILEdBQUc7d0NBR0gsR0FBRyxFQUNILEdBQUc7UUFmSiwrREFBQSx5QkFBQSxjQUFrQixDQUFDLFlBQUEsZ1JBQUE7UUFJbkIsOERBQUEsdUJBQUEsY0FBa0IsT0FBTyxDQUFDLENBQUMsQ0FBQyxDQUFDLGNBQUEscVFBQUE7UUFJN0IsOERBQUEsdUJBQUEsVUFBYyxLQUFhLElBQUksQ0FBQyxjQUFBLDBSQUFBO1FBUWhDLDBEQUFBLHVCQUFBLGdHQUF1QixjQUFBLEVBQXZCLHVCQUFBLHFHQUF1QixjQUFBLG9YQUFBO1FBcEN2QiwyS0FBQSxNQUFNLHdDQUFLO1FBSVgsZ0tBQUksQ0FBQyx3Q0FBZ0I7UUFJckIsMktBQUksQ0FBQyxtREFBbUI7UUFReEIsOEpBQVMsQ0FBQyw2QkFBRCxDQUFDLDhEQUFLO1FBZ0JmLDhYQUFjO1FBcEJkLHFKQUFBLENBQUMsNkJBQUQsQ0FBQyw4REFBSztRQWZWLHdKQXdDQzs7UUF4Q0ssd0RBQUM7O0lBbUNJLDRFQUFLLENBQUMsR0FBSixDQUFLO0lBSUUsNkZBQUssQ0FBQyxHQUFKLENBQUs7O1FBdkNyQix1REFBQyJ9,ZGVjbGFyZSB2YXIgZGVjOiBhbnk7CgpAZGVjCkBkZWMKY2xhc3MgQyB7CiAgICBAZGVjCiAgICBAZGVjCiAgICBtZXRob2QoKSB7fQoKICAgIEBkZWMKICAgIEBkZWMKICAgIGdldCB4KCkgeyByZXR1cm4gMTsgfQoKICAgIEBkZWMKICAgIEBkZWMKICAgIHNldCB4KHZhbHVlOiBudW1iZXIpIHsgfQoKICAgIEBkZWMKICAgIEBkZWMKICAgIHkgPSAxOwoKICAgIEBkZWMKICAgIEBkZWMKICAgIGFjY2Vzc29yIHogPSAxOwoKICAgIEBkZWMKICAgIEBkZWMKICAgIHN0YXRpYyAjbWV0aG9kKCkge30KCiAgICBAZGVjCiAgICBAZGVjCiAgICBzdGF0aWMgZ2V0ICN4KCkgeyByZXR1cm4gMTsgfQoKICAgIEBkZWMKICAgIEBkZWMKICAgIHN0YXRpYyBzZXQgI3godmFsdWU6IG51bWJlcikgeyB9CgogICAgQGRlYwogICAgQGRlYwogICAgc3RhdGljICN5ID0gMTsKCiAgICBAZGVjCiAgICBAZGVjCiAgICBzdGF0aWMgYWNjZXNzb3IgI3ogPSAxOwp9Cg== ++{"version":3,"file":"esDecorators-classDeclaration-sourceMap.js","sourceRoot":"","sources":["esDecorators-classDeclaration-sourceMap.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;IAIM,CAAC;;4BAFN,GAAG,EACH,GAAG;;;;;;;;;;;;;;;;;;;;;;;;;;YAgBA,MAAC,kGAAG,CAAC,GAAC;YAIG,2EAAI,CAAC,GAAC;QAqBnB,CAAC;QArCG,MAAM,KAAI,CAAC;QAIX,IAAI,CAAC,KAAK,OAAO,CAAC,CAAC,CAAC,CAAC;QAIrB,IAAI,CAAC,CAAC,KAAa,IAAI,CAAC;QAQxB,IAAS,CAAC,yEAAK;QAAf,IAAS,CAAC,8EAAK;;;;;;;;;;8BAlBd,GAAG,EACH,GAAG;6BAGH,GAAG,EACH,GAAG;6BAGH,GAAG,EACH,GAAG;yBAGH,GAAG,EACH,GAAG;yBAGH,GAAG,EACH,GAAG;6CAGH,GAAG,EACH,GAAG;4CAGH,GAAG,EACH,GAAG;4CAGH,GAAG,EACH,GAAG;wCAGH,GAAG,EACH,GAAG;wCAGH,GAAG,EACH,GAAG;QAfJ,+DAAA,yBAAA,cAAkB,CAAC,YAAA,kRAAA;QAInB,8DAAA,uBAAA,cAAkB,OAAO,CAAC,CAAC,CAAC,CAAC,cAAA,uQAAA;QAI7B,8DAAA,uBAAA,UAAc,KAAa,IAAI,CAAC,cAAA,4RAAA;QAQhC,0DAAA,uBAAA,kGAAuB,cAAA,EAAvB,uBAAA,uGAAuB,cAAA,wXAAA;QApCvB,2KAAA,MAAM,wCAAK;QAIX,gKAAI,CAAC,wCAAgB;QAIrB,2KAAI,CAAC,mDAAmB;QAQxB,8JAAS,CAAC,6BAAD,CAAC,8DAAK;QAgBf,kYAAc;QApBd,qJAAA,CAAC,6BAAD,CAAC,8DAAK;QAfV,wJAwCC;;QAxCK,wDAAC;;IAmCI,8EAAK,CAAC,GAAJ,CAAK;IAIE,+FAAK,CAAC,GAAJ,CAAK;;QAvCrB,uDAAC"} ++//// https://sokra.github.io/source-map-visualization#base64,dmFyIF9fZXNEZWNvcmF0ZSA9ICh0aGlzICYmIHRoaXMuX19lc0RlY29yYXRlKSB8fCBmdW5jdGlvbiAoY3RvciwgZGVzY3JpcHRvckluLCBkZWNvcmF0b3JzLCBjb250ZXh0SW4sIGluaXRpYWxpemVycywgZXh0cmFJbml0aWFsaXplcnMpIHsNCiAgICBmdW5jdGlvbiBhY2NlcHQoZikgeyBpZiAoZiAhPT0gdm9pZCAwICYmIHR5cGVvZiBmICE9PSAiZnVuY3Rpb24iKSB0aHJvdyBuZXcgVHlwZUVycm9yKCJGdW5jdGlvbiBleHBlY3RlZCIpOyByZXR1cm4gZjsgfQ0KICAgIHZhciBraW5kID0gY29udGV4dEluLmtpbmQsIGtleSA9IGtpbmQgPT09ICJnZXR0ZXIiID8gImdldCIgOiBraW5kID09PSAic2V0dGVyIiA/ICJzZXQiIDogInZhbHVlIjsNCiAgICB2YXIgdGFyZ2V0ID0gIWRlc2NyaXB0b3JJbiAmJiBjdG9yID8gY29udGV4dEluWyJzdGF0aWMiXSA/IGN0b3IgOiBjdG9yLnByb3RvdHlwZSA6IG51bGw7DQogICAgdmFyIGRlc2NyaXB0b3IgPSBkZXNjcmlwdG9ySW4gfHwgKHRhcmdldCA/IE9iamVjdC5nZXRPd25Qcm9wZXJ0eURlc2NyaXB0b3IodGFyZ2V0LCBjb250ZXh0SW4ubmFtZSkgOiB7fSk7DQogICAgdmFyIF8sIGRvbmUgPSBmYWxzZTsNCiAgICBmb3IgKHZhciBpID0gZGVjb3JhdG9ycy5sZW5ndGggLSAxOyBpID49IDA7IGktLSkgew0KICAgICAgICB2YXIgY29udGV4dCA9IHt9Ow0KICAgICAgICBmb3IgKHZhciBwIGluIGNvbnRleHRJbikgY29udGV4dFtwXSA9IHAgPT09ICJhY2Nlc3MiID8ge30gOiBjb250ZXh0SW5bcF07DQogICAgICAgIGZvciAodmFyIHAgaW4gY29udGV4dEluLmFjY2VzcykgY29udGV4dC5hY2Nlc3NbcF0gPSBjb250ZXh0SW4uYWNjZXNzW3BdOw0KICAgICAgICBjb250ZXh0LmFkZEluaXRpYWxpemVyID0gZnVuY3Rpb24gKGYpIHsgaWYgKGRvbmUpIHRocm93IG5ldyBUeXBlRXJyb3IoIkNhbm5vdCBhZGQgaW5pdGlhbGl6ZXJzIGFmdGVyIGRlY29yYXRpb24gaGFzIGNvbXBsZXRlZCIpOyBleHRyYUluaXRpYWxpemVycy5wdXNoKGFjY2VwdChmIHx8IG51bGwpKTsgfTsNCiAgICAgICAgdmFyIHJlc3VsdCA9ICgwLCBkZWNvcmF0b3JzW2ldKShraW5kID09PSAiYWNjZXNzb3IiID8geyBnZXQ6IGRlc2NyaXB0b3IuZ2V0LCBzZXQ6IGRlc2NyaXB0b3Iuc2V0IH0gOiBkZXNjcmlwdG9yW2tleV0sIGNvbnRleHQpOw0KICAgICAgICBpZiAoa2luZCA9PT0gImFjY2Vzc29yIikgew0KICAgICAgICAgICAgaWYgKHJlc3VsdCA9PT0gdm9pZCAwKSBjb250aW51ZTsNCiAgICAgICAgICAgIGlmIChyZXN1bHQgPT09IG51bGwgfHwgdHlwZW9mIHJlc3VsdCAhPT0gIm9iamVjdCIpIHRocm93IG5ldyBUeXBlRXJyb3IoIk9iamVjdCBleHBlY3RlZCIpOw0KICAgICAgICAgICAgaWYgKF8gPSBhY2NlcHQocmVzdWx0LmdldCkpIGRlc2NyaXB0b3IuZ2V0ID0gXzsNCiAgICAgICAgICAgIGlmIChfID0gYWNjZXB0KHJlc3VsdC5zZXQpKSBkZXNjcmlwdG9yLnNldCA9IF87DQogICAgICAgICAgICBpZiAoXyA9IGFjY2VwdChyZXN1bHQuaW5pdCkpIGluaXRpYWxpemVycy51bnNoaWZ0KF8pOw0KICAgICAgICB9DQogICAgICAgIGVsc2UgaWYgKF8gPSBhY2NlcHQocmVzdWx0KSkgew0KICAgICAgICAgICAgaWYgKGtpbmQgPT09ICJmaWVsZCIpIGluaXRpYWxpemVycy51bnNoaWZ0KF8pOw0KICAgICAgICAgICAgZWxzZSBkZXNjcmlwdG9yW2tleV0gPSBfOw0KICAgICAgICB9DQogICAgfQ0KICAgIGlmICh0YXJnZXQpIE9iamVjdC5kZWZpbmVQcm9wZXJ0eSh0YXJnZXQsIGNvbnRleHRJbi5uYW1lLCBkZXNjcmlwdG9yKTsNCiAgICBkb25lID0gdHJ1ZTsNCn07DQp2YXIgX19ydW5Jbml0aWFsaXplcnMgPSAodGhpcyAmJiB0aGlzLl9fcnVuSW5pdGlhbGl6ZXJzKSB8fCBmdW5jdGlvbiAodGhpc0FyZywgaW5pdGlhbGl6ZXJzLCB2YWx1ZSkgew0KICAgIHZhciB1c2VWYWx1ZSA9IGFyZ3VtZW50cy5sZW5ndGggPiAyOw0KICAgIGZvciAodmFyIGkgPSAwOyBpIDwgaW5pdGlhbGl6ZXJzLmxlbmd0aDsgaSsrKSB7DQogICAgICAgIHZhbHVlID0gdXNlVmFsdWUgPyBpbml0aWFsaXplcnNbaV0uY2FsbCh0aGlzQXJnLCB2YWx1ZSkgOiBpbml0aWFsaXplcnNbaV0uY2FsbCh0aGlzQXJnKTsNCiAgICB9DQogICAgcmV0dXJuIHVzZVZhbHVlID8gdmFsdWUgOiB2b2lkIDA7DQp9Ow0KdmFyIF9fc2V0RnVuY3Rpb25OYW1lID0gKHRoaXMgJiYgdGhpcy5fX3NldEZ1bmN0aW9uTmFtZSkgfHwgZnVuY3Rpb24gKGYsIG5hbWUsIHByZWZpeCkgew0KICAgIGlmICh0eXBlb2YgbmFtZSA9PT0gInN5bWJvbCIpIG5hbWUgPSBuYW1lLmRlc2NyaXB0aW9uID8gIlsiLmNvbmNhdChuYW1lLmRlc2NyaXB0aW9uLCAiXSIpIDogIiI7DQogICAgcmV0dXJuIE9iamVjdC5kZWZpbmVQcm9wZXJ0eShmLCAibmFtZSIsIHsgY29uZmlndXJhYmxlOiB0cnVlLCB2YWx1ZTogcHJlZml4ID8gIiIuY29uY2F0KHByZWZpeCwgIiAiLCBuYW1lKSA6IG5hbWUgfSk7DQp9Ow0KdmFyIF9fY2xhc3NQcml2YXRlRmllbGRHZXQgPSAodGhpcyAmJiB0aGlzLl9fY2xhc3NQcml2YXRlRmllbGRHZXQpIHx8IGZ1bmN0aW9uIChyZWNlaXZlciwgc3RhdGUsIGtpbmQsIGYpIHsNCiAgICBpZiAoa2luZCA9PT0gImEiICYmICFmKSB0aHJvdyBuZXcgVHlwZUVycm9yKCJQcml2YXRlIGFjY2Vzc29yIHdhcyBkZWZpbmVkIHdpdGhvdXQgYSBnZXR0ZXIiKTsNCiAgICBpZiAodHlwZW9mIHN0YXRlID09PSAiZnVuY3Rpb24iID8gcmVjZWl2ZXIgIT09IHN0YXRlIHx8ICFmIDogIXN0YXRlLmhhcyhyZWNlaXZlcikpIHRocm93IG5ldyBUeXBlRXJyb3IoIkNhbm5vdCByZWFkIHByaXZhdGUgbWVtYmVyIGZyb20gYW4gb2JqZWN0IHdob3NlIGNsYXNzIGRpZCBub3QgZGVjbGFyZSBpdCIpOw0KICAgIHJldHVybiBraW5kID09PSAibSIgPyBmIDoga2luZCA9PT0gImEiID8gZi5jYWxsKHJlY2VpdmVyKSA6IGYgPyBmLnZhbHVlIDogc3RhdGUuZ2V0KHJlY2VpdmVyKTsNCn07DQp2YXIgX19jbGFzc1ByaXZhdGVGaWVsZFNldCA9ICh0aGlzICYmIHRoaXMuX19jbGFzc1ByaXZhdGVGaWVsZFNldCkgfHwgZnVuY3Rpb24gKHJlY2VpdmVyLCBzdGF0ZSwgdmFsdWUsIGtpbmQsIGYpIHsNCiAgICBpZiAoa2luZCA9PT0gIm0iKSB0aHJvdyBuZXcgVHlwZUVycm9yKCJQcml2YXRlIG1ldGhvZCBpcyBub3Qgd3JpdGFibGUiKTsNCiAgICBpZiAoa2luZCA9PT0gImEiICYmICFmKSB0aHJvdyBuZXcgVHlwZUVycm9yKCJQcml2YXRlIGFjY2Vzc29yIHdhcyBkZWZpbmVkIHdpdGhvdXQgYSBzZXR0ZXIiKTsNCiAgICBpZiAodHlwZW9mIHN0YXRlID09PSAiZnVuY3Rpb24iID8gcmVjZWl2ZXIgIT09IHN0YXRlIHx8ICFmIDogIXN0YXRlLmhhcyhyZWNlaXZlcikpIHRocm93IG5ldyBUeXBlRXJyb3IoIkNhbm5vdCB3cml0ZSBwcml2YXRlIG1lbWJlciB0byBhbiBvYmplY3Qgd2hvc2UgY2xhc3MgZGlkIG5vdCBkZWNsYXJlIGl0Iik7DQogICAgcmV0dXJuIChraW5kID09PSAiYSIgPyBmLmNhbGwocmVjZWl2ZXIsIHZhbHVlKSA6IGYgPyBmLnZhbHVlID0gdmFsdWUgOiBzdGF0ZS5zZXQocmVjZWl2ZXIsIHZhbHVlKSksIHZhbHVlOw0KfTsNCnZhciBfX2NsYXNzUHJpdmF0ZUZpZWxkSW4gPSAodGhpcyAmJiB0aGlzLl9fY2xhc3NQcml2YXRlRmllbGRJbikgfHwgZnVuY3Rpb24oc3RhdGUsIHJlY2VpdmVyKSB7DQogICAgaWYgKHJlY2VpdmVyID09PSBudWxsIHx8ICh0eXBlb2YgcmVjZWl2ZXIgIT09ICJvYmplY3QiICYmIHR5cGVvZiByZWNlaXZlciAhPT0gImZ1bmN0aW9uIikpIHRocm93IG5ldyBUeXBlRXJyb3IoIkNhbm5vdCB1c2UgJ2luJyBvcGVyYXRvciBvbiBub24tb2JqZWN0Iik7DQogICAgcmV0dXJuIHR5cGVvZiBzdGF0ZSA9PT0gImZ1bmN0aW9uIiA/IHJlY2VpdmVyID09PSBzdGF0ZSA6IHN0YXRlLmhhcyhyZWNlaXZlcik7DQp9Ow0KbGV0IEMgPSAoKCkgPT4gew0KICAgIHZhciBfQ19tZXRob2RfZ2V0LCBfQ194X2dldCwgX0NfeF9zZXQsIF9DX3ksIF9DX3pfYWNjZXNzb3Jfc3RvcmFnZSwgX0Nfel9nZXQsIF9DX3pfc2V0LCBfQ196XzFfYWNjZXNzb3Jfc3RvcmFnZTsNCiAgICBsZXQgX2NsYXNzRGVjb3JhdG9ycyA9IFtkZWMsIGRlY107DQogICAgbGV0IF9jbGFzc0Rlc2NyaXB0b3I7DQogICAgbGV0IF9jbGFzc0V4dHJhSW5pdGlhbGl6ZXJzID0gW107DQogICAgbGV0IF9jbGFzc1RoaXM7DQogICAgbGV0IF9zdGF0aWNFeHRyYUluaXRpYWxpemVycyA9IFtdOw0KICAgIGxldCBfaW5zdGFuY2VFeHRyYUluaXRpYWxpemVycyA9IFtdOw0KICAgIGxldCBfc3RhdGljX3ByaXZhdGVfbWV0aG9kX2RlY29yYXRvcnM7DQogICAgbGV0IF9zdGF0aWNfcHJpdmF0ZV9tZXRob2RfZGVzY3JpcHRvcjsNCiAgICBsZXQgX3N0YXRpY19wcml2YXRlX2dldF94X2RlY29yYXRvcnM7DQogICAgbGV0IF9zdGF0aWNfcHJpdmF0ZV9nZXRfeF9kZXNjcmlwdG9yOw0KICAgIGxldCBfc3RhdGljX3ByaXZhdGVfc2V0X3hfZGVjb3JhdG9yczsNCiAgICBsZXQgX3N0YXRpY19wcml2YXRlX3NldF94X2Rlc2NyaXB0b3I7DQogICAgbGV0IF9zdGF0aWNfcHJpdmF0ZV95X2RlY29yYXRvcnM7DQogICAgbGV0IF9zdGF0aWNfcHJpdmF0ZV95X2luaXRpYWxpemVycyA9IFtdOw0KICAgIGxldCBfc3RhdGljX3ByaXZhdGVfel9kZWNvcmF0b3JzOw0KICAgIGxldCBfc3RhdGljX3ByaXZhdGVfel9pbml0aWFsaXplcnMgPSBbXTsNCiAgICBsZXQgX3N0YXRpY19wcml2YXRlX3pfZGVzY3JpcHRvcjsNCiAgICBsZXQgX21ldGhvZF9kZWNvcmF0b3JzOw0KICAgIGxldCBfZ2V0X3hfZGVjb3JhdG9yczsNCiAgICBsZXQgX3NldF94X2RlY29yYXRvcnM7DQogICAgbGV0IF95X2RlY29yYXRvcnM7DQogICAgbGV0IF95X2luaXRpYWxpemVycyA9IFtdOw0KICAgIGxldCBfel9kZWNvcmF0b3JzOw0KICAgIGxldCBfel9pbml0aWFsaXplcnMgPSBbXTsNCiAgICB2YXIgQyA9IF9jbGFzc1RoaXMgPSBjbGFzcyB7DQogICAgICAgIGNvbnN0cnVjdG9yKCkgew0KICAgICAgICAgICAgdGhpcy55ID0gKF9fcnVuSW5pdGlhbGl6ZXJzKHRoaXMsIF9pbnN0YW5jZUV4dHJhSW5pdGlhbGl6ZXJzKSwgX19ydW5Jbml0aWFsaXplcnModGhpcywgX3lfaW5pdGlhbGl6ZXJzLCAxKSk7DQogICAgICAgICAgICBfQ196XzFfYWNjZXNzb3Jfc3RvcmFnZS5zZXQodGhpcywgX19ydW5Jbml0aWFsaXplcnModGhpcywgX3pfaW5pdGlhbGl6ZXJzLCAxKSk7DQogICAgICAgIH0NCiAgICAgICAgbWV0aG9kKCkgeyB9DQogICAgICAgIGdldCB4KCkgeyByZXR1cm4gMTsgfQ0KICAgICAgICBzZXQgeCh2YWx1ZSkgeyB9DQogICAgICAgIGdldCB6KCkgeyByZXR1cm4gX19jbGFzc1ByaXZhdGVGaWVsZEdldCh0aGlzLCBfQ196XzFfYWNjZXNzb3Jfc3RvcmFnZSwgImYiKTsgfQ0KICAgICAgICBzZXQgeih2YWx1ZSkgeyBfX2NsYXNzUHJpdmF0ZUZpZWxkU2V0KHRoaXMsIF9DX3pfMV9hY2Nlc3Nvcl9zdG9yYWdlLCB2YWx1ZSwgImYiKTsgfQ0KICAgIH07DQogICAgX0Nfel8xX2FjY2Vzc29yX3N0b3JhZ2UgPSBuZXcgV2Vha01hcCgpOw0KICAgIF9DX21ldGhvZF9nZXQgPSBmdW5jdGlvbiBfQ19tZXRob2RfZ2V0KCkgeyByZXR1cm4gX3N0YXRpY19wcml2YXRlX21ldGhvZF9kZXNjcmlwdG9yLnZhbHVlOyB9Ow0KICAgIF9DX3hfZ2V0ID0gZnVuY3Rpb24gX0NfeF9nZXQoKSB7IHJldHVybiBfc3RhdGljX3ByaXZhdGVfZ2V0X3hfZGVzY3JpcHRvci5nZXQuY2FsbCh0aGlzKTsgfTsNCiAgICBfQ194X3NldCA9IGZ1bmN0aW9uIF9DX3hfc2V0KHZhbHVlKSB7IHJldHVybiBfc3RhdGljX3ByaXZhdGVfc2V0X3hfZGVzY3JpcHRvci5zZXQuY2FsbCh0aGlzLCB2YWx1ZSk7IH07DQogICAgX0Nfel9nZXQgPSBmdW5jdGlvbiBfQ196X2dldCgpIHsgcmV0dXJuIF9zdGF0aWNfcHJpdmF0ZV96X2Rlc2NyaXB0b3IuZ2V0LmNhbGwodGhpcyk7IH07DQogICAgX0Nfel9zZXQgPSBmdW5jdGlvbiBfQ196X3NldCh2YWx1ZSkgeyByZXR1cm4gX3N0YXRpY19wcml2YXRlX3pfZGVzY3JpcHRvci5zZXQuY2FsbCh0aGlzLCB2YWx1ZSk7IH07DQogICAgX19zZXRGdW5jdGlvbk5hbWUoX2NsYXNzVGhpcywgIkMiKTsNCiAgICAoKCkgPT4gew0KICAgICAgICBfbWV0aG9kX2RlY29yYXRvcnMgPSBbZGVjLCBkZWNdOw0KICAgICAgICBfZ2V0X3hfZGVjb3JhdG9ycyA9IFtkZWMsIGRlY107DQogICAgICAgIF9zZXRfeF9kZWNvcmF0b3JzID0gW2RlYywgZGVjXTsNCiAgICAgICAgX3lfZGVjb3JhdG9ycyA9IFtkZWMsIGRlY107DQogICAgICAgIF96X2RlY29yYXRvcnMgPSBbZGVjLCBkZWNdOw0KICAgICAgICBfc3RhdGljX3ByaXZhdGVfbWV0aG9kX2RlY29yYXRvcnMgPSBbZGVjLCBkZWNdOw0KICAgICAgICBfc3RhdGljX3ByaXZhdGVfZ2V0X3hfZGVjb3JhdG9ycyA9IFtkZWMsIGRlY107DQogICAgICAgIF9zdGF0aWNfcHJpdmF0ZV9zZXRfeF9kZWNvcmF0b3JzID0gW2RlYywgZGVjXTsNCiAgICAgICAgX3N0YXRpY19wcml2YXRlX3lfZGVjb3JhdG9ycyA9IFtkZWMsIGRlY107DQogICAgICAgIF9zdGF0aWNfcHJpdmF0ZV96X2RlY29yYXRvcnMgPSBbZGVjLCBkZWNdOw0KICAgICAgICBfX2VzRGVjb3JhdGUoX2NsYXNzVGhpcywgX3N0YXRpY19wcml2YXRlX21ldGhvZF9kZXNjcmlwdG9yID0geyB2YWx1ZTogX19zZXRGdW5jdGlvbk5hbWUoZnVuY3Rpb24gKCkgeyB9LCAiI21ldGhvZCIpIH0sIF9zdGF0aWNfcHJpdmF0ZV9tZXRob2RfZGVjb3JhdG9ycywgeyBraW5kOiAibWV0aG9kIiwgbmFtZTogIiNtZXRob2QiLCBzdGF0aWM6IHRydWUsIHByaXZhdGU6IHRydWUsIGFjY2VzczogeyBoYXM6IG9iaiA9PiBfX2NsYXNzUHJpdmF0ZUZpZWxkSW4oX2NsYXNzVGhpcywgb2JqKSwgZ2V0OiBvYmogPT4gX19jbGFzc1ByaXZhdGVGaWVsZEdldChvYmosIF9jbGFzc1RoaXMsICJhIiwgX0NfbWV0aG9kX2dldCkgfSB9LCBudWxsLCBfc3RhdGljRXh0cmFJbml0aWFsaXplcnMpOw0KICAgICAgICBfX2VzRGVjb3JhdGUoX2NsYXNzVGhpcywgX3N0YXRpY19wcml2YXRlX2dldF94X2Rlc2NyaXB0b3IgPSB7IGdldDogX19zZXRGdW5jdGlvbk5hbWUoZnVuY3Rpb24gKCkgeyByZXR1cm4gMTsgfSwgIiN4IiwgImdldCIpIH0sIF9zdGF0aWNfcHJpdmF0ZV9nZXRfeF9kZWNvcmF0b3JzLCB7IGtpbmQ6ICJnZXR0ZXIiLCBuYW1lOiAiI3giLCBzdGF0aWM6IHRydWUsIHByaXZhdGU6IHRydWUsIGFjY2VzczogeyBoYXM6IG9iaiA9PiBfX2NsYXNzUHJpdmF0ZUZpZWxkSW4oX2NsYXNzVGhpcywgb2JqKSwgZ2V0OiBvYmogPT4gX19jbGFzc1ByaXZhdGVGaWVsZEdldChvYmosIF9jbGFzc1RoaXMsICJhIiwgX0NfeF9nZXQpIH0gfSwgbnVsbCwgX3N0YXRpY0V4dHJhSW5pdGlhbGl6ZXJzKTsNCiAgICAgICAgX19lc0RlY29yYXRlKF9jbGFzc1RoaXMsIF9zdGF0aWNfcHJpdmF0ZV9zZXRfeF9kZXNjcmlwdG9yID0geyBzZXQ6IF9fc2V0RnVuY3Rpb25OYW1lKGZ1bmN0aW9uICh2YWx1ZSkgeyB9LCAiI3giLCAic2V0IikgfSwgX3N0YXRpY19wcml2YXRlX3NldF94X2RlY29yYXRvcnMsIHsga2luZDogInNldHRlciIsIG5hbWU6ICIjeCIsIHN0YXRpYzogdHJ1ZSwgcHJpdmF0ZTogdHJ1ZSwgYWNjZXNzOiB7IGhhczogb2JqID0+IF9fY2xhc3NQcml2YXRlRmllbGRJbihfY2xhc3NUaGlzLCBvYmopLCBzZXQ6IChvYmosIHZhbHVlKSA9PiB7IF9fY2xhc3NQcml2YXRlRmllbGRTZXQob2JqLCBfY2xhc3NUaGlzLCB2YWx1ZSwgImEiLCBfQ194X3NldCk7IH0gfSB9LCBudWxsLCBfc3RhdGljRXh0cmFJbml0aWFsaXplcnMpOw0KICAgICAgICBfX2VzRGVjb3JhdGUoX2NsYXNzVGhpcywgX3N0YXRpY19wcml2YXRlX3pfZGVzY3JpcHRvciA9IHsgZ2V0OiBfX3NldEZ1bmN0aW9uTmFtZShmdW5jdGlvbiAoKSB7IHJldHVybiBfX2NsYXNzUHJpdmF0ZUZpZWxkR2V0KF9jbGFzc1RoaXMsIF9jbGFzc1RoaXMsICJmIiwgX0Nfel9hY2Nlc3Nvcl9zdG9yYWdlKTsgfSwgIiN6IiwgImdldCIpLCBzZXQ6IF9fc2V0RnVuY3Rpb25OYW1lKGZ1bmN0aW9uICh2YWx1ZSkgeyBfX2NsYXNzUHJpdmF0ZUZpZWxkU2V0KF9jbGFzc1RoaXMsIF9jbGFzc1RoaXMsIHZhbHVlLCAiZiIsIF9DX3pfYWNjZXNzb3Jfc3RvcmFnZSk7IH0sICIjeiIsICJzZXQiKSB9LCBfc3RhdGljX3ByaXZhdGVfel9kZWNvcmF0b3JzLCB7IGtpbmQ6ICJhY2Nlc3NvciIsIG5hbWU6ICIjeiIsIHN0YXRpYzogdHJ1ZSwgcHJpdmF0ZTogdHJ1ZSwgYWNjZXNzOiB7IGhhczogb2JqID0+IF9fY2xhc3NQcml2YXRlRmllbGRJbihfY2xhc3NUaGlzLCBvYmopLCBnZXQ6IG9iaiA9PiBfX2NsYXNzUHJpdmF0ZUZpZWxkR2V0KG9iaiwgX2NsYXNzVGhpcywgImEiLCBfQ196X2dldCksIHNldDogKG9iaiwgdmFsdWUpID0+IHsgX19jbGFzc1ByaXZhdGVGaWVsZFNldChvYmosIF9jbGFzc1RoaXMsIHZhbHVlLCAiYSIsIF9DX3pfc2V0KTsgfSB9IH0sIF9zdGF0aWNfcHJpdmF0ZV96X2luaXRpYWxpemVycywgX3N0YXRpY0V4dHJhSW5pdGlhbGl6ZXJzKTsNCiAgICAgICAgX19lc0RlY29yYXRlKF9jbGFzc1RoaXMsIG51bGwsIF9tZXRob2RfZGVjb3JhdG9ycywgeyBraW5kOiAibWV0aG9kIiwgbmFtZTogIm1ldGhvZCIsIHN0YXRpYzogZmFsc2UsIHByaXZhdGU6IGZhbHNlLCBhY2Nlc3M6IHsgaGFzOiBvYmogPT4gIm1ldGhvZCIgaW4gb2JqLCBnZXQ6IG9iaiA9PiBvYmoubWV0aG9kIH0gfSwgbnVsbCwgX2luc3RhbmNlRXh0cmFJbml0aWFsaXplcnMpOw0KICAgICAgICBfX2VzRGVjb3JhdGUoX2NsYXNzVGhpcywgbnVsbCwgX2dldF94X2RlY29yYXRvcnMsIHsga2luZDogImdldHRlciIsIG5hbWU6ICJ4Iiwgc3RhdGljOiBmYWxzZSwgcHJpdmF0ZTogZmFsc2UsIGFjY2VzczogeyBoYXM6IG9iaiA9PiAieCIgaW4gb2JqLCBnZXQ6IG9iaiA9PiBvYmoueCB9IH0sIG51bGwsIF9pbnN0YW5jZUV4dHJhSW5pdGlhbGl6ZXJzKTsNCiAgICAgICAgX19lc0RlY29yYXRlKF9jbGFzc1RoaXMsIG51bGwsIF9zZXRfeF9kZWNvcmF0b3JzLCB7IGtpbmQ6ICJzZXR0ZXIiLCBuYW1lOiAieCIsIHN0YXRpYzogZmFsc2UsIHByaXZhdGU6IGZhbHNlLCBhY2Nlc3M6IHsgaGFzOiBvYmogPT4gIngiIGluIG9iaiwgc2V0OiAob2JqLCB2YWx1ZSkgPT4geyBvYmoueCA9IHZhbHVlOyB9IH0gfSwgbnVsbCwgX2luc3RhbmNlRXh0cmFJbml0aWFsaXplcnMpOw0KICAgICAgICBfX2VzRGVjb3JhdGUoX2NsYXNzVGhpcywgbnVsbCwgX3pfZGVjb3JhdG9ycywgeyBraW5kOiAiYWNjZXNzb3IiLCBuYW1lOiAieiIsIHN0YXRpYzogZmFsc2UsIHByaXZhdGU6IGZhbHNlLCBhY2Nlc3M6IHsgaGFzOiBvYmogPT4gInoiIGluIG9iaiwgZ2V0OiBvYmogPT4gb2JqLnosIHNldDogKG9iaiwgdmFsdWUpID0+IHsgb2JqLnogPSB2YWx1ZTsgfSB9IH0sIF96X2luaXRpYWxpemVycywgX2luc3RhbmNlRXh0cmFJbml0aWFsaXplcnMpOw0KICAgICAgICBfX2VzRGVjb3JhdGUobnVsbCwgbnVsbCwgX3N0YXRpY19wcml2YXRlX3lfZGVjb3JhdG9ycywgeyBraW5kOiAiZmllbGQiLCBuYW1lOiAiI3kiLCBzdGF0aWM6IHRydWUsIHByaXZhdGU6IHRydWUsIGFjY2VzczogeyBoYXM6IG9iaiA9PiBfX2NsYXNzUHJpdmF0ZUZpZWxkSW4oX2NsYXNzVGhpcywgb2JqKSwgZ2V0OiBvYmogPT4gX19jbGFzc1ByaXZhdGVGaWVsZEdldChvYmosIF9jbGFzc1RoaXMsICJmIiwgX0NfeSksIHNldDogKG9iaiwgdmFsdWUpID0+IHsgX19jbGFzc1ByaXZhdGVGaWVsZFNldChvYmosIF9jbGFzc1RoaXMsIHZhbHVlLCAiZiIsIF9DX3kpOyB9IH0gfSwgX3N0YXRpY19wcml2YXRlX3lfaW5pdGlhbGl6ZXJzLCBfc3RhdGljRXh0cmFJbml0aWFsaXplcnMpOw0KICAgICAgICBfX2VzRGVjb3JhdGUobnVsbCwgbnVsbCwgX3lfZGVjb3JhdG9ycywgeyBraW5kOiAiZmllbGQiLCBuYW1lOiAieSIsIHN0YXRpYzogZmFsc2UsIHByaXZhdGU6IGZhbHNlLCBhY2Nlc3M6IHsgaGFzOiBvYmogPT4gInkiIGluIG9iaiwgZ2V0OiBvYmogPT4gb2JqLnksIHNldDogKG9iaiwgdmFsdWUpID0+IHsgb2JqLnkgPSB2YWx1ZTsgfSB9IH0sIF95X2luaXRpYWxpemVycywgX2luc3RhbmNlRXh0cmFJbml0aWFsaXplcnMpOw0KICAgICAgICBfX2VzRGVjb3JhdGUobnVsbCwgX2NsYXNzRGVzY3JpcHRvciA9IHsgdmFsdWU6IF9jbGFzc1RoaXMgfSwgX2NsYXNzRGVjb3JhdG9ycywgeyBraW5kOiAiY2xhc3MiLCBuYW1lOiBfY2xhc3NUaGlzLm5hbWUgfSwgbnVsbCwgX2NsYXNzRXh0cmFJbml0aWFsaXplcnMpOw0KICAgICAgICBDID0gX2NsYXNzVGhpcyA9IF9jbGFzc0Rlc2NyaXB0b3IudmFsdWU7DQogICAgICAgIF9fcnVuSW5pdGlhbGl6ZXJzKF9jbGFzc1RoaXMsIF9zdGF0aWNFeHRyYUluaXRpYWxpemVycyk7DQogICAgfSkoKTsNCiAgICBfQ195ID0geyB2YWx1ZTogX19ydW5Jbml0aWFsaXplcnMoX2NsYXNzVGhpcywgX3N0YXRpY19wcml2YXRlX3lfaW5pdGlhbGl6ZXJzLCAxKSB9Ow0KICAgIF9DX3pfYWNjZXNzb3Jfc3RvcmFnZSA9IHsgdmFsdWU6IF9fcnVuSW5pdGlhbGl6ZXJzKF9jbGFzc1RoaXMsIF9zdGF0aWNfcHJpdmF0ZV96X2luaXRpYWxpemVycywgMSkgfTsNCiAgICAoKCkgPT4gew0KICAgICAgICBfX3J1bkluaXRpYWxpemVycyhfY2xhc3NUaGlzLCBfY2xhc3NFeHRyYUluaXRpYWxpemVycyk7DQogICAgfSkoKTsNCiAgICByZXR1cm4gQyA9IF9jbGFzc1RoaXM7DQp9KSgpOw0KLy8jIHNvdXJjZU1hcHBpbmdVUkw9ZXNEZWNvcmF0b3JzLWNsYXNzRGVjbGFyYXRpb24tc291cmNlTWFwLmpzLm1hcA==,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiZXNEZWNvcmF0b3JzLWNsYXNzRGVjbGFyYXRpb24tc291cmNlTWFwLmpzIiwic291cmNlUm9vdCI6IiIsInNvdXJjZXMiOlsiZXNEZWNvcmF0b3JzLWNsYXNzRGVjbGFyYXRpb24tc291cmNlTWFwLnRzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiI7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7O0lBSU0sQ0FBQzs7NEJBRk4sR0FBRyxFQUNILEdBQUc7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7O1lBZ0JBLE1BQUMsa0dBQUcsQ0FBQyxHQUFDO1lBSUcsMkVBQUksQ0FBQyxHQUFDO1FBcUJuQixDQUFDO1FBckNHLE1BQU0sS0FBSSxDQUFDO1FBSVgsSUFBSSxDQUFDLEtBQUssT0FBTyxDQUFDLENBQUMsQ0FBQyxDQUFDO1FBSXJCLElBQUksQ0FBQyxDQUFDLEtBQWEsSUFBSSxDQUFDO1FBUXhCLElBQVMsQ0FBQyx5RUFBSztRQUFmLElBQVMsQ0FBQyw4RUFBSzs7Ozs7Ozs7Ozs4QkFsQmQsR0FBRyxFQUNILEdBQUc7NkJBR0gsR0FBRyxFQUNILEdBQUc7NkJBR0gsR0FBRyxFQUNILEdBQUc7eUJBR0gsR0FBRyxFQUNILEdBQUc7eUJBR0gsR0FBRyxFQUNILEdBQUc7NkNBR0gsR0FBRyxFQUNILEdBQUc7NENBR0gsR0FBRyxFQUNILEdBQUc7NENBR0gsR0FBRyxFQUNILEdBQUc7d0NBR0gsR0FBRyxFQUNILEdBQUc7d0NBR0gsR0FBRyxFQUNILEdBQUc7UUFmSiwrREFBQSx5QkFBQSxjQUFrQixDQUFDLFlBQUEsa1JBQUE7UUFJbkIsOERBQUEsdUJBQUEsY0FBa0IsT0FBTyxDQUFDLENBQUMsQ0FBQyxDQUFDLGNBQUEsdVFBQUE7UUFJN0IsOERBQUEsdUJBQUEsVUFBYyxLQUFhLElBQUksQ0FBQyxjQUFBLDRSQUFBO1FBUWhDLDBEQUFBLHVCQUFBLGtHQUF1QixjQUFBLEVBQXZCLHVCQUFBLHVHQUF1QixjQUFBLHdYQUFBO1FBcEN2QiwyS0FBQSxNQUFNLHdDQUFLO1FBSVgsZ0tBQUksQ0FBQyx3Q0FBZ0I7UUFJckIsMktBQUksQ0FBQyxtREFBbUI7UUFReEIsOEpBQVMsQ0FBQyw2QkFBRCxDQUFDLDhEQUFLO1FBZ0JmLGtZQUFjO1FBcEJkLHFKQUFBLENBQUMsNkJBQUQsQ0FBQyw4REFBSztRQWZWLHdKQXdDQzs7UUF4Q0ssd0RBQUM7O0lBbUNJLDhFQUFLLENBQUMsR0FBSixDQUFLO0lBSUUsK0ZBQUssQ0FBQyxHQUFKLENBQUs7O1FBdkNyQix1REFBQyJ9,ZGVjbGFyZSB2YXIgZGVjOiBhbnk7CgpAZGVjCkBkZWMKY2xhc3MgQyB7CiAgICBAZGVjCiAgICBAZGVjCiAgICBtZXRob2QoKSB7fQoKICAgIEBkZWMKICAgIEBkZWMKICAgIGdldCB4KCkgeyByZXR1cm4gMTsgfQoKICAgIEBkZWMKICAgIEBkZWMKICAgIHNldCB4KHZhbHVlOiBudW1iZXIpIHsgfQoKICAgIEBkZWMKICAgIEBkZWMKICAgIHkgPSAxOwoKICAgIEBkZWMKICAgIEBkZWMKICAgIGFjY2Vzc29yIHogPSAxOwoKICAgIEBkZWMKICAgIEBkZWMKICAgIHN0YXRpYyAjbWV0aG9kKCkge30KCiAgICBAZGVjCiAgICBAZGVjCiAgICBzdGF0aWMgZ2V0ICN4KCkgeyByZXR1cm4gMTsgfQoKICAgIEBkZWMKICAgIEBkZWMKICAgIHN0YXRpYyBzZXQgI3godmFsdWU6IG51bWJlcikgeyB9CgogICAgQGRlYwogICAgQGRlYwogICAgc3RhdGljICN5ID0gMTsKCiAgICBAZGVjCiAgICBAZGVjCiAgICBzdGF0aWMgYWNjZXNzb3IgI3ogPSAxOwp9Cg== + + //// [esDecorators-classDeclaration-sourceMap.d.ts.map] + {"version":3,"file":"esDecorators-classDeclaration-sourceMap.d.ts","sourceRoot":"","sources":["esDecorators-classDeclaration-sourceMap.ts"],"names":[],"mappings":"AAAA,OAAO,CAAC,IAAI,GAAG,EAAE,GAAG,CAAC;AAErB,cAEM,CAAC;;IAGH,MAAM;IAEN,IAEI,CAAC,IAIQ,MAAM,CAJE;IAErB,IAEI,CAAC,CAAC,KAAK,EAAE,MAAM,EAAK;IAIxB,CAAC,SAAK;IAIN,QAAQ,CAAC,CAAC,SAAK;CAqBlB"} +diff --git a/tests/baselines/reference/esDecorators-classDeclaration-sourceMap(target=es2015).sourcemap.txt b/tests/baselines/reference/esDecorators-classDeclaration-sourceMap(target=es2015).sourcemap.txt +index 8598ca0a5..18c71aa82 100644 +--- a/tests/baselines/reference/esDecorators-classDeclaration-sourceMap(target=es2015).sourcemap.txt ++++ b/tests/baselines/reference/esDecorators-classDeclaration-sourceMap(target=es2015).sourcemap.txt +@@ -64,7 +64,7 @@ sourceFile:esDecorators-classDeclaration-sourceMap.ts + >>>let C = (() => { + 1 >^^^^ + 2 > ^ +-3 > ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^-> ++3 > ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^-> + 1 >declare var dec: any; + > + >@dec +@@ -74,7 +74,7 @@ sourceFile:esDecorators-classDeclaration-sourceMap.ts + 1 >Emitted(54, 5) Source(5, 7) + SourceIndex(0) + 2 >Emitted(54, 6) Source(5, 8) + SourceIndex(0) + --- +->>> var _method_get, _x_get, _x_set, _y, _z_accessor_storage, _z_get, _z_set, _z_1_accessor_storage; ++>>> var _C_method_get, _C_x_get, _C_x_set, _C_y, _C_z_accessor_storage, _C_z_get, _C_z_set, _C_z_1_accessor_storage; + >>> let _classDecorators = [dec, dec]; + 1->^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + 2 > ^^^ +@@ -148,23 +148,23 @@ sourceFile:esDecorators-classDeclaration-sourceMap.ts + 4 >Emitted(82, 118) Source(20, 10) + SourceIndex(0) + 5 >Emitted(82, 121) Source(20, 11) + SourceIndex(0) + --- +->>> _z_1_accessor_storage.set(this, __runInitializers(this, _z_initializers, 1)); ++>>> _C_z_1_accessor_storage.set(this, __runInitializers(this, _z_initializers, 1)); + 1 >^^^^^^^^^^^^ +-2 > ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +-3 > ^ +-4 > ^^^ ++2 > ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ++3 > ^ ++4 > ^^^ + 1 > + > + > @dec + > @dec + > accessor + 2 > z = +-3 > 1 +-4 > ; ++3 > 1 ++4 > ; + 1 >Emitted(83, 13) Source(24, 14) + SourceIndex(0) +-2 >Emitted(83, 86) Source(24, 18) + SourceIndex(0) +-3 >Emitted(83, 87) Source(24, 19) + SourceIndex(0) +-4 >Emitted(83, 90) Source(24, 20) + SourceIndex(0) ++2 >Emitted(83, 88) Source(24, 18) + SourceIndex(0) ++3 >Emitted(83, 89) Source(24, 19) + SourceIndex(0) ++4 >Emitted(83, 92) Source(24, 20) + SourceIndex(0) + --- + >>> } + 1 >^^^^^^^^ +@@ -252,7 +252,7 @@ sourceFile:esDecorators-classDeclaration-sourceMap.ts + 5 > ^^^^^ + 6 > ^^^^ + 7 > ^ +-8 > ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^-> ++8 > ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^-> + 1 > + > + > @dec +@@ -272,12 +272,12 @@ sourceFile:esDecorators-classDeclaration-sourceMap.ts + 6 >Emitted(87, 24) Source(16, 28) + SourceIndex(0) + 7 >Emitted(87, 25) Source(16, 29) + SourceIndex(0) + --- +->>> get z() { return __classPrivateFieldGet(this, _z_1_accessor_storage, "f"); } ++>>> get z() { return __classPrivateFieldGet(this, _C_z_1_accessor_storage, "f"); } + 1->^^^^^^^^ + 2 > ^^^^ + 3 > ^ +-4 > ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +-5 > ^^^^^^-> ++4 > ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ++5 > ^^^^^^-> + 1-> + > + > @dec +@@ -293,13 +293,13 @@ sourceFile:esDecorators-classDeclaration-sourceMap.ts + 1->Emitted(88, 9) Source(24, 5) + SourceIndex(0) + 2 >Emitted(88, 13) Source(24, 14) + SourceIndex(0) + 3 >Emitted(88, 14) Source(24, 15) + SourceIndex(0) +-4 >Emitted(88, 85) Source(24, 20) + SourceIndex(0) ++4 >Emitted(88, 87) Source(24, 20) + SourceIndex(0) + --- +->>> set z(value) { __classPrivateFieldSet(this, _z_1_accessor_storage, value, "f"); } ++>>> set z(value) { __classPrivateFieldSet(this, _C_z_1_accessor_storage, value, "f"); } + 1->^^^^^^^^ + 2 > ^^^^ + 3 > ^ +-4 > ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ++4 > ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + 1-> + 2 > accessor + 3 > z +@@ -307,15 +307,15 @@ sourceFile:esDecorators-classDeclaration-sourceMap.ts + 1->Emitted(89, 9) Source(24, 5) + SourceIndex(0) + 2 >Emitted(89, 13) Source(24, 14) + SourceIndex(0) + 3 >Emitted(89, 14) Source(24, 15) + SourceIndex(0) +-4 >Emitted(89, 90) Source(24, 20) + SourceIndex(0) ++4 >Emitted(89, 92) Source(24, 20) + SourceIndex(0) + --- + >>> }; +->>> _z_1_accessor_storage = new WeakMap(); +->>> _method_get = function _method_get() { return _static_private_method_descriptor.value; }; +->>> _x_get = function _x_get() { return _static_private_get_x_descriptor.get.call(this); }; +->>> _x_set = function _x_set(value) { return _static_private_set_x_descriptor.set.call(this, value); }; +->>> _z_get = function _z_get() { return _static_private_z_descriptor.get.call(this); }; +->>> _z_set = function _z_set(value) { return _static_private_z_descriptor.set.call(this, value); }; ++>>> _C_z_1_accessor_storage = new WeakMap(); ++>>> _C_method_get = function _C_method_get() { return _static_private_method_descriptor.value; }; ++>>> _C_x_get = function _C_x_get() { return _static_private_get_x_descriptor.get.call(this); }; ++>>> _C_x_set = function _C_x_set(value) { return _static_private_set_x_descriptor.set.call(this, value); }; ++>>> _C_z_get = function _C_z_get() { return _static_private_z_descriptor.get.call(this); }; ++>>> _C_z_set = function _C_z_set(value) { return _static_private_z_descriptor.set.call(this, value); }; + >>> __setFunctionName(_classThis, "C"); + >>> (() => { + >>> _method_decorators = [dec, dec]; +@@ -489,7 +489,7 @@ sourceFile:esDecorators-classDeclaration-sourceMap.ts + 2 > ^^^ + 3 > ^^ + 4 > ^^^ +-5 > ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^-> ++5 > ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^-> + 1-> + > static #y = 1; + > +@@ -503,14 +503,14 @@ sourceFile:esDecorators-classDeclaration-sourceMap.ts + 3 >Emitted(108, 46) Source(43, 6) + SourceIndex(0) + 4 >Emitted(108, 49) Source(43, 9) + SourceIndex(0) + --- +->>> __esDecorate(_classThis, _static_private_method_descriptor = { value: __setFunctionName(function () { }, "#method") }, _static_private_method_decorators, { kind: "method", name: "#method", static: true, private: true, access: { has: obj => __classPrivateFieldIn(_classThis, obj), get: obj => __classPrivateFieldGet(obj, _classThis, "a", _method_get) } }, null, _staticExtraInitializers); ++>>> __esDecorate(_classThis, _static_private_method_descriptor = { value: __setFunctionName(function () { }, "#method") }, _static_private_method_decorators, { kind: "method", name: "#method", static: true, private: true, access: { has: obj => __classPrivateFieldIn(_classThis, obj), get: obj => __classPrivateFieldGet(obj, _classThis, "a", _C_method_get) } }, null, _staticExtraInitializers); + 1->^^^^^^^^ + 2 > ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + 3 > ^^^^^^^^^^^^^^^^^^^^^^^^^ + 4 > ^^^^^^^^^^^^^^ + 5 > ^ + 6 > ^^^^^^^^^^^^ +-7 > ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ++7 > ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + 1-> + 2 > + 3 > +@@ -524,9 +524,9 @@ sourceFile:esDecorators-classDeclaration-sourceMap.ts + 4 >Emitted(109, 111) Source(28, 23) + SourceIndex(0) + 5 >Emitted(109, 112) Source(28, 24) + SourceIndex(0) + 6 >Emitted(109, 124) Source(28, 24) + SourceIndex(0) +-7 >Emitted(109, 396) Source(28, 24) + SourceIndex(0) ++7 >Emitted(109, 398) Source(28, 24) + SourceIndex(0) + --- +->>> __esDecorate(_classThis, _static_private_get_x_descriptor = { get: __setFunctionName(function () { return 1; }, "#x", "get") }, _static_private_get_x_decorators, { kind: "getter", name: "#x", static: true, private: true, access: { has: obj => __classPrivateFieldIn(_classThis, obj), get: obj => __classPrivateFieldGet(obj, _classThis, "a", _x_get) } }, null, _staticExtraInitializers); ++>>> __esDecorate(_classThis, _static_private_get_x_descriptor = { get: __setFunctionName(function () { return 1; }, "#x", "get") }, _static_private_get_x_decorators, { kind: "getter", name: "#x", static: true, private: true, access: { has: obj => __classPrivateFieldIn(_classThis, obj), get: obj => __classPrivateFieldGet(obj, _classThis, "a", _C_x_get) } }, null, _staticExtraInitializers); + 1 >^^^^^^^^ + 2 > ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + 3 > ^^^^^^^^^^^^^^^^^^^^^^^ +@@ -537,8 +537,8 @@ sourceFile:esDecorators-classDeclaration-sourceMap.ts + 8 > ^ + 9 > ^ + 10> ^^^^^^^^^^^^^^ +-11> ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +-12> ^^^^^^^^^^^^^^^^^-> ++11> ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ++12> ^^^^^^^^^^^^^^^^^-> + 1 > + > + > @dec +@@ -564,9 +564,9 @@ sourceFile:esDecorators-classDeclaration-sourceMap.ts + 8 >Emitted(110, 118) Source(32, 33) + SourceIndex(0) + 9 >Emitted(110, 119) Source(32, 34) + SourceIndex(0) + 10>Emitted(110, 133) Source(32, 34) + SourceIndex(0) +-11>Emitted(110, 394) Source(32, 34) + SourceIndex(0) ++11>Emitted(110, 396) Source(32, 34) + SourceIndex(0) + --- +->>> __esDecorate(_classThis, _static_private_set_x_descriptor = { set: __setFunctionName(function (value) { }, "#x", "set") }, _static_private_set_x_decorators, { kind: "setter", name: "#x", static: true, private: true, access: { has: obj => __classPrivateFieldIn(_classThis, obj), set: (obj, value) => { __classPrivateFieldSet(obj, _classThis, value, "a", _x_set); } } }, null, _staticExtraInitializers); ++>>> __esDecorate(_classThis, _static_private_set_x_descriptor = { set: __setFunctionName(function (value) { }, "#x", "set") }, _static_private_set_x_decorators, { kind: "setter", name: "#x", static: true, private: true, access: { has: obj => __classPrivateFieldIn(_classThis, obj), set: (obj, value) => { __classPrivateFieldSet(obj, _classThis, value, "a", _C_x_set); } } }, null, _staticExtraInitializers); + 1->^^^^^^^^ + 2 > ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + 3 > ^^^^^^^^^^^^^^^^^^^^^^^ +@@ -575,8 +575,8 @@ sourceFile:esDecorators-classDeclaration-sourceMap.ts + 6 > ^^^^ + 7 > ^ + 8 > ^^^^^^^^^^^^^^ +-9 > ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +-10> ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^-> ++9 > ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ++10> ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^-> + 1-> + > + > @dec +@@ -598,19 +598,19 @@ sourceFile:esDecorators-classDeclaration-sourceMap.ts + 6 >Emitted(111, 113) Source(36, 36) + SourceIndex(0) + 7 >Emitted(111, 114) Source(36, 37) + SourceIndex(0) + 8 >Emitted(111, 128) Source(36, 37) + SourceIndex(0) +-9 >Emitted(111, 410) Source(36, 37) + SourceIndex(0) ++9 >Emitted(111, 412) Source(36, 37) + SourceIndex(0) + --- +->>> __esDecorate(_classThis, _static_private_z_descriptor = { get: __setFunctionName(function () { return __classPrivateFieldGet(_classThis, _classThis, "f", _z_accessor_storage); }, "#z", "get"), set: __setFunctionName(function (value) { __classPrivateFieldSet(_classThis, _classThis, value, "f", _z_accessor_storage); }, "#z", "set") }, _static_private_z_decorators, { kind: "accessor", name: "#z", static: true, private: true, access: { has: obj => __classPrivateFieldIn(_classThis, obj), get: obj => __classPrivateFieldGet(obj, _classThis, "a", _z_get), set: (obj, value) => { __classPrivateFieldSet(obj, _classThis, value, "a", _z_set); } } }, _static_private_z_initializers, _staticExtraInitializers); ++>>> __esDecorate(_classThis, _static_private_z_descriptor = { get: __setFunctionName(function () { return __classPrivateFieldGet(_classThis, _classThis, "f", _C_z_accessor_storage); }, "#z", "get"), set: __setFunctionName(function (value) { __classPrivateFieldSet(_classThis, _classThis, value, "f", _C_z_accessor_storage); }, "#z", "set") }, _static_private_z_decorators, { kind: "accessor", name: "#z", static: true, private: true, access: { has: obj => __classPrivateFieldIn(_classThis, obj), get: obj => __classPrivateFieldGet(obj, _classThis, "a", _C_z_get), set: (obj, value) => { __classPrivateFieldSet(obj, _classThis, value, "a", _C_z_set); } } }, _static_private_z_initializers, _staticExtraInitializers); + 1->^^^^^^^^ + 2 > ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + 3 > ^^^^^^^^^^^^^^^^^^^^^^^ +-4 > ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +-5 > ^^^^^^^^^^^^^^ +-6 > ^^ +-7 > ^^^^^^^^^^^^^^^^^^^^^^^ +-8 > ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +-9 > ^^^^^^^^^^^^^^ +-10> ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ++4 > ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ++5 > ^^^^^^^^^^^^^^ ++6 > ^^ ++7 > ^^^^^^^^^^^^^^^^^^^^^^^ ++8 > ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ++9 > ^^^^^^^^^^^^^^ ++10> ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + 1-> + > + > @dec +@@ -623,22 +623,22 @@ sourceFile:esDecorators-classDeclaration-sourceMap.ts + 2 > + 3 > + 4 > static accessor #z = 1; +-5 > +-6 > +-7 > +-8 > static accessor #z = 1; +-9 > +-10> ++5 > ++6 > ++7 > ++8 > static accessor #z = 1; ++9 > ++10> + 1->Emitted(112, 9) Source(44, 5) + SourceIndex(0) + 2 >Emitted(112, 67) Source(44, 5) + SourceIndex(0) + 3 >Emitted(112, 90) Source(44, 5) + SourceIndex(0) +-4 >Emitted(112, 186) Source(44, 28) + SourceIndex(0) +-5 >Emitted(112, 200) Source(44, 28) + SourceIndex(0) +-6 >Emitted(112, 202) Source(44, 5) + SourceIndex(0) +-7 >Emitted(112, 225) Source(44, 5) + SourceIndex(0) +-8 >Emitted(112, 326) Source(44, 28) + SourceIndex(0) +-9 >Emitted(112, 340) Source(44, 28) + SourceIndex(0) +-10>Emitted(112, 712) Source(44, 28) + SourceIndex(0) ++4 >Emitted(112, 188) Source(44, 28) + SourceIndex(0) ++5 >Emitted(112, 202) Source(44, 28) + SourceIndex(0) ++6 >Emitted(112, 204) Source(44, 5) + SourceIndex(0) ++7 >Emitted(112, 227) Source(44, 5) + SourceIndex(0) ++8 >Emitted(112, 330) Source(44, 28) + SourceIndex(0) ++9 >Emitted(112, 344) Source(44, 28) + SourceIndex(0) ++10>Emitted(112, 720) Source(44, 28) + SourceIndex(0) + --- + >>> __esDecorate(_classThis, null, _method_decorators, { kind: "method", name: "method", static: false, private: false, access: { has: obj => "method" in obj, get: obj => obj.method } }, null, _instanceExtraInitializers); + 1 >^^^^^^^^ +@@ -699,7 +699,7 @@ sourceFile:esDecorators-classDeclaration-sourceMap.ts + 4 > ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + 5 > ^ + 6 > ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +-7 > ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^-> ++7 > ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^-> + 1-> + > + > @dec +@@ -721,9 +721,9 @@ sourceFile:esDecorators-classDeclaration-sourceMap.ts + 5 >Emitted(116, 198) Source(24, 15) + SourceIndex(0) + 6 >Emitted(116, 260) Source(24, 20) + SourceIndex(0) + --- +->>> __esDecorate(null, null, _static_private_y_decorators, { kind: "field", name: "#y", static: true, private: true, access: { has: obj => __classPrivateFieldIn(_classThis, obj), get: obj => __classPrivateFieldGet(obj, _classThis, "f", _y), set: (obj, value) => { __classPrivateFieldSet(obj, _classThis, value, "f", _y); } } }, _static_private_y_initializers, _staticExtraInitializers); ++>>> __esDecorate(null, null, _static_private_y_decorators, { kind: "field", name: "#y", static: true, private: true, access: { has: obj => __classPrivateFieldIn(_classThis, obj), get: obj => __classPrivateFieldGet(obj, _classThis, "f", _C_y), set: (obj, value) => { __classPrivateFieldSet(obj, _classThis, value, "f", _C_y); } } }, _static_private_y_initializers, _staticExtraInitializers); + 1->^^^^^^^^ +-2 > ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ++2 > ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + 1-> + > + > @dec +@@ -743,7 +743,7 @@ sourceFile:esDecorators-classDeclaration-sourceMap.ts + > + 2 > static #y = 1; + 1->Emitted(117, 9) Source(40, 5) + SourceIndex(0) +-2 >Emitted(117, 391) Source(40, 19) + SourceIndex(0) ++2 >Emitted(117, 395) Source(40, 19) + SourceIndex(0) + --- + >>> __esDecorate(null, null, _y_decorators, { kind: "field", name: "y", static: false, private: false, access: { has: obj => "y" in obj, get: obj => obj.y, set: (obj, value) => { obj.y = value; } } }, _y_initializers, _instanceExtraInitializers); + 1 >^^^^^^^^ +@@ -823,13 +823,13 @@ sourceFile:esDecorators-classDeclaration-sourceMap.ts + 2 >Emitted(121, 65) Source(5, 8) + SourceIndex(0) + --- + >>> })(); +->>> _y = { value: __runInitializers(_classThis, _static_private_y_initializers, 1) }; ++>>> _C_y = { value: __runInitializers(_classThis, _static_private_y_initializers, 1) }; + 1 >^^^^ +-2 > ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +-3 > ^ +-4 > ^^^ +-5 > ^ +-6 > ^^^^^^^^^^^^^^^^^^-> ++2 > ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ++3 > ^ ++4 > ^^^ ++5 > ^ ++6 > ^^^^^^^^^^^^^^^^^^-> + 1 > { + > @dec + > @dec +@@ -867,35 +867,35 @@ sourceFile:esDecorators-classDeclaration-sourceMap.ts + > @dec + > static + 2 > #y = +-3 > 1 +-4 > +-5 > = 1; ++3 > 1 ++4 > ++5 > = 1; + 1 >Emitted(123, 5) Source(40, 12) + SourceIndex(0) +-2 >Emitted(123, 81) Source(40, 17) + SourceIndex(0) +-3 >Emitted(123, 82) Source(40, 18) + SourceIndex(0) +-4 >Emitted(123, 85) Source(40, 14) + SourceIndex(0) +-5 >Emitted(123, 86) Source(40, 19) + SourceIndex(0) ++2 >Emitted(123, 83) Source(40, 17) + SourceIndex(0) ++3 >Emitted(123, 84) Source(40, 18) + SourceIndex(0) ++4 >Emitted(123, 87) Source(40, 14) + SourceIndex(0) ++5 >Emitted(123, 88) Source(40, 19) + SourceIndex(0) + --- +->>> _z_accessor_storage = { value: __runInitializers(_classThis, _static_private_z_initializers, 1) }; ++>>> _C_z_accessor_storage = { value: __runInitializers(_classThis, _static_private_z_initializers, 1) }; + 1->^^^^ +-2 > ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +-3 > ^ +-4 > ^^^ +-5 > ^ ++2 > ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ++3 > ^ ++4 > ^^^ ++5 > ^ + 1-> + > + > @dec + > @dec + > static accessor + 2 > #z = +-3 > 1 +-4 > +-5 > = 1; ++3 > 1 ++4 > ++5 > = 1; + 1->Emitted(124, 5) Source(44, 21) + SourceIndex(0) +-2 >Emitted(124, 98) Source(44, 26) + SourceIndex(0) +-3 >Emitted(124, 99) Source(44, 27) + SourceIndex(0) +-4 >Emitted(124, 102) Source(44, 23) + SourceIndex(0) +-5 >Emitted(124, 103) Source(44, 28) + SourceIndex(0) ++2 >Emitted(124, 100) Source(44, 26) + SourceIndex(0) ++3 >Emitted(124, 101) Source(44, 27) + SourceIndex(0) ++4 >Emitted(124, 104) Source(44, 23) + SourceIndex(0) ++5 >Emitted(124, 105) Source(44, 28) + SourceIndex(0) + --- + >>> (() => { + >>> __runInitializers(_classThis, _classExtraInitializers); +diff --git a/tests/baselines/reference/esDecorators-classDeclaration-sourceMap(target=es2022).js b/tests/baselines/reference/esDecorators-classDeclaration-sourceMap(target=es2022).js +index 9926b4f5b..4f43dcb46 100644 +--- a/tests/baselines/reference/esDecorators-classDeclaration-sourceMap(target=es2022).js ++++ b/tests/baselines/reference/esDecorators-classDeclaration-sourceMap(target=es2022).js +@@ -103,7 +103,7 @@ var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function ( + return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value; + }; + let C = (() => { +- var _method_get, _x_get, _x_set, _y, _z_accessor_storage, _z_get, _z_set; ++ var _C_method_get, _C_x_get, _C_x_set, _C_y, _C_z_accessor_storage, _C_z_get, _C_z_set; + let _classDecorators = [dec, dec]; + let _classDescriptor; + let _classExtraInitializers = []; +@@ -129,8 +129,9 @@ let C = (() => { + let _z_decorators; + let _z_initializers = []; + var C = class { ++ static { _classThis = this; } + static { __setFunctionName(this, "C"); } +- static { _method_get = function _method_get() { return _static_private_method_descriptor.value; }, _x_get = function _x_get() { return _static_private_get_x_descriptor.get.call(this); }, _x_set = function _x_set(value) { return _static_private_set_x_descriptor.set.call(this, value); }, _z_get = function _z_get() { return _static_private_z_descriptor.get.call(this); }, _z_set = function _z_set(value) { return _static_private_z_descriptor.set.call(this, value); }; } ++ static { _C_method_get = function _C_method_get() { return _static_private_method_descriptor.value; }, _C_x_get = function _C_x_get() { return _static_private_get_x_descriptor.get.call(this); }, _C_x_set = function _C_x_set(value) { return _static_private_set_x_descriptor.set.call(this, value); }, _C_z_get = function _C_z_get() { return _static_private_z_descriptor.get.call(this); }, _C_z_set = function _C_z_set(value) { return _static_private_z_descriptor.set.call(this, value); }; } + static { + _method_decorators = [dec, dec]; + _get_x_decorators = [dec, dec]; +@@ -142,17 +143,17 @@ let C = (() => { + _static_private_set_x_decorators = [dec, dec]; + _static_private_y_decorators = [dec, dec]; + _static_private_z_decorators = [dec, dec]; +- __esDecorate(this, _static_private_method_descriptor = { value: __setFunctionName(function () { }, "#method") }, _static_private_method_decorators, { kind: "method", name: "#method", static: true, private: true, access: { has: obj => __classPrivateFieldIn(_classThis, obj), get: obj => __classPrivateFieldGet(obj, _classThis, "a", _method_get) } }, null, _staticExtraInitializers); +- __esDecorate(this, _static_private_get_x_descriptor = { get: __setFunctionName(function () { return 1; }, "#x", "get") }, _static_private_get_x_decorators, { kind: "getter", name: "#x", static: true, private: true, access: { has: obj => __classPrivateFieldIn(_classThis, obj), get: obj => __classPrivateFieldGet(obj, _classThis, "a", _x_get) } }, null, _staticExtraInitializers); +- __esDecorate(this, _static_private_set_x_descriptor = { set: __setFunctionName(function (value) { }, "#x", "set") }, _static_private_set_x_decorators, { kind: "setter", name: "#x", static: true, private: true, access: { has: obj => __classPrivateFieldIn(_classThis, obj), set: (obj, value) => { __classPrivateFieldSet(obj, _classThis, value, "a", _x_set); } } }, null, _staticExtraInitializers); +- __esDecorate(this, _static_private_z_descriptor = { get: __setFunctionName(function () { return __classPrivateFieldGet(this, _classThis, "f", _z_accessor_storage); }, "#z", "get"), set: __setFunctionName(function (value) { __classPrivateFieldSet(this, _classThis, value, "f", _z_accessor_storage); }, "#z", "set") }, _static_private_z_decorators, { kind: "accessor", name: "#z", static: true, private: true, access: { has: obj => __classPrivateFieldIn(_classThis, obj), get: obj => __classPrivateFieldGet(obj, _classThis, "a", _z_get), set: (obj, value) => { __classPrivateFieldSet(obj, _classThis, value, "a", _z_set); } } }, _static_private_z_initializers, _staticExtraInitializers); ++ __esDecorate(this, _static_private_method_descriptor = { value: __setFunctionName(function () { }, "#method") }, _static_private_method_decorators, { kind: "method", name: "#method", static: true, private: true, access: { has: obj => __classPrivateFieldIn(_classThis, obj), get: obj => __classPrivateFieldGet(obj, _classThis, "a", _C_method_get) } }, null, _staticExtraInitializers); ++ __esDecorate(this, _static_private_get_x_descriptor = { get: __setFunctionName(function () { return 1; }, "#x", "get") }, _static_private_get_x_decorators, { kind: "getter", name: "#x", static: true, private: true, access: { has: obj => __classPrivateFieldIn(_classThis, obj), get: obj => __classPrivateFieldGet(obj, _classThis, "a", _C_x_get) } }, null, _staticExtraInitializers); ++ __esDecorate(this, _static_private_set_x_descriptor = { set: __setFunctionName(function (value) { }, "#x", "set") }, _static_private_set_x_decorators, { kind: "setter", name: "#x", static: true, private: true, access: { has: obj => __classPrivateFieldIn(_classThis, obj), set: (obj, value) => { __classPrivateFieldSet(obj, _classThis, value, "a", _C_x_set); } } }, null, _staticExtraInitializers); ++ __esDecorate(this, _static_private_z_descriptor = { get: __setFunctionName(function () { return __classPrivateFieldGet(this, _classThis, "f", _C_z_accessor_storage); }, "#z", "get"), set: __setFunctionName(function (value) { __classPrivateFieldSet(this, _classThis, value, "f", _C_z_accessor_storage); }, "#z", "set") }, _static_private_z_decorators, { kind: "accessor", name: "#z", static: true, private: true, access: { has: obj => __classPrivateFieldIn(_classThis, obj), get: obj => __classPrivateFieldGet(obj, _classThis, "a", _C_z_get), set: (obj, value) => { __classPrivateFieldSet(obj, _classThis, value, "a", _C_z_set); } } }, _static_private_z_initializers, _staticExtraInitializers); + __esDecorate(this, null, _method_decorators, { kind: "method", name: "method", static: false, private: false, access: { has: obj => "method" in obj, get: obj => obj.method } }, null, _instanceExtraInitializers); + __esDecorate(this, null, _get_x_decorators, { kind: "getter", name: "x", static: false, private: false, access: { has: obj => "x" in obj, get: obj => obj.x } }, null, _instanceExtraInitializers); + __esDecorate(this, null, _set_x_decorators, { kind: "setter", name: "x", static: false, private: false, access: { has: obj => "x" in obj, set: (obj, value) => { obj.x = value; } } }, null, _instanceExtraInitializers); + __esDecorate(this, null, _z_decorators, { kind: "accessor", name: "z", static: false, private: false, access: { has: obj => "z" in obj, get: obj => obj.z, set: (obj, value) => { obj.z = value; } } }, _z_initializers, _instanceExtraInitializers); +- __esDecorate(null, null, _static_private_y_decorators, { kind: "field", name: "#y", static: true, private: true, access: { has: obj => __classPrivateFieldIn(_classThis, obj), get: obj => __classPrivateFieldGet(obj, _classThis, "f", _y), set: (obj, value) => { __classPrivateFieldSet(obj, _classThis, value, "f", _y); } } }, _static_private_y_initializers, _staticExtraInitializers); ++ __esDecorate(null, null, _static_private_y_decorators, { kind: "field", name: "#y", static: true, private: true, access: { has: obj => __classPrivateFieldIn(_classThis, obj), get: obj => __classPrivateFieldGet(obj, _classThis, "f", _C_y), set: (obj, value) => { __classPrivateFieldSet(obj, _classThis, value, "f", _C_y); } } }, _static_private_y_initializers, _staticExtraInitializers); + __esDecorate(null, null, _y_decorators, { kind: "field", name: "y", static: false, private: false, access: { has: obj => "y" in obj, get: obj => obj.y, set: (obj, value) => { obj.y = value; } } }, _y_initializers, _instanceExtraInitializers); +- __esDecorate(null, _classDescriptor = { value: this }, _classDecorators, { kind: "class", name: this.name }, null, _classExtraInitializers); ++ __esDecorate(null, _classDescriptor = { value: _classThis }, _classDecorators, { kind: "class", name: _classThis.name }, null, _classExtraInitializers); + C = _classThis = _classDescriptor.value; + __runInitializers(_classThis, _staticExtraInitializers); + } +@@ -164,10 +165,10 @@ let C = (() => { + get z() { return this.#z_accessor_storage; } + set z(value) { this.#z_accessor_storage = value; } + static { +- _y = { value: __runInitializers(_classThis, _static_private_y_initializers, 1) }; ++ _C_y = { value: __runInitializers(_classThis, _static_private_y_initializers, 1) }; + } + static { +- _z_accessor_storage = { value: __runInitializers(_classThis, _static_private_z_initializers, 1) }; ++ _C_z_accessor_storage = { value: __runInitializers(_classThis, _static_private_z_initializers, 1) }; + } + static { + __runInitializers(_classThis, _classExtraInitializers); +diff --git a/tests/baselines/reference/esDecorators-classDeclaration-sourceMap(target=es2022).js.map b/tests/baselines/reference/esDecorators-classDeclaration-sourceMap(target=es2022).js.map +index 5752ff8d4..d40c64ee8 100644 +--- a/tests/baselines/reference/esDecorators-classDeclaration-sourceMap(target=es2022).js.map ++++ b/tests/baselines/reference/esDecorators-classDeclaration-sourceMap(target=es2022).js.map +@@ -1,6 +1,6 @@ + //// [esDecorators-classDeclaration-sourceMap.js.map] +-{"version":3,"file":"esDecorators-classDeclaration-sourceMap.js","sourceRoot":"","sources":["esDecorators-classDeclaration-sourceMap.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;IAIM,CAAC;;4BAFN,GAAG,EACH,GAAG;;;;;;;;;;;;;;;;;;;;;;;;;;;;kCAEC,GAAG,EACH,GAAG;iCAGH,GAAG,EACH,GAAG;iCAGH,GAAG,EACH,GAAG;6BAGH,GAAG,EACH,GAAG;6BAGH,GAAG,EACH,GAAG;iDAGH,GAAG,EACH,GAAG;gDAGH,GAAG,EACH,GAAG;gDAGH,GAAG,EACH,GAAG;4CAGH,GAAG,EACH,GAAG;4CAGH,GAAG,EACH,GAAG;YAfJ,yDAAA,yBAAA,cAAkB,CAAC,YAAA,gRAAA;YAInB,wDAAA,uBAAA,cAAkB,OAAO,CAAC,CAAC,CAAC,CAAC,cAAA,qQAAA;YAI7B,wDAAA,uBAAA,UAAc,KAAa,IAAI,CAAC,cAAA,0RAAA;YAQhC,oDAAA,uBAAA,0FAAuB,cAAA,EAAvB,uBAAA,+FAAuB,cAAA,oXAAA;YApCvB,qKAAA,MAAM,wCAAK;YAIX,0JAAI,CAAC,wCAAgB;YAIrB,qKAAI,CAAC,mDAAmB;YAQxB,wJAAS,CAAC,6BAAD,CAAC,8DAAK;YAgBf,8XAAc;YApBd,qJAAA,CAAC,6BAAD,CAAC,8DAAK;YAfV,4IAwCC;;YAxCK,wDAAC;;QAGH,MAAM,KAAI,CAAC;QAIX,IAAI,CAAC,KAAK,OAAO,CAAC,CAAC,CAAC,CAAC;QAIrB,IAAI,CAAC,CAAC,KAAa,IAAI,CAAC;QAIxB,CAAC,kGAAG,CAAC,GAAC;QAIN,+DAAa,CAAC,EAAC;QAAf,IAAS,CAAC,uCAAK;QAAf,IAAS,CAAC,6CAAK;;YAgBR,4EAAK,CAAC,GAAJ,CAAK;;;YAIE,6FAAK,CAAC,GAAJ,CAAK;;;YAvCrB,uDAAC"} +-//// https://sokra.github.io/source-map-visualization#base64,dmFyIF9fZXNEZWNvcmF0ZSA9ICh0aGlzICYmIHRoaXMuX19lc0RlY29yYXRlKSB8fCBmdW5jdGlvbiAoY3RvciwgZGVzY3JpcHRvckluLCBkZWNvcmF0b3JzLCBjb250ZXh0SW4sIGluaXRpYWxpemVycywgZXh0cmFJbml0aWFsaXplcnMpIHsNCiAgICBmdW5jdGlvbiBhY2NlcHQoZikgeyBpZiAoZiAhPT0gdm9pZCAwICYmIHR5cGVvZiBmICE9PSAiZnVuY3Rpb24iKSB0aHJvdyBuZXcgVHlwZUVycm9yKCJGdW5jdGlvbiBleHBlY3RlZCIpOyByZXR1cm4gZjsgfQ0KICAgIHZhciBraW5kID0gY29udGV4dEluLmtpbmQsIGtleSA9IGtpbmQgPT09ICJnZXR0ZXIiID8gImdldCIgOiBraW5kID09PSAic2V0dGVyIiA/ICJzZXQiIDogInZhbHVlIjsNCiAgICB2YXIgdGFyZ2V0ID0gIWRlc2NyaXB0b3JJbiAmJiBjdG9yID8gY29udGV4dEluWyJzdGF0aWMiXSA/IGN0b3IgOiBjdG9yLnByb3RvdHlwZSA6IG51bGw7DQogICAgdmFyIGRlc2NyaXB0b3IgPSBkZXNjcmlwdG9ySW4gfHwgKHRhcmdldCA/IE9iamVjdC5nZXRPd25Qcm9wZXJ0eURlc2NyaXB0b3IodGFyZ2V0LCBjb250ZXh0SW4ubmFtZSkgOiB7fSk7DQogICAgdmFyIF8sIGRvbmUgPSBmYWxzZTsNCiAgICBmb3IgKHZhciBpID0gZGVjb3JhdG9ycy5sZW5ndGggLSAxOyBpID49IDA7IGktLSkgew0KICAgICAgICB2YXIgY29udGV4dCA9IHt9Ow0KICAgICAgICBmb3IgKHZhciBwIGluIGNvbnRleHRJbikgY29udGV4dFtwXSA9IHAgPT09ICJhY2Nlc3MiID8ge30gOiBjb250ZXh0SW5bcF07DQogICAgICAgIGZvciAodmFyIHAgaW4gY29udGV4dEluLmFjY2VzcykgY29udGV4dC5hY2Nlc3NbcF0gPSBjb250ZXh0SW4uYWNjZXNzW3BdOw0KICAgICAgICBjb250ZXh0LmFkZEluaXRpYWxpemVyID0gZnVuY3Rpb24gKGYpIHsgaWYgKGRvbmUpIHRocm93IG5ldyBUeXBlRXJyb3IoIkNhbm5vdCBhZGQgaW5pdGlhbGl6ZXJzIGFmdGVyIGRlY29yYXRpb24gaGFzIGNvbXBsZXRlZCIpOyBleHRyYUluaXRpYWxpemVycy5wdXNoKGFjY2VwdChmIHx8IG51bGwpKTsgfTsNCiAgICAgICAgdmFyIHJlc3VsdCA9ICgwLCBkZWNvcmF0b3JzW2ldKShraW5kID09PSAiYWNjZXNzb3IiID8geyBnZXQ6IGRlc2NyaXB0b3IuZ2V0LCBzZXQ6IGRlc2NyaXB0b3Iuc2V0IH0gOiBkZXNjcmlwdG9yW2tleV0sIGNvbnRleHQpOw0KICAgICAgICBpZiAoa2luZCA9PT0gImFjY2Vzc29yIikgew0KICAgICAgICAgICAgaWYgKHJlc3VsdCA9PT0gdm9pZCAwKSBjb250aW51ZTsNCiAgICAgICAgICAgIGlmIChyZXN1bHQgPT09IG51bGwgfHwgdHlwZW9mIHJlc3VsdCAhPT0gIm9iamVjdCIpIHRocm93IG5ldyBUeXBlRXJyb3IoIk9iamVjdCBleHBlY3RlZCIpOw0KICAgICAgICAgICAgaWYgKF8gPSBhY2NlcHQocmVzdWx0LmdldCkpIGRlc2NyaXB0b3IuZ2V0ID0gXzsNCiAgICAgICAgICAgIGlmIChfID0gYWNjZXB0KHJlc3VsdC5zZXQpKSBkZXNjcmlwdG9yLnNldCA9IF87DQogICAgICAgICAgICBpZiAoXyA9IGFjY2VwdChyZXN1bHQuaW5pdCkpIGluaXRpYWxpemVycy51bnNoaWZ0KF8pOw0KICAgICAgICB9DQogICAgICAgIGVsc2UgaWYgKF8gPSBhY2NlcHQocmVzdWx0KSkgew0KICAgICAgICAgICAgaWYgKGtpbmQgPT09ICJmaWVsZCIpIGluaXRpYWxpemVycy51bnNoaWZ0KF8pOw0KICAgICAgICAgICAgZWxzZSBkZXNjcmlwdG9yW2tleV0gPSBfOw0KICAgICAgICB9DQogICAgfQ0KICAgIGlmICh0YXJnZXQpIE9iamVjdC5kZWZpbmVQcm9wZXJ0eSh0YXJnZXQsIGNvbnRleHRJbi5uYW1lLCBkZXNjcmlwdG9yKTsNCiAgICBkb25lID0gdHJ1ZTsNCn07DQp2YXIgX19ydW5Jbml0aWFsaXplcnMgPSAodGhpcyAmJiB0aGlzLl9fcnVuSW5pdGlhbGl6ZXJzKSB8fCBmdW5jdGlvbiAodGhpc0FyZywgaW5pdGlhbGl6ZXJzLCB2YWx1ZSkgew0KICAgIHZhciB1c2VWYWx1ZSA9IGFyZ3VtZW50cy5sZW5ndGggPiAyOw0KICAgIGZvciAodmFyIGkgPSAwOyBpIDwgaW5pdGlhbGl6ZXJzLmxlbmd0aDsgaSsrKSB7DQogICAgICAgIHZhbHVlID0gdXNlVmFsdWUgPyBpbml0aWFsaXplcnNbaV0uY2FsbCh0aGlzQXJnLCB2YWx1ZSkgOiBpbml0aWFsaXplcnNbaV0uY2FsbCh0aGlzQXJnKTsNCiAgICB9DQogICAgcmV0dXJuIHVzZVZhbHVlID8gdmFsdWUgOiB2b2lkIDA7DQp9Ow0KdmFyIF9fc2V0RnVuY3Rpb25OYW1lID0gKHRoaXMgJiYgdGhpcy5fX3NldEZ1bmN0aW9uTmFtZSkgfHwgZnVuY3Rpb24gKGYsIG5hbWUsIHByZWZpeCkgew0KICAgIGlmICh0eXBlb2YgbmFtZSA9PT0gInN5bWJvbCIpIG5hbWUgPSBuYW1lLmRlc2NyaXB0aW9uID8gIlsiLmNvbmNhdChuYW1lLmRlc2NyaXB0aW9uLCAiXSIpIDogIiI7DQogICAgcmV0dXJuIE9iamVjdC5kZWZpbmVQcm9wZXJ0eShmLCAibmFtZSIsIHsgY29uZmlndXJhYmxlOiB0cnVlLCB2YWx1ZTogcHJlZml4ID8gIiIuY29uY2F0KHByZWZpeCwgIiAiLCBuYW1lKSA6IG5hbWUgfSk7DQp9Ow0KdmFyIF9fY2xhc3NQcml2YXRlRmllbGRJbiA9ICh0aGlzICYmIHRoaXMuX19jbGFzc1ByaXZhdGVGaWVsZEluKSB8fCBmdW5jdGlvbihzdGF0ZSwgcmVjZWl2ZXIpIHsNCiAgICBpZiAocmVjZWl2ZXIgPT09IG51bGwgfHwgKHR5cGVvZiByZWNlaXZlciAhPT0gIm9iamVjdCIgJiYgdHlwZW9mIHJlY2VpdmVyICE9PSAiZnVuY3Rpb24iKSkgdGhyb3cgbmV3IFR5cGVFcnJvcigiQ2Fubm90IHVzZSAnaW4nIG9wZXJhdG9yIG9uIG5vbi1vYmplY3QiKTsNCiAgICByZXR1cm4gdHlwZW9mIHN0YXRlID09PSAiZnVuY3Rpb24iID8gcmVjZWl2ZXIgPT09IHN0YXRlIDogc3RhdGUuaGFzKHJlY2VpdmVyKTsNCn07DQp2YXIgX19jbGFzc1ByaXZhdGVGaWVsZEdldCA9ICh0aGlzICYmIHRoaXMuX19jbGFzc1ByaXZhdGVGaWVsZEdldCkgfHwgZnVuY3Rpb24gKHJlY2VpdmVyLCBzdGF0ZSwga2luZCwgZikgew0KICAgIGlmIChraW5kID09PSAiYSIgJiYgIWYpIHRocm93IG5ldyBUeXBlRXJyb3IoIlByaXZhdGUgYWNjZXNzb3Igd2FzIGRlZmluZWQgd2l0aG91dCBhIGdldHRlciIpOw0KICAgIGlmICh0eXBlb2Ygc3RhdGUgPT09ICJmdW5jdGlvbiIgPyByZWNlaXZlciAhPT0gc3RhdGUgfHwgIWYgOiAhc3RhdGUuaGFzKHJlY2VpdmVyKSkgdGhyb3cgbmV3IFR5cGVFcnJvcigiQ2Fubm90IHJlYWQgcHJpdmF0ZSBtZW1iZXIgZnJvbSBhbiBvYmplY3Qgd2hvc2UgY2xhc3MgZGlkIG5vdCBkZWNsYXJlIGl0Iik7DQogICAgcmV0dXJuIGtpbmQgPT09ICJtIiA/IGYgOiBraW5kID09PSAiYSIgPyBmLmNhbGwocmVjZWl2ZXIpIDogZiA/IGYudmFsdWUgOiBzdGF0ZS5nZXQocmVjZWl2ZXIpOw0KfTsNCnZhciBfX2NsYXNzUHJpdmF0ZUZpZWxkU2V0ID0gKHRoaXMgJiYgdGhpcy5fX2NsYXNzUHJpdmF0ZUZpZWxkU2V0KSB8fCBmdW5jdGlvbiAocmVjZWl2ZXIsIHN0YXRlLCB2YWx1ZSwga2luZCwgZikgew0KICAgIGlmIChraW5kID09PSAibSIpIHRocm93IG5ldyBUeXBlRXJyb3IoIlByaXZhdGUgbWV0aG9kIGlzIG5vdCB3cml0YWJsZSIpOw0KICAgIGlmIChraW5kID09PSAiYSIgJiYgIWYpIHRocm93IG5ldyBUeXBlRXJyb3IoIlByaXZhdGUgYWNjZXNzb3Igd2FzIGRlZmluZWQgd2l0aG91dCBhIHNldHRlciIpOw0KICAgIGlmICh0eXBlb2Ygc3RhdGUgPT09ICJmdW5jdGlvbiIgPyByZWNlaXZlciAhPT0gc3RhdGUgfHwgIWYgOiAhc3RhdGUuaGFzKHJlY2VpdmVyKSkgdGhyb3cgbmV3IFR5cGVFcnJvcigiQ2Fubm90IHdyaXRlIHByaXZhdGUgbWVtYmVyIHRvIGFuIG9iamVjdCB3aG9zZSBjbGFzcyBkaWQgbm90IGRlY2xhcmUgaXQiKTsNCiAgICByZXR1cm4gKGtpbmQgPT09ICJhIiA/IGYuY2FsbChyZWNlaXZlciwgdmFsdWUpIDogZiA/IGYudmFsdWUgPSB2YWx1ZSA6IHN0YXRlLnNldChyZWNlaXZlciwgdmFsdWUpKSwgdmFsdWU7DQp9Ow0KbGV0IEMgPSAoKCkgPT4gew0KICAgIHZhciBfbWV0aG9kX2dldCwgX3hfZ2V0LCBfeF9zZXQsIF95LCBfel9hY2Nlc3Nvcl9zdG9yYWdlLCBfel9nZXQsIF96X3NldDsNCiAgICBsZXQgX2NsYXNzRGVjb3JhdG9ycyA9IFtkZWMsIGRlY107DQogICAgbGV0IF9jbGFzc0Rlc2NyaXB0b3I7DQogICAgbGV0IF9jbGFzc0V4dHJhSW5pdGlhbGl6ZXJzID0gW107DQogICAgbGV0IF9jbGFzc1RoaXM7DQogICAgbGV0IF9zdGF0aWNFeHRyYUluaXRpYWxpemVycyA9IFtdOw0KICAgIGxldCBfaW5zdGFuY2VFeHRyYUluaXRpYWxpemVycyA9IFtdOw0KICAgIGxldCBfc3RhdGljX3ByaXZhdGVfbWV0aG9kX2RlY29yYXRvcnM7DQogICAgbGV0IF9zdGF0aWNfcHJpdmF0ZV9tZXRob2RfZGVzY3JpcHRvcjsNCiAgICBsZXQgX3N0YXRpY19wcml2YXRlX2dldF94X2RlY29yYXRvcnM7DQogICAgbGV0IF9zdGF0aWNfcHJpdmF0ZV9nZXRfeF9kZXNjcmlwdG9yOw0KICAgIGxldCBfc3RhdGljX3ByaXZhdGVfc2V0X3hfZGVjb3JhdG9yczsNCiAgICBsZXQgX3N0YXRpY19wcml2YXRlX3NldF94X2Rlc2NyaXB0b3I7DQogICAgbGV0IF9zdGF0aWNfcHJpdmF0ZV95X2RlY29yYXRvcnM7DQogICAgbGV0IF9zdGF0aWNfcHJpdmF0ZV95X2luaXRpYWxpemVycyA9IFtdOw0KICAgIGxldCBfc3RhdGljX3ByaXZhdGVfel9kZWNvcmF0b3JzOw0KICAgIGxldCBfc3RhdGljX3ByaXZhdGVfel9pbml0aWFsaXplcnMgPSBbXTsNCiAgICBsZXQgX3N0YXRpY19wcml2YXRlX3pfZGVzY3JpcHRvcjsNCiAgICBsZXQgX21ldGhvZF9kZWNvcmF0b3JzOw0KICAgIGxldCBfZ2V0X3hfZGVjb3JhdG9yczsNCiAgICBsZXQgX3NldF94X2RlY29yYXRvcnM7DQogICAgbGV0IF95X2RlY29yYXRvcnM7DQogICAgbGV0IF95X2luaXRpYWxpemVycyA9IFtdOw0KICAgIGxldCBfel9kZWNvcmF0b3JzOw0KICAgIGxldCBfel9pbml0aWFsaXplcnMgPSBbXTsNCiAgICB2YXIgQyA9IGNsYXNzIHsNCiAgICAgICAgc3RhdGljIHsgX19zZXRGdW5jdGlvbk5hbWUodGhpcywgIkMiKTsgfQ0KICAgICAgICBzdGF0aWMgeyBfbWV0aG9kX2dldCA9IGZ1bmN0aW9uIF9tZXRob2RfZ2V0KCkgeyByZXR1cm4gX3N0YXRpY19wcml2YXRlX21ldGhvZF9kZXNjcmlwdG9yLnZhbHVlOyB9LCBfeF9nZXQgPSBmdW5jdGlvbiBfeF9nZXQoKSB7IHJldHVybiBfc3RhdGljX3ByaXZhdGVfZ2V0X3hfZGVzY3JpcHRvci5nZXQuY2FsbCh0aGlzKTsgfSwgX3hfc2V0ID0gZnVuY3Rpb24gX3hfc2V0KHZhbHVlKSB7IHJldHVybiBfc3RhdGljX3ByaXZhdGVfc2V0X3hfZGVzY3JpcHRvci5zZXQuY2FsbCh0aGlzLCB2YWx1ZSk7IH0sIF96X2dldCA9IGZ1bmN0aW9uIF96X2dldCgpIHsgcmV0dXJuIF9zdGF0aWNfcHJpdmF0ZV96X2Rlc2NyaXB0b3IuZ2V0LmNhbGwodGhpcyk7IH0sIF96X3NldCA9IGZ1bmN0aW9uIF96X3NldCh2YWx1ZSkgeyByZXR1cm4gX3N0YXRpY19wcml2YXRlX3pfZGVzY3JpcHRvci5zZXQuY2FsbCh0aGlzLCB2YWx1ZSk7IH07IH0NCiAgICAgICAgc3RhdGljIHsNCiAgICAgICAgICAgIF9tZXRob2RfZGVjb3JhdG9ycyA9IFtkZWMsIGRlY107DQogICAgICAgICAgICBfZ2V0X3hfZGVjb3JhdG9ycyA9IFtkZWMsIGRlY107DQogICAgICAgICAgICBfc2V0X3hfZGVjb3JhdG9ycyA9IFtkZWMsIGRlY107DQogICAgICAgICAgICBfeV9kZWNvcmF0b3JzID0gW2RlYywgZGVjXTsNCiAgICAgICAgICAgIF96X2RlY29yYXRvcnMgPSBbZGVjLCBkZWNdOw0KICAgICAgICAgICAgX3N0YXRpY19wcml2YXRlX21ldGhvZF9kZWNvcmF0b3JzID0gW2RlYywgZGVjXTsNCiAgICAgICAgICAgIF9zdGF0aWNfcHJpdmF0ZV9nZXRfeF9kZWNvcmF0b3JzID0gW2RlYywgZGVjXTsNCiAgICAgICAgICAgIF9zdGF0aWNfcHJpdmF0ZV9zZXRfeF9kZWNvcmF0b3JzID0gW2RlYywgZGVjXTsNCiAgICAgICAgICAgIF9zdGF0aWNfcHJpdmF0ZV95X2RlY29yYXRvcnMgPSBbZGVjLCBkZWNdOw0KICAgICAgICAgICAgX3N0YXRpY19wcml2YXRlX3pfZGVjb3JhdG9ycyA9IFtkZWMsIGRlY107DQogICAgICAgICAgICBfX2VzRGVjb3JhdGUodGhpcywgX3N0YXRpY19wcml2YXRlX21ldGhvZF9kZXNjcmlwdG9yID0geyB2YWx1ZTogX19zZXRGdW5jdGlvbk5hbWUoZnVuY3Rpb24gKCkgeyB9LCAiI21ldGhvZCIpIH0sIF9zdGF0aWNfcHJpdmF0ZV9tZXRob2RfZGVjb3JhdG9ycywgeyBraW5kOiAibWV0aG9kIiwgbmFtZTogIiNtZXRob2QiLCBzdGF0aWM6IHRydWUsIHByaXZhdGU6IHRydWUsIGFjY2VzczogeyBoYXM6IG9iaiA9PiBfX2NsYXNzUHJpdmF0ZUZpZWxkSW4oX2NsYXNzVGhpcywgb2JqKSwgZ2V0OiBvYmogPT4gX19jbGFzc1ByaXZhdGVGaWVsZEdldChvYmosIF9jbGFzc1RoaXMsICJhIiwgX21ldGhvZF9nZXQpIH0gfSwgbnVsbCwgX3N0YXRpY0V4dHJhSW5pdGlhbGl6ZXJzKTsNCiAgICAgICAgICAgIF9fZXNEZWNvcmF0ZSh0aGlzLCBfc3RhdGljX3ByaXZhdGVfZ2V0X3hfZGVzY3JpcHRvciA9IHsgZ2V0OiBfX3NldEZ1bmN0aW9uTmFtZShmdW5jdGlvbiAoKSB7IHJldHVybiAxOyB9LCAiI3giLCAiZ2V0IikgfSwgX3N0YXRpY19wcml2YXRlX2dldF94X2RlY29yYXRvcnMsIHsga2luZDogImdldHRlciIsIG5hbWU6ICIjeCIsIHN0YXRpYzogdHJ1ZSwgcHJpdmF0ZTogdHJ1ZSwgYWNjZXNzOiB7IGhhczogb2JqID0+IF9fY2xhc3NQcml2YXRlRmllbGRJbihfY2xhc3NUaGlzLCBvYmopLCBnZXQ6IG9iaiA9PiBfX2NsYXNzUHJpdmF0ZUZpZWxkR2V0KG9iaiwgX2NsYXNzVGhpcywgImEiLCBfeF9nZXQpIH0gfSwgbnVsbCwgX3N0YXRpY0V4dHJhSW5pdGlhbGl6ZXJzKTsNCiAgICAgICAgICAgIF9fZXNEZWNvcmF0ZSh0aGlzLCBfc3RhdGljX3ByaXZhdGVfc2V0X3hfZGVzY3JpcHRvciA9IHsgc2V0OiBfX3NldEZ1bmN0aW9uTmFtZShmdW5jdGlvbiAodmFsdWUpIHsgfSwgIiN4IiwgInNldCIpIH0sIF9zdGF0aWNfcHJpdmF0ZV9zZXRfeF9kZWNvcmF0b3JzLCB7IGtpbmQ6ICJzZXR0ZXIiLCBuYW1lOiAiI3giLCBzdGF0aWM6IHRydWUsIHByaXZhdGU6IHRydWUsIGFjY2VzczogeyBoYXM6IG9iaiA9PiBfX2NsYXNzUHJpdmF0ZUZpZWxkSW4oX2NsYXNzVGhpcywgb2JqKSwgc2V0OiAob2JqLCB2YWx1ZSkgPT4geyBfX2NsYXNzUHJpdmF0ZUZpZWxkU2V0KG9iaiwgX2NsYXNzVGhpcywgdmFsdWUsICJhIiwgX3hfc2V0KTsgfSB9IH0sIG51bGwsIF9zdGF0aWNFeHRyYUluaXRpYWxpemVycyk7DQogICAgICAgICAgICBfX2VzRGVjb3JhdGUodGhpcywgX3N0YXRpY19wcml2YXRlX3pfZGVzY3JpcHRvciA9IHsgZ2V0OiBfX3NldEZ1bmN0aW9uTmFtZShmdW5jdGlvbiAoKSB7IHJldHVybiBfX2NsYXNzUHJpdmF0ZUZpZWxkR2V0KHRoaXMsIF9jbGFzc1RoaXMsICJmIiwgX3pfYWNjZXNzb3Jfc3RvcmFnZSk7IH0sICIjeiIsICJnZXQiKSwgc2V0OiBfX3NldEZ1bmN0aW9uTmFtZShmdW5jdGlvbiAodmFsdWUpIHsgX19jbGFzc1ByaXZhdGVGaWVsZFNldCh0aGlzLCBfY2xhc3NUaGlzLCB2YWx1ZSwgImYiLCBfel9hY2Nlc3Nvcl9zdG9yYWdlKTsgfSwgIiN6IiwgInNldCIpIH0sIF9zdGF0aWNfcHJpdmF0ZV96X2RlY29yYXRvcnMsIHsga2luZDogImFjY2Vzc29yIiwgbmFtZTogIiN6Iiwgc3RhdGljOiB0cnVlLCBwcml2YXRlOiB0cnVlLCBhY2Nlc3M6IHsgaGFzOiBvYmogPT4gX19jbGFzc1ByaXZhdGVGaWVsZEluKF9jbGFzc1RoaXMsIG9iaiksIGdldDogb2JqID0+IF9fY2xhc3NQcml2YXRlRmllbGRHZXQob2JqLCBfY2xhc3NUaGlzLCAiYSIsIF96X2dldCksIHNldDogKG9iaiwgdmFsdWUpID0+IHsgX19jbGFzc1ByaXZhdGVGaWVsZFNldChvYmosIF9jbGFzc1RoaXMsIHZhbHVlLCAiYSIsIF96X3NldCk7IH0gfSB9LCBfc3RhdGljX3ByaXZhdGVfel9pbml0aWFsaXplcnMsIF9zdGF0aWNFeHRyYUluaXRpYWxpemVycyk7DQogICAgICAgICAgICBfX2VzRGVjb3JhdGUodGhpcywgbnVsbCwgX21ldGhvZF9kZWNvcmF0b3JzLCB7IGtpbmQ6ICJtZXRob2QiLCBuYW1lOiAibWV0aG9kIiwgc3RhdGljOiBmYWxzZSwgcHJpdmF0ZTogZmFsc2UsIGFjY2VzczogeyBoYXM6IG9iaiA9PiAibWV0aG9kIiBpbiBvYmosIGdldDogb2JqID0+IG9iai5tZXRob2QgfSB9LCBudWxsLCBfaW5zdGFuY2VFeHRyYUluaXRpYWxpemVycyk7DQogICAgICAgICAgICBfX2VzRGVjb3JhdGUodGhpcywgbnVsbCwgX2dldF94X2RlY29yYXRvcnMsIHsga2luZDogImdldHRlciIsIG5hbWU6ICJ4Iiwgc3RhdGljOiBmYWxzZSwgcHJpdmF0ZTogZmFsc2UsIGFjY2VzczogeyBoYXM6IG9iaiA9PiAieCIgaW4gb2JqLCBnZXQ6IG9iaiA9PiBvYmoueCB9IH0sIG51bGwsIF9pbnN0YW5jZUV4dHJhSW5pdGlhbGl6ZXJzKTsNCiAgICAgICAgICAgIF9fZXNEZWNvcmF0ZSh0aGlzLCBudWxsLCBfc2V0X3hfZGVjb3JhdG9ycywgeyBraW5kOiAic2V0dGVyIiwgbmFtZTogIngiLCBzdGF0aWM6IGZhbHNlLCBwcml2YXRlOiBmYWxzZSwgYWNjZXNzOiB7IGhhczogb2JqID0+ICJ4IiBpbiBvYmosIHNldDogKG9iaiwgdmFsdWUpID0+IHsgb2JqLnggPSB2YWx1ZTsgfSB9IH0sIG51bGwsIF9pbnN0YW5jZUV4dHJhSW5pdGlhbGl6ZXJzKTsNCiAgICAgICAgICAgIF9fZXNEZWNvcmF0ZSh0aGlzLCBudWxsLCBfel9kZWNvcmF0b3JzLCB7IGtpbmQ6ICJhY2Nlc3NvciIsIG5hbWU6ICJ6Iiwgc3RhdGljOiBmYWxzZSwgcHJpdmF0ZTogZmFsc2UsIGFjY2VzczogeyBoYXM6IG9iaiA9PiAieiIgaW4gb2JqLCBnZXQ6IG9iaiA9PiBvYmoueiwgc2V0OiAob2JqLCB2YWx1ZSkgPT4geyBvYmoueiA9IHZhbHVlOyB9IH0gfSwgX3pfaW5pdGlhbGl6ZXJzLCBfaW5zdGFuY2VFeHRyYUluaXRpYWxpemVycyk7DQogICAgICAgICAgICBfX2VzRGVjb3JhdGUobnVsbCwgbnVsbCwgX3N0YXRpY19wcml2YXRlX3lfZGVjb3JhdG9ycywgeyBraW5kOiAiZmllbGQiLCBuYW1lOiAiI3kiLCBzdGF0aWM6IHRydWUsIHByaXZhdGU6IHRydWUsIGFjY2VzczogeyBoYXM6IG9iaiA9PiBfX2NsYXNzUHJpdmF0ZUZpZWxkSW4oX2NsYXNzVGhpcywgb2JqKSwgZ2V0OiBvYmogPT4gX19jbGFzc1ByaXZhdGVGaWVsZEdldChvYmosIF9jbGFzc1RoaXMsICJmIiwgX3kpLCBzZXQ6IChvYmosIHZhbHVlKSA9PiB7IF9fY2xhc3NQcml2YXRlRmllbGRTZXQob2JqLCBfY2xhc3NUaGlzLCB2YWx1ZSwgImYiLCBfeSk7IH0gfSB9LCBfc3RhdGljX3ByaXZhdGVfeV9pbml0aWFsaXplcnMsIF9zdGF0aWNFeHRyYUluaXRpYWxpemVycyk7DQogICAgICAgICAgICBfX2VzRGVjb3JhdGUobnVsbCwgbnVsbCwgX3lfZGVjb3JhdG9ycywgeyBraW5kOiAiZmllbGQiLCBuYW1lOiAieSIsIHN0YXRpYzogZmFsc2UsIHByaXZhdGU6IGZhbHNlLCBhY2Nlc3M6IHsgaGFzOiBvYmogPT4gInkiIGluIG9iaiwgZ2V0OiBvYmogPT4gb2JqLnksIHNldDogKG9iaiwgdmFsdWUpID0+IHsgb2JqLnkgPSB2YWx1ZTsgfSB9IH0sIF95X2luaXRpYWxpemVycywgX2luc3RhbmNlRXh0cmFJbml0aWFsaXplcnMpOw0KICAgICAgICAgICAgX19lc0RlY29yYXRlKG51bGwsIF9jbGFzc0Rlc2NyaXB0b3IgPSB7IHZhbHVlOiB0aGlzIH0sIF9jbGFzc0RlY29yYXRvcnMsIHsga2luZDogImNsYXNzIiwgbmFtZTogdGhpcy5uYW1lIH0sIG51bGwsIF9jbGFzc0V4dHJhSW5pdGlhbGl6ZXJzKTsNCiAgICAgICAgICAgIEMgPSBfY2xhc3NUaGlzID0gX2NsYXNzRGVzY3JpcHRvci52YWx1ZTsNCiAgICAgICAgICAgIF9fcnVuSW5pdGlhbGl6ZXJzKF9jbGFzc1RoaXMsIF9zdGF0aWNFeHRyYUluaXRpYWxpemVycyk7DQogICAgICAgIH0NCiAgICAgICAgbWV0aG9kKCkgeyB9DQogICAgICAgIGdldCB4KCkgeyByZXR1cm4gMTsgfQ0KICAgICAgICBzZXQgeCh2YWx1ZSkgeyB9DQogICAgICAgIHkgPSAoX19ydW5Jbml0aWFsaXplcnModGhpcywgX2luc3RhbmNlRXh0cmFJbml0aWFsaXplcnMpLCBfX3J1bkluaXRpYWxpemVycyh0aGlzLCBfeV9pbml0aWFsaXplcnMsIDEpKTsNCiAgICAgICAgI3pfYWNjZXNzb3Jfc3RvcmFnZSA9IF9fcnVuSW5pdGlhbGl6ZXJzKHRoaXMsIF96X2luaXRpYWxpemVycywgMSk7DQogICAgICAgIGdldCB6KCkgeyByZXR1cm4gdGhpcy4jel9hY2Nlc3Nvcl9zdG9yYWdlOyB9DQogICAgICAgIHNldCB6KHZhbHVlKSB7IHRoaXMuI3pfYWNjZXNzb3Jfc3RvcmFnZSA9IHZhbHVlOyB9DQogICAgICAgIHN0YXRpYyB7DQogICAgICAgICAgICBfeSA9IHsgdmFsdWU6IF9fcnVuSW5pdGlhbGl6ZXJzKF9jbGFzc1RoaXMsIF9zdGF0aWNfcHJpdmF0ZV95X2luaXRpYWxpemVycywgMSkgfTsNCiAgICAgICAgfQ0KICAgICAgICBzdGF0aWMgew0KICAgICAgICAgICAgX3pfYWNjZXNzb3Jfc3RvcmFnZSA9IHsgdmFsdWU6IF9fcnVuSW5pdGlhbGl6ZXJzKF9jbGFzc1RoaXMsIF9zdGF0aWNfcHJpdmF0ZV96X2luaXRpYWxpemVycywgMSkgfTsNCiAgICAgICAgfQ0KICAgICAgICBzdGF0aWMgew0KICAgICAgICAgICAgX19ydW5Jbml0aWFsaXplcnMoX2NsYXNzVGhpcywgX2NsYXNzRXh0cmFJbml0aWFsaXplcnMpOw0KICAgICAgICB9DQogICAgfTsNCiAgICByZXR1cm4gQyA9IF9jbGFzc1RoaXM7DQp9KSgpOw0KLy8jIHNvdXJjZU1hcHBpbmdVUkw9ZXNEZWNvcmF0b3JzLWNsYXNzRGVjbGFyYXRpb24tc291cmNlTWFwLmpzLm1hcA==,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiZXNEZWNvcmF0b3JzLWNsYXNzRGVjbGFyYXRpb24tc291cmNlTWFwLmpzIiwic291cmNlUm9vdCI6IiIsInNvdXJjZXMiOlsiZXNEZWNvcmF0b3JzLWNsYXNzRGVjbGFyYXRpb24tc291cmNlTWFwLnRzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiI7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7O0lBSU0sQ0FBQzs7NEJBRk4sR0FBRyxFQUNILEdBQUc7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7a0NBRUMsR0FBRyxFQUNILEdBQUc7aUNBR0gsR0FBRyxFQUNILEdBQUc7aUNBR0gsR0FBRyxFQUNILEdBQUc7NkJBR0gsR0FBRyxFQUNILEdBQUc7NkJBR0gsR0FBRyxFQUNILEdBQUc7aURBR0gsR0FBRyxFQUNILEdBQUc7Z0RBR0gsR0FBRyxFQUNILEdBQUc7Z0RBR0gsR0FBRyxFQUNILEdBQUc7NENBR0gsR0FBRyxFQUNILEdBQUc7NENBR0gsR0FBRyxFQUNILEdBQUc7WUFmSix5REFBQSx5QkFBQSxjQUFrQixDQUFDLFlBQUEsZ1JBQUE7WUFJbkIsd0RBQUEsdUJBQUEsY0FBa0IsT0FBTyxDQUFDLENBQUMsQ0FBQyxDQUFDLGNBQUEscVFBQUE7WUFJN0Isd0RBQUEsdUJBQUEsVUFBYyxLQUFhLElBQUksQ0FBQyxjQUFBLDBSQUFBO1lBUWhDLG9EQUFBLHVCQUFBLDBGQUF1QixjQUFBLEVBQXZCLHVCQUFBLCtGQUF1QixjQUFBLG9YQUFBO1lBcEN2QixxS0FBQSxNQUFNLHdDQUFLO1lBSVgsMEpBQUksQ0FBQyx3Q0FBZ0I7WUFJckIscUtBQUksQ0FBQyxtREFBbUI7WUFReEIsd0pBQVMsQ0FBQyw2QkFBRCxDQUFDLDhEQUFLO1lBZ0JmLDhYQUFjO1lBcEJkLHFKQUFBLENBQUMsNkJBQUQsQ0FBQyw4REFBSztZQWZWLDRJQXdDQzs7WUF4Q0ssd0RBQUM7O1FBR0gsTUFBTSxLQUFJLENBQUM7UUFJWCxJQUFJLENBQUMsS0FBSyxPQUFPLENBQUMsQ0FBQyxDQUFDLENBQUM7UUFJckIsSUFBSSxDQUFDLENBQUMsS0FBYSxJQUFJLENBQUM7UUFJeEIsQ0FBQyxrR0FBRyxDQUFDLEdBQUM7UUFJTiwrREFBYSxDQUFDLEVBQUM7UUFBZixJQUFTLENBQUMsdUNBQUs7UUFBZixJQUFTLENBQUMsNkNBQUs7O1lBZ0JSLDRFQUFLLENBQUMsR0FBSixDQUFLOzs7WUFJRSw2RkFBSyxDQUFDLEdBQUosQ0FBSzs7O1lBdkNyQix1REFBQyJ9,ZGVjbGFyZSB2YXIgZGVjOiBhbnk7CgpAZGVjCkBkZWMKY2xhc3MgQyB7CiAgICBAZGVjCiAgICBAZGVjCiAgICBtZXRob2QoKSB7fQoKICAgIEBkZWMKICAgIEBkZWMKICAgIGdldCB4KCkgeyByZXR1cm4gMTsgfQoKICAgIEBkZWMKICAgIEBkZWMKICAgIHNldCB4KHZhbHVlOiBudW1iZXIpIHsgfQoKICAgIEBkZWMKICAgIEBkZWMKICAgIHkgPSAxOwoKICAgIEBkZWMKICAgIEBkZWMKICAgIGFjY2Vzc29yIHogPSAxOwoKICAgIEBkZWMKICAgIEBkZWMKICAgIHN0YXRpYyAjbWV0aG9kKCkge30KCiAgICBAZGVjCiAgICBAZGVjCiAgICBzdGF0aWMgZ2V0ICN4KCkgeyByZXR1cm4gMTsgfQoKICAgIEBkZWMKICAgIEBkZWMKICAgIHN0YXRpYyBzZXQgI3godmFsdWU6IG51bWJlcikgeyB9CgogICAgQGRlYwogICAgQGRlYwogICAgc3RhdGljICN5ID0gMTsKCiAgICBAZGVjCiAgICBAZGVjCiAgICBzdGF0aWMgYWNjZXNzb3IgI3ogPSAxOwp9Cg== ++{"version":3,"file":"esDecorators-classDeclaration-sourceMap.js","sourceRoot":"","sources":["esDecorators-classDeclaration-sourceMap.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;IAIM,CAAC;;4BAFN,GAAG,EACH,GAAG;;;;;;;;;;;;;;;;;;;;;;;;;;;;;kCAEC,GAAG,EACH,GAAG;iCAGH,GAAG,EACH,GAAG;iCAGH,GAAG,EACH,GAAG;6BAGH,GAAG,EACH,GAAG;6BAGH,GAAG,EACH,GAAG;iDAGH,GAAG,EACH,GAAG;gDAGH,GAAG,EACH,GAAG;gDAGH,GAAG,EACH,GAAG;4CAGH,GAAG,EACH,GAAG;4CAGH,GAAG,EACH,GAAG;YAfJ,yDAAA,yBAAA,cAAkB,CAAC,YAAA,kRAAA;YAInB,wDAAA,uBAAA,cAAkB,OAAO,CAAC,CAAC,CAAC,CAAC,cAAA,uQAAA;YAI7B,wDAAA,uBAAA,UAAc,KAAa,IAAI,CAAC,cAAA,4RAAA;YAQhC,oDAAA,uBAAA,4FAAuB,cAAA,EAAvB,uBAAA,iGAAuB,cAAA,wXAAA;YApCvB,qKAAA,MAAM,wCAAK;YAIX,0JAAI,CAAC,wCAAgB;YAIrB,qKAAI,CAAC,mDAAmB;YAQxB,wJAAS,CAAC,6BAAD,CAAC,8DAAK;YAgBf,kYAAc;YApBd,qJAAA,CAAC,6BAAD,CAAC,8DAAK;YAfV,wJAwCC;;YAxCK,wDAAC;;QAGH,MAAM,KAAI,CAAC;QAIX,IAAI,CAAC,KAAK,OAAO,CAAC,CAAC,CAAC,CAAC;QAIrB,IAAI,CAAC,CAAC,KAAa,IAAI,CAAC;QAIxB,CAAC,kGAAG,CAAC,GAAC;QAIN,+DAAa,CAAC,EAAC;QAAf,IAAS,CAAC,uCAAK;QAAf,IAAS,CAAC,6CAAK;;YAgBR,8EAAK,CAAC,GAAJ,CAAK;;;YAIE,+FAAK,CAAC,GAAJ,CAAK;;;YAvCrB,uDAAC"} ++//// https://sokra.github.io/source-map-visualization#base64,dmFyIF9fZXNEZWNvcmF0ZSA9ICh0aGlzICYmIHRoaXMuX19lc0RlY29yYXRlKSB8fCBmdW5jdGlvbiAoY3RvciwgZGVzY3JpcHRvckluLCBkZWNvcmF0b3JzLCBjb250ZXh0SW4sIGluaXRpYWxpemVycywgZXh0cmFJbml0aWFsaXplcnMpIHsNCiAgICBmdW5jdGlvbiBhY2NlcHQoZikgeyBpZiAoZiAhPT0gdm9pZCAwICYmIHR5cGVvZiBmICE9PSAiZnVuY3Rpb24iKSB0aHJvdyBuZXcgVHlwZUVycm9yKCJGdW5jdGlvbiBleHBlY3RlZCIpOyByZXR1cm4gZjsgfQ0KICAgIHZhciBraW5kID0gY29udGV4dEluLmtpbmQsIGtleSA9IGtpbmQgPT09ICJnZXR0ZXIiID8gImdldCIgOiBraW5kID09PSAic2V0dGVyIiA/ICJzZXQiIDogInZhbHVlIjsNCiAgICB2YXIgdGFyZ2V0ID0gIWRlc2NyaXB0b3JJbiAmJiBjdG9yID8gY29udGV4dEluWyJzdGF0aWMiXSA/IGN0b3IgOiBjdG9yLnByb3RvdHlwZSA6IG51bGw7DQogICAgdmFyIGRlc2NyaXB0b3IgPSBkZXNjcmlwdG9ySW4gfHwgKHRhcmdldCA/IE9iamVjdC5nZXRPd25Qcm9wZXJ0eURlc2NyaXB0b3IodGFyZ2V0LCBjb250ZXh0SW4ubmFtZSkgOiB7fSk7DQogICAgdmFyIF8sIGRvbmUgPSBmYWxzZTsNCiAgICBmb3IgKHZhciBpID0gZGVjb3JhdG9ycy5sZW5ndGggLSAxOyBpID49IDA7IGktLSkgew0KICAgICAgICB2YXIgY29udGV4dCA9IHt9Ow0KICAgICAgICBmb3IgKHZhciBwIGluIGNvbnRleHRJbikgY29udGV4dFtwXSA9IHAgPT09ICJhY2Nlc3MiID8ge30gOiBjb250ZXh0SW5bcF07DQogICAgICAgIGZvciAodmFyIHAgaW4gY29udGV4dEluLmFjY2VzcykgY29udGV4dC5hY2Nlc3NbcF0gPSBjb250ZXh0SW4uYWNjZXNzW3BdOw0KICAgICAgICBjb250ZXh0LmFkZEluaXRpYWxpemVyID0gZnVuY3Rpb24gKGYpIHsgaWYgKGRvbmUpIHRocm93IG5ldyBUeXBlRXJyb3IoIkNhbm5vdCBhZGQgaW5pdGlhbGl6ZXJzIGFmdGVyIGRlY29yYXRpb24gaGFzIGNvbXBsZXRlZCIpOyBleHRyYUluaXRpYWxpemVycy5wdXNoKGFjY2VwdChmIHx8IG51bGwpKTsgfTsNCiAgICAgICAgdmFyIHJlc3VsdCA9ICgwLCBkZWNvcmF0b3JzW2ldKShraW5kID09PSAiYWNjZXNzb3IiID8geyBnZXQ6IGRlc2NyaXB0b3IuZ2V0LCBzZXQ6IGRlc2NyaXB0b3Iuc2V0IH0gOiBkZXNjcmlwdG9yW2tleV0sIGNvbnRleHQpOw0KICAgICAgICBpZiAoa2luZCA9PT0gImFjY2Vzc29yIikgew0KICAgICAgICAgICAgaWYgKHJlc3VsdCA9PT0gdm9pZCAwKSBjb250aW51ZTsNCiAgICAgICAgICAgIGlmIChyZXN1bHQgPT09IG51bGwgfHwgdHlwZW9mIHJlc3VsdCAhPT0gIm9iamVjdCIpIHRocm93IG5ldyBUeXBlRXJyb3IoIk9iamVjdCBleHBlY3RlZCIpOw0KICAgICAgICAgICAgaWYgKF8gPSBhY2NlcHQocmVzdWx0LmdldCkpIGRlc2NyaXB0b3IuZ2V0ID0gXzsNCiAgICAgICAgICAgIGlmIChfID0gYWNjZXB0KHJlc3VsdC5zZXQpKSBkZXNjcmlwdG9yLnNldCA9IF87DQogICAgICAgICAgICBpZiAoXyA9IGFjY2VwdChyZXN1bHQuaW5pdCkpIGluaXRpYWxpemVycy51bnNoaWZ0KF8pOw0KICAgICAgICB9DQogICAgICAgIGVsc2UgaWYgKF8gPSBhY2NlcHQocmVzdWx0KSkgew0KICAgICAgICAgICAgaWYgKGtpbmQgPT09ICJmaWVsZCIpIGluaXRpYWxpemVycy51bnNoaWZ0KF8pOw0KICAgICAgICAgICAgZWxzZSBkZXNjcmlwdG9yW2tleV0gPSBfOw0KICAgICAgICB9DQogICAgfQ0KICAgIGlmICh0YXJnZXQpIE9iamVjdC5kZWZpbmVQcm9wZXJ0eSh0YXJnZXQsIGNvbnRleHRJbi5uYW1lLCBkZXNjcmlwdG9yKTsNCiAgICBkb25lID0gdHJ1ZTsNCn07DQp2YXIgX19ydW5Jbml0aWFsaXplcnMgPSAodGhpcyAmJiB0aGlzLl9fcnVuSW5pdGlhbGl6ZXJzKSB8fCBmdW5jdGlvbiAodGhpc0FyZywgaW5pdGlhbGl6ZXJzLCB2YWx1ZSkgew0KICAgIHZhciB1c2VWYWx1ZSA9IGFyZ3VtZW50cy5sZW5ndGggPiAyOw0KICAgIGZvciAodmFyIGkgPSAwOyBpIDwgaW5pdGlhbGl6ZXJzLmxlbmd0aDsgaSsrKSB7DQogICAgICAgIHZhbHVlID0gdXNlVmFsdWUgPyBpbml0aWFsaXplcnNbaV0uY2FsbCh0aGlzQXJnLCB2YWx1ZSkgOiBpbml0aWFsaXplcnNbaV0uY2FsbCh0aGlzQXJnKTsNCiAgICB9DQogICAgcmV0dXJuIHVzZVZhbHVlID8gdmFsdWUgOiB2b2lkIDA7DQp9Ow0KdmFyIF9fc2V0RnVuY3Rpb25OYW1lID0gKHRoaXMgJiYgdGhpcy5fX3NldEZ1bmN0aW9uTmFtZSkgfHwgZnVuY3Rpb24gKGYsIG5hbWUsIHByZWZpeCkgew0KICAgIGlmICh0eXBlb2YgbmFtZSA9PT0gInN5bWJvbCIpIG5hbWUgPSBuYW1lLmRlc2NyaXB0aW9uID8gIlsiLmNvbmNhdChuYW1lLmRlc2NyaXB0aW9uLCAiXSIpIDogIiI7DQogICAgcmV0dXJuIE9iamVjdC5kZWZpbmVQcm9wZXJ0eShmLCAibmFtZSIsIHsgY29uZmlndXJhYmxlOiB0cnVlLCB2YWx1ZTogcHJlZml4ID8gIiIuY29uY2F0KHByZWZpeCwgIiAiLCBuYW1lKSA6IG5hbWUgfSk7DQp9Ow0KdmFyIF9fY2xhc3NQcml2YXRlRmllbGRJbiA9ICh0aGlzICYmIHRoaXMuX19jbGFzc1ByaXZhdGVGaWVsZEluKSB8fCBmdW5jdGlvbihzdGF0ZSwgcmVjZWl2ZXIpIHsNCiAgICBpZiAocmVjZWl2ZXIgPT09IG51bGwgfHwgKHR5cGVvZiByZWNlaXZlciAhPT0gIm9iamVjdCIgJiYgdHlwZW9mIHJlY2VpdmVyICE9PSAiZnVuY3Rpb24iKSkgdGhyb3cgbmV3IFR5cGVFcnJvcigiQ2Fubm90IHVzZSAnaW4nIG9wZXJhdG9yIG9uIG5vbi1vYmplY3QiKTsNCiAgICByZXR1cm4gdHlwZW9mIHN0YXRlID09PSAiZnVuY3Rpb24iID8gcmVjZWl2ZXIgPT09IHN0YXRlIDogc3RhdGUuaGFzKHJlY2VpdmVyKTsNCn07DQp2YXIgX19jbGFzc1ByaXZhdGVGaWVsZEdldCA9ICh0aGlzICYmIHRoaXMuX19jbGFzc1ByaXZhdGVGaWVsZEdldCkgfHwgZnVuY3Rpb24gKHJlY2VpdmVyLCBzdGF0ZSwga2luZCwgZikgew0KICAgIGlmIChraW5kID09PSAiYSIgJiYgIWYpIHRocm93IG5ldyBUeXBlRXJyb3IoIlByaXZhdGUgYWNjZXNzb3Igd2FzIGRlZmluZWQgd2l0aG91dCBhIGdldHRlciIpOw0KICAgIGlmICh0eXBlb2Ygc3RhdGUgPT09ICJmdW5jdGlvbiIgPyByZWNlaXZlciAhPT0gc3RhdGUgfHwgIWYgOiAhc3RhdGUuaGFzKHJlY2VpdmVyKSkgdGhyb3cgbmV3IFR5cGVFcnJvcigiQ2Fubm90IHJlYWQgcHJpdmF0ZSBtZW1iZXIgZnJvbSBhbiBvYmplY3Qgd2hvc2UgY2xhc3MgZGlkIG5vdCBkZWNsYXJlIGl0Iik7DQogICAgcmV0dXJuIGtpbmQgPT09ICJtIiA/IGYgOiBraW5kID09PSAiYSIgPyBmLmNhbGwocmVjZWl2ZXIpIDogZiA/IGYudmFsdWUgOiBzdGF0ZS5nZXQocmVjZWl2ZXIpOw0KfTsNCnZhciBfX2NsYXNzUHJpdmF0ZUZpZWxkU2V0ID0gKHRoaXMgJiYgdGhpcy5fX2NsYXNzUHJpdmF0ZUZpZWxkU2V0KSB8fCBmdW5jdGlvbiAocmVjZWl2ZXIsIHN0YXRlLCB2YWx1ZSwga2luZCwgZikgew0KICAgIGlmIChraW5kID09PSAibSIpIHRocm93IG5ldyBUeXBlRXJyb3IoIlByaXZhdGUgbWV0aG9kIGlzIG5vdCB3cml0YWJsZSIpOw0KICAgIGlmIChraW5kID09PSAiYSIgJiYgIWYpIHRocm93IG5ldyBUeXBlRXJyb3IoIlByaXZhdGUgYWNjZXNzb3Igd2FzIGRlZmluZWQgd2l0aG91dCBhIHNldHRlciIpOw0KICAgIGlmICh0eXBlb2Ygc3RhdGUgPT09ICJmdW5jdGlvbiIgPyByZWNlaXZlciAhPT0gc3RhdGUgfHwgIWYgOiAhc3RhdGUuaGFzKHJlY2VpdmVyKSkgdGhyb3cgbmV3IFR5cGVFcnJvcigiQ2Fubm90IHdyaXRlIHByaXZhdGUgbWVtYmVyIHRvIGFuIG9iamVjdCB3aG9zZSBjbGFzcyBkaWQgbm90IGRlY2xhcmUgaXQiKTsNCiAgICByZXR1cm4gKGtpbmQgPT09ICJhIiA/IGYuY2FsbChyZWNlaXZlciwgdmFsdWUpIDogZiA/IGYudmFsdWUgPSB2YWx1ZSA6IHN0YXRlLnNldChyZWNlaXZlciwgdmFsdWUpKSwgdmFsdWU7DQp9Ow0KbGV0IEMgPSAoKCkgPT4gew0KICAgIHZhciBfQ19tZXRob2RfZ2V0LCBfQ194X2dldCwgX0NfeF9zZXQsIF9DX3ksIF9DX3pfYWNjZXNzb3Jfc3RvcmFnZSwgX0Nfel9nZXQsIF9DX3pfc2V0Ow0KICAgIGxldCBfY2xhc3NEZWNvcmF0b3JzID0gW2RlYywgZGVjXTsNCiAgICBsZXQgX2NsYXNzRGVzY3JpcHRvcjsNCiAgICBsZXQgX2NsYXNzRXh0cmFJbml0aWFsaXplcnMgPSBbXTsNCiAgICBsZXQgX2NsYXNzVGhpczsNCiAgICBsZXQgX3N0YXRpY0V4dHJhSW5pdGlhbGl6ZXJzID0gW107DQogICAgbGV0IF9pbnN0YW5jZUV4dHJhSW5pdGlhbGl6ZXJzID0gW107DQogICAgbGV0IF9zdGF0aWNfcHJpdmF0ZV9tZXRob2RfZGVjb3JhdG9yczsNCiAgICBsZXQgX3N0YXRpY19wcml2YXRlX21ldGhvZF9kZXNjcmlwdG9yOw0KICAgIGxldCBfc3RhdGljX3ByaXZhdGVfZ2V0X3hfZGVjb3JhdG9yczsNCiAgICBsZXQgX3N0YXRpY19wcml2YXRlX2dldF94X2Rlc2NyaXB0b3I7DQogICAgbGV0IF9zdGF0aWNfcHJpdmF0ZV9zZXRfeF9kZWNvcmF0b3JzOw0KICAgIGxldCBfc3RhdGljX3ByaXZhdGVfc2V0X3hfZGVzY3JpcHRvcjsNCiAgICBsZXQgX3N0YXRpY19wcml2YXRlX3lfZGVjb3JhdG9yczsNCiAgICBsZXQgX3N0YXRpY19wcml2YXRlX3lfaW5pdGlhbGl6ZXJzID0gW107DQogICAgbGV0IF9zdGF0aWNfcHJpdmF0ZV96X2RlY29yYXRvcnM7DQogICAgbGV0IF9zdGF0aWNfcHJpdmF0ZV96X2luaXRpYWxpemVycyA9IFtdOw0KICAgIGxldCBfc3RhdGljX3ByaXZhdGVfel9kZXNjcmlwdG9yOw0KICAgIGxldCBfbWV0aG9kX2RlY29yYXRvcnM7DQogICAgbGV0IF9nZXRfeF9kZWNvcmF0b3JzOw0KICAgIGxldCBfc2V0X3hfZGVjb3JhdG9yczsNCiAgICBsZXQgX3lfZGVjb3JhdG9yczsNCiAgICBsZXQgX3lfaW5pdGlhbGl6ZXJzID0gW107DQogICAgbGV0IF96X2RlY29yYXRvcnM7DQogICAgbGV0IF96X2luaXRpYWxpemVycyA9IFtdOw0KICAgIHZhciBDID0gY2xhc3Mgew0KICAgICAgICBzdGF0aWMgeyBfY2xhc3NUaGlzID0gdGhpczsgfQ0KICAgICAgICBzdGF0aWMgeyBfX3NldEZ1bmN0aW9uTmFtZSh0aGlzLCAiQyIpOyB9DQogICAgICAgIHN0YXRpYyB7IF9DX21ldGhvZF9nZXQgPSBmdW5jdGlvbiBfQ19tZXRob2RfZ2V0KCkgeyByZXR1cm4gX3N0YXRpY19wcml2YXRlX21ldGhvZF9kZXNjcmlwdG9yLnZhbHVlOyB9LCBfQ194X2dldCA9IGZ1bmN0aW9uIF9DX3hfZ2V0KCkgeyByZXR1cm4gX3N0YXRpY19wcml2YXRlX2dldF94X2Rlc2NyaXB0b3IuZ2V0LmNhbGwodGhpcyk7IH0sIF9DX3hfc2V0ID0gZnVuY3Rpb24gX0NfeF9zZXQodmFsdWUpIHsgcmV0dXJuIF9zdGF0aWNfcHJpdmF0ZV9zZXRfeF9kZXNjcmlwdG9yLnNldC5jYWxsKHRoaXMsIHZhbHVlKTsgfSwgX0Nfel9nZXQgPSBmdW5jdGlvbiBfQ196X2dldCgpIHsgcmV0dXJuIF9zdGF0aWNfcHJpdmF0ZV96X2Rlc2NyaXB0b3IuZ2V0LmNhbGwodGhpcyk7IH0sIF9DX3pfc2V0ID0gZnVuY3Rpb24gX0Nfel9zZXQodmFsdWUpIHsgcmV0dXJuIF9zdGF0aWNfcHJpdmF0ZV96X2Rlc2NyaXB0b3Iuc2V0LmNhbGwodGhpcywgdmFsdWUpOyB9OyB9DQogICAgICAgIHN0YXRpYyB7DQogICAgICAgICAgICBfbWV0aG9kX2RlY29yYXRvcnMgPSBbZGVjLCBkZWNdOw0KICAgICAgICAgICAgX2dldF94X2RlY29yYXRvcnMgPSBbZGVjLCBkZWNdOw0KICAgICAgICAgICAgX3NldF94X2RlY29yYXRvcnMgPSBbZGVjLCBkZWNdOw0KICAgICAgICAgICAgX3lfZGVjb3JhdG9ycyA9IFtkZWMsIGRlY107DQogICAgICAgICAgICBfel9kZWNvcmF0b3JzID0gW2RlYywgZGVjXTsNCiAgICAgICAgICAgIF9zdGF0aWNfcHJpdmF0ZV9tZXRob2RfZGVjb3JhdG9ycyA9IFtkZWMsIGRlY107DQogICAgICAgICAgICBfc3RhdGljX3ByaXZhdGVfZ2V0X3hfZGVjb3JhdG9ycyA9IFtkZWMsIGRlY107DQogICAgICAgICAgICBfc3RhdGljX3ByaXZhdGVfc2V0X3hfZGVjb3JhdG9ycyA9IFtkZWMsIGRlY107DQogICAgICAgICAgICBfc3RhdGljX3ByaXZhdGVfeV9kZWNvcmF0b3JzID0gW2RlYywgZGVjXTsNCiAgICAgICAgICAgIF9zdGF0aWNfcHJpdmF0ZV96X2RlY29yYXRvcnMgPSBbZGVjLCBkZWNdOw0KICAgICAgICAgICAgX19lc0RlY29yYXRlKHRoaXMsIF9zdGF0aWNfcHJpdmF0ZV9tZXRob2RfZGVzY3JpcHRvciA9IHsgdmFsdWU6IF9fc2V0RnVuY3Rpb25OYW1lKGZ1bmN0aW9uICgpIHsgfSwgIiNtZXRob2QiKSB9LCBfc3RhdGljX3ByaXZhdGVfbWV0aG9kX2RlY29yYXRvcnMsIHsga2luZDogIm1ldGhvZCIsIG5hbWU6ICIjbWV0aG9kIiwgc3RhdGljOiB0cnVlLCBwcml2YXRlOiB0cnVlLCBhY2Nlc3M6IHsgaGFzOiBvYmogPT4gX19jbGFzc1ByaXZhdGVGaWVsZEluKF9jbGFzc1RoaXMsIG9iaiksIGdldDogb2JqID0+IF9fY2xhc3NQcml2YXRlRmllbGRHZXQob2JqLCBfY2xhc3NUaGlzLCAiYSIsIF9DX21ldGhvZF9nZXQpIH0gfSwgbnVsbCwgX3N0YXRpY0V4dHJhSW5pdGlhbGl6ZXJzKTsNCiAgICAgICAgICAgIF9fZXNEZWNvcmF0ZSh0aGlzLCBfc3RhdGljX3ByaXZhdGVfZ2V0X3hfZGVzY3JpcHRvciA9IHsgZ2V0OiBfX3NldEZ1bmN0aW9uTmFtZShmdW5jdGlvbiAoKSB7IHJldHVybiAxOyB9LCAiI3giLCAiZ2V0IikgfSwgX3N0YXRpY19wcml2YXRlX2dldF94X2RlY29yYXRvcnMsIHsga2luZDogImdldHRlciIsIG5hbWU6ICIjeCIsIHN0YXRpYzogdHJ1ZSwgcHJpdmF0ZTogdHJ1ZSwgYWNjZXNzOiB7IGhhczogb2JqID0+IF9fY2xhc3NQcml2YXRlRmllbGRJbihfY2xhc3NUaGlzLCBvYmopLCBnZXQ6IG9iaiA9PiBfX2NsYXNzUHJpdmF0ZUZpZWxkR2V0KG9iaiwgX2NsYXNzVGhpcywgImEiLCBfQ194X2dldCkgfSB9LCBudWxsLCBfc3RhdGljRXh0cmFJbml0aWFsaXplcnMpOw0KICAgICAgICAgICAgX19lc0RlY29yYXRlKHRoaXMsIF9zdGF0aWNfcHJpdmF0ZV9zZXRfeF9kZXNjcmlwdG9yID0geyBzZXQ6IF9fc2V0RnVuY3Rpb25OYW1lKGZ1bmN0aW9uICh2YWx1ZSkgeyB9LCAiI3giLCAic2V0IikgfSwgX3N0YXRpY19wcml2YXRlX3NldF94X2RlY29yYXRvcnMsIHsga2luZDogInNldHRlciIsIG5hbWU6ICIjeCIsIHN0YXRpYzogdHJ1ZSwgcHJpdmF0ZTogdHJ1ZSwgYWNjZXNzOiB7IGhhczogb2JqID0+IF9fY2xhc3NQcml2YXRlRmllbGRJbihfY2xhc3NUaGlzLCBvYmopLCBzZXQ6IChvYmosIHZhbHVlKSA9PiB7IF9fY2xhc3NQcml2YXRlRmllbGRTZXQob2JqLCBfY2xhc3NUaGlzLCB2YWx1ZSwgImEiLCBfQ194X3NldCk7IH0gfSB9LCBudWxsLCBfc3RhdGljRXh0cmFJbml0aWFsaXplcnMpOw0KICAgICAgICAgICAgX19lc0RlY29yYXRlKHRoaXMsIF9zdGF0aWNfcHJpdmF0ZV96X2Rlc2NyaXB0b3IgPSB7IGdldDogX19zZXRGdW5jdGlvbk5hbWUoZnVuY3Rpb24gKCkgeyByZXR1cm4gX19jbGFzc1ByaXZhdGVGaWVsZEdldCh0aGlzLCBfY2xhc3NUaGlzLCAiZiIsIF9DX3pfYWNjZXNzb3Jfc3RvcmFnZSk7IH0sICIjeiIsICJnZXQiKSwgc2V0OiBfX3NldEZ1bmN0aW9uTmFtZShmdW5jdGlvbiAodmFsdWUpIHsgX19jbGFzc1ByaXZhdGVGaWVsZFNldCh0aGlzLCBfY2xhc3NUaGlzLCB2YWx1ZSwgImYiLCBfQ196X2FjY2Vzc29yX3N0b3JhZ2UpOyB9LCAiI3oiLCAic2V0IikgfSwgX3N0YXRpY19wcml2YXRlX3pfZGVjb3JhdG9ycywgeyBraW5kOiAiYWNjZXNzb3IiLCBuYW1lOiAiI3oiLCBzdGF0aWM6IHRydWUsIHByaXZhdGU6IHRydWUsIGFjY2VzczogeyBoYXM6IG9iaiA9PiBfX2NsYXNzUHJpdmF0ZUZpZWxkSW4oX2NsYXNzVGhpcywgb2JqKSwgZ2V0OiBvYmogPT4gX19jbGFzc1ByaXZhdGVGaWVsZEdldChvYmosIF9jbGFzc1RoaXMsICJhIiwgX0Nfel9nZXQpLCBzZXQ6IChvYmosIHZhbHVlKSA9PiB7IF9fY2xhc3NQcml2YXRlRmllbGRTZXQob2JqLCBfY2xhc3NUaGlzLCB2YWx1ZSwgImEiLCBfQ196X3NldCk7IH0gfSB9LCBfc3RhdGljX3ByaXZhdGVfel9pbml0aWFsaXplcnMsIF9zdGF0aWNFeHRyYUluaXRpYWxpemVycyk7DQogICAgICAgICAgICBfX2VzRGVjb3JhdGUodGhpcywgbnVsbCwgX21ldGhvZF9kZWNvcmF0b3JzLCB7IGtpbmQ6ICJtZXRob2QiLCBuYW1lOiAibWV0aG9kIiwgc3RhdGljOiBmYWxzZSwgcHJpdmF0ZTogZmFsc2UsIGFjY2VzczogeyBoYXM6IG9iaiA9PiAibWV0aG9kIiBpbiBvYmosIGdldDogb2JqID0+IG9iai5tZXRob2QgfSB9LCBudWxsLCBfaW5zdGFuY2VFeHRyYUluaXRpYWxpemVycyk7DQogICAgICAgICAgICBfX2VzRGVjb3JhdGUodGhpcywgbnVsbCwgX2dldF94X2RlY29yYXRvcnMsIHsga2luZDogImdldHRlciIsIG5hbWU6ICJ4Iiwgc3RhdGljOiBmYWxzZSwgcHJpdmF0ZTogZmFsc2UsIGFjY2VzczogeyBoYXM6IG9iaiA9PiAieCIgaW4gb2JqLCBnZXQ6IG9iaiA9PiBvYmoueCB9IH0sIG51bGwsIF9pbnN0YW5jZUV4dHJhSW5pdGlhbGl6ZXJzKTsNCiAgICAgICAgICAgIF9fZXNEZWNvcmF0ZSh0aGlzLCBudWxsLCBfc2V0X3hfZGVjb3JhdG9ycywgeyBraW5kOiAic2V0dGVyIiwgbmFtZTogIngiLCBzdGF0aWM6IGZhbHNlLCBwcml2YXRlOiBmYWxzZSwgYWNjZXNzOiB7IGhhczogb2JqID0+ICJ4IiBpbiBvYmosIHNldDogKG9iaiwgdmFsdWUpID0+IHsgb2JqLnggPSB2YWx1ZTsgfSB9IH0sIG51bGwsIF9pbnN0YW5jZUV4dHJhSW5pdGlhbGl6ZXJzKTsNCiAgICAgICAgICAgIF9fZXNEZWNvcmF0ZSh0aGlzLCBudWxsLCBfel9kZWNvcmF0b3JzLCB7IGtpbmQ6ICJhY2Nlc3NvciIsIG5hbWU6ICJ6Iiwgc3RhdGljOiBmYWxzZSwgcHJpdmF0ZTogZmFsc2UsIGFjY2VzczogeyBoYXM6IG9iaiA9PiAieiIgaW4gb2JqLCBnZXQ6IG9iaiA9PiBvYmoueiwgc2V0OiAob2JqLCB2YWx1ZSkgPT4geyBvYmoueiA9IHZhbHVlOyB9IH0gfSwgX3pfaW5pdGlhbGl6ZXJzLCBfaW5zdGFuY2VFeHRyYUluaXRpYWxpemVycyk7DQogICAgICAgICAgICBfX2VzRGVjb3JhdGUobnVsbCwgbnVsbCwgX3N0YXRpY19wcml2YXRlX3lfZGVjb3JhdG9ycywgeyBraW5kOiAiZmllbGQiLCBuYW1lOiAiI3kiLCBzdGF0aWM6IHRydWUsIHByaXZhdGU6IHRydWUsIGFjY2VzczogeyBoYXM6IG9iaiA9PiBfX2NsYXNzUHJpdmF0ZUZpZWxkSW4oX2NsYXNzVGhpcywgb2JqKSwgZ2V0OiBvYmogPT4gX19jbGFzc1ByaXZhdGVGaWVsZEdldChvYmosIF9jbGFzc1RoaXMsICJmIiwgX0NfeSksIHNldDogKG9iaiwgdmFsdWUpID0+IHsgX19jbGFzc1ByaXZhdGVGaWVsZFNldChvYmosIF9jbGFzc1RoaXMsIHZhbHVlLCAiZiIsIF9DX3kpOyB9IH0gfSwgX3N0YXRpY19wcml2YXRlX3lfaW5pdGlhbGl6ZXJzLCBfc3RhdGljRXh0cmFJbml0aWFsaXplcnMpOw0KICAgICAgICAgICAgX19lc0RlY29yYXRlKG51bGwsIG51bGwsIF95X2RlY29yYXRvcnMsIHsga2luZDogImZpZWxkIiwgbmFtZTogInkiLCBzdGF0aWM6IGZhbHNlLCBwcml2YXRlOiBmYWxzZSwgYWNjZXNzOiB7IGhhczogb2JqID0+ICJ5IiBpbiBvYmosIGdldDogb2JqID0+IG9iai55LCBzZXQ6IChvYmosIHZhbHVlKSA9PiB7IG9iai55ID0gdmFsdWU7IH0gfSB9LCBfeV9pbml0aWFsaXplcnMsIF9pbnN0YW5jZUV4dHJhSW5pdGlhbGl6ZXJzKTsNCiAgICAgICAgICAgIF9fZXNEZWNvcmF0ZShudWxsLCBfY2xhc3NEZXNjcmlwdG9yID0geyB2YWx1ZTogX2NsYXNzVGhpcyB9LCBfY2xhc3NEZWNvcmF0b3JzLCB7IGtpbmQ6ICJjbGFzcyIsIG5hbWU6IF9jbGFzc1RoaXMubmFtZSB9LCBudWxsLCBfY2xhc3NFeHRyYUluaXRpYWxpemVycyk7DQogICAgICAgICAgICBDID0gX2NsYXNzVGhpcyA9IF9jbGFzc0Rlc2NyaXB0b3IudmFsdWU7DQogICAgICAgICAgICBfX3J1bkluaXRpYWxpemVycyhfY2xhc3NUaGlzLCBfc3RhdGljRXh0cmFJbml0aWFsaXplcnMpOw0KICAgICAgICB9DQogICAgICAgIG1ldGhvZCgpIHsgfQ0KICAgICAgICBnZXQgeCgpIHsgcmV0dXJuIDE7IH0NCiAgICAgICAgc2V0IHgodmFsdWUpIHsgfQ0KICAgICAgICB5ID0gKF9fcnVuSW5pdGlhbGl6ZXJzKHRoaXMsIF9pbnN0YW5jZUV4dHJhSW5pdGlhbGl6ZXJzKSwgX19ydW5Jbml0aWFsaXplcnModGhpcywgX3lfaW5pdGlhbGl6ZXJzLCAxKSk7DQogICAgICAgICN6X2FjY2Vzc29yX3N0b3JhZ2UgPSBfX3J1bkluaXRpYWxpemVycyh0aGlzLCBfel9pbml0aWFsaXplcnMsIDEpOw0KICAgICAgICBnZXQgeigpIHsgcmV0dXJuIHRoaXMuI3pfYWNjZXNzb3Jfc3RvcmFnZTsgfQ0KICAgICAgICBzZXQgeih2YWx1ZSkgeyB0aGlzLiN6X2FjY2Vzc29yX3N0b3JhZ2UgPSB2YWx1ZTsgfQ0KICAgICAgICBzdGF0aWMgew0KICAgICAgICAgICAgX0NfeSA9IHsgdmFsdWU6IF9fcnVuSW5pdGlhbGl6ZXJzKF9jbGFzc1RoaXMsIF9zdGF0aWNfcHJpdmF0ZV95X2luaXRpYWxpemVycywgMSkgfTsNCiAgICAgICAgfQ0KICAgICAgICBzdGF0aWMgew0KICAgICAgICAgICAgX0Nfel9hY2Nlc3Nvcl9zdG9yYWdlID0geyB2YWx1ZTogX19ydW5Jbml0aWFsaXplcnMoX2NsYXNzVGhpcywgX3N0YXRpY19wcml2YXRlX3pfaW5pdGlhbGl6ZXJzLCAxKSB9Ow0KICAgICAgICB9DQogICAgICAgIHN0YXRpYyB7DQogICAgICAgICAgICBfX3J1bkluaXRpYWxpemVycyhfY2xhc3NUaGlzLCBfY2xhc3NFeHRyYUluaXRpYWxpemVycyk7DQogICAgICAgIH0NCiAgICB9Ow0KICAgIHJldHVybiBDID0gX2NsYXNzVGhpczsNCn0pKCk7DQovLyMgc291cmNlTWFwcGluZ1VSTD1lc0RlY29yYXRvcnMtY2xhc3NEZWNsYXJhdGlvbi1zb3VyY2VNYXAuanMubWFw,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiZXNEZWNvcmF0b3JzLWNsYXNzRGVjbGFyYXRpb24tc291cmNlTWFwLmpzIiwic291cmNlUm9vdCI6IiIsInNvdXJjZXMiOlsiZXNEZWNvcmF0b3JzLWNsYXNzRGVjbGFyYXRpb24tc291cmNlTWFwLnRzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiI7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7O0lBSU0sQ0FBQzs7NEJBRk4sR0FBRyxFQUNILEdBQUc7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7O2tDQUVDLEdBQUcsRUFDSCxHQUFHO2lDQUdILEdBQUcsRUFDSCxHQUFHO2lDQUdILEdBQUcsRUFDSCxHQUFHOzZCQUdILEdBQUcsRUFDSCxHQUFHOzZCQUdILEdBQUcsRUFDSCxHQUFHO2lEQUdILEdBQUcsRUFDSCxHQUFHO2dEQUdILEdBQUcsRUFDSCxHQUFHO2dEQUdILEdBQUcsRUFDSCxHQUFHOzRDQUdILEdBQUcsRUFDSCxHQUFHOzRDQUdILEdBQUcsRUFDSCxHQUFHO1lBZkoseURBQUEseUJBQUEsY0FBa0IsQ0FBQyxZQUFBLGtSQUFBO1lBSW5CLHdEQUFBLHVCQUFBLGNBQWtCLE9BQU8sQ0FBQyxDQUFDLENBQUMsQ0FBQyxjQUFBLHVRQUFBO1lBSTdCLHdEQUFBLHVCQUFBLFVBQWMsS0FBYSxJQUFJLENBQUMsY0FBQSw0UkFBQTtZQVFoQyxvREFBQSx1QkFBQSw0RkFBdUIsY0FBQSxFQUF2Qix1QkFBQSxpR0FBdUIsY0FBQSx3WEFBQTtZQXBDdkIscUtBQUEsTUFBTSx3Q0FBSztZQUlYLDBKQUFJLENBQUMsd0NBQWdCO1lBSXJCLHFLQUFJLENBQUMsbURBQW1CO1lBUXhCLHdKQUFTLENBQUMsNkJBQUQsQ0FBQyw4REFBSztZQWdCZixrWUFBYztZQXBCZCxxSkFBQSxDQUFDLDZCQUFELENBQUMsOERBQUs7WUFmVix3SkF3Q0M7O1lBeENLLHdEQUFDOztRQUdILE1BQU0sS0FBSSxDQUFDO1FBSVgsSUFBSSxDQUFDLEtBQUssT0FBTyxDQUFDLENBQUMsQ0FBQyxDQUFDO1FBSXJCLElBQUksQ0FBQyxDQUFDLEtBQWEsSUFBSSxDQUFDO1FBSXhCLENBQUMsa0dBQUcsQ0FBQyxHQUFDO1FBSU4sK0RBQWEsQ0FBQyxFQUFDO1FBQWYsSUFBUyxDQUFDLHVDQUFLO1FBQWYsSUFBUyxDQUFDLDZDQUFLOztZQWdCUiw4RUFBSyxDQUFDLEdBQUosQ0FBSzs7O1lBSUUsK0ZBQUssQ0FBQyxHQUFKLENBQUs7OztZQXZDckIsdURBQUMifQ==,ZGVjbGFyZSB2YXIgZGVjOiBhbnk7CgpAZGVjCkBkZWMKY2xhc3MgQyB7CiAgICBAZGVjCiAgICBAZGVjCiAgICBtZXRob2QoKSB7fQoKICAgIEBkZWMKICAgIEBkZWMKICAgIGdldCB4KCkgeyByZXR1cm4gMTsgfQoKICAgIEBkZWMKICAgIEBkZWMKICAgIHNldCB4KHZhbHVlOiBudW1iZXIpIHsgfQoKICAgIEBkZWMKICAgIEBkZWMKICAgIHkgPSAxOwoKICAgIEBkZWMKICAgIEBkZWMKICAgIGFjY2Vzc29yIHogPSAxOwoKICAgIEBkZWMKICAgIEBkZWMKICAgIHN0YXRpYyAjbWV0aG9kKCkge30KCiAgICBAZGVjCiAgICBAZGVjCiAgICBzdGF0aWMgZ2V0ICN4KCkgeyByZXR1cm4gMTsgfQoKICAgIEBkZWMKICAgIEBkZWMKICAgIHN0YXRpYyBzZXQgI3godmFsdWU6IG51bWJlcikgeyB9CgogICAgQGRlYwogICAgQGRlYwogICAgc3RhdGljICN5ID0gMTsKCiAgICBAZGVjCiAgICBAZGVjCiAgICBzdGF0aWMgYWNjZXNzb3IgI3ogPSAxOwp9Cg== + + //// [esDecorators-classDeclaration-sourceMap.d.ts.map] + {"version":3,"file":"esDecorators-classDeclaration-sourceMap.d.ts","sourceRoot":"","sources":["esDecorators-classDeclaration-sourceMap.ts"],"names":[],"mappings":"AAAA,OAAO,CAAC,IAAI,GAAG,EAAE,GAAG,CAAC;AAErB,cAEM,CAAC;;IAGH,MAAM;IAEN,IAEI,CAAC,IAIQ,MAAM,CAJE;IAErB,IAEI,CAAC,CAAC,KAAK,EAAE,MAAM,EAAK;IAIxB,CAAC,SAAK;IAIN,QAAQ,CAAC,CAAC,SAAK;CAqBlB"} +diff --git a/tests/baselines/reference/esDecorators-classDeclaration-sourceMap(target=es2022).sourcemap.txt b/tests/baselines/reference/esDecorators-classDeclaration-sourceMap(target=es2022).sourcemap.txt +index 05acdcfc7..c1e2b24cb 100644 +--- a/tests/baselines/reference/esDecorators-classDeclaration-sourceMap(target=es2022).sourcemap.txt ++++ b/tests/baselines/reference/esDecorators-classDeclaration-sourceMap(target=es2022).sourcemap.txt +@@ -64,7 +64,7 @@ sourceFile:esDecorators-classDeclaration-sourceMap.ts + >>>let C = (() => { + 1 >^^^^ + 2 > ^ +-3 > ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^-> ++3 > ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^-> + 1 >declare var dec: any; + > + >@dec +@@ -74,7 +74,7 @@ sourceFile:esDecorators-classDeclaration-sourceMap.ts + 1 >Emitted(54, 5) Source(5, 7) + SourceIndex(0) + 2 >Emitted(54, 6) Source(5, 8) + SourceIndex(0) + --- +->>> var _method_get, _x_get, _x_set, _y, _z_accessor_storage, _z_get, _z_set; ++>>> var _C_method_get, _C_x_get, _C_x_set, _C_y, _C_z_accessor_storage, _C_z_get, _C_z_set; + >>> let _classDecorators = [dec, dec]; + 1->^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + 2 > ^^^ +@@ -114,8 +114,9 @@ sourceFile:esDecorators-classDeclaration-sourceMap.ts + >>> let _z_decorators; + >>> let _z_initializers = []; + >>> var C = class { ++>>> static { _classThis = this; } + >>> static { __setFunctionName(this, "C"); } +->>> static { _method_get = function _method_get() { return _static_private_method_descriptor.value; }, _x_get = function _x_get() { return _static_private_get_x_descriptor.get.call(this); }, _x_set = function _x_set(value) { return _static_private_set_x_descriptor.set.call(this, value); }, _z_get = function _z_get() { return _static_private_z_descriptor.get.call(this); }, _z_set = function _z_set(value) { return _static_private_z_descriptor.set.call(this, value); }; } ++>>> static { _C_method_get = function _C_method_get() { return _static_private_method_descriptor.value; }, _C_x_get = function _C_x_get() { return _static_private_get_x_descriptor.get.call(this); }, _C_x_set = function _C_x_set(value) { return _static_private_set_x_descriptor.set.call(this, value); }, _C_z_get = function _C_z_get() { return _static_private_z_descriptor.get.call(this); }, _C_z_set = function _C_z_set(value) { return _static_private_z_descriptor.set.call(this, value); }; } + >>> static { + >>> _method_decorators = [dec, dec]; + 1 >^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +@@ -130,10 +131,10 @@ sourceFile:esDecorators-classDeclaration-sourceMap.ts + 3 > + > @ + 4 > dec +-1 >Emitted(84, 35) Source(6, 6) + SourceIndex(0) +-2 >Emitted(84, 38) Source(6, 9) + SourceIndex(0) +-3 >Emitted(84, 40) Source(7, 6) + SourceIndex(0) +-4 >Emitted(84, 43) Source(7, 9) + SourceIndex(0) ++1 >Emitted(85, 35) Source(6, 6) + SourceIndex(0) ++2 >Emitted(85, 38) Source(6, 9) + SourceIndex(0) ++3 >Emitted(85, 40) Source(7, 6) + SourceIndex(0) ++4 >Emitted(85, 43) Source(7, 9) + SourceIndex(0) + --- + >>> _get_x_decorators = [dec, dec]; + 1->^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +@@ -149,10 +150,10 @@ sourceFile:esDecorators-classDeclaration-sourceMap.ts + 3 > + > @ + 4 > dec +-1->Emitted(85, 34) Source(10, 6) + SourceIndex(0) +-2 >Emitted(85, 37) Source(10, 9) + SourceIndex(0) +-3 >Emitted(85, 39) Source(11, 6) + SourceIndex(0) +-4 >Emitted(85, 42) Source(11, 9) + SourceIndex(0) ++1->Emitted(86, 34) Source(10, 6) + SourceIndex(0) ++2 >Emitted(86, 37) Source(10, 9) + SourceIndex(0) ++3 >Emitted(86, 39) Source(11, 6) + SourceIndex(0) ++4 >Emitted(86, 42) Source(11, 9) + SourceIndex(0) + --- + >>> _set_x_decorators = [dec, dec]; + 1->^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +@@ -167,10 +168,10 @@ sourceFile:esDecorators-classDeclaration-sourceMap.ts + 3 > + > @ + 4 > dec +-1->Emitted(86, 34) Source(14, 6) + SourceIndex(0) +-2 >Emitted(86, 37) Source(14, 9) + SourceIndex(0) +-3 >Emitted(86, 39) Source(15, 6) + SourceIndex(0) +-4 >Emitted(86, 42) Source(15, 9) + SourceIndex(0) ++1->Emitted(87, 34) Source(14, 6) + SourceIndex(0) ++2 >Emitted(87, 37) Source(14, 9) + SourceIndex(0) ++3 >Emitted(87, 39) Source(15, 6) + SourceIndex(0) ++4 >Emitted(87, 42) Source(15, 9) + SourceIndex(0) + --- + >>> _y_decorators = [dec, dec]; + 1 >^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +@@ -186,10 +187,10 @@ sourceFile:esDecorators-classDeclaration-sourceMap.ts + 3 > + > @ + 4 > dec +-1 >Emitted(87, 30) Source(18, 6) + SourceIndex(0) +-2 >Emitted(87, 33) Source(18, 9) + SourceIndex(0) +-3 >Emitted(87, 35) Source(19, 6) + SourceIndex(0) +-4 >Emitted(87, 38) Source(19, 9) + SourceIndex(0) ++1 >Emitted(88, 30) Source(18, 6) + SourceIndex(0) ++2 >Emitted(88, 33) Source(18, 9) + SourceIndex(0) ++3 >Emitted(88, 35) Source(19, 6) + SourceIndex(0) ++4 >Emitted(88, 38) Source(19, 9) + SourceIndex(0) + --- + >>> _z_decorators = [dec, dec]; + 1->^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +@@ -205,10 +206,10 @@ sourceFile:esDecorators-classDeclaration-sourceMap.ts + 3 > + > @ + 4 > dec +-1->Emitted(88, 30) Source(22, 6) + SourceIndex(0) +-2 >Emitted(88, 33) Source(22, 9) + SourceIndex(0) +-3 >Emitted(88, 35) Source(23, 6) + SourceIndex(0) +-4 >Emitted(88, 38) Source(23, 9) + SourceIndex(0) ++1->Emitted(89, 30) Source(22, 6) + SourceIndex(0) ++2 >Emitted(89, 33) Source(22, 9) + SourceIndex(0) ++3 >Emitted(89, 35) Source(23, 6) + SourceIndex(0) ++4 >Emitted(89, 38) Source(23, 9) + SourceIndex(0) + --- + >>> _static_private_method_decorators = [dec, dec]; + 1->^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +@@ -224,10 +225,10 @@ sourceFile:esDecorators-classDeclaration-sourceMap.ts + 3 > + > @ + 4 > dec +-1->Emitted(89, 50) Source(26, 6) + SourceIndex(0) +-2 >Emitted(89, 53) Source(26, 9) + SourceIndex(0) +-3 >Emitted(89, 55) Source(27, 6) + SourceIndex(0) +-4 >Emitted(89, 58) Source(27, 9) + SourceIndex(0) ++1->Emitted(90, 50) Source(26, 6) + SourceIndex(0) ++2 >Emitted(90, 53) Source(26, 9) + SourceIndex(0) ++3 >Emitted(90, 55) Source(27, 6) + SourceIndex(0) ++4 >Emitted(90, 58) Source(27, 9) + SourceIndex(0) + --- + >>> _static_private_get_x_decorators = [dec, dec]; + 1->^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +@@ -243,10 +244,10 @@ sourceFile:esDecorators-classDeclaration-sourceMap.ts + 3 > + > @ + 4 > dec +-1->Emitted(90, 49) Source(30, 6) + SourceIndex(0) +-2 >Emitted(90, 52) Source(30, 9) + SourceIndex(0) +-3 >Emitted(90, 54) Source(31, 6) + SourceIndex(0) +-4 >Emitted(90, 57) Source(31, 9) + SourceIndex(0) ++1->Emitted(91, 49) Source(30, 6) + SourceIndex(0) ++2 >Emitted(91, 52) Source(30, 9) + SourceIndex(0) ++3 >Emitted(91, 54) Source(31, 6) + SourceIndex(0) ++4 >Emitted(91, 57) Source(31, 9) + SourceIndex(0) + --- + >>> _static_private_set_x_decorators = [dec, dec]; + 1->^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +@@ -261,10 +262,10 @@ sourceFile:esDecorators-classDeclaration-sourceMap.ts + 3 > + > @ + 4 > dec +-1->Emitted(91, 49) Source(34, 6) + SourceIndex(0) +-2 >Emitted(91, 52) Source(34, 9) + SourceIndex(0) +-3 >Emitted(91, 54) Source(35, 6) + SourceIndex(0) +-4 >Emitted(91, 57) Source(35, 9) + SourceIndex(0) ++1->Emitted(92, 49) Source(34, 6) + SourceIndex(0) ++2 >Emitted(92, 52) Source(34, 9) + SourceIndex(0) ++3 >Emitted(92, 54) Source(35, 6) + SourceIndex(0) ++4 >Emitted(92, 57) Source(35, 9) + SourceIndex(0) + --- + >>> _static_private_y_decorators = [dec, dec]; + 1 >^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +@@ -280,17 +281,17 @@ sourceFile:esDecorators-classDeclaration-sourceMap.ts + 3 > + > @ + 4 > dec +-1 >Emitted(92, 45) Source(38, 6) + SourceIndex(0) +-2 >Emitted(92, 48) Source(38, 9) + SourceIndex(0) +-3 >Emitted(92, 50) Source(39, 6) + SourceIndex(0) +-4 >Emitted(92, 53) Source(39, 9) + SourceIndex(0) ++1 >Emitted(93, 45) Source(38, 6) + SourceIndex(0) ++2 >Emitted(93, 48) Source(38, 9) + SourceIndex(0) ++3 >Emitted(93, 50) Source(39, 6) + SourceIndex(0) ++4 >Emitted(93, 53) Source(39, 9) + SourceIndex(0) + --- + >>> _static_private_z_decorators = [dec, dec]; + 1->^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + 2 > ^^^ + 3 > ^^ + 4 > ^^^ +-5 > ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^-> ++5 > ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^-> + 1-> + > static #y = 1; + > +@@ -299,19 +300,19 @@ sourceFile:esDecorators-classDeclaration-sourceMap.ts + 3 > + > @ + 4 > dec +-1->Emitted(93, 45) Source(42, 6) + SourceIndex(0) +-2 >Emitted(93, 48) Source(42, 9) + SourceIndex(0) +-3 >Emitted(93, 50) Source(43, 6) + SourceIndex(0) +-4 >Emitted(93, 53) Source(43, 9) + SourceIndex(0) ++1->Emitted(94, 45) Source(42, 6) + SourceIndex(0) ++2 >Emitted(94, 48) Source(42, 9) + SourceIndex(0) ++3 >Emitted(94, 50) Source(43, 6) + SourceIndex(0) ++4 >Emitted(94, 53) Source(43, 9) + SourceIndex(0) + --- +->>> __esDecorate(this, _static_private_method_descriptor = { value: __setFunctionName(function () { }, "#method") }, _static_private_method_decorators, { kind: "method", name: "#method", static: true, private: true, access: { has: obj => __classPrivateFieldIn(_classThis, obj), get: obj => __classPrivateFieldGet(obj, _classThis, "a", _method_get) } }, null, _staticExtraInitializers); ++>>> __esDecorate(this, _static_private_method_descriptor = { value: __setFunctionName(function () { }, "#method") }, _static_private_method_decorators, { kind: "method", name: "#method", static: true, private: true, access: { has: obj => __classPrivateFieldIn(_classThis, obj), get: obj => __classPrivateFieldGet(obj, _classThis, "a", _C_method_get) } }, null, _staticExtraInitializers); + 1->^^^^^^^^^^^^ + 2 > ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + 3 > ^^^^^^^^^^^^^^^^^^^^^^^^^ + 4 > ^^^^^^^^^^^^^^ + 5 > ^ + 6 > ^^^^^^^^^^^^ +-7 > ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ++7 > ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + 1-> + 2 > + 3 > +@@ -319,15 +320,15 @@ sourceFile:esDecorators-classDeclaration-sourceMap.ts + 5 > } + 6 > + 7 > +-1->Emitted(94, 13) Source(28, 5) + SourceIndex(0) +-2 >Emitted(94, 70) Source(28, 5) + SourceIndex(0) +-3 >Emitted(94, 95) Source(28, 5) + SourceIndex(0) +-4 >Emitted(94, 109) Source(28, 23) + SourceIndex(0) +-5 >Emitted(94, 110) Source(28, 24) + SourceIndex(0) +-6 >Emitted(94, 122) Source(28, 24) + SourceIndex(0) +-7 >Emitted(94, 394) Source(28, 24) + SourceIndex(0) ++1->Emitted(95, 13) Source(28, 5) + SourceIndex(0) ++2 >Emitted(95, 70) Source(28, 5) + SourceIndex(0) ++3 >Emitted(95, 95) Source(28, 5) + SourceIndex(0) ++4 >Emitted(95, 109) Source(28, 23) + SourceIndex(0) ++5 >Emitted(95, 110) Source(28, 24) + SourceIndex(0) ++6 >Emitted(95, 122) Source(28, 24) + SourceIndex(0) ++7 >Emitted(95, 396) Source(28, 24) + SourceIndex(0) + --- +->>> __esDecorate(this, _static_private_get_x_descriptor = { get: __setFunctionName(function () { return 1; }, "#x", "get") }, _static_private_get_x_decorators, { kind: "getter", name: "#x", static: true, private: true, access: { has: obj => __classPrivateFieldIn(_classThis, obj), get: obj => __classPrivateFieldGet(obj, _classThis, "a", _x_get) } }, null, _staticExtraInitializers); ++>>> __esDecorate(this, _static_private_get_x_descriptor = { get: __setFunctionName(function () { return 1; }, "#x", "get") }, _static_private_get_x_decorators, { kind: "getter", name: "#x", static: true, private: true, access: { has: obj => __classPrivateFieldIn(_classThis, obj), get: obj => __classPrivateFieldGet(obj, _classThis, "a", _C_x_get) } }, null, _staticExtraInitializers); + 1 >^^^^^^^^^^^^ + 2 > ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + 3 > ^^^^^^^^^^^^^^^^^^^^^^^ +@@ -338,8 +339,8 @@ sourceFile:esDecorators-classDeclaration-sourceMap.ts + 8 > ^ + 9 > ^ + 10> ^^^^^^^^^^^^^^ +-11> ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +-12> ^^^^^^^^^^^^^^^^^-> ++11> ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ++12> ^^^^^^^^^^^^^^^^^-> + 1 > + > + > @dec +@@ -355,19 +356,19 @@ sourceFile:esDecorators-classDeclaration-sourceMap.ts + 9 > } + 10> + 11> +-1 >Emitted(95, 13) Source(32, 5) + SourceIndex(0) +-2 >Emitted(95, 69) Source(32, 5) + SourceIndex(0) +-3 >Emitted(95, 92) Source(32, 5) + SourceIndex(0) +-4 >Emitted(95, 106) Source(32, 23) + SourceIndex(0) +-5 >Emitted(95, 113) Source(32, 30) + SourceIndex(0) +-6 >Emitted(95, 114) Source(32, 31) + SourceIndex(0) +-7 >Emitted(95, 115) Source(32, 32) + SourceIndex(0) +-8 >Emitted(95, 116) Source(32, 33) + SourceIndex(0) +-9 >Emitted(95, 117) Source(32, 34) + SourceIndex(0) +-10>Emitted(95, 131) Source(32, 34) + SourceIndex(0) +-11>Emitted(95, 392) Source(32, 34) + SourceIndex(0) ++1 >Emitted(96, 13) Source(32, 5) + SourceIndex(0) ++2 >Emitted(96, 69) Source(32, 5) + SourceIndex(0) ++3 >Emitted(96, 92) Source(32, 5) + SourceIndex(0) ++4 >Emitted(96, 106) Source(32, 23) + SourceIndex(0) ++5 >Emitted(96, 113) Source(32, 30) + SourceIndex(0) ++6 >Emitted(96, 114) Source(32, 31) + SourceIndex(0) ++7 >Emitted(96, 115) Source(32, 32) + SourceIndex(0) ++8 >Emitted(96, 116) Source(32, 33) + SourceIndex(0) ++9 >Emitted(96, 117) Source(32, 34) + SourceIndex(0) ++10>Emitted(96, 131) Source(32, 34) + SourceIndex(0) ++11>Emitted(96, 394) Source(32, 34) + SourceIndex(0) + --- +->>> __esDecorate(this, _static_private_set_x_descriptor = { set: __setFunctionName(function (value) { }, "#x", "set") }, _static_private_set_x_decorators, { kind: "setter", name: "#x", static: true, private: true, access: { has: obj => __classPrivateFieldIn(_classThis, obj), set: (obj, value) => { __classPrivateFieldSet(obj, _classThis, value, "a", _x_set); } } }, null, _staticExtraInitializers); ++>>> __esDecorate(this, _static_private_set_x_descriptor = { set: __setFunctionName(function (value) { }, "#x", "set") }, _static_private_set_x_decorators, { kind: "setter", name: "#x", static: true, private: true, access: { has: obj => __classPrivateFieldIn(_classThis, obj), set: (obj, value) => { __classPrivateFieldSet(obj, _classThis, value, "a", _C_x_set); } } }, null, _staticExtraInitializers); + 1->^^^^^^^^^^^^ + 2 > ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + 3 > ^^^^^^^^^^^^^^^^^^^^^^^ +@@ -376,8 +377,8 @@ sourceFile:esDecorators-classDeclaration-sourceMap.ts + 6 > ^^^^ + 7 > ^ + 8 > ^^^^^^^^^^^^^^ +-9 > ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +-10> ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^-> ++9 > ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ++10> ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^-> + 1-> + > + > @dec +@@ -391,27 +392,27 @@ sourceFile:esDecorators-classDeclaration-sourceMap.ts + 7 > } + 8 > + 9 > +-1->Emitted(96, 13) Source(36, 5) + SourceIndex(0) +-2 >Emitted(96, 69) Source(36, 5) + SourceIndex(0) +-3 >Emitted(96, 92) Source(36, 5) + SourceIndex(0) +-4 >Emitted(96, 102) Source(36, 19) + SourceIndex(0) +-5 >Emitted(96, 107) Source(36, 32) + SourceIndex(0) +-6 >Emitted(96, 111) Source(36, 36) + SourceIndex(0) +-7 >Emitted(96, 112) Source(36, 37) + SourceIndex(0) +-8 >Emitted(96, 126) Source(36, 37) + SourceIndex(0) +-9 >Emitted(96, 408) Source(36, 37) + SourceIndex(0) ++1->Emitted(97, 13) Source(36, 5) + SourceIndex(0) ++2 >Emitted(97, 69) Source(36, 5) + SourceIndex(0) ++3 >Emitted(97, 92) Source(36, 5) + SourceIndex(0) ++4 >Emitted(97, 102) Source(36, 19) + SourceIndex(0) ++5 >Emitted(97, 107) Source(36, 32) + SourceIndex(0) ++6 >Emitted(97, 111) Source(36, 36) + SourceIndex(0) ++7 >Emitted(97, 112) Source(36, 37) + SourceIndex(0) ++8 >Emitted(97, 126) Source(36, 37) + SourceIndex(0) ++9 >Emitted(97, 410) Source(36, 37) + SourceIndex(0) + --- +->>> __esDecorate(this, _static_private_z_descriptor = { get: __setFunctionName(function () { return __classPrivateFieldGet(this, _classThis, "f", _z_accessor_storage); }, "#z", "get"), set: __setFunctionName(function (value) { __classPrivateFieldSet(this, _classThis, value, "f", _z_accessor_storage); }, "#z", "set") }, _static_private_z_decorators, { kind: "accessor", name: "#z", static: true, private: true, access: { has: obj => __classPrivateFieldIn(_classThis, obj), get: obj => __classPrivateFieldGet(obj, _classThis, "a", _z_get), set: (obj, value) => { __classPrivateFieldSet(obj, _classThis, value, "a", _z_set); } } }, _static_private_z_initializers, _staticExtraInitializers); ++>>> __esDecorate(this, _static_private_z_descriptor = { get: __setFunctionName(function () { return __classPrivateFieldGet(this, _classThis, "f", _C_z_accessor_storage); }, "#z", "get"), set: __setFunctionName(function (value) { __classPrivateFieldSet(this, _classThis, value, "f", _C_z_accessor_storage); }, "#z", "set") }, _static_private_z_decorators, { kind: "accessor", name: "#z", static: true, private: true, access: { has: obj => __classPrivateFieldIn(_classThis, obj), get: obj => __classPrivateFieldGet(obj, _classThis, "a", _C_z_get), set: (obj, value) => { __classPrivateFieldSet(obj, _classThis, value, "a", _C_z_set); } } }, _static_private_z_initializers, _staticExtraInitializers); + 1->^^^^^^^^^^^^ + 2 > ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + 3 > ^^^^^^^^^^^^^^^^^^^^^^^ +-4 > ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +-5 > ^^^^^^^^^^^^^^ +-6 > ^^ +-7 > ^^^^^^^^^^^^^^^^^^^^^^^ +-8 > ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +-9 > ^^^^^^^^^^^^^^ +-10> ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ++4 > ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ++5 > ^^^^^^^^^^^^^^ ++6 > ^^ ++7 > ^^^^^^^^^^^^^^^^^^^^^^^ ++8 > ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ++9 > ^^^^^^^^^^^^^^ ++10> ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + 1-> + > + > @dec +@@ -424,22 +425,22 @@ sourceFile:esDecorators-classDeclaration-sourceMap.ts + 2 > + 3 > + 4 > static accessor #z = 1; +-5 > +-6 > +-7 > +-8 > static accessor #z = 1; +-9 > +-10> +-1->Emitted(97, 13) Source(44, 5) + SourceIndex(0) +-2 >Emitted(97, 65) Source(44, 5) + SourceIndex(0) +-3 >Emitted(97, 88) Source(44, 5) + SourceIndex(0) +-4 >Emitted(97, 178) Source(44, 28) + SourceIndex(0) +-5 >Emitted(97, 192) Source(44, 28) + SourceIndex(0) +-6 >Emitted(97, 194) Source(44, 5) + SourceIndex(0) +-7 >Emitted(97, 217) Source(44, 5) + SourceIndex(0) +-8 >Emitted(97, 312) Source(44, 28) + SourceIndex(0) +-9 >Emitted(97, 326) Source(44, 28) + SourceIndex(0) +-10>Emitted(97, 698) Source(44, 28) + SourceIndex(0) ++5 > ++6 > ++7 > ++8 > static accessor #z = 1; ++9 > ++10> ++1->Emitted(98, 13) Source(44, 5) + SourceIndex(0) ++2 >Emitted(98, 65) Source(44, 5) + SourceIndex(0) ++3 >Emitted(98, 88) Source(44, 5) + SourceIndex(0) ++4 >Emitted(98, 180) Source(44, 28) + SourceIndex(0) ++5 >Emitted(98, 194) Source(44, 28) + SourceIndex(0) ++6 >Emitted(98, 196) Source(44, 5) + SourceIndex(0) ++7 >Emitted(98, 219) Source(44, 5) + SourceIndex(0) ++8 >Emitted(98, 316) Source(44, 28) + SourceIndex(0) ++9 >Emitted(98, 330) Source(44, 28) + SourceIndex(0) ++10>Emitted(98, 706) Source(44, 28) + SourceIndex(0) + --- + >>> __esDecorate(this, null, _method_decorators, { kind: "method", name: "method", static: false, private: false, access: { has: obj => "method" in obj, get: obj => obj.method } }, null, _instanceExtraInitializers); + 1 >^^^^^^^^^^^^ +@@ -450,10 +451,10 @@ sourceFile:esDecorators-classDeclaration-sourceMap.ts + 2 > + 3 > method + 4 > () {} +-1 >Emitted(98, 13) Source(8, 5) + SourceIndex(0) +-2 >Emitted(98, 178) Source(8, 5) + SourceIndex(0) +-3 >Emitted(98, 184) Source(8, 11) + SourceIndex(0) +-4 >Emitted(98, 224) Source(8, 16) + SourceIndex(0) ++1 >Emitted(99, 13) Source(8, 5) + SourceIndex(0) ++2 >Emitted(99, 178) Source(8, 5) + SourceIndex(0) ++3 >Emitted(99, 184) Source(8, 11) + SourceIndex(0) ++4 >Emitted(99, 224) Source(8, 16) + SourceIndex(0) + --- + >>> __esDecorate(this, null, _get_x_decorators, { kind: "getter", name: "x", static: false, private: false, access: { has: obj => "x" in obj, get: obj => obj.x } }, null, _instanceExtraInitializers); + 1 >^^^^^^^^^^^^ +@@ -469,10 +470,10 @@ sourceFile:esDecorators-classDeclaration-sourceMap.ts + 2 > get + 3 > x + 4 > () { return 1; } +-1 >Emitted(99, 13) Source(12, 5) + SourceIndex(0) +-2 >Emitted(99, 167) Source(12, 9) + SourceIndex(0) +-3 >Emitted(99, 168) Source(12, 10) + SourceIndex(0) +-4 >Emitted(99, 208) Source(12, 26) + SourceIndex(0) ++1 >Emitted(100, 13) Source(12, 5) + SourceIndex(0) ++2 >Emitted(100, 167) Source(12, 9) + SourceIndex(0) ++3 >Emitted(100, 168) Source(12, 10) + SourceIndex(0) ++4 >Emitted(100, 208) Source(12, 26) + SourceIndex(0) + --- + >>> __esDecorate(this, null, _set_x_decorators, { kind: "setter", name: "x", static: false, private: false, access: { has: obj => "x" in obj, set: (obj, value) => { obj.x = value; } } }, null, _instanceExtraInitializers); + 1->^^^^^^^^^^^^ +@@ -488,10 +489,10 @@ sourceFile:esDecorators-classDeclaration-sourceMap.ts + 2 > set + 3 > x + 4 > (value: number) { } +-1->Emitted(100, 13) Source(16, 5) + SourceIndex(0) +-2 >Emitted(100, 178) Source(16, 9) + SourceIndex(0) +-3 >Emitted(100, 179) Source(16, 10) + SourceIndex(0) +-4 >Emitted(100, 230) Source(16, 29) + SourceIndex(0) ++1->Emitted(101, 13) Source(16, 5) + SourceIndex(0) ++2 >Emitted(101, 178) Source(16, 9) + SourceIndex(0) ++3 >Emitted(101, 179) Source(16, 10) + SourceIndex(0) ++4 >Emitted(101, 230) Source(16, 29) + SourceIndex(0) + --- + >>> __esDecorate(this, null, _z_decorators, { kind: "accessor", name: "z", static: false, private: false, access: { has: obj => "z" in obj, get: obj => obj.z, set: (obj, value) => { obj.z = value; } } }, _z_initializers, _instanceExtraInitializers); + 1->^^^^^^^^^^^^ +@@ -500,7 +501,7 @@ sourceFile:esDecorators-classDeclaration-sourceMap.ts + 4 > ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + 5 > ^ + 6 > ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +-7 > ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^-> ++7 > ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^-> + 1-> + > + > @dec +@@ -515,16 +516,16 @@ sourceFile:esDecorators-classDeclaration-sourceMap.ts + 4 > + 5 > z + 6 > = 1; +-1->Emitted(101, 13) Source(24, 5) + SourceIndex(0) +-2 >Emitted(101, 165) Source(24, 14) + SourceIndex(0) +-3 >Emitted(101, 166) Source(24, 15) + SourceIndex(0) +-4 >Emitted(101, 195) Source(24, 14) + SourceIndex(0) +-5 >Emitted(101, 196) Source(24, 15) + SourceIndex(0) +-6 >Emitted(101, 258) Source(24, 20) + SourceIndex(0) ++1->Emitted(102, 13) Source(24, 5) + SourceIndex(0) ++2 >Emitted(102, 165) Source(24, 14) + SourceIndex(0) ++3 >Emitted(102, 166) Source(24, 15) + SourceIndex(0) ++4 >Emitted(102, 195) Source(24, 14) + SourceIndex(0) ++5 >Emitted(102, 196) Source(24, 15) + SourceIndex(0) ++6 >Emitted(102, 258) Source(24, 20) + SourceIndex(0) + --- +->>> __esDecorate(null, null, _static_private_y_decorators, { kind: "field", name: "#y", static: true, private: true, access: { has: obj => __classPrivateFieldIn(_classThis, obj), get: obj => __classPrivateFieldGet(obj, _classThis, "f", _y), set: (obj, value) => { __classPrivateFieldSet(obj, _classThis, value, "f", _y); } } }, _static_private_y_initializers, _staticExtraInitializers); ++>>> __esDecorate(null, null, _static_private_y_decorators, { kind: "field", name: "#y", static: true, private: true, access: { has: obj => __classPrivateFieldIn(_classThis, obj), get: obj => __classPrivateFieldGet(obj, _classThis, "f", _C_y), set: (obj, value) => { __classPrivateFieldSet(obj, _classThis, value, "f", _C_y); } } }, _static_private_y_initializers, _staticExtraInitializers); + 1->^^^^^^^^^^^^ +-2 > ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ++2 > ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + 1-> + > + > @dec +@@ -543,8 +544,8 @@ sourceFile:esDecorators-classDeclaration-sourceMap.ts + > @dec + > + 2 > static #y = 1; +-1->Emitted(102, 13) Source(40, 5) + SourceIndex(0) +-2 >Emitted(102, 395) Source(40, 19) + SourceIndex(0) ++1->Emitted(103, 13) Source(40, 5) + SourceIndex(0) ++2 >Emitted(103, 399) Source(40, 19) + SourceIndex(0) + --- + >>> __esDecorate(null, null, _y_decorators, { kind: "field", name: "y", static: false, private: false, access: { has: obj => "y" in obj, get: obj => obj.y, set: (obj, value) => { obj.y = value; } } }, _y_initializers, _instanceExtraInitializers); + 1 >^^^^^^^^^^^^ +@@ -559,16 +560,16 @@ sourceFile:esDecorators-classDeclaration-sourceMap.ts + 4 > + 5 > y + 6 > = 1; +-1 >Emitted(103, 13) Source(20, 5) + SourceIndex(0) +-2 >Emitted(103, 162) Source(20, 5) + SourceIndex(0) +-3 >Emitted(103, 163) Source(20, 6) + SourceIndex(0) +-4 >Emitted(103, 192) Source(20, 5) + SourceIndex(0) +-5 >Emitted(103, 193) Source(20, 6) + SourceIndex(0) +-6 >Emitted(103, 255) Source(20, 11) + SourceIndex(0) ++1 >Emitted(104, 13) Source(20, 5) + SourceIndex(0) ++2 >Emitted(104, 162) Source(20, 5) + SourceIndex(0) ++3 >Emitted(104, 163) Source(20, 6) + SourceIndex(0) ++4 >Emitted(104, 192) Source(20, 5) + SourceIndex(0) ++5 >Emitted(104, 193) Source(20, 6) + SourceIndex(0) ++6 >Emitted(104, 255) Source(20, 11) + SourceIndex(0) + --- +->>> __esDecorate(null, _classDescriptor = { value: this }, _classDecorators, { kind: "class", name: this.name }, null, _classExtraInitializers); ++>>> __esDecorate(null, _classDescriptor = { value: _classThis }, _classDecorators, { kind: "class", name: _classThis.name }, null, _classExtraInitializers); + 1 >^^^^^^^^^^^^ +-2 > ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ++2 > ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + 1 > + 2 > class C { + > @dec +@@ -611,8 +612,8 @@ sourceFile:esDecorators-classDeclaration-sourceMap.ts + > @dec + > static accessor #z = 1; + > } +-1 >Emitted(104, 13) Source(5, 1) + SourceIndex(0) +-2 >Emitted(104, 153) Source(45, 2) + SourceIndex(0) ++1 >Emitted(105, 13) Source(5, 1) + SourceIndex(0) ++2 >Emitted(105, 165) Source(45, 2) + SourceIndex(0) + --- + >>> C = _classThis = _classDescriptor.value; + >>> __runInitializers(_classThis, _staticExtraInitializers); +@@ -620,8 +621,8 @@ sourceFile:esDecorators-classDeclaration-sourceMap.ts + 2 > ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + 1 > + 2 > C +-1 >Emitted(106, 13) Source(5, 7) + SourceIndex(0) +-2 >Emitted(106, 69) Source(5, 8) + SourceIndex(0) ++1 >Emitted(107, 13) Source(5, 7) + SourceIndex(0) ++2 >Emitted(107, 69) Source(5, 8) + SourceIndex(0) + --- + >>> } + >>> method() { } +@@ -637,10 +638,10 @@ sourceFile:esDecorators-classDeclaration-sourceMap.ts + 2 > method + 3 > () { + 4 > } +-1 >Emitted(108, 9) Source(8, 5) + SourceIndex(0) +-2 >Emitted(108, 15) Source(8, 11) + SourceIndex(0) +-3 >Emitted(108, 20) Source(8, 15) + SourceIndex(0) +-4 >Emitted(108, 21) Source(8, 16) + SourceIndex(0) ++1 >Emitted(109, 9) Source(8, 5) + SourceIndex(0) ++2 >Emitted(109, 15) Source(8, 11) + SourceIndex(0) ++3 >Emitted(109, 20) Source(8, 15) + SourceIndex(0) ++4 >Emitted(109, 21) Source(8, 16) + SourceIndex(0) + --- + >>> get x() { return 1; } + 1->^^^^^^^^ +@@ -665,15 +666,15 @@ sourceFile:esDecorators-classDeclaration-sourceMap.ts + 7 > ; + 8 > + 9 > } +-1->Emitted(109, 9) Source(12, 5) + SourceIndex(0) +-2 >Emitted(109, 13) Source(12, 9) + SourceIndex(0) +-3 >Emitted(109, 14) Source(12, 10) + SourceIndex(0) +-4 >Emitted(109, 19) Source(12, 15) + SourceIndex(0) +-5 >Emitted(109, 26) Source(12, 22) + SourceIndex(0) +-6 >Emitted(109, 27) Source(12, 23) + SourceIndex(0) +-7 >Emitted(109, 28) Source(12, 24) + SourceIndex(0) +-8 >Emitted(109, 29) Source(12, 25) + SourceIndex(0) +-9 >Emitted(109, 30) Source(12, 26) + SourceIndex(0) ++1->Emitted(110, 9) Source(12, 5) + SourceIndex(0) ++2 >Emitted(110, 13) Source(12, 9) + SourceIndex(0) ++3 >Emitted(110, 14) Source(12, 10) + SourceIndex(0) ++4 >Emitted(110, 19) Source(12, 15) + SourceIndex(0) ++5 >Emitted(110, 26) Source(12, 22) + SourceIndex(0) ++6 >Emitted(110, 27) Source(12, 23) + SourceIndex(0) ++7 >Emitted(110, 28) Source(12, 24) + SourceIndex(0) ++8 >Emitted(110, 29) Source(12, 25) + SourceIndex(0) ++9 >Emitted(110, 30) Source(12, 26) + SourceIndex(0) + --- + >>> set x(value) { } + 1 >^^^^^^^^ +@@ -695,13 +696,13 @@ sourceFile:esDecorators-classDeclaration-sourceMap.ts + 5 > value: number + 6 > ) { + 7 > } +-1 >Emitted(110, 9) Source(16, 5) + SourceIndex(0) +-2 >Emitted(110, 13) Source(16, 9) + SourceIndex(0) +-3 >Emitted(110, 14) Source(16, 10) + SourceIndex(0) +-4 >Emitted(110, 15) Source(16, 11) + SourceIndex(0) +-5 >Emitted(110, 20) Source(16, 24) + SourceIndex(0) +-6 >Emitted(110, 24) Source(16, 28) + SourceIndex(0) +-7 >Emitted(110, 25) Source(16, 29) + SourceIndex(0) ++1 >Emitted(111, 9) Source(16, 5) + SourceIndex(0) ++2 >Emitted(111, 13) Source(16, 9) + SourceIndex(0) ++3 >Emitted(111, 14) Source(16, 10) + SourceIndex(0) ++4 >Emitted(111, 15) Source(16, 11) + SourceIndex(0) ++5 >Emitted(111, 20) Source(16, 24) + SourceIndex(0) ++6 >Emitted(111, 24) Source(16, 28) + SourceIndex(0) ++7 >Emitted(111, 25) Source(16, 29) + SourceIndex(0) + --- + >>> y = (__runInitializers(this, _instanceExtraInitializers), __runInitializers(this, _y_initializers, 1)); + 1->^^^^^^^^ +@@ -718,11 +719,11 @@ sourceFile:esDecorators-classDeclaration-sourceMap.ts + 3 > = + 4 > 1 + 5 > ; +-1->Emitted(111, 9) Source(20, 5) + SourceIndex(0) +-2 >Emitted(111, 10) Source(20, 6) + SourceIndex(0) +-3 >Emitted(111, 108) Source(20, 9) + SourceIndex(0) +-4 >Emitted(111, 109) Source(20, 10) + SourceIndex(0) +-5 >Emitted(111, 112) Source(20, 11) + SourceIndex(0) ++1->Emitted(112, 9) Source(20, 5) + SourceIndex(0) ++2 >Emitted(112, 10) Source(20, 6) + SourceIndex(0) ++3 >Emitted(112, 108) Source(20, 9) + SourceIndex(0) ++4 >Emitted(112, 109) Source(20, 10) + SourceIndex(0) ++5 >Emitted(112, 112) Source(20, 11) + SourceIndex(0) + --- + >>> #z_accessor_storage = __runInitializers(this, _z_initializers, 1); + 1 >^^^^^^^^ +@@ -737,10 +738,10 @@ sourceFile:esDecorators-classDeclaration-sourceMap.ts + 2 > accessor z = + 3 > 1 + 4 > ; +-1 >Emitted(112, 9) Source(24, 5) + SourceIndex(0) +-2 >Emitted(112, 72) Source(24, 18) + SourceIndex(0) +-3 >Emitted(112, 73) Source(24, 19) + SourceIndex(0) +-4 >Emitted(112, 75) Source(24, 20) + SourceIndex(0) ++1 >Emitted(113, 9) Source(24, 5) + SourceIndex(0) ++2 >Emitted(113, 72) Source(24, 18) + SourceIndex(0) ++3 >Emitted(113, 73) Source(24, 19) + SourceIndex(0) ++4 >Emitted(113, 75) Source(24, 20) + SourceIndex(0) + --- + >>> get z() { return this.#z_accessor_storage; } + 1 >^^^^^^^^ +@@ -752,10 +753,10 @@ sourceFile:esDecorators-classDeclaration-sourceMap.ts + 2 > accessor + 3 > z + 4 > = 1; +-1 >Emitted(113, 9) Source(24, 5) + SourceIndex(0) +-2 >Emitted(113, 13) Source(24, 14) + SourceIndex(0) +-3 >Emitted(113, 14) Source(24, 15) + SourceIndex(0) +-4 >Emitted(113, 53) Source(24, 20) + SourceIndex(0) ++1 >Emitted(114, 9) Source(24, 5) + SourceIndex(0) ++2 >Emitted(114, 13) Source(24, 14) + SourceIndex(0) ++3 >Emitted(114, 14) Source(24, 15) + SourceIndex(0) ++4 >Emitted(114, 53) Source(24, 20) + SourceIndex(0) + --- + >>> set z(value) { this.#z_accessor_storage = value; } + 1->^^^^^^^^ +@@ -766,18 +767,18 @@ sourceFile:esDecorators-classDeclaration-sourceMap.ts + 2 > accessor + 3 > z + 4 > = 1; +-1->Emitted(114, 9) Source(24, 5) + SourceIndex(0) +-2 >Emitted(114, 13) Source(24, 14) + SourceIndex(0) +-3 >Emitted(114, 14) Source(24, 15) + SourceIndex(0) +-4 >Emitted(114, 59) Source(24, 20) + SourceIndex(0) ++1->Emitted(115, 9) Source(24, 5) + SourceIndex(0) ++2 >Emitted(115, 13) Source(24, 14) + SourceIndex(0) ++3 >Emitted(115, 14) Source(24, 15) + SourceIndex(0) ++4 >Emitted(115, 59) Source(24, 20) + SourceIndex(0) + --- + >>> static { +->>> _y = { value: __runInitializers(_classThis, _static_private_y_initializers, 1) }; ++>>> _C_y = { value: __runInitializers(_classThis, _static_private_y_initializers, 1) }; + 1 >^^^^^^^^^^^^ +-2 > ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +-3 > ^ +-4 > ^^^ +-5 > ^ ++2 > ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ++3 > ^ ++4 > ^^^ ++5 > ^ + 1 > + > + > @dec +@@ -796,37 +797,37 @@ sourceFile:esDecorators-classDeclaration-sourceMap.ts + > @dec + > static + 2 > #y = +-3 > 1 +-4 > +-5 > = 1; +-1 >Emitted(116, 13) Source(40, 12) + SourceIndex(0) +-2 >Emitted(116, 89) Source(40, 17) + SourceIndex(0) +-3 >Emitted(116, 90) Source(40, 18) + SourceIndex(0) +-4 >Emitted(116, 93) Source(40, 14) + SourceIndex(0) +-5 >Emitted(116, 94) Source(40, 19) + SourceIndex(0) ++3 > 1 ++4 > ++5 > = 1; ++1 >Emitted(117, 13) Source(40, 12) + SourceIndex(0) ++2 >Emitted(117, 91) Source(40, 17) + SourceIndex(0) ++3 >Emitted(117, 92) Source(40, 18) + SourceIndex(0) ++4 >Emitted(117, 95) Source(40, 14) + SourceIndex(0) ++5 >Emitted(117, 96) Source(40, 19) + SourceIndex(0) + --- + >>> } + >>> static { +->>> _z_accessor_storage = { value: __runInitializers(_classThis, _static_private_z_initializers, 1) }; ++>>> _C_z_accessor_storage = { value: __runInitializers(_classThis, _static_private_z_initializers, 1) }; + 1 >^^^^^^^^^^^^ +-2 > ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +-3 > ^ +-4 > ^^^ +-5 > ^ ++2 > ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ++3 > ^ ++4 > ^^^ ++5 > ^ + 1 > + > + > @dec + > @dec + > static accessor + 2 > #z = +-3 > 1 +-4 > +-5 > = 1; +-1 >Emitted(119, 13) Source(44, 21) + SourceIndex(0) +-2 >Emitted(119, 106) Source(44, 26) + SourceIndex(0) +-3 >Emitted(119, 107) Source(44, 27) + SourceIndex(0) +-4 >Emitted(119, 110) Source(44, 23) + SourceIndex(0) +-5 >Emitted(119, 111) Source(44, 28) + SourceIndex(0) ++3 > 1 ++4 > ++5 > = 1; ++1 >Emitted(120, 13) Source(44, 21) + SourceIndex(0) ++2 >Emitted(120, 108) Source(44, 26) + SourceIndex(0) ++3 >Emitted(120, 109) Source(44, 27) + SourceIndex(0) ++4 >Emitted(120, 112) Source(44, 23) + SourceIndex(0) ++5 >Emitted(120, 113) Source(44, 28) + SourceIndex(0) + --- + >>> } + >>> static { +@@ -835,8 +836,8 @@ sourceFile:esDecorators-classDeclaration-sourceMap.ts + 2 > ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + 1 > + 2 > C +-1 >Emitted(122, 13) Source(5, 7) + SourceIndex(0) +-2 >Emitted(122, 68) Source(5, 8) + SourceIndex(0) ++1 >Emitted(123, 13) Source(5, 7) + SourceIndex(0) ++2 >Emitted(123, 68) Source(5, 8) + SourceIndex(0) + --- + >>> } + >>> }; +diff --git a/tests/baselines/reference/esDecorators-classExpression-classSuper.1.js b/tests/baselines/reference/esDecorators-classExpression-classSuper.1.js +index dfa5dd90a..e6f01b2d0 100644 +--- a/tests/baselines/reference/esDecorators-classExpression-classSuper.1.js ++++ b/tests/baselines/reference/esDecorators-classExpression-classSuper.1.js +@@ -31,8 +31,9 @@ const method = "method"; + let _classThis; + let _classSuper = Base; + var C = class extends _classSuper { ++ static { _classThis = this; } + static { +- __esDecorate(null, _classDescriptor = { value: this }, _classDecorators, { kind: "class", name: this.name }, null, _classExtraInitializers); ++ __esDecorate(null, _classDescriptor = { value: _classThis }, _classDecorators, { kind: "class", name: _classThis.name }, null, _classExtraInitializers); + C = _classThis = _classDescriptor.value; + } + static { +diff --git a/tests/baselines/reference/esDecorators-classExpression-classSuper.2.js b/tests/baselines/reference/esDecorators-classExpression-classSuper.2.js +index e4ea7908a..337eeb74c 100644 +--- a/tests/baselines/reference/esDecorators-classExpression-classSuper.2.js ++++ b/tests/baselines/reference/esDecorators-classExpression-classSuper.2.js +@@ -38,8 +38,9 @@ class C3 extends ((() => {}) as any) { + let _classSuper = (0, class { + }); + var C1 = class extends _classSuper { ++ static { _classThis = this; } + static { +- __esDecorate(null, _classDescriptor = { value: this }, _classDecorators, { kind: "class", name: this.name }, null, _classExtraInitializers); ++ __esDecorate(null, _classDescriptor = { value: _classThis }, _classDecorators, { kind: "class", name: _classThis.name }, null, _classExtraInitializers); + C1 = _classThis = _classDescriptor.value; + } + static { +@@ -53,43 +54,45 @@ class C3 extends ((() => {}) as any) { + })()); + // function expression in extends should not get an assigned name + ((() => { +- let _classDecorators_1 = [dec]; +- let _classDescriptor_1; +- let _classExtraInitializers_1 = []; +- let _classThis_1; +- let _classSuper_1 = (0, function () { }); +- var C2 = class extends _classSuper_1 { ++ let _classDecorators = [dec]; ++ let _classDescriptor; ++ let _classExtraInitializers = []; ++ let _classThis; ++ let _classSuper = (0, function () { }); ++ var C2 = class extends _classSuper { ++ static { _classThis = this; } + static { +- __esDecorate(null, _classDescriptor_1 = { value: this }, _classDecorators_1, { kind: "class", name: this.name }, null, _classExtraInitializers_1); +- C2 = _classThis_1 = _classDescriptor_1.value; ++ __esDecorate(null, _classDescriptor = { value: _classThis }, _classDecorators, { kind: "class", name: _classThis.name }, null, _classExtraInitializers); ++ C2 = _classThis = _classDescriptor.value; + } + static { +- Reflect.get(_classSuper_1, "name", _classThis_1); ++ Reflect.get(_classSuper, "name", _classThis); + } + static { +- __runInitializers(_classThis_1, _classExtraInitializers_1); ++ __runInitializers(_classThis, _classExtraInitializers); + } + }; +- return C2 = _classThis_1; ++ return C2 = _classThis; + })()); + // arrow function in extends should not get an assigned name + ((() => { +- let _classDecorators_2 = [dec]; +- let _classDescriptor_2; +- let _classExtraInitializers_2 = []; +- let _classThis_2; +- let _classSuper_2 = (0, (() => { })); +- var C3 = class extends _classSuper_2 { ++ let _classDecorators = [dec]; ++ let _classDescriptor; ++ let _classExtraInitializers = []; ++ let _classThis; ++ let _classSuper = (0, (() => { })); ++ var C3 = class extends _classSuper { ++ static { _classThis = this; } + static { +- __esDecorate(null, _classDescriptor_2 = { value: this }, _classDecorators_2, { kind: "class", name: this.name }, null, _classExtraInitializers_2); +- C3 = _classThis_2 = _classDescriptor_2.value; ++ __esDecorate(null, _classDescriptor = { value: _classThis }, _classDecorators, { kind: "class", name: _classThis.name }, null, _classExtraInitializers); ++ C3 = _classThis = _classDescriptor.value; + } + static { +- Reflect.get(_classSuper_2, "name", _classThis_2); ++ Reflect.get(_classSuper, "name", _classThis); + } + static { +- __runInitializers(_classThis_2, _classExtraInitializers_2); ++ __runInitializers(_classThis, _classExtraInitializers); + } + }; +- return C3 = _classThis_2; ++ return C3 = _classThis; + })()); +diff --git a/tests/baselines/reference/esDecorators-classExpression-classSuper.3.js b/tests/baselines/reference/esDecorators-classExpression-classSuper.3.js +index aa4104c48..d83ef08e2 100644 +--- a/tests/baselines/reference/esDecorators-classExpression-classSuper.3.js ++++ b/tests/baselines/reference/esDecorators-classExpression-classSuper.3.js +@@ -54,8 +54,9 @@ const x = "x"; + let _classThis; + let _classSuper = Base; + var C = class extends _classSuper { ++ static { _classThis = this; } + static { +- __esDecorate(null, _classDescriptor = { value: this }, _classDecorators, { kind: "class", name: this.name }, null, _classExtraInitializers); ++ __esDecorate(null, _classDescriptor = { value: _classThis }, _classDecorators, { kind: "class", name: _classThis.name }, null, _classExtraInitializers); + C = _classThis = _classDescriptor.value; + } + static { +diff --git a/tests/baselines/reference/esDecorators-classExpression-classSuper.4.js b/tests/baselines/reference/esDecorators-classExpression-classSuper.4.js +index 73aa13f6e..0fcd1b040 100644 +--- a/tests/baselines/reference/esDecorators-classExpression-classSuper.4.js ++++ b/tests/baselines/reference/esDecorators-classExpression-classSuper.4.js +@@ -29,8 +29,9 @@ const method = "method"; + let _classThis; + let _classSuper = Base; + var C = class extends _classSuper { ++ static { _classThis = this; } + static { +- __esDecorate(null, _classDescriptor = { value: this }, _classDecorators, { kind: "class", name: this.name }, null, _classExtraInitializers); ++ __esDecorate(null, _classDescriptor = { value: _classThis }, _classDecorators, { kind: "class", name: _classThis.name }, null, _classExtraInitializers); + C = _classThis = _classDescriptor.value; + } + static a = Reflect.get(_classSuper, "method", _classThis).call(_classThis); +diff --git a/tests/baselines/reference/esDecorators-classExpression-classSuper.5.js b/tests/baselines/reference/esDecorators-classExpression-classSuper.5.js +index 6e528ea49..b6996be15 100644 +--- a/tests/baselines/reference/esDecorators-classExpression-classSuper.5.js ++++ b/tests/baselines/reference/esDecorators-classExpression-classSuper.5.js +@@ -58,8 +58,9 @@ const x = "x"; + let _classThis; + let _classSuper = Base; + var C1 = class extends _classSuper { ++ static { _classThis = this; } + static { +- __esDecorate(null, _classDescriptor = { value: this }, _classDecorators, { kind: "class", name: this.name }, null, _classExtraInitializers); ++ __esDecorate(null, _classDescriptor = { value: _classThis }, _classDecorators, { kind: "class", name: _classThis.name }, null, _classExtraInitializers); + C1 = _classThis = _classDescriptor.value; + } + static a = Reflect.get(_classSuper, "x", _classThis); +@@ -96,90 +97,92 @@ const x = "x"; + return C1 = _classThis; + })()); + ((() => { +- let _classDecorators_1 = [dec]; +- let _classDescriptor_1; +- let _classExtraInitializers_1 = []; +- let _classThis_1; +- let _classSuper_1 = Base; +- var C2 = class extends _classSuper_1 { ++ let _classDecorators = [dec]; ++ let _classDescriptor; ++ let _classExtraInitializers = []; ++ let _classThis; ++ let _classSuper = Base; ++ var C2 = class extends _classSuper { ++ static { _classThis = this; } + static { +- __esDecorate(null, _classDescriptor_1 = { value: this }, _classDecorators_1, { kind: "class", name: this.name }, null, _classExtraInitializers_1); +- C2 = _classThis_1 = _classDescriptor_1.value; ++ __esDecorate(null, _classDescriptor = { value: _classThis }, _classDecorators, { kind: "class", name: _classThis.name }, null, _classExtraInitializers); ++ C2 = _classThis = _classDescriptor.value; + } +- static a = Reflect.get(_classSuper_1, "x", _classThis_1); ++ static a = Reflect.get(_classSuper, "x", _classThis); + static b = (() => { + var _a; +- return Reflect.set(_classSuper_1, "x", _a = 1, _classThis_1), _a; ++ return Reflect.set(_classSuper, "x", _a = 1, _classThis), _a; + })(); + static c = (() => { + var _a; +- return Reflect.set(_classSuper_1, "x", _a = Reflect.get(_classSuper_1, "x", _classThis_1) + 1, _classThis_1), _a; ++ return Reflect.set(_classSuper, "x", _a = Reflect.get(_classSuper, "x", _classThis) + 1, _classThis), _a; + })(); + static d = (() => { + var _a, _b; +- return Reflect.set(_classSuper_1, "x", (_b = Reflect.get(_classSuper_1, "x", _classThis_1), _a = _b++, _b), _classThis_1), _a; ++ return Reflect.set(_classSuper, "x", (_b = Reflect.get(_classSuper, "x", _classThis), _a = _b++, _b), _classThis), _a; + })(); + static e = (() => { + var _a, _b; +- return Reflect.set(_classSuper_1, "x", (_b = Reflect.get(_classSuper_1, "x", _classThis_1), _a = _b--, _b), _classThis_1), _a; ++ return Reflect.set(_classSuper, "x", (_b = Reflect.get(_classSuper, "x", _classThis), _a = _b--, _b), _classThis), _a; + })(); + static f = (() => { + var _a, _b; +- return Reflect.set(_classSuper_1, "x", (_b = Reflect.get(_classSuper_1, "x", _classThis_1), _a = ++_b), _classThis_1), _a; ++ return Reflect.set(_classSuper, "x", (_b = Reflect.get(_classSuper, "x", _classThis), _a = ++_b), _classThis), _a; + })(); + static g = (() => { + var _a, _b; +- return Reflect.set(_classSuper_1, "x", (_b = Reflect.get(_classSuper_1, "x", _classThis_1), _a = --_b), _classThis_1), _a; ++ return Reflect.set(_classSuper, "x", (_b = Reflect.get(_classSuper, "x", _classThis), _a = --_b), _classThis), _a; + })(); +- static h = ({ x: ({ set value(_a) { Reflect.set(_classSuper_1, "x", _a, _classThis_1); } }).value } = { x: 1 }); +- static i = [({ set value(_a) { Reflect.set(_classSuper_1, "x", _a, _classThis_1); } }).value] = [1]; ++ static h = ({ x: ({ set value(_a) { Reflect.set(_classSuper, "x", _a, _classThis); } }).value } = { x: 1 }); ++ static i = [({ set value(_a) { Reflect.set(_classSuper, "x", _a, _classThis); } }).value] = [1]; + static { +- __runInitializers(_classThis_1, _classExtraInitializers_1); ++ __runInitializers(_classThis, _classExtraInitializers); + } + }; +- return C2 = _classThis_1; ++ return C2 = _classThis; + })()); + ((() => { +- let _classDecorators_2 = [dec]; +- let _classDescriptor_2; +- let _classExtraInitializers_2 = []; +- let _classThis_2; +- let _classSuper_2 = Base; +- var C3 = class extends _classSuper_2 { ++ let _classDecorators = [dec]; ++ let _classDescriptor; ++ let _classExtraInitializers = []; ++ let _classThis; ++ let _classSuper = Base; ++ var C3 = class extends _classSuper { ++ static { _classThis = this; } + static { +- __esDecorate(null, _classDescriptor_2 = { value: this }, _classDecorators_2, { kind: "class", name: this.name }, null, _classExtraInitializers_2); +- C3 = _classThis_2 = _classDescriptor_2.value; ++ __esDecorate(null, _classDescriptor = { value: _classThis }, _classDecorators, { kind: "class", name: _classThis.name }, null, _classExtraInitializers); ++ C3 = _classThis = _classDescriptor.value; + } +- static a = Reflect.get(_classSuper_2, x, _classThis_2); ++ static a = Reflect.get(_classSuper, x, _classThis); + static b = (() => { + var _a; +- return Reflect.set(_classSuper_2, x, _a = 1, _classThis_2), _a; ++ return Reflect.set(_classSuper, x, _a = 1, _classThis), _a; + })(); + static c = (() => { + var _a, _b; +- return Reflect.set(_classSuper_2, _a = x, _b = Reflect.get(_classSuper_2, _a, _classThis_2) + 1, _classThis_2), _b; ++ return Reflect.set(_classSuper, _a = x, _b = Reflect.get(_classSuper, _a, _classThis) + 1, _classThis), _b; + })(); + static d = (() => { + var _a, _b, _c; +- return Reflect.set(_classSuper_2, _a = x, (_c = Reflect.get(_classSuper_2, _a, _classThis_2), _b = _c++, _c), _classThis_2), _b; ++ return Reflect.set(_classSuper, _a = x, (_c = Reflect.get(_classSuper, _a, _classThis), _b = _c++, _c), _classThis), _b; + })(); + static e = (() => { + var _a, _b, _c; +- return Reflect.set(_classSuper_2, _a = x, (_c = Reflect.get(_classSuper_2, _a, _classThis_2), _b = _c--, _c), _classThis_2), _b; ++ return Reflect.set(_classSuper, _a = x, (_c = Reflect.get(_classSuper, _a, _classThis), _b = _c--, _c), _classThis), _b; + })(); + static f = (() => { + var _a, _b, _c; +- return Reflect.set(_classSuper_2, _a = x, (_c = Reflect.get(_classSuper_2, _a, _classThis_2), _b = ++_c), _classThis_2), _b; ++ return Reflect.set(_classSuper, _a = x, (_c = Reflect.get(_classSuper, _a, _classThis), _b = ++_c), _classThis), _b; + })(); + static g = (() => { + var _a, _b, _c; +- return Reflect.set(_classSuper_2, _a = x, (_c = Reflect.get(_classSuper_2, _a, _classThis_2), _b = --_c), _classThis_2), _b; ++ return Reflect.set(_classSuper, _a = x, (_c = Reflect.get(_classSuper, _a, _classThis), _b = --_c), _classThis), _b; + })(); +- static h = ({ x: ({ set value(_a) { Reflect.set(_classSuper_2, x, _a, _classThis_2); } }).value } = { x: 1 }); +- static i = [({ set value(_a) { Reflect.set(_classSuper_2, x, _a, _classThis_2); } }).value] = [1]; ++ static h = ({ x: ({ set value(_a) { Reflect.set(_classSuper, x, _a, _classThis); } }).value } = { x: 1 }); ++ static i = [({ set value(_a) { Reflect.set(_classSuper, x, _a, _classThis); } }).value] = [1]; + static { +- __runInitializers(_classThis_2, _classExtraInitializers_2); ++ __runInitializers(_classThis, _classExtraInitializers); + } + }; +- return C3 = _classThis_2; ++ return C3 = _classThis; + })()); +diff --git a/tests/baselines/reference/esDecorators-classExpression-classSuper.6.js b/tests/baselines/reference/esDecorators-classExpression-classSuper.6.js +index 881208b12..ed594b11c 100644 +--- a/tests/baselines/reference/esDecorators-classExpression-classSuper.6.js ++++ b/tests/baselines/reference/esDecorators-classExpression-classSuper.6.js +@@ -35,8 +35,9 @@ class C extends Base { + let _classExtraInitializers = []; + let _classThis; + var C = class extends Base { ++ static { _classThis = this; } + static { +- __esDecorate(null, _classDescriptor = { value: this }, _classDecorators, { kind: "class", name: this.name }, null, _classExtraInitializers); ++ __esDecorate(null, _classDescriptor = { value: _classThis }, _classDecorators, { kind: "class", name: _classThis.name }, null, _classExtraInitializers); + C = _classThis = _classDescriptor.value; + __runInitializers(_classThis, _classExtraInitializers); + } +diff --git a/tests/baselines/reference/esDecorators-classExpression-commentPreservation(target=es2015).js b/tests/baselines/reference/esDecorators-classExpression-commentPreservation(target=es2015).js +index 3acbc6dbb..427341245 100644 +--- a/tests/baselines/reference/esDecorators-classExpression-commentPreservation(target=es2015).js ++++ b/tests/baselines/reference/esDecorators-classExpression-commentPreservation(target=es2015).js +@@ -87,7 +87,7 @@ class C { + //// [esDecorators-classExpression-commentPreservation.js] + /*1*/ + ((() => { +- var _method_get, _x_get, _x_set, _y, _z_accessor_storage, _z_get, _z_set, _z_1_accessor_storage; ++ var _C_method_get, _C_x_get, _C_x_set, _C_y, _C_z_accessor_storage, _C_z_get, _C_z_set, _C_z_1_accessor_storage; + let _classDecorators = [dec, dec]; + let _classDescriptor; + let _classExtraInitializers = []; +@@ -116,7 +116,7 @@ class C { + constructor() { + /*14*/ + this.y = (__runInitializers(this, _instanceExtraInitializers), __runInitializers(this, _y_initializers, 1)); +- _z_1_accessor_storage.set(this, __runInitializers(this, _z_initializers, 1)); ++ _C_z_1_accessor_storage.set(this, __runInitializers(this, _z_initializers, 1)); + } + /*5*/ + method() { } +@@ -125,15 +125,15 @@ class C { + /*11*/ + set x(value) { } + /*17*/ +- get z() { return __classPrivateFieldGet(this, _z_1_accessor_storage, "f"); } +- set z(value) { __classPrivateFieldSet(this, _z_1_accessor_storage, value, "f"); } ++ get z() { return __classPrivateFieldGet(this, _C_z_1_accessor_storage, "f"); } ++ set z(value) { __classPrivateFieldSet(this, _C_z_1_accessor_storage, value, "f"); } + }, +- _z_1_accessor_storage = new WeakMap(), +- _method_get = function _method_get() { return _static_private_method_descriptor.value; }, +- _x_get = function _x_get() { return _static_private_get_x_descriptor.get.call(this); }, +- _x_set = function _x_set(value) { return _static_private_set_x_descriptor.set.call(this, value); }, +- _z_get = function _z_get() { return _static_private_z_descriptor.get.call(this); }, +- _z_set = function _z_set(value) { return _static_private_z_descriptor.set.call(this, value); }, ++ _C_z_1_accessor_storage = new WeakMap(), ++ _C_method_get = function _C_method_get() { return _static_private_method_descriptor.value; }, ++ _C_x_get = function _C_x_get() { return _static_private_get_x_descriptor.get.call(this); }, ++ _C_x_set = function _C_x_set(value) { return _static_private_set_x_descriptor.set.call(this, value); }, ++ _C_z_get = function _C_z_get() { return _static_private_z_descriptor.get.call(this); }, ++ _C_z_set = function _C_z_set(value) { return _static_private_z_descriptor.set.call(this, value); }, + __setFunctionName(_classThis, "C"), + (() => { + _method_decorators = [dec, dec]; +@@ -146,23 +146,23 @@ class C { + _static_private_set_x_decorators = [dec, dec]; + _static_private_y_decorators = [dec, dec]; + _static_private_z_decorators = [dec, dec]; +- __esDecorate(_classThis, _static_private_method_descriptor = { value: __setFunctionName(function () { }, "#method") }, _static_private_method_decorators, { kind: "method", name: "#method", static: true, private: true, access: { has: obj => __classPrivateFieldIn(_classThis, obj), get: obj => __classPrivateFieldGet(obj, _classThis, "a", _method_get) } }, null, _staticExtraInitializers); +- __esDecorate(_classThis, _static_private_get_x_descriptor = { get: __setFunctionName(function () { return 1; }, "#x", "get") }, _static_private_get_x_decorators, { kind: "getter", name: "#x", static: true, private: true, access: { has: obj => __classPrivateFieldIn(_classThis, obj), get: obj => __classPrivateFieldGet(obj, _classThis, "a", _x_get) } }, null, _staticExtraInitializers); +- __esDecorate(_classThis, _static_private_set_x_descriptor = { set: __setFunctionName(function (value) { }, "#x", "set") }, _static_private_set_x_decorators, { kind: "setter", name: "#x", static: true, private: true, access: { has: obj => __classPrivateFieldIn(_classThis, obj), set: (obj, value) => { __classPrivateFieldSet(obj, _classThis, value, "a", _x_set); } } }, null, _staticExtraInitializers); +- __esDecorate(_classThis, _static_private_z_descriptor = { get: __setFunctionName(function () { return __classPrivateFieldGet(_classThis, _classThis, "f", _z_accessor_storage); }, "#z", "get"), set: __setFunctionName(function (value) { __classPrivateFieldSet(_classThis, _classThis, value, "f", _z_accessor_storage); }, "#z", "set") }, _static_private_z_decorators, { kind: "accessor", name: "#z", static: true, private: true, access: { has: obj => __classPrivateFieldIn(_classThis, obj), get: obj => __classPrivateFieldGet(obj, _classThis, "a", _z_get), set: (obj, value) => { __classPrivateFieldSet(obj, _classThis, value, "a", _z_set); } } }, _static_private_z_initializers, _staticExtraInitializers); ++ __esDecorate(_classThis, _static_private_method_descriptor = { value: __setFunctionName(function () { }, "#method") }, _static_private_method_decorators, { kind: "method", name: "#method", static: true, private: true, access: { has: obj => __classPrivateFieldIn(_classThis, obj), get: obj => __classPrivateFieldGet(obj, _classThis, "a", _C_method_get) } }, null, _staticExtraInitializers); ++ __esDecorate(_classThis, _static_private_get_x_descriptor = { get: __setFunctionName(function () { return 1; }, "#x", "get") }, _static_private_get_x_decorators, { kind: "getter", name: "#x", static: true, private: true, access: { has: obj => __classPrivateFieldIn(_classThis, obj), get: obj => __classPrivateFieldGet(obj, _classThis, "a", _C_x_get) } }, null, _staticExtraInitializers); ++ __esDecorate(_classThis, _static_private_set_x_descriptor = { set: __setFunctionName(function (value) { }, "#x", "set") }, _static_private_set_x_decorators, { kind: "setter", name: "#x", static: true, private: true, access: { has: obj => __classPrivateFieldIn(_classThis, obj), set: (obj, value) => { __classPrivateFieldSet(obj, _classThis, value, "a", _C_x_set); } } }, null, _staticExtraInitializers); ++ __esDecorate(_classThis, _static_private_z_descriptor = { get: __setFunctionName(function () { return __classPrivateFieldGet(_classThis, _classThis, "f", _C_z_accessor_storage); }, "#z", "get"), set: __setFunctionName(function (value) { __classPrivateFieldSet(_classThis, _classThis, value, "f", _C_z_accessor_storage); }, "#z", "set") }, _static_private_z_decorators, { kind: "accessor", name: "#z", static: true, private: true, access: { has: obj => __classPrivateFieldIn(_classThis, obj), get: obj => __classPrivateFieldGet(obj, _classThis, "a", _C_z_get), set: (obj, value) => { __classPrivateFieldSet(obj, _classThis, value, "a", _C_z_set); } } }, _static_private_z_initializers, _staticExtraInitializers); + __esDecorate(_classThis, null, _method_decorators, { kind: "method", name: "method", static: false, private: false, access: { has: obj => "method" in obj, get: obj => obj.method } }, null, _instanceExtraInitializers); + __esDecorate(_classThis, null, _get_x_decorators, { kind: "getter", name: "x", static: false, private: false, access: { has: obj => "x" in obj, get: obj => obj.x } }, null, _instanceExtraInitializers); + __esDecorate(_classThis, null, _set_x_decorators, { kind: "setter", name: "x", static: false, private: false, access: { has: obj => "x" in obj, set: (obj, value) => { obj.x = value; } } }, null, _instanceExtraInitializers); + __esDecorate(_classThis, null, _z_decorators, { kind: "accessor", name: "z", static: false, private: false, access: { has: obj => "z" in obj, get: obj => obj.z, set: (obj, value) => { obj.z = value; } } }, _z_initializers, _instanceExtraInitializers); +- __esDecorate(null, null, _static_private_y_decorators, { kind: "field", name: "#y", static: true, private: true, access: { has: obj => __classPrivateFieldIn(_classThis, obj), get: obj => __classPrivateFieldGet(obj, _classThis, "f", _y), set: (obj, value) => { __classPrivateFieldSet(obj, _classThis, value, "f", _y); } } }, _static_private_y_initializers, _staticExtraInitializers); ++ __esDecorate(null, null, _static_private_y_decorators, { kind: "field", name: "#y", static: true, private: true, access: { has: obj => __classPrivateFieldIn(_classThis, obj), get: obj => __classPrivateFieldGet(obj, _classThis, "f", _C_y), set: (obj, value) => { __classPrivateFieldSet(obj, _classThis, value, "f", _C_y); } } }, _static_private_y_initializers, _staticExtraInitializers); + __esDecorate(null, null, _y_decorators, { kind: "field", name: "y", static: false, private: false, access: { has: obj => "y" in obj, get: obj => obj.y, set: (obj, value) => { obj.y = value; } } }, _y_initializers, _instanceExtraInitializers); + __esDecorate(null, _classDescriptor = { value: _classThis }, _classDecorators, { kind: "class", name: _classThis.name }, null, _classExtraInitializers); + C = _classThis = _classDescriptor.value; + __runInitializers(_classThis, _staticExtraInitializers); + })(), + /*29*/ +- _y = { value: __runInitializers(_classThis, _static_private_y_initializers, 1) }, +- _z_accessor_storage = { value: __runInitializers(_classThis, _static_private_z_initializers, 1) }, ++ _C_y = { value: __runInitializers(_classThis, _static_private_y_initializers, 1) }, ++ _C_z_accessor_storage = { value: __runInitializers(_classThis, _static_private_z_initializers, 1) }, + (() => { + __runInitializers(_classThis, _classExtraInitializers); + })(), +diff --git a/tests/baselines/reference/esDecorators-classExpression-commentPreservation(target=es2022).js b/tests/baselines/reference/esDecorators-classExpression-commentPreservation(target=es2022).js +index 16d4e1c12..f51427a9c 100644 +--- a/tests/baselines/reference/esDecorators-classExpression-commentPreservation(target=es2022).js ++++ b/tests/baselines/reference/esDecorators-classExpression-commentPreservation(target=es2022).js +@@ -87,7 +87,7 @@ class C { + //// [esDecorators-classExpression-commentPreservation.js] + /*1*/ + ((() => { +- var _method_get, _x_get, _x_set, _y, _z_accessor_storage, _z_get, _z_set, _a; ++ var _C_method_get, _C_x_get, _C_x_set, _C_y, _C_z_accessor_storage, _C_z_get, _C_z_set, _a; + let _classDecorators = [dec, dec]; + let _classDescriptor; + let _classExtraInitializers = []; +@@ -113,7 +113,9 @@ class C { + let _z_decorators; + let _z_initializers = []; + var C = (_a = class { +- static { _method_get = function _method_get() { return _static_private_method_descriptor.value; }, _x_get = function _x_get() { return _static_private_get_x_descriptor.get.call(this); }, _x_set = function _x_set(value) { return _static_private_set_x_descriptor.set.call(this, value); }, _z_get = function _z_get() { return _static_private_z_descriptor.get.call(this); }, _z_set = function _z_set(value) { return _static_private_z_descriptor.set.call(this, value); }; } ++ static { _classThis = this; } ++ static { __setFunctionName(this, "C"); } ++ static { _C_method_get = function _C_method_get() { return _static_private_method_descriptor.value; }, _C_x_get = function _C_x_get() { return _static_private_get_x_descriptor.get.call(this); }, _C_x_set = function _C_x_set(value) { return _static_private_set_x_descriptor.set.call(this, value); }, _C_z_get = function _C_z_get() { return _static_private_z_descriptor.get.call(this); }, _C_z_set = function _C_z_set(value) { return _static_private_z_descriptor.set.call(this, value); }; } + static { + _method_decorators = [dec, dec]; + _get_x_decorators = [dec, dec]; +@@ -125,17 +127,17 @@ class C { + _static_private_set_x_decorators = [dec, dec]; + _static_private_y_decorators = [dec, dec]; + _static_private_z_decorators = [dec, dec]; +- __esDecorate(this, _static_private_method_descriptor = { value: __setFunctionName(function () { }, "#method") }, _static_private_method_decorators, { kind: "method", name: "#method", static: true, private: true, access: { has: obj => __classPrivateFieldIn(_classThis, obj), get: obj => __classPrivateFieldGet(obj, _classThis, "a", _method_get) } }, null, _staticExtraInitializers); +- __esDecorate(this, _static_private_get_x_descriptor = { get: __setFunctionName(function () { return 1; }, "#x", "get") }, _static_private_get_x_decorators, { kind: "getter", name: "#x", static: true, private: true, access: { has: obj => __classPrivateFieldIn(_classThis, obj), get: obj => __classPrivateFieldGet(obj, _classThis, "a", _x_get) } }, null, _staticExtraInitializers); +- __esDecorate(this, _static_private_set_x_descriptor = { set: __setFunctionName(function (value) { }, "#x", "set") }, _static_private_set_x_decorators, { kind: "setter", name: "#x", static: true, private: true, access: { has: obj => __classPrivateFieldIn(_classThis, obj), set: (obj, value) => { __classPrivateFieldSet(obj, _classThis, value, "a", _x_set); } } }, null, _staticExtraInitializers); +- __esDecorate(this, _static_private_z_descriptor = { get: __setFunctionName(function () { return __classPrivateFieldGet(this, _classThis, "f", _z_accessor_storage); }, "#z", "get"), set: __setFunctionName(function (value) { __classPrivateFieldSet(this, _classThis, value, "f", _z_accessor_storage); }, "#z", "set") }, _static_private_z_decorators, { kind: "accessor", name: "#z", static: true, private: true, access: { has: obj => __classPrivateFieldIn(_classThis, obj), get: obj => __classPrivateFieldGet(obj, _classThis, "a", _z_get), set: (obj, value) => { __classPrivateFieldSet(obj, _classThis, value, "a", _z_set); } } }, _static_private_z_initializers, _staticExtraInitializers); ++ __esDecorate(this, _static_private_method_descriptor = { value: __setFunctionName(function () { }, "#method") }, _static_private_method_decorators, { kind: "method", name: "#method", static: true, private: true, access: { has: obj => __classPrivateFieldIn(_classThis, obj), get: obj => __classPrivateFieldGet(obj, _classThis, "a", _C_method_get) } }, null, _staticExtraInitializers); ++ __esDecorate(this, _static_private_get_x_descriptor = { get: __setFunctionName(function () { return 1; }, "#x", "get") }, _static_private_get_x_decorators, { kind: "getter", name: "#x", static: true, private: true, access: { has: obj => __classPrivateFieldIn(_classThis, obj), get: obj => __classPrivateFieldGet(obj, _classThis, "a", _C_x_get) } }, null, _staticExtraInitializers); ++ __esDecorate(this, _static_private_set_x_descriptor = { set: __setFunctionName(function (value) { }, "#x", "set") }, _static_private_set_x_decorators, { kind: "setter", name: "#x", static: true, private: true, access: { has: obj => __classPrivateFieldIn(_classThis, obj), set: (obj, value) => { __classPrivateFieldSet(obj, _classThis, value, "a", _C_x_set); } } }, null, _staticExtraInitializers); ++ __esDecorate(this, _static_private_z_descriptor = { get: __setFunctionName(function () { return __classPrivateFieldGet(this, _classThis, "f", _C_z_accessor_storage); }, "#z", "get"), set: __setFunctionName(function (value) { __classPrivateFieldSet(this, _classThis, value, "f", _C_z_accessor_storage); }, "#z", "set") }, _static_private_z_decorators, { kind: "accessor", name: "#z", static: true, private: true, access: { has: obj => __classPrivateFieldIn(_classThis, obj), get: obj => __classPrivateFieldGet(obj, _classThis, "a", _C_z_get), set: (obj, value) => { __classPrivateFieldSet(obj, _classThis, value, "a", _C_z_set); } } }, _static_private_z_initializers, _staticExtraInitializers); + __esDecorate(this, null, _method_decorators, { kind: "method", name: "method", static: false, private: false, access: { has: obj => "method" in obj, get: obj => obj.method } }, null, _instanceExtraInitializers); + __esDecorate(this, null, _get_x_decorators, { kind: "getter", name: "x", static: false, private: false, access: { has: obj => "x" in obj, get: obj => obj.x } }, null, _instanceExtraInitializers); + __esDecorate(this, null, _set_x_decorators, { kind: "setter", name: "x", static: false, private: false, access: { has: obj => "x" in obj, set: (obj, value) => { obj.x = value; } } }, null, _instanceExtraInitializers); + __esDecorate(this, null, _z_decorators, { kind: "accessor", name: "z", static: false, private: false, access: { has: obj => "z" in obj, get: obj => obj.z, set: (obj, value) => { obj.z = value; } } }, _z_initializers, _instanceExtraInitializers); +- __esDecorate(null, null, _static_private_y_decorators, { kind: "field", name: "#y", static: true, private: true, access: { has: obj => __classPrivateFieldIn(_classThis, obj), get: obj => __classPrivateFieldGet(obj, _classThis, "f", _y), set: (obj, value) => { __classPrivateFieldSet(obj, _classThis, value, "f", _y); } } }, _static_private_y_initializers, _staticExtraInitializers); ++ __esDecorate(null, null, _static_private_y_decorators, { kind: "field", name: "#y", static: true, private: true, access: { has: obj => __classPrivateFieldIn(_classThis, obj), get: obj => __classPrivateFieldGet(obj, _classThis, "f", _C_y), set: (obj, value) => { __classPrivateFieldSet(obj, _classThis, value, "f", _C_y); } } }, _static_private_y_initializers, _staticExtraInitializers); + __esDecorate(null, null, _y_decorators, { kind: "field", name: "y", static: false, private: false, access: { has: obj => "y" in obj, get: obj => obj.y, set: (obj, value) => { obj.y = value; } } }, _y_initializers, _instanceExtraInitializers); +- __esDecorate(null, _classDescriptor = { value: this }, _classDecorators, { kind: "class", name: this.name }, null, _classExtraInitializers); ++ __esDecorate(null, _classDescriptor = { value: _classThis }, _classDecorators, { kind: "class", name: _classThis.name }, null, _classExtraInitializers); + C = _classThis = _classDescriptor.value; + __runInitializers(_classThis, _staticExtraInitializers); + } +@@ -153,19 +155,18 @@ class C { + set z(value) { this.#z_accessor_storage = value; } + static { + /*29*/ +- _y = { value: __runInitializers(_classThis, _static_private_y_initializers, 1) }; ++ _C_y = { value: __runInitializers(_classThis, _static_private_y_initializers, 1) }; + } + static { +- _z_accessor_storage = { value: __runInitializers(_classThis, _static_private_z_initializers, 1) }; ++ _C_z_accessor_storage = { value: __runInitializers(_classThis, _static_private_z_initializers, 1) }; + } + static { + __runInitializers(_classThis, _classExtraInitializers); + } + }, +- __setFunctionName(_a, "C"), + /*29*/ +- _y = { value: __runInitializers(_classThis, _static_private_y_initializers, 1) }, +- _z_accessor_storage = { value: __runInitializers(_classThis, _static_private_z_initializers, 1) }, ++ _C_y = { value: __runInitializers(_classThis, _static_private_y_initializers, 1) }, ++ _C_z_accessor_storage = { value: __runInitializers(_classThis, _static_private_z_initializers, 1) }, + _a); + return C = _classThis; + })()); +diff --git a/tests/baselines/reference/esDecorators-classExpression-missingEmitHelpers-classDecorator.1.js b/tests/baselines/reference/esDecorators-classExpression-missingEmitHelpers-classDecorator.1.js +index 50b51a2c1..754ce68f5 100644 +--- a/tests/baselines/reference/esDecorators-classExpression-missingEmitHelpers-classDecorator.1.js ++++ b/tests/baselines/reference/esDecorators-classExpression-missingEmitHelpers-classDecorator.1.js +@@ -22,9 +22,10 @@ exports.C = (() => { + let _classExtraInitializers = []; + let _classThis; + var class_1 = class { ++ static { _classThis = this; } ++ static { tslib_1.__setFunctionName(_classThis, "C"); } + static { +- tslib_1.__setFunctionName(this, "C"); +- tslib_1.__esDecorate(null, _classDescriptor = { value: this }, _classDecorators, { kind: "class", name: this.name }, null, _classExtraInitializers); ++ tslib_1.__esDecorate(null, _classDescriptor = { value: _classThis }, _classDecorators, { kind: "class", name: _classThis.name }, null, _classExtraInitializers); + class_1 = _classThis = _classDescriptor.value; + tslib_1.__runInitializers(_classThis, _classExtraInitializers); + } +diff --git a/tests/baselines/reference/esDecorators-classExpression-missingEmitHelpers-classDecorator.10.js b/tests/baselines/reference/esDecorators-classExpression-missingEmitHelpers-classDecorator.10.js +index 197a8d003..5a7c9f591 100644 +--- a/tests/baselines/reference/esDecorators-classExpression-missingEmitHelpers-classDecorator.10.js ++++ b/tests/baselines/reference/esDecorators-classExpression-missingEmitHelpers-classDecorator.10.js +@@ -25,9 +25,10 @@ C &&= (() => { + let _classExtraInitializers = []; + let _classThis; + var class_1 = class { ++ static { _classThis = this; } ++ static { tslib_1.__setFunctionName(_classThis, "C"); } + static { +- tslib_1.__setFunctionName(this, "C"); +- tslib_1.__esDecorate(null, _classDescriptor = { value: this }, _classDecorators, { kind: "class", name: this.name }, null, _classExtraInitializers); ++ tslib_1.__esDecorate(null, _classDescriptor = { value: _classThis }, _classDecorators, { kind: "class", name: _classThis.name }, null, _classExtraInitializers); + class_1 = _classThis = _classDescriptor.value; + tslib_1.__runInitializers(_classThis, _classExtraInitializers); + } +diff --git a/tests/baselines/reference/esDecorators-classExpression-missingEmitHelpers-classDecorator.11.js b/tests/baselines/reference/esDecorators-classExpression-missingEmitHelpers-classDecorator.11.js +index 3f059fb32..fe34668e4 100644 +--- a/tests/baselines/reference/esDecorators-classExpression-missingEmitHelpers-classDecorator.11.js ++++ b/tests/baselines/reference/esDecorators-classExpression-missingEmitHelpers-classDecorator.11.js +@@ -25,9 +25,10 @@ C ??= (() => { + let _classExtraInitializers = []; + let _classThis; + var class_1 = class { ++ static { _classThis = this; } ++ static { tslib_1.__setFunctionName(_classThis, "C"); } + static { +- tslib_1.__setFunctionName(this, "C"); +- tslib_1.__esDecorate(null, _classDescriptor = { value: this }, _classDecorators, { kind: "class", name: this.name }, null, _classExtraInitializers); ++ tslib_1.__esDecorate(null, _classDescriptor = { value: _classThis }, _classDecorators, { kind: "class", name: _classThis.name }, null, _classExtraInitializers); + class_1 = _classThis = _classDescriptor.value; + tslib_1.__runInitializers(_classThis, _classExtraInitializers); + } +diff --git a/tests/baselines/reference/esDecorators-classExpression-missingEmitHelpers-classDecorator.12.js b/tests/baselines/reference/esDecorators-classExpression-missingEmitHelpers-classDecorator.12.js +index c5b94a7fe..9d037ab86 100644 +--- a/tests/baselines/reference/esDecorators-classExpression-missingEmitHelpers-classDecorator.12.js ++++ b/tests/baselines/reference/esDecorators-classExpression-missingEmitHelpers-classDecorator.12.js +@@ -22,9 +22,10 @@ function f(C = (() => { + let _classExtraInitializers = []; + let _classThis; + var class_1 = class { ++ static { _classThis = this; } ++ static { tslib_1.__setFunctionName(_classThis, "C"); } + static { +- tslib_1.__setFunctionName(this, "C"); +- tslib_1.__esDecorate(null, _classDescriptor = { value: this }, _classDecorators, { kind: "class", name: this.name }, null, _classExtraInitializers); ++ tslib_1.__esDecorate(null, _classDescriptor = { value: _classThis }, _classDecorators, { kind: "class", name: _classThis.name }, null, _classExtraInitializers); + class_1 = _classThis = _classDescriptor.value; + tslib_1.__runInitializers(_classThis, _classExtraInitializers); + } +diff --git a/tests/baselines/reference/esDecorators-classExpression-missingEmitHelpers-classDecorator.13.js b/tests/baselines/reference/esDecorators-classExpression-missingEmitHelpers-classDecorator.13.js +index 838ba46d2..5288d3a9a 100644 +--- a/tests/baselines/reference/esDecorators-classExpression-missingEmitHelpers-classDecorator.13.js ++++ b/tests/baselines/reference/esDecorators-classExpression-missingEmitHelpers-classDecorator.13.js +@@ -22,9 +22,10 @@ exports.C = (((() => { + let _classExtraInitializers = []; + let _classThis; + var class_1 = class { ++ static { _classThis = this; } ++ static { tslib_1.__setFunctionName(_classThis, "C"); } + static { +- tslib_1.__setFunctionName(this, "C"); +- tslib_1.__esDecorate(null, _classDescriptor = { value: this }, _classDecorators, { kind: "class", name: this.name }, null, _classExtraInitializers); ++ tslib_1.__esDecorate(null, _classDescriptor = { value: _classThis }, _classDecorators, { kind: "class", name: _classThis.name }, null, _classExtraInitializers); + class_1 = _classThis = _classDescriptor.value; + tslib_1.__runInitializers(_classThis, _classExtraInitializers); + } +diff --git a/tests/baselines/reference/esDecorators-classExpression-missingEmitHelpers-classDecorator.14.js b/tests/baselines/reference/esDecorators-classExpression-missingEmitHelpers-classDecorator.14.js +index d1b27d096..c84185add 100644 +--- a/tests/baselines/reference/esDecorators-classExpression-missingEmitHelpers-classDecorator.14.js ++++ b/tests/baselines/reference/esDecorators-classExpression-missingEmitHelpers-classDecorator.14.js +@@ -24,9 +24,10 @@ const tslib_1 = require("tslib"); + let _classExtraInitializers = []; + let _classThis; + var class_1 = class { ++ static { _classThis = this; } ++ static { tslib_1.__setFunctionName(_classThis, _a); } + static { +- tslib_1.__setFunctionName(this, _a); +- tslib_1.__esDecorate(null, _classDescriptor = { value: this }, _classDecorators, { kind: "class", name: this.name }, null, _classExtraInitializers); ++ tslib_1.__esDecorate(null, _classDescriptor = { value: _classThis }, _classDecorators, { kind: "class", name: _classThis.name }, null, _classExtraInitializers); + class_1 = _classThis = _classDescriptor.value; + tslib_1.__runInitializers(_classThis, _classExtraInitializers); + } +diff --git a/tests/baselines/reference/esDecorators-classExpression-missingEmitHelpers-classDecorator.15.js b/tests/baselines/reference/esDecorators-classExpression-missingEmitHelpers-classDecorator.15.js +index 76e9f13ae..3feb9c2aa 100644 +--- a/tests/baselines/reference/esDecorators-classExpression-missingEmitHelpers-classDecorator.15.js ++++ b/tests/baselines/reference/esDecorators-classExpression-missingEmitHelpers-classDecorator.15.js +@@ -23,9 +23,10 @@ class C { + let _classExtraInitializers = []; + let _classThis; + var class_1 = class { ++ static { _classThis = this; } ++ static { tslib_1.__setFunctionName(_classThis, "D"); } + static { +- tslib_1.__setFunctionName(this, "D"); +- tslib_1.__esDecorate(null, _classDescriptor = { value: this }, _classDecorators, { kind: "class", name: this.name }, null, _classExtraInitializers); ++ tslib_1.__esDecorate(null, _classDescriptor = { value: _classThis }, _classDecorators, { kind: "class", name: _classThis.name }, null, _classExtraInitializers); + class_1 = _classThis = _classDescriptor.value; + tslib_1.__runInitializers(_classThis, _classExtraInitializers); + } +diff --git a/tests/baselines/reference/esDecorators-classExpression-missingEmitHelpers-classDecorator.16.js b/tests/baselines/reference/esDecorators-classExpression-missingEmitHelpers-classDecorator.16.js +index e61323d96..474810fce 100644 +--- a/tests/baselines/reference/esDecorators-classExpression-missingEmitHelpers-classDecorator.16.js ++++ b/tests/baselines/reference/esDecorators-classExpression-missingEmitHelpers-classDecorator.16.js +@@ -25,9 +25,10 @@ class C { + let _classExtraInitializers = []; + let _classThis; + var class_1 = class { ++ static { _classThis = this; } ++ static { tslib_1.__setFunctionName(_classThis, _a); } + static { +- tslib_1.__setFunctionName(this, _a); +- tslib_1.__esDecorate(null, _classDescriptor = { value: this }, _classDecorators, { kind: "class", name: this.name }, null, _classExtraInitializers); ++ tslib_1.__esDecorate(null, _classDescriptor = { value: _classThis }, _classDecorators, { kind: "class", name: _classThis.name }, null, _classExtraInitializers); + class_1 = _classThis = _classDescriptor.value; + tslib_1.__runInitializers(_classThis, _classExtraInitializers); + } +diff --git a/tests/baselines/reference/esDecorators-classExpression-missingEmitHelpers-classDecorator.17.js b/tests/baselines/reference/esDecorators-classExpression-missingEmitHelpers-classDecorator.17.js +index 0c3cc126a..d53f60306 100644 +--- a/tests/baselines/reference/esDecorators-classExpression-missingEmitHelpers-classDecorator.17.js ++++ b/tests/baselines/reference/esDecorators-classExpression-missingEmitHelpers-classDecorator.17.js +@@ -26,9 +26,10 @@ var C; + let _classExtraInitializers = []; + let _classThis; + var class_1 = class { ++ static { _classThis = this; } ++ static { tslib_1.__setFunctionName(_classThis, "C"); } + static { +- tslib_1.__setFunctionName(this, "C"); +- tslib_1.__esDecorate(null, _classDescriptor = { value: this }, _classDecorators, { kind: "class", name: this.name }, null, _classExtraInitializers); ++ tslib_1.__esDecorate(null, _classDescriptor = { value: _classThis }, _classDecorators, { kind: "class", name: _classThis.name }, null, _classExtraInitializers); + class_1 = _classThis = _classDescriptor.value; + tslib_1.__runInitializers(_classThis, _classExtraInitializers); + } +diff --git a/tests/baselines/reference/esDecorators-classExpression-missingEmitHelpers-classDecorator.2.js b/tests/baselines/reference/esDecorators-classExpression-missingEmitHelpers-classDecorator.2.js +index a6ab301b3..6931e4369 100644 +--- a/tests/baselines/reference/esDecorators-classExpression-missingEmitHelpers-classDecorator.2.js ++++ b/tests/baselines/reference/esDecorators-classExpression-missingEmitHelpers-classDecorator.2.js +@@ -22,8 +22,9 @@ exports.C = (() => { + let _classExtraInitializers = []; + let _classThis; + var C = class { ++ static { _classThis = this; } + static { +- tslib_1.__esDecorate(null, _classDescriptor = { value: this }, _classDecorators, { kind: "class", name: this.name }, null, _classExtraInitializers); ++ tslib_1.__esDecorate(null, _classDescriptor = { value: _classThis }, _classDecorators, { kind: "class", name: _classThis.name }, null, _classExtraInitializers); + C = _classThis = _classDescriptor.value; + tslib_1.__runInitializers(_classThis, _classExtraInitializers); + } +diff --git a/tests/baselines/reference/esDecorators-classExpression-missingEmitHelpers-classDecorator.3.js b/tests/baselines/reference/esDecorators-classExpression-missingEmitHelpers-classDecorator.3.js +index bd13effbc..5b9ea5b59 100644 +--- a/tests/baselines/reference/esDecorators-classExpression-missingEmitHelpers-classDecorator.3.js ++++ b/tests/baselines/reference/esDecorators-classExpression-missingEmitHelpers-classDecorator.3.js +@@ -21,9 +21,10 @@ exports.default = ((() => { + let _classExtraInitializers = []; + let _classThis; + var class_1 = class { ++ static { _classThis = this; } ++ static { tslib_1.__setFunctionName(_classThis, "default"); } + static { +- tslib_1.__setFunctionName(this, "default"); +- tslib_1.__esDecorate(null, _classDescriptor = { value: this }, _classDecorators, { kind: "class", name: this.name }, null, _classExtraInitializers); ++ tslib_1.__esDecorate(null, _classDescriptor = { value: _classThis }, _classDecorators, { kind: "class", name: _classThis.name }, null, _classExtraInitializers); + class_1 = _classThis = _classDescriptor.value; + tslib_1.__runInitializers(_classThis, _classExtraInitializers); + } +diff --git a/tests/baselines/reference/esDecorators-classExpression-missingEmitHelpers-classDecorator.4.js b/tests/baselines/reference/esDecorators-classExpression-missingEmitHelpers-classDecorator.4.js +index 1e5e1f8b1..2a0adf73d 100644 +--- a/tests/baselines/reference/esDecorators-classExpression-missingEmitHelpers-classDecorator.4.js ++++ b/tests/baselines/reference/esDecorators-classExpression-missingEmitHelpers-classDecorator.4.js +@@ -25,9 +25,10 @@ C = (() => { + let _classExtraInitializers = []; + let _classThis; + var class_1 = class { ++ static { _classThis = this; } ++ static { tslib_1.__setFunctionName(_classThis, "C"); } + static { +- tslib_1.__setFunctionName(this, "C"); +- tslib_1.__esDecorate(null, _classDescriptor = { value: this }, _classDecorators, { kind: "class", name: this.name }, null, _classExtraInitializers); ++ tslib_1.__esDecorate(null, _classDescriptor = { value: _classThis }, _classDecorators, { kind: "class", name: _classThis.name }, null, _classExtraInitializers); + class_1 = _classThis = _classDescriptor.value; + tslib_1.__runInitializers(_classThis, _classExtraInitializers); + } +diff --git a/tests/baselines/reference/esDecorators-classExpression-missingEmitHelpers-classDecorator.5.js b/tests/baselines/reference/esDecorators-classExpression-missingEmitHelpers-classDecorator.5.js +index e772afc6a..81d750cb6 100644 +--- a/tests/baselines/reference/esDecorators-classExpression-missingEmitHelpers-classDecorator.5.js ++++ b/tests/baselines/reference/esDecorators-classExpression-missingEmitHelpers-classDecorator.5.js +@@ -25,9 +25,10 @@ var C; + let _classExtraInitializers = []; + let _classThis; + var class_1 = class { ++ static { _classThis = this; } ++ static { tslib_1.__setFunctionName(_classThis, "C"); } + static { +- tslib_1.__setFunctionName(this, "C"); +- tslib_1.__esDecorate(null, _classDescriptor = { value: this }, _classDecorators, { kind: "class", name: this.name }, null, _classExtraInitializers); ++ tslib_1.__esDecorate(null, _classDescriptor = { value: _classThis }, _classDecorators, { kind: "class", name: _classThis.name }, null, _classExtraInitializers); + class_1 = _classThis = _classDescriptor.value; + tslib_1.__runInitializers(_classThis, _classExtraInitializers); + } +diff --git a/tests/baselines/reference/esDecorators-classExpression-missingEmitHelpers-classDecorator.6.js b/tests/baselines/reference/esDecorators-classExpression-missingEmitHelpers-classDecorator.6.js +index 6206e34b9..1f926cb2b 100644 +--- a/tests/baselines/reference/esDecorators-classExpression-missingEmitHelpers-classDecorator.6.js ++++ b/tests/baselines/reference/esDecorators-classExpression-missingEmitHelpers-classDecorator.6.js +@@ -22,9 +22,10 @@ const tslib_1 = require("tslib"); + let _classExtraInitializers = []; + let _classThis; + var class_1 = class { ++ static { _classThis = this; } ++ static { tslib_1.__setFunctionName(_classThis, "C"); } + static { +- tslib_1.__setFunctionName(this, "C"); +- tslib_1.__esDecorate(null, _classDescriptor = { value: this }, _classDecorators, { kind: "class", name: this.name }, null, _classExtraInitializers); ++ tslib_1.__esDecorate(null, _classDescriptor = { value: _classThis }, _classDecorators, { kind: "class", name: _classThis.name }, null, _classExtraInitializers); + class_1 = _classThis = _classDescriptor.value; + tslib_1.__runInitializers(_classThis, _classExtraInitializers); + } +diff --git a/tests/baselines/reference/esDecorators-classExpression-missingEmitHelpers-classDecorator.7.js b/tests/baselines/reference/esDecorators-classExpression-missingEmitHelpers-classDecorator.7.js +index d428e95b2..6c6e7adde 100644 +--- a/tests/baselines/reference/esDecorators-classExpression-missingEmitHelpers-classDecorator.7.js ++++ b/tests/baselines/reference/esDecorators-classExpression-missingEmitHelpers-classDecorator.7.js +@@ -25,9 +25,10 @@ var C; + let _classExtraInitializers = []; + let _classThis; + var class_1 = class { ++ static { _classThis = this; } ++ static { tslib_1.__setFunctionName(_classThis, "C"); } + static { +- tslib_1.__setFunctionName(this, "C"); +- tslib_1.__esDecorate(null, _classDescriptor = { value: this }, _classDecorators, { kind: "class", name: this.name }, null, _classExtraInitializers); ++ tslib_1.__esDecorate(null, _classDescriptor = { value: _classThis }, _classDecorators, { kind: "class", name: _classThis.name }, null, _classExtraInitializers); + class_1 = _classThis = _classDescriptor.value; + tslib_1.__runInitializers(_classThis, _classExtraInitializers); + } +diff --git a/tests/baselines/reference/esDecorators-classExpression-missingEmitHelpers-classDecorator.8.js b/tests/baselines/reference/esDecorators-classExpression-missingEmitHelpers-classDecorator.8.js +index e5118d682..7f9989666 100644 +--- a/tests/baselines/reference/esDecorators-classExpression-missingEmitHelpers-classDecorator.8.js ++++ b/tests/baselines/reference/esDecorators-classExpression-missingEmitHelpers-classDecorator.8.js +@@ -25,9 +25,10 @@ var C; + let _classExtraInitializers = []; + let _classThis; + var class_1 = class { ++ static { _classThis = this; } ++ static { tslib_1.__setFunctionName(_classThis, "C"); } + static { +- tslib_1.__setFunctionName(this, "C"); +- tslib_1.__esDecorate(null, _classDescriptor = { value: this }, _classDecorators, { kind: "class", name: this.name }, null, _classExtraInitializers); ++ tslib_1.__esDecorate(null, _classDescriptor = { value: _classThis }, _classDecorators, { kind: "class", name: _classThis.name }, null, _classExtraInitializers); + class_1 = _classThis = _classDescriptor.value; + tslib_1.__runInitializers(_classThis, _classExtraInitializers); + } +diff --git a/tests/baselines/reference/esDecorators-classExpression-missingEmitHelpers-classDecorator.9.js b/tests/baselines/reference/esDecorators-classExpression-missingEmitHelpers-classDecorator.9.js +index 12695aac7..2938134bb 100644 +--- a/tests/baselines/reference/esDecorators-classExpression-missingEmitHelpers-classDecorator.9.js ++++ b/tests/baselines/reference/esDecorators-classExpression-missingEmitHelpers-classDecorator.9.js +@@ -25,9 +25,10 @@ C ||= (() => { + let _classExtraInitializers = []; + let _classThis; + var class_1 = class { ++ static { _classThis = this; } ++ static { tslib_1.__setFunctionName(_classThis, "C"); } + static { +- tslib_1.__setFunctionName(this, "C"); +- tslib_1.__esDecorate(null, _classDescriptor = { value: this }, _classDecorators, { kind: "class", name: this.name }, null, _classExtraInitializers); ++ tslib_1.__esDecorate(null, _classDescriptor = { value: _classThis }, _classDecorators, { kind: "class", name: _classThis.name }, null, _classExtraInitializers); + class_1 = _classThis = _classDescriptor.value; + tslib_1.__runInitializers(_classThis, _classExtraInitializers); + } +diff --git a/tests/baselines/reference/esDecorators-classExpression-namedEvaluation.1.js b/tests/baselines/reference/esDecorators-classExpression-namedEvaluation.1.js +index 9a3cb19e2..96bdd18d4 100644 +--- a/tests/baselines/reference/esDecorators-classExpression-namedEvaluation.1.js ++++ b/tests/baselines/reference/esDecorators-classExpression-namedEvaluation.1.js +@@ -40,9 +40,10 @@ x = (() => { + let _classExtraInitializers = []; + let _classThis; + var class_1 = class { ++ static { _classThis = this; } ++ static { __setFunctionName(_classThis, "x"); } + static { +- __setFunctionName(this, "x"); +- __esDecorate(null, _classDescriptor = { value: this }, _classDecorators, { kind: "class", name: this.name }, null, _classExtraInitializers); ++ __esDecorate(null, _classDescriptor = { value: _classThis }, _classDecorators, { kind: "class", name: _classThis.name }, null, _classExtraInitializers); + class_1 = _classThis = _classDescriptor.value; + __runInitializers(_classThis, _classExtraInitializers); + } +@@ -54,8 +55,8 @@ x = (() => { + let _y_decorators; + let _y_initializers = []; + return class { ++ static { __setFunctionName(this, "x"); } + static { +- __setFunctionName(this, "x"); + _y_decorators = [dec]; + __esDecorate(null, null, _y_decorators, { kind: "field", name: "y", static: false, private: false, access: { has: obj => "y" in obj, get: obj => obj.y, set: (obj, value) => { obj.y = value; } } }, _y_initializers, _instanceExtraInitializers); + } +@@ -65,90 +66,93 @@ x = (() => { + // 13.15.2 RS: Evaluation + // AssignmentExpression : LeftHandSideExpression `&&=` AssignmentExpression + x &&= (() => { +- let _classDecorators_1 = [dec]; +- let _classDescriptor_1; +- let _classExtraInitializers_1 = []; +- let _classThis_1; ++ let _classDecorators = [dec]; ++ let _classDescriptor; ++ let _classExtraInitializers = []; ++ let _classThis; + var class_2 = class { ++ static { _classThis = this; } ++ static { __setFunctionName(_classThis, "x"); } + static { +- __setFunctionName(this, "x"); +- __esDecorate(null, _classDescriptor_1 = { value: this }, _classDecorators_1, { kind: "class", name: this.name }, null, _classExtraInitializers_1); +- class_2 = _classThis_1 = _classDescriptor_1.value; +- __runInitializers(_classThis_1, _classExtraInitializers_1); ++ __esDecorate(null, _classDescriptor = { value: _classThis }, _classDecorators, { kind: "class", name: _classThis.name }, null, _classExtraInitializers); ++ class_2 = _classThis = _classDescriptor.value; ++ __runInitializers(_classThis, _classExtraInitializers); + } + }; +- return class_2 = _classThis_1; ++ return class_2 = _classThis; + })(); + x &&= (() => { +- let _instanceExtraInitializers_1 = []; ++ let _instanceExtraInitializers = []; + let _y_decorators; + let _y_initializers = []; + return class { ++ static { __setFunctionName(this, "x"); } + static { +- __setFunctionName(this, "x"); + _y_decorators = [dec]; +- __esDecorate(null, null, _y_decorators, { kind: "field", name: "y", static: false, private: false, access: { has: obj => "y" in obj, get: obj => obj.y, set: (obj, value) => { obj.y = value; } } }, _y_initializers, _instanceExtraInitializers_1); ++ __esDecorate(null, null, _y_decorators, { kind: "field", name: "y", static: false, private: false, access: { has: obj => "y" in obj, get: obj => obj.y, set: (obj, value) => { obj.y = value; } } }, _y_initializers, _instanceExtraInitializers); + } +- y = (__runInitializers(this, _instanceExtraInitializers_1), __runInitializers(this, _y_initializers, void 0)); ++ y = (__runInitializers(this, _instanceExtraInitializers), __runInitializers(this, _y_initializers, void 0)); + }; + })(); + // 13.15.2 RS: Evaluation + // AssignmentExpression : LeftHandSideExpression `||=` AssignmentExpression + x ||= (() => { +- let _classDecorators_2 = [dec]; +- let _classDescriptor_2; +- let _classExtraInitializers_2 = []; +- let _classThis_2; ++ let _classDecorators = [dec]; ++ let _classDescriptor; ++ let _classExtraInitializers = []; ++ let _classThis; + var class_3 = class { ++ static { _classThis = this; } ++ static { __setFunctionName(_classThis, "x"); } + static { +- __setFunctionName(this, "x"); +- __esDecorate(null, _classDescriptor_2 = { value: this }, _classDecorators_2, { kind: "class", name: this.name }, null, _classExtraInitializers_2); +- class_3 = _classThis_2 = _classDescriptor_2.value; +- __runInitializers(_classThis_2, _classExtraInitializers_2); ++ __esDecorate(null, _classDescriptor = { value: _classThis }, _classDecorators, { kind: "class", name: _classThis.name }, null, _classExtraInitializers); ++ class_3 = _classThis = _classDescriptor.value; ++ __runInitializers(_classThis, _classExtraInitializers); + } + }; +- return class_3 = _classThis_2; ++ return class_3 = _classThis; + })(); + x ||= (() => { +- let _instanceExtraInitializers_2 = []; ++ let _instanceExtraInitializers = []; + let _y_decorators; + let _y_initializers = []; + return class { ++ static { __setFunctionName(this, "x"); } + static { +- __setFunctionName(this, "x"); + _y_decorators = [dec]; +- __esDecorate(null, null, _y_decorators, { kind: "field", name: "y", static: false, private: false, access: { has: obj => "y" in obj, get: obj => obj.y, set: (obj, value) => { obj.y = value; } } }, _y_initializers, _instanceExtraInitializers_2); ++ __esDecorate(null, null, _y_decorators, { kind: "field", name: "y", static: false, private: false, access: { has: obj => "y" in obj, get: obj => obj.y, set: (obj, value) => { obj.y = value; } } }, _y_initializers, _instanceExtraInitializers); + } +- y = (__runInitializers(this, _instanceExtraInitializers_2), __runInitializers(this, _y_initializers, void 0)); ++ y = (__runInitializers(this, _instanceExtraInitializers), __runInitializers(this, _y_initializers, void 0)); + }; + })(); + // 13.15.2 RS: Evaluation + // AssignmentExpression : LeftHandSideExpression `??=` AssignmentExpression + x ??= (() => { +- let _classDecorators_3 = [dec]; +- let _classDescriptor_3; +- let _classExtraInitializers_3 = []; +- let _classThis_3; ++ let _classDecorators = [dec]; ++ let _classDescriptor; ++ let _classExtraInitializers = []; ++ let _classThis; + var class_4 = class { ++ static { _classThis = this; } ++ static { __setFunctionName(_classThis, "x"); } + static { +- __setFunctionName(this, "x"); +- __esDecorate(null, _classDescriptor_3 = { value: this }, _classDecorators_3, { kind: "class", name: this.name }, null, _classExtraInitializers_3); +- class_4 = _classThis_3 = _classDescriptor_3.value; +- __runInitializers(_classThis_3, _classExtraInitializers_3); ++ __esDecorate(null, _classDescriptor = { value: _classThis }, _classDecorators, { kind: "class", name: _classThis.name }, null, _classExtraInitializers); ++ class_4 = _classThis = _classDescriptor.value; ++ __runInitializers(_classThis, _classExtraInitializers); + } + }; +- return class_4 = _classThis_3; ++ return class_4 = _classThis; + })(); + x ??= (() => { +- let _instanceExtraInitializers_3 = []; ++ let _instanceExtraInitializers = []; + let _y_decorators; + let _y_initializers = []; + return class { ++ static { __setFunctionName(this, "x"); } + static { +- __setFunctionName(this, "x"); + _y_decorators = [dec]; +- __esDecorate(null, null, _y_decorators, { kind: "field", name: "y", static: false, private: false, access: { has: obj => "y" in obj, get: obj => obj.y, set: (obj, value) => { obj.y = value; } } }, _y_initializers, _instanceExtraInitializers_3); ++ __esDecorate(null, null, _y_decorators, { kind: "field", name: "y", static: false, private: false, access: { has: obj => "y" in obj, get: obj => obj.y, set: (obj, value) => { obj.y = value; } } }, _y_initializers, _instanceExtraInitializers); + } +- y = (__runInitializers(this, _instanceExtraInitializers_3), __runInitializers(this, _y_initializers, void 0)); ++ y = (__runInitializers(this, _instanceExtraInitializers), __runInitializers(this, _y_initializers, void 0)); + }; + })(); +diff --git a/tests/baselines/reference/esDecorators-classExpression-namedEvaluation.10.js b/tests/baselines/reference/esDecorators-classExpression-namedEvaluation.10.js +index 1649959a1..0e332832d 100644 +--- a/tests/baselines/reference/esDecorators-classExpression-namedEvaluation.10.js ++++ b/tests/baselines/reference/esDecorators-classExpression-namedEvaluation.10.js +@@ -46,9 +46,10 @@ var _a, _b; + let _classExtraInitializers = []; + let _classThis; + var class_1 = class { ++ static { _classThis = this; } ++ static { __setFunctionName(_classThis, "x"); } + static { +- __setFunctionName(this, "x"); +- __esDecorate(null, _classDescriptor = { value: this }, _classDecorators, { kind: "class", name: this.name }, null, _classExtraInitializers); ++ __esDecorate(null, _classDescriptor = { value: _classThis }, _classDecorators, { kind: "class", name: _classThis.name }, null, _classExtraInitializers); + class_1 = _classThis = _classDescriptor.value; + __runInitializers(_classThis, _classExtraInitializers); + } +@@ -60,76 +61,80 @@ var _a, _b; + { + class C { + static "x" = (() => { +- let _classDecorators_1 = [dec]; +- let _classDescriptor_1; +- let _classExtraInitializers_1 = []; +- let _classThis_1; ++ let _classDecorators = [dec]; ++ let _classDescriptor; ++ let _classExtraInitializers = []; ++ let _classThis; + var class_2 = class { ++ static { _classThis = this; } ++ static { __setFunctionName(_classThis, "x"); } + static { +- __setFunctionName(this, "x"); +- __esDecorate(null, _classDescriptor_1 = { value: this }, _classDecorators_1, { kind: "class", name: this.name }, null, _classExtraInitializers_1); +- class_2 = _classThis_1 = _classDescriptor_1.value; +- __runInitializers(_classThis_1, _classExtraInitializers_1); ++ __esDecorate(null, _classDescriptor = { value: _classThis }, _classDecorators, { kind: "class", name: _classThis.name }, null, _classExtraInitializers); ++ class_2 = _classThis = _classDescriptor.value; ++ __runInitializers(_classThis, _classExtraInitializers); + } + }; +- return class_2 = _classThis_1; ++ return class_2 = _classThis; + })(); + } + } + { + class C { + static 0 = (() => { +- let _classDecorators_2 = [dec]; +- let _classDescriptor_2; +- let _classExtraInitializers_2 = []; +- let _classThis_2; ++ let _classDecorators = [dec]; ++ let _classDescriptor; ++ let _classExtraInitializers = []; ++ let _classThis; + var class_3 = class { ++ static { _classThis = this; } ++ static { __setFunctionName(_classThis, "0"); } + static { +- __setFunctionName(this, "0"); +- __esDecorate(null, _classDescriptor_2 = { value: this }, _classDecorators_2, { kind: "class", name: this.name }, null, _classExtraInitializers_2); +- class_3 = _classThis_2 = _classDescriptor_2.value; +- __runInitializers(_classThis_2, _classExtraInitializers_2); ++ __esDecorate(null, _classDescriptor = { value: _classThis }, _classDecorators, { kind: "class", name: _classThis.name }, null, _classExtraInitializers); ++ class_3 = _classThis = _classDescriptor.value; ++ __runInitializers(_classThis, _classExtraInitializers); + } + }; +- return class_3 = _classThis_2; ++ return class_3 = _classThis; + })(); + } + } + { + class C { + static ["x"] = (() => { +- let _classDecorators_3 = [dec]; +- let _classDescriptor_3; +- let _classExtraInitializers_3 = []; +- let _classThis_3; ++ let _classDecorators = [dec]; ++ let _classDescriptor; ++ let _classExtraInitializers = []; ++ let _classThis; + var class_4 = class { ++ static { _classThis = this; } ++ static { __setFunctionName(_classThis, "x"); } + static { +- __setFunctionName(this, "x"); +- __esDecorate(null, _classDescriptor_3 = { value: this }, _classDecorators_3, { kind: "class", name: this.name }, null, _classExtraInitializers_3); +- class_4 = _classThis_3 = _classDescriptor_3.value; +- __runInitializers(_classThis_3, _classExtraInitializers_3); ++ __esDecorate(null, _classDescriptor = { value: _classThis }, _classDecorators, { kind: "class", name: _classThis.name }, null, _classExtraInitializers); ++ class_4 = _classThis = _classDescriptor.value; ++ __runInitializers(_classThis, _classExtraInitializers); + } + }; +- return class_4 = _classThis_3; ++ return class_4 = _classThis; + })(); + } + } + { + class C { + static [0] = (() => { +- let _classDecorators_4 = [dec]; +- let _classDescriptor_4; +- let _classExtraInitializers_4 = []; +- let _classThis_4; ++ let _classDecorators = [dec]; ++ let _classDescriptor; ++ let _classExtraInitializers = []; ++ let _classThis; + var class_5 = class { ++ static { _classThis = this; } ++ static { __setFunctionName(_classThis, "0"); } + static { +- __setFunctionName(this, "0"); +- __esDecorate(null, _classDescriptor_4 = { value: this }, _classDecorators_4, { kind: "class", name: this.name }, null, _classExtraInitializers_4); +- class_5 = _classThis_4 = _classDescriptor_4.value; +- __runInitializers(_classThis_4, _classExtraInitializers_4); ++ __esDecorate(null, _classDescriptor = { value: _classThis }, _classDecorators, { kind: "class", name: _classThis.name }, null, _classExtraInitializers); ++ class_5 = _classThis = _classDescriptor.value; ++ __runInitializers(_classThis, _classExtraInitializers); + } + }; +- return class_5 = _classThis_4; ++ return class_5 = _classThis; + })(); + } + } +@@ -137,19 +142,20 @@ var _a, _b; + { + class C { + static [_a = __propKey(f())] = (() => { +- let _classDecorators_5 = [dec]; +- let _classDescriptor_5; +- let _classExtraInitializers_5 = []; +- let _classThis_5; ++ let _classDecorators = [dec]; ++ let _classDescriptor; ++ let _classExtraInitializers = []; ++ let _classThis; + var class_6 = class { ++ static { _classThis = this; } ++ static { __setFunctionName(_classThis, _a); } + static { +- __setFunctionName(this, _a); +- __esDecorate(null, _classDescriptor_5 = { value: this }, _classDecorators_5, { kind: "class", name: this.name }, null, _classExtraInitializers_5); +- class_6 = _classThis_5 = _classDescriptor_5.value; +- __runInitializers(_classThis_5, _classExtraInitializers_5); ++ __esDecorate(null, _classDescriptor = { value: _classThis }, _classDecorators, { kind: "class", name: _classThis.name }, null, _classExtraInitializers); ++ class_6 = _classThis = _classDescriptor.value; ++ __runInitializers(_classThis, _classExtraInitializers); + } + }; +- return class_6 = _classThis_5; ++ return class_6 = _classThis; + })(); + } + } +@@ -157,38 +163,40 @@ var _a, _b; + { + class C { + static __proto__ = (() => { +- let _classDecorators_6 = [dec]; +- let _classDescriptor_6; +- let _classExtraInitializers_6 = []; +- let _classThis_6; ++ let _classDecorators = [dec]; ++ let _classDescriptor; ++ let _classExtraInitializers = []; ++ let _classThis; + var class_7 = class { ++ static { _classThis = this; } ++ static { __setFunctionName(_classThis, "__proto__"); } + static { +- __setFunctionName(this, "__proto__"); +- __esDecorate(null, _classDescriptor_6 = { value: this }, _classDecorators_6, { kind: "class", name: this.name }, null, _classExtraInitializers_6); +- class_7 = _classThis_6 = _classDescriptor_6.value; +- __runInitializers(_classThis_6, _classExtraInitializers_6); ++ __esDecorate(null, _classDescriptor = { value: _classThis }, _classDecorators, { kind: "class", name: _classThis.name }, null, _classExtraInitializers); ++ class_7 = _classThis = _classDescriptor.value; ++ __runInitializers(_classThis, _classExtraInitializers); + } + }; +- return class_7 = _classThis_6; ++ return class_7 = _classThis; + })(); + } + } + { + class C { + static "__proto__" = (() => { +- let _classDecorators_7 = [dec]; +- let _classDescriptor_7; +- let _classExtraInitializers_7 = []; +- let _classThis_7; ++ let _classDecorators = [dec]; ++ let _classDescriptor; ++ let _classExtraInitializers = []; ++ let _classThis; + var class_8 = class { ++ static { _classThis = this; } ++ static { __setFunctionName(_classThis, "__proto__"); } + static { +- __setFunctionName(this, "__proto__"); +- __esDecorate(null, _classDescriptor_7 = { value: this }, _classDecorators_7, { kind: "class", name: this.name }, null, _classExtraInitializers_7); +- class_8 = _classThis_7 = _classDescriptor_7.value; +- __runInitializers(_classThis_7, _classExtraInitializers_7); ++ __esDecorate(null, _classDescriptor = { value: _classThis }, _classDecorators, { kind: "class", name: _classThis.name }, null, _classExtraInitializers); ++ class_8 = _classThis = _classDescriptor.value; ++ __runInitializers(_classThis, _classExtraInitializers); + } + }; +- return class_8 = _classThis_7; ++ return class_8 = _classThis; + })(); + } + } +@@ -199,8 +207,8 @@ var _a, _b; + let _y_decorators; + let _y_initializers = []; + return class { ++ static { __setFunctionName(this, "x"); } + static { +- __setFunctionName(this, "x"); + _y_decorators = [dec]; + __esDecorate(null, null, _y_decorators, { kind: "field", name: "y", static: false, private: false, access: { has: obj => "y" in obj, get: obj => obj.y, set: (obj, value) => { obj.y = value; } } }, _y_initializers, _instanceExtraInitializers); + } +@@ -212,16 +220,16 @@ var _a, _b; + { + class C { + static "x" = (() => { +- let _instanceExtraInitializers_1 = []; ++ let _instanceExtraInitializers = []; + let _y_decorators; + let _y_initializers = []; + return class { ++ static { __setFunctionName(this, "x"); } + static { +- __setFunctionName(this, "x"); + _y_decorators = [dec]; +- __esDecorate(null, null, _y_decorators, { kind: "field", name: "y", static: false, private: false, access: { has: obj => "y" in obj, get: obj => obj.y, set: (obj, value) => { obj.y = value; } } }, _y_initializers, _instanceExtraInitializers_1); ++ __esDecorate(null, null, _y_decorators, { kind: "field", name: "y", static: false, private: false, access: { has: obj => "y" in obj, get: obj => obj.y, set: (obj, value) => { obj.y = value; } } }, _y_initializers, _instanceExtraInitializers); + } +- y = (__runInitializers(this, _instanceExtraInitializers_1), __runInitializers(this, _y_initializers, void 0)); ++ y = (__runInitializers(this, _instanceExtraInitializers), __runInitializers(this, _y_initializers, void 0)); + }; + })(); + } +@@ -229,16 +237,16 @@ var _a, _b; + { + class C { + static 0 = (() => { +- let _instanceExtraInitializers_2 = []; ++ let _instanceExtraInitializers = []; + let _y_decorators; + let _y_initializers = []; + return class { ++ static { __setFunctionName(this, "0"); } + static { +- __setFunctionName(this, "0"); + _y_decorators = [dec]; +- __esDecorate(null, null, _y_decorators, { kind: "field", name: "y", static: false, private: false, access: { has: obj => "y" in obj, get: obj => obj.y, set: (obj, value) => { obj.y = value; } } }, _y_initializers, _instanceExtraInitializers_2); ++ __esDecorate(null, null, _y_decorators, { kind: "field", name: "y", static: false, private: false, access: { has: obj => "y" in obj, get: obj => obj.y, set: (obj, value) => { obj.y = value; } } }, _y_initializers, _instanceExtraInitializers); + } +- y = (__runInitializers(this, _instanceExtraInitializers_2), __runInitializers(this, _y_initializers, void 0)); ++ y = (__runInitializers(this, _instanceExtraInitializers), __runInitializers(this, _y_initializers, void 0)); + }; + })(); + } +@@ -246,16 +254,16 @@ var _a, _b; + { + class C { + static ["x"] = (() => { +- let _instanceExtraInitializers_3 = []; ++ let _instanceExtraInitializers = []; + let _y_decorators; + let _y_initializers = []; + return class { ++ static { __setFunctionName(this, "x"); } + static { +- __setFunctionName(this, "x"); + _y_decorators = [dec]; +- __esDecorate(null, null, _y_decorators, { kind: "field", name: "y", static: false, private: false, access: { has: obj => "y" in obj, get: obj => obj.y, set: (obj, value) => { obj.y = value; } } }, _y_initializers, _instanceExtraInitializers_3); ++ __esDecorate(null, null, _y_decorators, { kind: "field", name: "y", static: false, private: false, access: { has: obj => "y" in obj, get: obj => obj.y, set: (obj, value) => { obj.y = value; } } }, _y_initializers, _instanceExtraInitializers); + } +- y = (__runInitializers(this, _instanceExtraInitializers_3), __runInitializers(this, _y_initializers, void 0)); ++ y = (__runInitializers(this, _instanceExtraInitializers), __runInitializers(this, _y_initializers, void 0)); + }; + })(); + } +@@ -263,16 +271,16 @@ var _a, _b; + { + class C { + static [0] = (() => { +- let _instanceExtraInitializers_4 = []; ++ let _instanceExtraInitializers = []; + let _y_decorators; + let _y_initializers = []; + return class { ++ static { __setFunctionName(this, "0"); } + static { +- __setFunctionName(this, "0"); + _y_decorators = [dec]; +- __esDecorate(null, null, _y_decorators, { kind: "field", name: "y", static: false, private: false, access: { has: obj => "y" in obj, get: obj => obj.y, set: (obj, value) => { obj.y = value; } } }, _y_initializers, _instanceExtraInitializers_4); ++ __esDecorate(null, null, _y_decorators, { kind: "field", name: "y", static: false, private: false, access: { has: obj => "y" in obj, get: obj => obj.y, set: (obj, value) => { obj.y = value; } } }, _y_initializers, _instanceExtraInitializers); + } +- y = (__runInitializers(this, _instanceExtraInitializers_4), __runInitializers(this, _y_initializers, void 0)); ++ y = (__runInitializers(this, _instanceExtraInitializers), __runInitializers(this, _y_initializers, void 0)); + }; + })(); + } +@@ -281,19 +289,20 @@ var _a, _b; + { + class C { + static [_b = __propKey(f())] = (() => { +- let _classDecorators_8 = [dec]; +- let _classDescriptor_8; +- let _classExtraInitializers_8 = []; +- let _classThis_8; ++ let _classDecorators = [dec]; ++ let _classDescriptor; ++ let _classExtraInitializers = []; ++ let _classThis; + var class_9 = class { ++ static { _classThis = this; } ++ static { __setFunctionName(_classThis, _b); } + static { +- __setFunctionName(this, _b); +- __esDecorate(null, _classDescriptor_8 = { value: this }, _classDecorators_8, { kind: "class", name: this.name }, null, _classExtraInitializers_8); +- class_9 = _classThis_8 = _classDescriptor_8.value; +- __runInitializers(_classThis_8, _classExtraInitializers_8); ++ __esDecorate(null, _classDescriptor = { value: _classThis }, _classDecorators, { kind: "class", name: _classThis.name }, null, _classExtraInitializers); ++ class_9 = _classThis = _classDescriptor.value; ++ __runInitializers(_classThis, _classExtraInitializers); + } + }; +- return class_9 = _classThis_8; ++ return class_9 = _classThis; + })(); + } + } +@@ -301,16 +310,16 @@ var _a, _b; + { + class C { + static __proto__ = (() => { +- let _instanceExtraInitializers_5 = []; ++ let _instanceExtraInitializers = []; + let _y_decorators; + let _y_initializers = []; + return class { ++ static { __setFunctionName(this, "__proto__"); } + static { +- __setFunctionName(this, "__proto__"); + _y_decorators = [dec]; +- __esDecorate(null, null, _y_decorators, { kind: "field", name: "y", static: false, private: false, access: { has: obj => "y" in obj, get: obj => obj.y, set: (obj, value) => { obj.y = value; } } }, _y_initializers, _instanceExtraInitializers_5); ++ __esDecorate(null, null, _y_decorators, { kind: "field", name: "y", static: false, private: false, access: { has: obj => "y" in obj, get: obj => obj.y, set: (obj, value) => { obj.y = value; } } }, _y_initializers, _instanceExtraInitializers); + } +- y = (__runInitializers(this, _instanceExtraInitializers_5), __runInitializers(this, _y_initializers, void 0)); ++ y = (__runInitializers(this, _instanceExtraInitializers), __runInitializers(this, _y_initializers, void 0)); + }; + })(); + } +@@ -318,16 +327,16 @@ var _a, _b; + { + class C { + static "__proto__" = (() => { +- let _instanceExtraInitializers_6 = []; ++ let _instanceExtraInitializers = []; + let _y_decorators; + let _y_initializers = []; + return class { ++ static { __setFunctionName(this, "__proto__"); } + static { +- __setFunctionName(this, "__proto__"); + _y_decorators = [dec]; +- __esDecorate(null, null, _y_decorators, { kind: "field", name: "y", static: false, private: false, access: { has: obj => "y" in obj, get: obj => obj.y, set: (obj, value) => { obj.y = value; } } }, _y_initializers, _instanceExtraInitializers_6); ++ __esDecorate(null, null, _y_decorators, { kind: "field", name: "y", static: false, private: false, access: { has: obj => "y" in obj, get: obj => obj.y, set: (obj, value) => { obj.y = value; } } }, _y_initializers, _instanceExtraInitializers); + } +- y = (__runInitializers(this, _instanceExtraInitializers_6), __runInitializers(this, _y_initializers, void 0)); ++ y = (__runInitializers(this, _instanceExtraInitializers), __runInitializers(this, _y_initializers, void 0)); + }; + })(); + } +@@ -345,19 +354,20 @@ var _a, _b; + __runInitializers(this, _staticExtraInitializers); + } + static x = __runInitializers(this, _static_x_initializers, (() => { +- let _classDecorators_9 = [dec]; +- let _classDescriptor_9; +- let _classExtraInitializers_9 = []; +- let _classThis_9; ++ let _classDecorators = [dec]; ++ let _classDescriptor; ++ let _classExtraInitializers = []; ++ let _classThis; + var class_10 = class { ++ static { _classThis = this; } ++ static { __setFunctionName(_classThis, "x"); } + static { +- __setFunctionName(this, "x"); +- __esDecorate(null, _classDescriptor_9 = { value: this }, _classDecorators_9, { kind: "class", name: this.name }, null, _classExtraInitializers_9); +- class_10 = _classThis_9 = _classDescriptor_9.value; +- __runInitializers(_classThis_9, _classExtraInitializers_9); ++ __esDecorate(null, _classDescriptor = { value: _classThis }, _classDecorators, { kind: "class", name: _classThis.name }, null, _classExtraInitializers); ++ class_10 = _classThis = _classDescriptor.value; ++ __runInitializers(_classThis, _classExtraInitializers); + } + }; +- return class_10 = _classThis_9; ++ return class_10 = _classThis; + })()); + }; + })(); +diff --git a/tests/baselines/reference/esDecorators-classExpression-namedEvaluation.11.js b/tests/baselines/reference/esDecorators-classExpression-namedEvaluation.11.js +index 8244d9bb8..87f76af69 100644 +--- a/tests/baselines/reference/esDecorators-classExpression-namedEvaluation.11.js ++++ b/tests/baselines/reference/esDecorators-classExpression-namedEvaluation.11.js +@@ -22,9 +22,10 @@ declare let dec: any; + let _classExtraInitializers = []; + let _classThis; + var class_1 = class { ++ static { _classThis = this; } ++ static { __setFunctionName(_classThis, ""); } + static { +- __setFunctionName(this, ""); +- __esDecorate(null, _classDescriptor = { value: this }, _classDecorators, { kind: "class", name: this.name }, null, _classExtraInitializers); ++ __esDecorate(null, _classDescriptor = { value: _classThis }, _classDecorators, { kind: "class", name: _classThis.name }, null, _classExtraInitializers); + class_1 = _classThis = _classDescriptor.value; + __runInitializers(_classThis, _classExtraInitializers); + } +@@ -45,28 +46,29 @@ declare let dec: any; + })()); + // No NamedEvaluation, class name + ((() => { +- let _classDecorators_1 = [dec]; +- let _classDescriptor_1; +- let _classExtraInitializers_1 = []; +- let _classThis_1; ++ let _classDecorators = [dec]; ++ let _classDescriptor; ++ let _classExtraInitializers = []; ++ let _classThis; + var C = class { ++ static { _classThis = this; } + static { +- __esDecorate(null, _classDescriptor_1 = { value: this }, _classDecorators_1, { kind: "class", name: this.name }, null, _classExtraInitializers_1); +- C = _classThis_1 = _classDescriptor_1.value; +- __runInitializers(_classThis_1, _classExtraInitializers_1); ++ __esDecorate(null, _classDescriptor = { value: _classThis }, _classDecorators, { kind: "class", name: _classThis.name }, null, _classExtraInitializers); ++ C = _classThis = _classDescriptor.value; ++ __runInitializers(_classThis, _classExtraInitializers); + } + }; +- return C = _classThis_1; ++ return C = _classThis; + })()); + ((() => { +- let _instanceExtraInitializers_1 = []; ++ let _instanceExtraInitializers = []; + let _y_decorators; + let _y_initializers = []; + return class C { + static { + _y_decorators = [dec]; +- __esDecorate(null, null, _y_decorators, { kind: "field", name: "y", static: false, private: false, access: { has: obj => "y" in obj, get: obj => obj.y, set: (obj, value) => { obj.y = value; } } }, _y_initializers, _instanceExtraInitializers_1); ++ __esDecorate(null, null, _y_decorators, { kind: "field", name: "y", static: false, private: false, access: { has: obj => "y" in obj, get: obj => obj.y, set: (obj, value) => { obj.y = value; } } }, _y_initializers, _instanceExtraInitializers); + } +- y = (__runInitializers(this, _instanceExtraInitializers_1), __runInitializers(this, _y_initializers, void 0)); ++ y = (__runInitializers(this, _instanceExtraInitializers), __runInitializers(this, _y_initializers, void 0)); + }; + })()); +diff --git a/tests/baselines/reference/esDecorators-classExpression-namedEvaluation.2.js b/tests/baselines/reference/esDecorators-classExpression-namedEvaluation.2.js +index 3007f132e..c698897e3 100644 +--- a/tests/baselines/reference/esDecorators-classExpression-namedEvaluation.2.js ++++ b/tests/baselines/reference/esDecorators-classExpression-namedEvaluation.2.js +@@ -44,9 +44,10 @@ let x, f; + let _classExtraInitializers = []; + let _classThis; + var class_1 = class { ++ static { _classThis = this; } ++ static { __setFunctionName(_classThis, "x"); } + static { +- __setFunctionName(this, "x"); +- __esDecorate(null, _classDescriptor = { value: this }, _classDecorators, { kind: "class", name: this.name }, null, _classExtraInitializers); ++ __esDecorate(null, _classDescriptor = { value: _classThis }, _classDecorators, { kind: "class", name: _classThis.name }, null, _classExtraInitializers); + class_1 = _classThis = _classDescriptor.value; + __runInitializers(_classThis, _classExtraInitializers); + } +@@ -58,8 +59,8 @@ let x, f; + let _y_decorators; + let _y_initializers = []; + return class { ++ static { __setFunctionName(this, "x"); } + static { +- __setFunctionName(this, "x"); + _y_decorators = [dec]; + __esDecorate(null, null, _y_decorators, { kind: "field", name: "y", static: false, private: false, access: { has: obj => "y" in obj, get: obj => obj.y, set: (obj, value) => { obj.y = value; } } }, _y_initializers, _instanceExtraInitializers); + } +@@ -67,189 +68,197 @@ let x, f; + }; + })() }); + ({ "x": (() => { +- let _classDecorators_1 = [dec]; +- let _classDescriptor_1; +- let _classExtraInitializers_1 = []; +- let _classThis_1; ++ let _classDecorators = [dec]; ++ let _classDescriptor; ++ let _classExtraInitializers = []; ++ let _classThis; + var class_2 = class { ++ static { _classThis = this; } ++ static { __setFunctionName(_classThis, "x"); } + static { +- __setFunctionName(this, "x"); +- __esDecorate(null, _classDescriptor_1 = { value: this }, _classDecorators_1, { kind: "class", name: this.name }, null, _classExtraInitializers_1); +- class_2 = _classThis_1 = _classDescriptor_1.value; +- __runInitializers(_classThis_1, _classExtraInitializers_1); ++ __esDecorate(null, _classDescriptor = { value: _classThis }, _classDecorators, { kind: "class", name: _classThis.name }, null, _classExtraInitializers); ++ class_2 = _classThis = _classDescriptor.value; ++ __runInitializers(_classThis, _classExtraInitializers); + } + }; +- return class_2 = _classThis_1; ++ return class_2 = _classThis; + })() }); + ({ "x": (() => { +- let _instanceExtraInitializers_1 = []; ++ let _instanceExtraInitializers = []; + let _y_decorators; + let _y_initializers = []; + return class { ++ static { __setFunctionName(this, "x"); } + static { +- __setFunctionName(this, "x"); + _y_decorators = [dec]; +- __esDecorate(null, null, _y_decorators, { kind: "field", name: "y", static: false, private: false, access: { has: obj => "y" in obj, get: obj => obj.y, set: (obj, value) => { obj.y = value; } } }, _y_initializers, _instanceExtraInitializers_1); ++ __esDecorate(null, null, _y_decorators, { kind: "field", name: "y", static: false, private: false, access: { has: obj => "y" in obj, get: obj => obj.y, set: (obj, value) => { obj.y = value; } } }, _y_initializers, _instanceExtraInitializers); + } +- y = (__runInitializers(this, _instanceExtraInitializers_1), __runInitializers(this, _y_initializers, void 0)); ++ y = (__runInitializers(this, _instanceExtraInitializers), __runInitializers(this, _y_initializers, void 0)); + }; + })() }); + ({ 0: (() => { +- let _classDecorators_2 = [dec]; +- let _classDescriptor_2; +- let _classExtraInitializers_2 = []; +- let _classThis_2; ++ let _classDecorators = [dec]; ++ let _classDescriptor; ++ let _classExtraInitializers = []; ++ let _classThis; + var class_3 = class { ++ static { _classThis = this; } ++ static { __setFunctionName(_classThis, "0"); } + static { +- __setFunctionName(this, "0"); +- __esDecorate(null, _classDescriptor_2 = { value: this }, _classDecorators_2, { kind: "class", name: this.name }, null, _classExtraInitializers_2); +- class_3 = _classThis_2 = _classDescriptor_2.value; +- __runInitializers(_classThis_2, _classExtraInitializers_2); ++ __esDecorate(null, _classDescriptor = { value: _classThis }, _classDecorators, { kind: "class", name: _classThis.name }, null, _classExtraInitializers); ++ class_3 = _classThis = _classDescriptor.value; ++ __runInitializers(_classThis, _classExtraInitializers); + } + }; +- return class_3 = _classThis_2; ++ return class_3 = _classThis; + })() }); + ({ 0: (() => { +- let _instanceExtraInitializers_2 = []; ++ let _instanceExtraInitializers = []; + let _y_decorators; + let _y_initializers = []; + return class { ++ static { __setFunctionName(this, "0"); } + static { +- __setFunctionName(this, "0"); + _y_decorators = [dec]; +- __esDecorate(null, null, _y_decorators, { kind: "field", name: "y", static: false, private: false, access: { has: obj => "y" in obj, get: obj => obj.y, set: (obj, value) => { obj.y = value; } } }, _y_initializers, _instanceExtraInitializers_2); ++ __esDecorate(null, null, _y_decorators, { kind: "field", name: "y", static: false, private: false, access: { has: obj => "y" in obj, get: obj => obj.y, set: (obj, value) => { obj.y = value; } } }, _y_initializers, _instanceExtraInitializers); + } +- y = (__runInitializers(this, _instanceExtraInitializers_2), __runInitializers(this, _y_initializers, void 0)); ++ y = (__runInitializers(this, _instanceExtraInitializers), __runInitializers(this, _y_initializers, void 0)); + }; + })() }); + ({ ["x"]: (() => { +- let _classDecorators_3 = [dec]; +- let _classDescriptor_3; +- let _classExtraInitializers_3 = []; +- let _classThis_3; ++ let _classDecorators = [dec]; ++ let _classDescriptor; ++ let _classExtraInitializers = []; ++ let _classThis; + var class_4 = class { ++ static { _classThis = this; } ++ static { __setFunctionName(_classThis, "x"); } + static { +- __setFunctionName(this, "x"); +- __esDecorate(null, _classDescriptor_3 = { value: this }, _classDecorators_3, { kind: "class", name: this.name }, null, _classExtraInitializers_3); +- class_4 = _classThis_3 = _classDescriptor_3.value; +- __runInitializers(_classThis_3, _classExtraInitializers_3); ++ __esDecorate(null, _classDescriptor = { value: _classThis }, _classDecorators, { kind: "class", name: _classThis.name }, null, _classExtraInitializers); ++ class_4 = _classThis = _classDescriptor.value; ++ __runInitializers(_classThis, _classExtraInitializers); + } + }; +- return class_4 = _classThis_3; ++ return class_4 = _classThis; + })() }); + ({ ["x"]: (() => { +- let _instanceExtraInitializers_3 = []; ++ let _instanceExtraInitializers = []; + let _y_decorators; + let _y_initializers = []; + return class { ++ static { __setFunctionName(this, "x"); } + static { +- __setFunctionName(this, "x"); + _y_decorators = [dec]; +- __esDecorate(null, null, _y_decorators, { kind: "field", name: "y", static: false, private: false, access: { has: obj => "y" in obj, get: obj => obj.y, set: (obj, value) => { obj.y = value; } } }, _y_initializers, _instanceExtraInitializers_3); ++ __esDecorate(null, null, _y_decorators, { kind: "field", name: "y", static: false, private: false, access: { has: obj => "y" in obj, get: obj => obj.y, set: (obj, value) => { obj.y = value; } } }, _y_initializers, _instanceExtraInitializers); + } +- y = (__runInitializers(this, _instanceExtraInitializers_3), __runInitializers(this, _y_initializers, void 0)); ++ y = (__runInitializers(this, _instanceExtraInitializers), __runInitializers(this, _y_initializers, void 0)); + }; + })() }); + ({ [0]: (() => { +- let _classDecorators_4 = [dec]; +- let _classDescriptor_4; +- let _classExtraInitializers_4 = []; +- let _classThis_4; ++ let _classDecorators = [dec]; ++ let _classDescriptor; ++ let _classExtraInitializers = []; ++ let _classThis; + var class_5 = class { ++ static { _classThis = this; } ++ static { __setFunctionName(_classThis, "0"); } + static { +- __setFunctionName(this, "0"); +- __esDecorate(null, _classDescriptor_4 = { value: this }, _classDecorators_4, { kind: "class", name: this.name }, null, _classExtraInitializers_4); +- class_5 = _classThis_4 = _classDescriptor_4.value; +- __runInitializers(_classThis_4, _classExtraInitializers_4); ++ __esDecorate(null, _classDescriptor = { value: _classThis }, _classDecorators, { kind: "class", name: _classThis.name }, null, _classExtraInitializers); ++ class_5 = _classThis = _classDescriptor.value; ++ __runInitializers(_classThis, _classExtraInitializers); + } + }; +- return class_5 = _classThis_4; ++ return class_5 = _classThis; + })() }); + ({ [0]: (() => { +- let _instanceExtraInitializers_4 = []; ++ let _instanceExtraInitializers = []; + let _y_decorators; + let _y_initializers = []; + return class { ++ static { __setFunctionName(this, "0"); } + static { +- __setFunctionName(this, "0"); + _y_decorators = [dec]; +- __esDecorate(null, null, _y_decorators, { kind: "field", name: "y", static: false, private: false, access: { has: obj => "y" in obj, get: obj => obj.y, set: (obj, value) => { obj.y = value; } } }, _y_initializers, _instanceExtraInitializers_4); ++ __esDecorate(null, null, _y_decorators, { kind: "field", name: "y", static: false, private: false, access: { has: obj => "y" in obj, get: obj => obj.y, set: (obj, value) => { obj.y = value; } } }, _y_initializers, _instanceExtraInitializers); + } +- y = (__runInitializers(this, _instanceExtraInitializers_4), __runInitializers(this, _y_initializers, void 0)); ++ y = (__runInitializers(this, _instanceExtraInitializers), __runInitializers(this, _y_initializers, void 0)); + }; + })() }); + ({ [_a = __propKey(f())]: (() => { +- let _classDecorators_5 = [dec]; +- let _classDescriptor_5; +- let _classExtraInitializers_5 = []; +- let _classThis_5; ++ let _classDecorators = [dec]; ++ let _classDescriptor; ++ let _classExtraInitializers = []; ++ let _classThis; + var class_6 = class { ++ static { _classThis = this; } ++ static { __setFunctionName(_classThis, _a); } + static { +- __setFunctionName(this, _a); +- __esDecorate(null, _classDescriptor_5 = { value: this }, _classDecorators_5, { kind: "class", name: this.name }, null, _classExtraInitializers_5); +- class_6 = _classThis_5 = _classDescriptor_5.value; +- __runInitializers(_classThis_5, _classExtraInitializers_5); ++ __esDecorate(null, _classDescriptor = { value: _classThis }, _classDecorators, { kind: "class", name: _classThis.name }, null, _classExtraInitializers); ++ class_6 = _classThis = _classDescriptor.value; ++ __runInitializers(_classThis, _classExtraInitializers); + } + }; +- return class_6 = _classThis_5; ++ return class_6 = _classThis; + })() }); + ({ [_b = __propKey(f())]: (() => { +- let _instanceExtraInitializers_5 = []; ++ let _instanceExtraInitializers = []; + let _y_decorators; + let _y_initializers = []; + return class { ++ static { __setFunctionName(this, _b); } + static { +- __setFunctionName(this, _b); + _y_decorators = [dec]; +- __esDecorate(null, null, _y_decorators, { kind: "field", name: "y", static: false, private: false, access: { has: obj => "y" in obj, get: obj => obj.y, set: (obj, value) => { obj.y = value; } } }, _y_initializers, _instanceExtraInitializers_5); ++ __esDecorate(null, null, _y_decorators, { kind: "field", name: "y", static: false, private: false, access: { has: obj => "y" in obj, get: obj => obj.y, set: (obj, value) => { obj.y = value; } } }, _y_initializers, _instanceExtraInitializers); + } +- y = (__runInitializers(this, _instanceExtraInitializers_5), __runInitializers(this, _y_initializers, void 0)); ++ y = (__runInitializers(this, _instanceExtraInitializers), __runInitializers(this, _y_initializers, void 0)); + }; + })() }); + // __proto__ setters do not perform NamedEvaluation + ({ __proto__: (() => { +- let _classDecorators_6 = [dec]; +- let _classDescriptor_6; +- let _classExtraInitializers_6 = []; +- let _classThis_6; ++ let _classDecorators = [dec]; ++ let _classDescriptor; ++ let _classExtraInitializers = []; ++ let _classThis; + var class_7 = class { ++ static { _classThis = this; } ++ static { __setFunctionName(_classThis, ""); } + static { +- __setFunctionName(this, ""); +- __esDecorate(null, _classDescriptor_6 = { value: this }, _classDecorators_6, { kind: "class", name: this.name }, null, _classExtraInitializers_6); +- class_7 = _classThis_6 = _classDescriptor_6.value; +- __runInitializers(_classThis_6, _classExtraInitializers_6); ++ __esDecorate(null, _classDescriptor = { value: _classThis }, _classDecorators, { kind: "class", name: _classThis.name }, null, _classExtraInitializers); ++ class_7 = _classThis = _classDescriptor.value; ++ __runInitializers(_classThis, _classExtraInitializers); + } + }; +- return class_7 = _classThis_6; ++ return class_7 = _classThis; + })() }); + ({ "__proto__": (() => { +- let _classDecorators_7 = [dec]; +- let _classDescriptor_7; +- let _classExtraInitializers_7 = []; +- let _classThis_7; ++ let _classDecorators = [dec]; ++ let _classDescriptor; ++ let _classExtraInitializers = []; ++ let _classThis; + var class_8 = class { ++ static { _classThis = this; } ++ static { __setFunctionName(_classThis, ""); } + static { +- __setFunctionName(this, ""); +- __esDecorate(null, _classDescriptor_7 = { value: this }, _classDecorators_7, { kind: "class", name: this.name }, null, _classExtraInitializers_7); +- class_8 = _classThis_7 = _classDescriptor_7.value; +- __runInitializers(_classThis_7, _classExtraInitializers_7); ++ __esDecorate(null, _classDescriptor = { value: _classThis }, _classDecorators, { kind: "class", name: _classThis.name }, null, _classExtraInitializers); ++ class_8 = _classThis = _classDescriptor.value; ++ __runInitializers(_classThis, _classExtraInitializers); + } + }; +- return class_8 = _classThis_7; ++ return class_8 = _classThis; + })() }); + // "__proto__" in a computed property name *does* perform NamedEvaluation + ({ ["__proto__"]: (() => { +- let _classDecorators_8 = [dec]; +- let _classDescriptor_8; +- let _classExtraInitializers_8 = []; +- let _classThis_8; ++ let _classDecorators = [dec]; ++ let _classDescriptor; ++ let _classExtraInitializers = []; ++ let _classThis; + var class_9 = class { ++ static { _classThis = this; } ++ static { __setFunctionName(_classThis, "__proto__"); } + static { +- __setFunctionName(this, "__proto__"); +- __esDecorate(null, _classDescriptor_8 = { value: this }, _classDecorators_8, { kind: "class", name: this.name }, null, _classExtraInitializers_8); +- class_9 = _classThis_8 = _classDescriptor_8.value; +- __runInitializers(_classThis_8, _classExtraInitializers_8); ++ __esDecorate(null, _classDescriptor = { value: _classThis }, _classDecorators, { kind: "class", name: _classThis.name }, null, _classExtraInitializers); ++ class_9 = _classThis = _classDescriptor.value; ++ __runInitializers(_classThis, _classExtraInitializers); + } + }; +- return class_9 = _classThis_8; ++ return class_9 = _classThis; + })() }); +diff --git a/tests/baselines/reference/esDecorators-classExpression-namedEvaluation.3.js b/tests/baselines/reference/esDecorators-classExpression-namedEvaluation.3.js +index 35ae75922..43402ed43 100644 +--- a/tests/baselines/reference/esDecorators-classExpression-namedEvaluation.3.js ++++ b/tests/baselines/reference/esDecorators-classExpression-namedEvaluation.3.js +@@ -29,9 +29,10 @@ declare let dec: any; + let _classExtraInitializers = []; + let _classThis; + var class_1 = class { ++ static { _classThis = this; } ++ static { __setFunctionName(_classThis, "x"); } + static { +- __setFunctionName(this, "x"); +- __esDecorate(null, _classDescriptor = { value: this }, _classDecorators, { kind: "class", name: this.name }, null, _classExtraInitializers); ++ __esDecorate(null, _classDescriptor = { value: _classThis }, _classDecorators, { kind: "class", name: _classThis.name }, null, _classExtraInitializers); + class_1 = _classThis = _classDescriptor.value; + __runInitializers(_classThis, _classExtraInitializers); + } +@@ -45,8 +46,8 @@ declare let dec: any; + let _y_decorators; + let _y_initializers = []; + return class { ++ static { __setFunctionName(this, "x"); } + static { +- __setFunctionName(this, "x"); + _y_decorators = [dec]; + __esDecorate(null, null, _y_decorators, { kind: "field", name: "y", static: false, private: false, access: { has: obj => "y" in obj, get: obj => obj.y, set: (obj, value) => { obj.y = value; } } }, _y_initializers, _instanceExtraInitializers); + } +@@ -56,33 +57,34 @@ declare let dec: any; + } + { + const x = (() => { +- let _classDecorators_1 = [dec]; +- let _classDescriptor_1; +- let _classExtraInitializers_1 = []; +- let _classThis_1; ++ let _classDecorators = [dec]; ++ let _classDescriptor; ++ let _classExtraInitializers = []; ++ let _classThis; + var class_2 = class { ++ static { _classThis = this; } ++ static { __setFunctionName(_classThis, "x"); } + static { +- __setFunctionName(this, "x"); +- __esDecorate(null, _classDescriptor_1 = { value: this }, _classDecorators_1, { kind: "class", name: this.name }, null, _classExtraInitializers_1); +- class_2 = _classThis_1 = _classDescriptor_1.value; +- __runInitializers(_classThis_1, _classExtraInitializers_1); ++ __esDecorate(null, _classDescriptor = { value: _classThis }, _classDecorators, { kind: "class", name: _classThis.name }, null, _classExtraInitializers); ++ class_2 = _classThis = _classDescriptor.value; ++ __runInitializers(_classThis, _classExtraInitializers); + } + }; +- return class_2 = _classThis_1; ++ return class_2 = _classThis; + })(); + } + { + const x = (() => { +- let _instanceExtraInitializers_1 = []; ++ let _instanceExtraInitializers = []; + let _y_decorators; + let _y_initializers = []; + return class { ++ static { __setFunctionName(this, "x"); } + static { +- __setFunctionName(this, "x"); + _y_decorators = [dec]; +- __esDecorate(null, null, _y_decorators, { kind: "field", name: "y", static: false, private: false, access: { has: obj => "y" in obj, get: obj => obj.y, set: (obj, value) => { obj.y = value; } } }, _y_initializers, _instanceExtraInitializers_1); ++ __esDecorate(null, null, _y_decorators, { kind: "field", name: "y", static: false, private: false, access: { has: obj => "y" in obj, get: obj => obj.y, set: (obj, value) => { obj.y = value; } } }, _y_initializers, _instanceExtraInitializers); + } +- y = (__runInitializers(this, _instanceExtraInitializers_1), __runInitializers(this, _y_initializers, void 0)); ++ y = (__runInitializers(this, _instanceExtraInitializers), __runInitializers(this, _y_initializers, void 0)); + }; + })(); + } +@@ -90,33 +92,34 @@ declare let dec: any; + // VariableDeclaration : BindingIdentifier Initializer + { + var x2 = (() => { +- let _classDecorators_2 = [dec]; +- let _classDescriptor_2; +- let _classExtraInitializers_2 = []; +- let _classThis_2; ++ let _classDecorators = [dec]; ++ let _classDescriptor; ++ let _classExtraInitializers = []; ++ let _classThis; + var class_3 = class { ++ static { _classThis = this; } ++ static { __setFunctionName(_classThis, "x2"); } + static { +- __setFunctionName(this, "x2"); +- __esDecorate(null, _classDescriptor_2 = { value: this }, _classDecorators_2, { kind: "class", name: this.name }, null, _classExtraInitializers_2); +- class_3 = _classThis_2 = _classDescriptor_2.value; +- __runInitializers(_classThis_2, _classExtraInitializers_2); ++ __esDecorate(null, _classDescriptor = { value: _classThis }, _classDecorators, { kind: "class", name: _classThis.name }, null, _classExtraInitializers); ++ class_3 = _classThis = _classDescriptor.value; ++ __runInitializers(_classThis, _classExtraInitializers); + } + }; +- return class_3 = _classThis_2; ++ return class_3 = _classThis; + })(); + } + { + var x1 = (() => { +- let _instanceExtraInitializers_2 = []; ++ let _instanceExtraInitializers = []; + let _y_decorators; + let _y_initializers = []; + return class { ++ static { __setFunctionName(this, "x1"); } + static { +- __setFunctionName(this, "x1"); + _y_decorators = [dec]; +- __esDecorate(null, null, _y_decorators, { kind: "field", name: "y", static: false, private: false, access: { has: obj => "y" in obj, get: obj => obj.y, set: (obj, value) => { obj.y = value; } } }, _y_initializers, _instanceExtraInitializers_2); ++ __esDecorate(null, null, _y_decorators, { kind: "field", name: "y", static: false, private: false, access: { has: obj => "y" in obj, get: obj => obj.y, set: (obj, value) => { obj.y = value; } } }, _y_initializers, _instanceExtraInitializers); + } +- y = (__runInitializers(this, _instanceExtraInitializers_2), __runInitializers(this, _y_initializers, void 0)); ++ y = (__runInitializers(this, _instanceExtraInitializers), __runInitializers(this, _y_initializers, void 0)); + }; + })(); + } +diff --git a/tests/baselines/reference/esDecorators-classExpression-namedEvaluation.4.js b/tests/baselines/reference/esDecorators-classExpression-namedEvaluation.4.js +index f55622075..17204f782 100644 +--- a/tests/baselines/reference/esDecorators-classExpression-namedEvaluation.4.js ++++ b/tests/baselines/reference/esDecorators-classExpression-namedEvaluation.4.js +@@ -30,9 +30,10 @@ declare let dec: any, obj: any; + let _classExtraInitializers = []; + let _classThis; + var class_1 = class { ++ static { _classThis = this; } ++ static { __setFunctionName(_classThis, "x"); } + static { +- __setFunctionName(this, "x"); +- __esDecorate(null, _classDescriptor = { value: this }, _classDecorators, { kind: "class", name: this.name }, null, _classExtraInitializers); ++ __esDecorate(null, _classDescriptor = { value: _classThis }, _classDecorators, { kind: "class", name: _classThis.name }, null, _classExtraInitializers); + class_1 = _classThis = _classDescriptor.value; + __runInitializers(_classThis, _classExtraInitializers); + } +@@ -46,8 +47,8 @@ declare let dec: any, obj: any; + let _y_decorators; + let _y_initializers = []; + return class { ++ static { __setFunctionName(this, "x"); } + static { +- __setFunctionName(this, "x"); + _y_decorators = [dec]; + __esDecorate(null, null, _y_decorators, { kind: "field", name: "y", static: false, private: false, access: { has: obj => "y" in obj, get: obj => obj.y, set: (obj, value) => { obj.y = value; } } }, _y_initializers, _instanceExtraInitializers); + } +@@ -59,65 +60,67 @@ declare let dec: any, obj: any; + // SingleNameBinding : BindingIdentifier Initializer? + { + const { x = (() => { +- let _classDecorators_1 = [dec]; +- let _classDescriptor_1; +- let _classExtraInitializers_1 = []; +- let _classThis_1; ++ let _classDecorators = [dec]; ++ let _classDescriptor; ++ let _classExtraInitializers = []; ++ let _classThis; + var class_2 = class { ++ static { _classThis = this; } ++ static { __setFunctionName(_classThis, "x"); } + static { +- __setFunctionName(this, "x"); +- __esDecorate(null, _classDescriptor_1 = { value: this }, _classDecorators_1, { kind: "class", name: this.name }, null, _classExtraInitializers_1); +- class_2 = _classThis_1 = _classDescriptor_1.value; +- __runInitializers(_classThis_1, _classExtraInitializers_1); ++ __esDecorate(null, _classDescriptor = { value: _classThis }, _classDecorators, { kind: "class", name: _classThis.name }, null, _classExtraInitializers); ++ class_2 = _classThis = _classDescriptor.value; ++ __runInitializers(_classThis, _classExtraInitializers); + } + }; +- return class_2 = _classThis_1; ++ return class_2 = _classThis; + })() } = obj; + } + { + const { x = (() => { +- let _instanceExtraInitializers_1 = []; ++ let _instanceExtraInitializers = []; + let _y_decorators; + let _y_initializers = []; + return class { ++ static { __setFunctionName(this, "x"); } + static { +- __setFunctionName(this, "x"); + _y_decorators = [dec]; +- __esDecorate(null, null, _y_decorators, { kind: "field", name: "y", static: false, private: false, access: { has: obj => "y" in obj, get: obj => obj.y, set: (obj, value) => { obj.y = value; } } }, _y_initializers, _instanceExtraInitializers_1); ++ __esDecorate(null, null, _y_decorators, { kind: "field", name: "y", static: false, private: false, access: { has: obj => "y" in obj, get: obj => obj.y, set: (obj, value) => { obj.y = value; } } }, _y_initializers, _instanceExtraInitializers); + } +- y = (__runInitializers(this, _instanceExtraInitializers_1), __runInitializers(this, _y_initializers, void 0)); ++ y = (__runInitializers(this, _instanceExtraInitializers), __runInitializers(this, _y_initializers, void 0)); + }; + })() } = obj; + } + { + const { y: x = (() => { +- let _classDecorators_2 = [dec]; +- let _classDescriptor_2; +- let _classExtraInitializers_2 = []; +- let _classThis_2; ++ let _classDecorators = [dec]; ++ let _classDescriptor; ++ let _classExtraInitializers = []; ++ let _classThis; + var class_3 = class { ++ static { _classThis = this; } ++ static { __setFunctionName(_classThis, "x"); } + static { +- __setFunctionName(this, "x"); +- __esDecorate(null, _classDescriptor_2 = { value: this }, _classDecorators_2, { kind: "class", name: this.name }, null, _classExtraInitializers_2); +- class_3 = _classThis_2 = _classDescriptor_2.value; +- __runInitializers(_classThis_2, _classExtraInitializers_2); ++ __esDecorate(null, _classDescriptor = { value: _classThis }, _classDecorators, { kind: "class", name: _classThis.name }, null, _classExtraInitializers); ++ class_3 = _classThis = _classDescriptor.value; ++ __runInitializers(_classThis, _classExtraInitializers); + } + }; +- return class_3 = _classThis_2; ++ return class_3 = _classThis; + })() } = obj; + } + { + const { y: x = (() => { +- let _instanceExtraInitializers_2 = []; ++ let _instanceExtraInitializers = []; + let _y_decorators; + let _y_initializers = []; + return class { ++ static { __setFunctionName(this, "x"); } + static { +- __setFunctionName(this, "x"); + _y_decorators = [dec]; +- __esDecorate(null, null, _y_decorators, { kind: "field", name: "y", static: false, private: false, access: { has: obj => "y" in obj, get: obj => obj.y, set: (obj, value) => { obj.y = value; } } }, _y_initializers, _instanceExtraInitializers_2); ++ __esDecorate(null, null, _y_decorators, { kind: "field", name: "y", static: false, private: false, access: { has: obj => "y" in obj, get: obj => obj.y, set: (obj, value) => { obj.y = value; } } }, _y_initializers, _instanceExtraInitializers); + } +- y = (__runInitializers(this, _instanceExtraInitializers_2), __runInitializers(this, _y_initializers, void 0)); ++ y = (__runInitializers(this, _instanceExtraInitializers), __runInitializers(this, _y_initializers, void 0)); + }; + })() } = obj; + } +diff --git a/tests/baselines/reference/esDecorators-classExpression-namedEvaluation.5.js b/tests/baselines/reference/esDecorators-classExpression-namedEvaluation.5.js +index b36091aeb..e024e3a08 100644 +--- a/tests/baselines/reference/esDecorators-classExpression-namedEvaluation.5.js ++++ b/tests/baselines/reference/esDecorators-classExpression-namedEvaluation.5.js +@@ -19,9 +19,10 @@ declare let dec: any, obj: any, x: any; + let _classExtraInitializers = []; + let _classThis; + var class_1 = class { ++ static { _classThis = this; } ++ static { __setFunctionName(_classThis, "x"); } + static { +- __setFunctionName(this, "x"); +- __esDecorate(null, _classDescriptor = { value: this }, _classDecorators, { kind: "class", name: this.name }, null, _classExtraInitializers); ++ __esDecorate(null, _classDescriptor = { value: _classThis }, _classDecorators, { kind: "class", name: _classThis.name }, null, _classExtraInitializers); + class_1 = _classThis = _classDescriptor.value; + __runInitializers(_classThis, _classExtraInitializers); + } +@@ -33,8 +34,8 @@ declare let dec: any, obj: any, x: any; + let _y_decorators; + let _y_initializers = []; + return class { ++ static { __setFunctionName(this, "x"); } + static { +- __setFunctionName(this, "x"); + _y_decorators = [dec]; + __esDecorate(null, null, _y_decorators, { kind: "field", name: "y", static: false, private: false, access: { has: obj => "y" in obj, get: obj => obj.y, set: (obj, value) => { obj.y = value; } } }, _y_initializers, _instanceExtraInitializers); + } +diff --git a/tests/baselines/reference/esDecorators-classExpression-namedEvaluation.6.js b/tests/baselines/reference/esDecorators-classExpression-namedEvaluation.6.js +index c345b7bad..e5f81d339 100644 +--- a/tests/baselines/reference/esDecorators-classExpression-namedEvaluation.6.js ++++ b/tests/baselines/reference/esDecorators-classExpression-namedEvaluation.6.js +@@ -19,9 +19,10 @@ declare let dec: any, obj: any, x: any; + let _classExtraInitializers = []; + let _classThis; + var class_1 = class { ++ static { _classThis = this; } ++ static { __setFunctionName(_classThis, "x"); } + static { +- __setFunctionName(this, "x"); +- __esDecorate(null, _classDescriptor = { value: this }, _classDecorators, { kind: "class", name: this.name }, null, _classExtraInitializers); ++ __esDecorate(null, _classDescriptor = { value: _classThis }, _classDecorators, { kind: "class", name: _classThis.name }, null, _classExtraInitializers); + class_1 = _classThis = _classDescriptor.value; + __runInitializers(_classThis, _classExtraInitializers); + } +@@ -33,8 +34,8 @@ declare let dec: any, obj: any, x: any; + let _y_decorators; + let _y_initializers = []; + return class { ++ static { __setFunctionName(this, "x"); } + static { +- __setFunctionName(this, "x"); + _y_decorators = [dec]; + __esDecorate(null, null, _y_decorators, { kind: "field", name: "y", static: false, private: false, access: { has: obj => "y" in obj, get: obj => obj.y, set: (obj, value) => { obj.y = value; } } }, _y_initializers, _instanceExtraInitializers); + } +diff --git a/tests/baselines/reference/esDecorators-classExpression-namedEvaluation.7.js b/tests/baselines/reference/esDecorators-classExpression-namedEvaluation.7.js +index de766d9a1..86f3a7296 100644 +--- a/tests/baselines/reference/esDecorators-classExpression-namedEvaluation.7.js ++++ b/tests/baselines/reference/esDecorators-classExpression-namedEvaluation.7.js +@@ -19,9 +19,10 @@ declare let dec: any, obj: any, x: any; + let _classExtraInitializers = []; + let _classThis; + var class_1 = class { ++ static { _classThis = this; } ++ static { __setFunctionName(_classThis, "x"); } + static { +- __setFunctionName(this, "x"); +- __esDecorate(null, _classDescriptor = { value: this }, _classDecorators, { kind: "class", name: this.name }, null, _classExtraInitializers); ++ __esDecorate(null, _classDescriptor = { value: _classThis }, _classDecorators, { kind: "class", name: _classThis.name }, null, _classExtraInitializers); + class_1 = _classThis = _classDescriptor.value; + __runInitializers(_classThis, _classExtraInitializers); + } +@@ -33,8 +34,8 @@ declare let dec: any, obj: any, x: any; + let _y_decorators; + let _y_initializers = []; + return class { ++ static { __setFunctionName(this, "x"); } + static { +- __setFunctionName(this, "x"); + _y_decorators = [dec]; + __esDecorate(null, null, _y_decorators, { kind: "field", name: "y", static: false, private: false, access: { has: obj => "y" in obj, get: obj => obj.y, set: (obj, value) => { obj.y = value; } } }, _y_initializers, _instanceExtraInitializers); + } +diff --git a/tests/baselines/reference/esDecorators-classExpression-namedEvaluation.8.js b/tests/baselines/reference/esDecorators-classExpression-namedEvaluation.8.js +index 8f2a6b536..6a4035312 100644 +--- a/tests/baselines/reference/esDecorators-classExpression-namedEvaluation.8.js ++++ b/tests/baselines/reference/esDecorators-classExpression-namedEvaluation.8.js +@@ -25,9 +25,10 @@ export default ((() => { + let _classExtraInitializers = []; + let _classThis; + var class_1 = class { ++ static { _classThis = this; } ++ static { __setFunctionName(_classThis, "default"); } + static { +- __setFunctionName(this, "default"); +- __esDecorate(null, _classDescriptor = { value: this }, _classDecorators, { kind: "class", name: this.name }, null, _classExtraInitializers); ++ __esDecorate(null, _classDescriptor = { value: _classThis }, _classDecorators, { kind: "class", name: _classThis.name }, null, _classExtraInitializers); + class_1 = _classThis = _classDescriptor.value; + __runInitializers(_classThis, _classExtraInitializers); + } +@@ -42,8 +43,8 @@ export default ((() => { + let _y_decorators; + let _y_initializers = []; + return class { ++ static { __setFunctionName(this, "default"); } + static { +- __setFunctionName(this, "default"); + _y_decorators = [dec]; + __esDecorate(null, null, _y_decorators, { kind: "field", name: "y", static: false, private: false, access: { has: obj => "y" in obj, get: obj => obj.y, set: (obj, value) => { obj.y = value; } } }, _y_initializers, _instanceExtraInitializers); + } +diff --git a/tests/baselines/reference/esDecorators-classExpression-namedEvaluation.9.js b/tests/baselines/reference/esDecorators-classExpression-namedEvaluation.9.js +index 166c60180..30507680e 100644 +--- a/tests/baselines/reference/esDecorators-classExpression-namedEvaluation.9.js ++++ b/tests/baselines/reference/esDecorators-classExpression-namedEvaluation.9.js +@@ -18,9 +18,10 @@ module.exports = (() => { + let _classExtraInitializers = []; + let _classThis; + var class_1 = class { ++ static { _classThis = this; } ++ static { __setFunctionName(_classThis, ""); } + static { +- __setFunctionName(this, ""); +- __esDecorate(null, _classDescriptor = { value: this }, _classDecorators, { kind: "class", name: this.name }, null, _classExtraInitializers); ++ __esDecorate(null, _classDescriptor = { value: _classThis }, _classDecorators, { kind: "class", name: _classThis.name }, null, _classExtraInitializers); + class_1 = _classThis = _classDescriptor.value; + __runInitializers(_classThis, _classExtraInitializers); + } +diff --git a/tests/baselines/reference/esDecorators-emitDecoratorMetadata(target=es2015).js b/tests/baselines/reference/esDecorators-emitDecoratorMetadata(target=es2015).js +index cc1200fad..3f4948ba2 100644 +--- a/tests/baselines/reference/esDecorators-emitDecoratorMetadata(target=es2015).js ++++ b/tests/baselines/reference/esDecorators-emitDecoratorMetadata(target=es2015).js +@@ -98,12 +98,12 @@ let C = (() => { + return C = _classThis; + })(); + ((() => { +- let _classDecorators_1 = [dec]; +- let _classDescriptor_1; +- let _classExtraInitializers_1 = []; +- let _classThis_1; +- let _staticExtraInitializers_1 = []; +- let _instanceExtraInitializers_1 = []; ++ let _classDecorators = [dec]; ++ let _classDescriptor; ++ let _classExtraInitializers = []; ++ let _classThis; ++ let _staticExtraInitializers = []; ++ let _instanceExtraInitializers = []; + let _static_method_decorators; + let _static_set_x_decorators; + let _static_y_decorators; +@@ -112,16 +112,16 @@ let C = (() => { + let _set_x_decorators; + let _y_decorators; + let _y_initializers = []; +- var C = (_classThis_1 = class { ++ var C = (_classThis = class { + constructor(x) { +- this.y = (__runInitializers(this, _instanceExtraInitializers_1), __runInitializers(this, _y_initializers, void 0)); ++ this.y = (__runInitializers(this, _instanceExtraInitializers), __runInitializers(this, _y_initializers, void 0)); + } + method(x) { } + set x(x) { } + static method(x) { } + static set x(x) { } + }, +- __setFunctionName(_classThis_1, "C"), ++ __setFunctionName(_classThis, "C"), + (() => { + _method_decorators = [dec]; + _set_x_decorators = [dec]; +@@ -129,20 +129,20 @@ let C = (() => { + _static_method_decorators = [dec]; + _static_set_x_decorators = [dec]; + _static_y_decorators = [dec]; +- __esDecorate(_classThis_1, null, _static_method_decorators, { kind: "method", name: "method", static: true, private: false, access: { has: obj => "method" in obj, get: obj => obj.method } }, null, _staticExtraInitializers_1); +- __esDecorate(_classThis_1, null, _static_set_x_decorators, { kind: "setter", name: "x", static: true, private: false, access: { has: obj => "x" in obj, set: (obj, value) => { obj.x = value; } } }, null, _staticExtraInitializers_1); +- __esDecorate(_classThis_1, null, _method_decorators, { kind: "method", name: "method", static: false, private: false, access: { has: obj => "method" in obj, get: obj => obj.method } }, null, _instanceExtraInitializers_1); +- __esDecorate(_classThis_1, null, _set_x_decorators, { kind: "setter", name: "x", static: false, private: false, access: { has: obj => "x" in obj, set: (obj, value) => { obj.x = value; } } }, null, _instanceExtraInitializers_1); +- __esDecorate(null, null, _static_y_decorators, { kind: "field", name: "y", static: true, private: false, access: { has: obj => "y" in obj, get: obj => obj.y, set: (obj, value) => { obj.y = value; } } }, _static_y_initializers, _staticExtraInitializers_1); +- __esDecorate(null, null, _y_decorators, { kind: "field", name: "y", static: false, private: false, access: { has: obj => "y" in obj, get: obj => obj.y, set: (obj, value) => { obj.y = value; } } }, _y_initializers, _instanceExtraInitializers_1); +- __esDecorate(null, _classDescriptor_1 = { value: _classThis_1 }, _classDecorators_1, { kind: "class", name: _classThis_1.name }, null, _classExtraInitializers_1); +- C = _classThis_1 = _classDescriptor_1.value; +- __runInitializers(_classThis_1, _staticExtraInitializers_1); ++ __esDecorate(_classThis, null, _static_method_decorators, { kind: "method", name: "method", static: true, private: false, access: { has: obj => "method" in obj, get: obj => obj.method } }, null, _staticExtraInitializers); ++ __esDecorate(_classThis, null, _static_set_x_decorators, { kind: "setter", name: "x", static: true, private: false, access: { has: obj => "x" in obj, set: (obj, value) => { obj.x = value; } } }, null, _staticExtraInitializers); ++ __esDecorate(_classThis, null, _method_decorators, { kind: "method", name: "method", static: false, private: false, access: { has: obj => "method" in obj, get: obj => obj.method } }, null, _instanceExtraInitializers); ++ __esDecorate(_classThis, null, _set_x_decorators, { kind: "setter", name: "x", static: false, private: false, access: { has: obj => "x" in obj, set: (obj, value) => { obj.x = value; } } }, null, _instanceExtraInitializers); ++ __esDecorate(null, null, _static_y_decorators, { kind: "field", name: "y", static: true, private: false, access: { has: obj => "y" in obj, get: obj => obj.y, set: (obj, value) => { obj.y = value; } } }, _static_y_initializers, _staticExtraInitializers); ++ __esDecorate(null, null, _y_decorators, { kind: "field", name: "y", static: false, private: false, access: { has: obj => "y" in obj, get: obj => obj.y, set: (obj, value) => { obj.y = value; } } }, _y_initializers, _instanceExtraInitializers); ++ __esDecorate(null, _classDescriptor = { value: _classThis }, _classDecorators, { kind: "class", name: _classThis.name }, null, _classExtraInitializers); ++ C = _classThis = _classDescriptor.value; ++ __runInitializers(_classThis, _staticExtraInitializers); + })(), +- _classThis_1.y = __runInitializers(_classThis_1, _static_y_initializers, void 0), ++ _classThis.y = __runInitializers(_classThis, _static_y_initializers, void 0), + (() => { +- __runInitializers(_classThis_1, _classExtraInitializers_1); ++ __runInitializers(_classThis, _classExtraInitializers); + })(), +- _classThis_1); +- return C = _classThis_1; ++ _classThis); ++ return C = _classThis; + })()); +diff --git a/tests/baselines/reference/esDecorators-emitDecoratorMetadata(target=es2022).js b/tests/baselines/reference/esDecorators-emitDecoratorMetadata(target=es2022).js +index fec2864b5..5cb50c2cb 100644 +--- a/tests/baselines/reference/esDecorators-emitDecoratorMetadata(target=es2022).js ++++ b/tests/baselines/reference/esDecorators-emitDecoratorMetadata(target=es2022).js +@@ -65,6 +65,7 @@ let C = (() => { + let _y_decorators; + let _y_initializers = []; + var C = class { ++ static { _classThis = this; } + static { + _method_decorators = [dec]; + _set_x_decorators = [dec]; +@@ -78,7 +79,7 @@ let C = (() => { + __esDecorate(this, null, _set_x_decorators, { kind: "setter", name: "x", static: false, private: false, access: { has: obj => "x" in obj, set: (obj, value) => { obj.x = value; } } }, null, _instanceExtraInitializers); + __esDecorate(null, null, _static_y_decorators, { kind: "field", name: "y", static: true, private: false, access: { has: obj => "y" in obj, get: obj => obj.y, set: (obj, value) => { obj.y = value; } } }, _static_y_initializers, _staticExtraInitializers); + __esDecorate(null, null, _y_decorators, { kind: "field", name: "y", static: false, private: false, access: { has: obj => "y" in obj, get: obj => obj.y, set: (obj, value) => { obj.y = value; } } }, _y_initializers, _instanceExtraInitializers); +- __esDecorate(null, _classDescriptor = { value: this }, _classDecorators, { kind: "class", name: this.name }, null, _classExtraInitializers); ++ __esDecorate(null, _classDescriptor = { value: _classThis }, _classDecorators, { kind: "class", name: _classThis.name }, null, _classExtraInitializers); + C = _classThis = _classDescriptor.value; + __runInitializers(_classThis, _staticExtraInitializers); + } +@@ -96,12 +97,12 @@ let C = (() => { + return C = _classThis; + })(); + ((() => { +- let _classDecorators_1 = [dec]; +- let _classDescriptor_1; +- let _classExtraInitializers_1 = []; +- let _classThis_1; +- let _staticExtraInitializers_1 = []; +- let _instanceExtraInitializers_1 = []; ++ let _classDecorators = [dec]; ++ let _classDescriptor; ++ let _classExtraInitializers = []; ++ let _classThis; ++ let _staticExtraInitializers = []; ++ let _instanceExtraInitializers = []; + let _static_method_decorators; + let _static_set_x_decorators; + let _static_y_decorators; +@@ -111,6 +112,7 @@ let C = (() => { + let _y_decorators; + let _y_initializers = []; + var C = class { ++ static { _classThis = this; } + static { + _method_decorators = [dec]; + _set_x_decorators = [dec]; +@@ -118,26 +120,26 @@ let C = (() => { + _static_method_decorators = [dec]; + _static_set_x_decorators = [dec]; + _static_y_decorators = [dec]; +- __esDecorate(this, null, _static_method_decorators, { kind: "method", name: "method", static: true, private: false, access: { has: obj => "method" in obj, get: obj => obj.method } }, null, _staticExtraInitializers_1); +- __esDecorate(this, null, _static_set_x_decorators, { kind: "setter", name: "x", static: true, private: false, access: { has: obj => "x" in obj, set: (obj, value) => { obj.x = value; } } }, null, _staticExtraInitializers_1); +- __esDecorate(this, null, _method_decorators, { kind: "method", name: "method", static: false, private: false, access: { has: obj => "method" in obj, get: obj => obj.method } }, null, _instanceExtraInitializers_1); +- __esDecorate(this, null, _set_x_decorators, { kind: "setter", name: "x", static: false, private: false, access: { has: obj => "x" in obj, set: (obj, value) => { obj.x = value; } } }, null, _instanceExtraInitializers_1); +- __esDecorate(null, null, _static_y_decorators, { kind: "field", name: "y", static: true, private: false, access: { has: obj => "y" in obj, get: obj => obj.y, set: (obj, value) => { obj.y = value; } } }, _static_y_initializers, _staticExtraInitializers_1); +- __esDecorate(null, null, _y_decorators, { kind: "field", name: "y", static: false, private: false, access: { has: obj => "y" in obj, get: obj => obj.y, set: (obj, value) => { obj.y = value; } } }, _y_initializers, _instanceExtraInitializers_1); +- __esDecorate(null, _classDescriptor_1 = { value: this }, _classDecorators_1, { kind: "class", name: this.name }, null, _classExtraInitializers_1); +- C = _classThis_1 = _classDescriptor_1.value; +- __runInitializers(_classThis_1, _staticExtraInitializers_1); ++ __esDecorate(this, null, _static_method_decorators, { kind: "method", name: "method", static: true, private: false, access: { has: obj => "method" in obj, get: obj => obj.method } }, null, _staticExtraInitializers); ++ __esDecorate(this, null, _static_set_x_decorators, { kind: "setter", name: "x", static: true, private: false, access: { has: obj => "x" in obj, set: (obj, value) => { obj.x = value; } } }, null, _staticExtraInitializers); ++ __esDecorate(this, null, _method_decorators, { kind: "method", name: "method", static: false, private: false, access: { has: obj => "method" in obj, get: obj => obj.method } }, null, _instanceExtraInitializers); ++ __esDecorate(this, null, _set_x_decorators, { kind: "setter", name: "x", static: false, private: false, access: { has: obj => "x" in obj, set: (obj, value) => { obj.x = value; } } }, null, _instanceExtraInitializers); ++ __esDecorate(null, null, _static_y_decorators, { kind: "field", name: "y", static: true, private: false, access: { has: obj => "y" in obj, get: obj => obj.y, set: (obj, value) => { obj.y = value; } } }, _static_y_initializers, _staticExtraInitializers); ++ __esDecorate(null, null, _y_decorators, { kind: "field", name: "y", static: false, private: false, access: { has: obj => "y" in obj, get: obj => obj.y, set: (obj, value) => { obj.y = value; } } }, _y_initializers, _instanceExtraInitializers); ++ __esDecorate(null, _classDescriptor = { value: _classThis }, _classDecorators, { kind: "class", name: _classThis.name }, null, _classExtraInitializers); ++ C = _classThis = _classDescriptor.value; ++ __runInitializers(_classThis, _staticExtraInitializers); + } + constructor(x) { } + method(x) { } + set x(x) { } +- y = (__runInitializers(this, _instanceExtraInitializers_1), __runInitializers(this, _y_initializers, void 0)); ++ y = (__runInitializers(this, _instanceExtraInitializers), __runInitializers(this, _y_initializers, void 0)); + static method(x) { } + static set x(x) { } +- static y = __runInitializers(_classThis_1, _static_y_initializers, void 0); ++ static y = __runInitializers(_classThis, _static_y_initializers, void 0); + static { +- __runInitializers(_classThis_1, _classExtraInitializers_1); ++ __runInitializers(_classThis, _classExtraInitializers); + } + }; +- return C = _classThis_1; ++ return C = _classThis; + })()); +diff --git a/tests/baselines/reference/esDecorators-emitDecoratorMetadata(target=es5).js b/tests/baselines/reference/esDecorators-emitDecoratorMetadata(target=es5).js +index 7ee7ed280..9402cc94d 100644 +--- a/tests/baselines/reference/esDecorators-emitDecoratorMetadata(target=es5).js ++++ b/tests/baselines/reference/esDecorators-emitDecoratorMetadata(target=es5).js +@@ -49,7 +49,6 @@ class C { + }); + + //// [esDecorators-emitDecoratorMetadata.js] +-var _this = this; + var C = function () { + var _classDecorators = [dec]; + var _classDescriptor; +@@ -108,12 +107,12 @@ var C = function () { + return C = _classThis; + }(); + ((function () { +- var _classDecorators_1 = [dec]; +- var _classDescriptor_1; +- var _classExtraInitializers_1 = []; +- var _classThis_1; +- var _staticExtraInitializers_1 = []; +- var _instanceExtraInitializers_1 = []; ++ var _classDecorators = [dec]; ++ var _classDescriptor; ++ var _classExtraInitializers = []; ++ var _classThis; ++ var _staticExtraInitializers = []; ++ var _instanceExtraInitializers = []; + var _static_method_decorators; + var _static_set_x_decorators; + var _static_y_decorators; +@@ -122,9 +121,9 @@ var C = function () { + var _set_x_decorators; + var _y_decorators; + var _y_initializers = []; +- var C = (_classThis_1 = /** @class */ (function () { ++ var C = (_classThis = /** @class */ (function () { + function class_1(x) { +- this.y = (__runInitializers(this, _instanceExtraInitializers_1), __runInitializers(this, _y_initializers, void 0)); ++ this.y = (__runInitializers(this, _instanceExtraInitializers), __runInitializers(this, _y_initializers, void 0)); + } + class_1.prototype.method = function (x) { }; + Object.defineProperty(class_1.prototype, "x", { +@@ -140,7 +139,7 @@ var C = function () { + }); + return class_1; + }()), +- __setFunctionName(_classThis_1, "C"), ++ __setFunctionName(_classThis, "C"), + (function () { + _method_decorators = [dec]; + _set_x_decorators = [dec]; +@@ -148,20 +147,20 @@ var C = function () { + _static_method_decorators = [dec]; + _static_set_x_decorators = [dec]; + _static_y_decorators = [dec]; +- __esDecorate(_classThis_1, null, _static_method_decorators, { kind: "method", name: "method", static: true, private: false, access: { has: function (obj) { return "method" in obj; }, get: function (obj) { return obj.method; } } }, null, _staticExtraInitializers_1); +- __esDecorate(_classThis_1, null, _static_set_x_decorators, { kind: "setter", name: "x", static: true, private: false, access: { has: function (obj) { return "x" in obj; }, set: function (obj, value) { obj.x = value; } } }, null, _staticExtraInitializers_1); +- __esDecorate(_classThis_1, null, _method_decorators, { kind: "method", name: "method", static: false, private: false, access: { has: function (obj) { return "method" in obj; }, get: function (obj) { return obj.method; } } }, null, _instanceExtraInitializers_1); +- __esDecorate(_classThis_1, null, _set_x_decorators, { kind: "setter", name: "x", static: false, private: false, access: { has: function (obj) { return "x" in obj; }, set: function (obj, value) { obj.x = value; } } }, null, _instanceExtraInitializers_1); +- __esDecorate(null, null, _static_y_decorators, { kind: "field", name: "y", static: true, private: false, access: { has: function (obj) { return "y" in obj; }, get: function (obj) { return obj.y; }, set: function (obj, value) { obj.y = value; } } }, _static_y_initializers, _staticExtraInitializers_1); +- __esDecorate(null, null, _y_decorators, { kind: "field", name: "y", static: false, private: false, access: { has: function (obj) { return "y" in obj; }, get: function (obj) { return obj.y; }, set: function (obj, value) { obj.y = value; } } }, _y_initializers, _instanceExtraInitializers_1); +- __esDecorate(null, _classDescriptor_1 = { value: _classThis_1 }, _classDecorators_1, { kind: "class", name: _classThis_1.name }, null, _classExtraInitializers_1); +- C = _classThis_1 = _classDescriptor_1.value; +- __runInitializers(_classThis_1, _staticExtraInitializers_1); ++ __esDecorate(_classThis, null, _static_method_decorators, { kind: "method", name: "method", static: true, private: false, access: { has: function (obj) { return "method" in obj; }, get: function (obj) { return obj.method; } } }, null, _staticExtraInitializers); ++ __esDecorate(_classThis, null, _static_set_x_decorators, { kind: "setter", name: "x", static: true, private: false, access: { has: function (obj) { return "x" in obj; }, set: function (obj, value) { obj.x = value; } } }, null, _staticExtraInitializers); ++ __esDecorate(_classThis, null, _method_decorators, { kind: "method", name: "method", static: false, private: false, access: { has: function (obj) { return "method" in obj; }, get: function (obj) { return obj.method; } } }, null, _instanceExtraInitializers); ++ __esDecorate(_classThis, null, _set_x_decorators, { kind: "setter", name: "x", static: false, private: false, access: { has: function (obj) { return "x" in obj; }, set: function (obj, value) { obj.x = value; } } }, null, _instanceExtraInitializers); ++ __esDecorate(null, null, _static_y_decorators, { kind: "field", name: "y", static: true, private: false, access: { has: function (obj) { return "y" in obj; }, get: function (obj) { return obj.y; }, set: function (obj, value) { obj.y = value; } } }, _static_y_initializers, _staticExtraInitializers); ++ __esDecorate(null, null, _y_decorators, { kind: "field", name: "y", static: false, private: false, access: { has: function (obj) { return "y" in obj; }, get: function (obj) { return obj.y; }, set: function (obj, value) { obj.y = value; } } }, _y_initializers, _instanceExtraInitializers); ++ __esDecorate(null, _classDescriptor = { value: _classThis }, _classDecorators, { kind: "class", name: _classThis.name }, null, _classExtraInitializers); ++ C = _classThis = _classDescriptor.value; ++ __runInitializers(_classThis, _staticExtraInitializers); + })(), +- _classThis_1.y = __runInitializers(_classThis_1, _static_y_initializers, void 0), ++ _classThis.y = __runInitializers(_classThis, _static_y_initializers, void 0), + (function () { +- __runInitializers(_classThis_1, _classExtraInitializers_1); ++ __runInitializers(_classThis, _classExtraInitializers); + })(), +- _classThis_1); +- return C = _classThis_1; ++ _classThis); ++ return C = _classThis; + })()); +diff --git a/tests/baselines/reference/esnextmodulekindWithES5Target.js b/tests/baselines/reference/esnextmodulekindWithES5Target.js +index 6ef97503c..21d0ceb3a 100644 +--- a/tests/baselines/reference/esnextmodulekindWithES5Target.js ++++ b/tests/baselines/reference/esnextmodulekindWithES5Target.js +@@ -28,7 +28,7 @@ var __decorate = (this && this.__decorate) || function (decorators, target, key, + else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; + return c > 3 && r && Object.defineProperty(target, key, r), r; + }; +-export var C = /** @class */ (function () { ++var C = /** @class */ (function () { + function C() { + this.p = 1; + } +@@ -36,8 +36,9 @@ export var C = /** @class */ (function () { + C.s = 0; + return C; + }()); ++export { C }; + export { C as C2 }; +-export var D = /** @class */ (function () { ++var D = /** @class */ (function () { + function D() { + this.p = 1; + } +@@ -48,6 +49,7 @@ export var D = /** @class */ (function () { + ], D); + return D; + }()); ++export { D }; + export { D as D2 }; + var E = /** @class */ (function () { + function E() { +diff --git a/tests/baselines/reference/for-of-excess-declarations.errors.txt b/tests/baselines/reference/for-of-excess-declarations.errors.txt +new file mode 100644 +index 000000000..516dfb68c +--- /dev/null ++++ b/tests/baselines/reference/for-of-excess-declarations.errors.txt +@@ -0,0 +1,15 @@ ++for-of-excess-declarations.ts(1,15): error TS1188: Only a single variable declaration is allowed in a 'for...of' statement. ++for-of-excess-declarations.ts(1,18): error TS2304: Cannot find name 'b'. ++for-of-excess-declarations.ts(1,18): error TS2538: Type 'any' cannot be used as an index type. ++ ++ ++==== for-of-excess-declarations.ts (3 errors) ==== ++ for (const a, { [b]: c} of [1]) { ++ ~ ++!!! error TS1188: Only a single variable declaration is allowed in a 'for...of' statement. ++ ~ ++!!! error TS2304: Cannot find name 'b'. ++ ~ ++!!! error TS2538: Type 'any' cannot be used as an index type. ++ ++ } +\ No newline at end of file +diff --git a/tests/baselines/reference/for-of-excess-declarations.js b/tests/baselines/reference/for-of-excess-declarations.js +new file mode 100644 +index 000000000..84783caa0 +--- /dev/null ++++ b/tests/baselines/reference/for-of-excess-declarations.js +@@ -0,0 +1,10 @@ ++//// [tests/cases/conformance/es6/for-ofStatements/for-of-excess-declarations.ts] //// ++ ++//// [for-of-excess-declarations.ts] ++for (const a, { [b]: c} of [1]) { ++ ++} ++ ++//// [for-of-excess-declarations.js] ++for (const a, { [b]: c } of [1]) { ++} +diff --git a/tests/baselines/reference/for-of-excess-declarations.symbols b/tests/baselines/reference/for-of-excess-declarations.symbols +new file mode 100644 +index 000000000..3fdc2f7f4 +--- /dev/null ++++ b/tests/baselines/reference/for-of-excess-declarations.symbols +@@ -0,0 +1,8 @@ ++//// [tests/cases/conformance/es6/for-ofStatements/for-of-excess-declarations.ts] //// ++ ++=== for-of-excess-declarations.ts === ++for (const a, { [b]: c} of [1]) { ++>a : Symbol(a, Decl(for-of-excess-declarations.ts, 0, 10)) ++>c : Symbol(c, Decl(for-of-excess-declarations.ts, 0, 15)) ++ ++} +diff --git a/tests/baselines/reference/for-of-excess-declarations.types b/tests/baselines/reference/for-of-excess-declarations.types +new file mode 100644 +index 000000000..31fa3901c +--- /dev/null ++++ b/tests/baselines/reference/for-of-excess-declarations.types +@@ -0,0 +1,11 @@ ++//// [tests/cases/conformance/es6/for-ofStatements/for-of-excess-declarations.ts] //// ++ ++=== for-of-excess-declarations.ts === ++for (const a, { [b]: c} of [1]) { ++>a : number ++>b : any ++>c : any ++>[1] : number[] ++>1 : 1 ++ ++} +diff --git a/tests/baselines/reference/importHelpersES6.js b/tests/baselines/reference/importHelpersES6.js +index 92c57ba8b..ec2ca96a5 100644 +--- a/tests/baselines/reference/importHelpersES6.js ++++ b/tests/baselines/reference/importHelpersES6.js +@@ -25,7 +25,7 @@ export declare function __classPrivateFieldIn(a: any, b: any): boolean; + //// [a.js] + var _A_x; + import { __awaiter, __classPrivateFieldGet, __classPrivateFieldIn, __classPrivateFieldSet, __decorate } from "tslib"; +-export let A = class A { ++let A = class A { + constructor() { + _A_x.set(this, 1); + } +@@ -38,5 +38,6 @@ _A_x = new WeakMap(); + A = __decorate([ + dec + ], A); ++export { A }; + const o = { a: 1 }; + const y = Object.assign({}, o); +diff --git a/tests/baselines/reference/importHelpersWithLocalCollisions(module=amd).js b/tests/baselines/reference/importHelpersWithLocalCollisions(module=amd).js +index 260f6f64d..8cd41ea7a 100644 +--- a/tests/baselines/reference/importHelpersWithLocalCollisions(module=amd).js ++++ b/tests/baselines/reference/importHelpersWithLocalCollisions(module=amd).js +@@ -22,8 +22,9 @@ define(["require", "exports", "tslib"], function (require, exports, tslib_1) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.A = void 0; +- let A = exports.A = class A { ++ let A = class A { + }; ++ exports.A = A; + exports.A = A = tslib_1.__decorate([ + dec + ], A); +diff --git a/tests/baselines/reference/importHelpersWithLocalCollisions(module=commonjs).js b/tests/baselines/reference/importHelpersWithLocalCollisions(module=commonjs).js +index 2a8868ef9..adaba14dc 100644 +--- a/tests/baselines/reference/importHelpersWithLocalCollisions(module=commonjs).js ++++ b/tests/baselines/reference/importHelpersWithLocalCollisions(module=commonjs).js +@@ -22,8 +22,9 @@ export declare function __awaiter(thisArg: any, _arguments: any, P: Function, ge + Object.defineProperty(exports, "__esModule", { value: true }); + exports.A = void 0; + const tslib_1 = require("tslib"); +-let A = exports.A = class A { ++let A = class A { + }; ++exports.A = A; + exports.A = A = tslib_1.__decorate([ + dec + ], A); +diff --git a/tests/baselines/reference/importHelpersWithLocalCollisions(module=es2015).js b/tests/baselines/reference/importHelpersWithLocalCollisions(module=es2015).js +index 1225d694a..ba22069c3 100644 +--- a/tests/baselines/reference/importHelpersWithLocalCollisions(module=es2015).js ++++ b/tests/baselines/reference/importHelpersWithLocalCollisions(module=es2015).js +@@ -19,10 +19,11 @@ export declare function __awaiter(thisArg: any, _arguments: any, P: Function, ge + + //// [a.js] + import { __decorate as __decorate_1 } from "tslib"; +-export let A = class A { ++let A = class A { + }; + A = __decorate_1([ + dec + ], A); ++export { A }; + const o = { a: 1 }; + const y = Object.assign({}, o); +diff --git a/tests/baselines/reference/importHelpersWithLocalCollisions(module=system).js b/tests/baselines/reference/importHelpersWithLocalCollisions(module=system).js +index 189159cd0..788e5ae4d 100644 +--- a/tests/baselines/reference/importHelpersWithLocalCollisions(module=system).js ++++ b/tests/baselines/reference/importHelpersWithLocalCollisions(module=system).js +@@ -29,8 +29,9 @@ System.register(["tslib"], function (exports_1, context_1) { + } + ], + execute: function () { +- exports_1("A", A = class A { +- }); ++ A = class A { ++ }; ++ exports_1("A", A); + exports_1("A", A = tslib_1.__decorate([ + dec + ], A)); +diff --git a/tests/baselines/reference/importImportOnlyModule.js b/tests/baselines/reference/importImportOnlyModule.js +index d60eaa720..b77081064 100644 +--- a/tests/baselines/reference/importImportOnlyModule.js ++++ b/tests/baselines/reference/importImportOnlyModule.js +@@ -20,13 +20,14 @@ define(["require", "exports"], function (require, exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.C1 = void 0; +- var C1 = exports.C1 = /** @class */ (function () { ++ var C1 = /** @class */ (function () { + function C1() { + this.m1 = 42; + } + C1.s1 = true; + return C1; + }()); ++ exports.C1 = C1; + }); + //// [foo_1.js] + define(["require", "exports"], function (require, exports) { +diff --git a/tests/baselines/reference/javascriptThisAssignmentInStaticBlock.js b/tests/baselines/reference/javascriptThisAssignmentInStaticBlock.js +index 5d9fa75d5..bae195f80 100644 +--- a/tests/baselines/reference/javascriptThisAssignmentInStaticBlock.js ++++ b/tests/baselines/reference/javascriptThisAssignmentInStaticBlock.js +@@ -37,7 +37,6 @@ var __extends = (this && this.__extends) || (function () { + }; + })(); + var _a, _b; +-var _this = this; + var Thing = /** @class */ (function () { + function Thing() { + } +diff --git a/tests/baselines/reference/jsDeclarationsClasses.js b/tests/baselines/reference/jsDeclarationsClasses.js +index c751e3ae0..ec208cded 100644 +--- a/tests/baselines/reference/jsDeclarationsClasses.js ++++ b/tests/baselines/reference/jsDeclarationsClasses.js +@@ -221,13 +221,14 @@ var A = /** @class */ (function () { + return A; + }()); + exports.A = A; +-var B = exports.B = /** @class */ (function () { ++var B = /** @class */ (function () { + function B() { + } + B.cat = "cat"; + return B; + }()); +-var C = exports.C = /** @class */ (function () { ++exports.B = B; ++var C = /** @class */ (function () { + function C() { + } + C.Cls = /** @class */ (function () { +@@ -237,6 +238,7 @@ var C = exports.C = /** @class */ (function () { + }()); + return C; + }()); ++exports.C = C; + var D = /** @class */ (function () { + /** + * @param {number} a +@@ -250,7 +252,7 @@ exports.D = D; + /** + * @template T,U + */ +-var E = exports.E = /** @class */ (function () { ++var E = /** @class */ (function () { + /** + * @param {T} a + * @param {U} b +@@ -317,6 +319,7 @@ var E = exports.E = /** @class */ (function () { + E.staticInitializedField = 12; + return E; + }()); ++exports.E = E; + /** + * @template T,U + */ +diff --git a/tests/baselines/reference/jsDeclarationsComputedNames.js b/tests/baselines/reference/jsDeclarationsComputedNames.js +index 8b21f98c0..127b46045 100644 +--- a/tests/baselines/reference/jsDeclarationsComputedNames.js ++++ b/tests/baselines/reference/jsDeclarationsComputedNames.js +@@ -50,7 +50,7 @@ Object.defineProperty(exports, "__esModule", { value: true }); + exports.MyClass = void 0; + var TopLevelSym = Symbol(); + var InnerSym = Symbol(); +-var MyClass = exports.MyClass = /** @class */ (function () { ++var MyClass = /** @class */ (function () { + /** + * @param {typeof TopLevelSym | typeof InnerSym} _p + */ +@@ -64,6 +64,7 @@ var MyClass = exports.MyClass = /** @class */ (function () { + MyClass[_a] = 12; + return MyClass; + }()); ++exports.MyClass = MyClass; + + + //// [index.d.ts] +diff --git a/tests/baselines/reference/letDeclarations-invalidContexts.errors.txt b/tests/baselines/reference/letDeclarations-invalidContexts.errors.txt +index 229ebdba0..645962e02 100644 +--- a/tests/baselines/reference/letDeclarations-invalidContexts.errors.txt ++++ b/tests/baselines/reference/letDeclarations-invalidContexts.errors.txt +@@ -1,12 +1,12 @@ +-letDeclarations-invalidContexts.ts(3,5): error TS1157: 'let' declarations can only be declared inside a block. +-letDeclarations-invalidContexts.ts(5,5): error TS1157: 'let' declarations can only be declared inside a block. +-letDeclarations-invalidContexts.ts(8,5): error TS1157: 'let' declarations can only be declared inside a block. +-letDeclarations-invalidContexts.ts(11,5): error TS1157: 'let' declarations can only be declared inside a block. ++letDeclarations-invalidContexts.ts(3,5): error TS1156: 'let' declarations can only be declared inside a block. ++letDeclarations-invalidContexts.ts(5,5): error TS1156: 'let' declarations can only be declared inside a block. ++letDeclarations-invalidContexts.ts(8,5): error TS1156: 'let' declarations can only be declared inside a block. ++letDeclarations-invalidContexts.ts(11,5): error TS1156: 'let' declarations can only be declared inside a block. + letDeclarations-invalidContexts.ts(15,1): error TS2410: The 'with' statement is not supported. All symbols in a 'with' block will have type 'any'. +-letDeclarations-invalidContexts.ts(19,5): error TS1157: 'let' declarations can only be declared inside a block. +-letDeclarations-invalidContexts.ts(22,5): error TS1157: 'let' declarations can only be declared inside a block. +-letDeclarations-invalidContexts.ts(25,12): error TS1157: 'let' declarations can only be declared inside a block. +-letDeclarations-invalidContexts.ts(28,29): error TS1157: 'let' declarations can only be declared inside a block. ++letDeclarations-invalidContexts.ts(19,5): error TS1156: 'let' declarations can only be declared inside a block. ++letDeclarations-invalidContexts.ts(22,5): error TS1156: 'let' declarations can only be declared inside a block. ++letDeclarations-invalidContexts.ts(25,12): error TS1156: 'let' declarations can only be declared inside a block. ++letDeclarations-invalidContexts.ts(28,29): error TS1156: 'let' declarations can only be declared inside a block. + + + ==== letDeclarations-invalidContexts.ts (9 errors) ==== +@@ -14,21 +14,21 @@ letDeclarations-invalidContexts.ts(28,29): error TS1157: 'let' declarations can + if (true) + let l1 = 0; + ~~~~~~~~~~~ +-!!! error TS1157: 'let' declarations can only be declared inside a block. ++!!! error TS1156: 'let' declarations can only be declared inside a block. + else + let l2 = 0; + ~~~~~~~~~~~ +-!!! error TS1157: 'let' declarations can only be declared inside a block. ++!!! error TS1156: 'let' declarations can only be declared inside a block. + + while (true) + let l3 = 0; + ~~~~~~~~~~~ +-!!! error TS1157: 'let' declarations can only be declared inside a block. ++!!! error TS1156: 'let' declarations can only be declared inside a block. + + do + let l4 = 0; + ~~~~~~~~~~~ +-!!! error TS1157: 'let' declarations can only be declared inside a block. ++!!! error TS1156: 'let' declarations can only be declared inside a block. + while (true); + + var obj; +@@ -40,22 +40,22 @@ letDeclarations-invalidContexts.ts(28,29): error TS1157: 'let' declarations can + for (var i = 0; i < 10; i++) + let l6 = 0; + ~~~~~~~~~~~ +-!!! error TS1157: 'let' declarations can only be declared inside a block. ++!!! error TS1156: 'let' declarations can only be declared inside a block. + + for (var i2 in {}) + let l7 = 0; + ~~~~~~~~~~~ +-!!! error TS1157: 'let' declarations can only be declared inside a block. ++!!! error TS1156: 'let' declarations can only be declared inside a block. + + if (true) + label: let l8 = 0; + ~~~~~~~~~~~ +-!!! error TS1157: 'let' declarations can only be declared inside a block. ++!!! error TS1156: 'let' declarations can only be declared inside a block. + + while (false) + label2: label3: label4: let l9 = 0; + ~~~~~~~~~~~ +-!!! error TS1157: 'let' declarations can only be declared inside a block. ++!!! error TS1156: 'let' declarations can only be declared inside a block. + + + +diff --git a/tests/baselines/reference/metadataImportType.js b/tests/baselines/reference/metadataImportType.js +index 46560f9e1..f37594ca1 100644 +--- a/tests/baselines/reference/metadataImportType.js ++++ b/tests/baselines/reference/metadataImportType.js +@@ -19,7 +19,7 @@ var __metadata = (this && this.__metadata) || function (k, v) { + }; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.A = void 0; +-var A = exports.A = /** @class */ (function () { ++var A = /** @class */ (function () { + function A() { + } + __decorate([ +@@ -28,3 +28,4 @@ var A = exports.A = /** @class */ (function () { + ], A.prototype, "b", void 0); + return A; + }()); ++exports.A = A; +diff --git a/tests/baselines/reference/metadataOfClassFromAlias.js b/tests/baselines/reference/metadataOfClassFromAlias.js +index e63697b56..657cdf21f 100644 +--- a/tests/baselines/reference/metadataOfClassFromAlias.js ++++ b/tests/baselines/reference/metadataOfClassFromAlias.js +@@ -41,7 +41,7 @@ var auxiliry_1 = require("./auxiliry"); + function annotation() { + return function (target) { }; + } +-var ClassA = exports.ClassA = /** @class */ (function () { ++var ClassA = /** @class */ (function () { + function ClassA() { + } + __decorate([ +@@ -50,3 +50,4 @@ var ClassA = exports.ClassA = /** @class */ (function () { + ], ClassA.prototype, "array", void 0); + return ClassA; + }()); ++exports.ClassA = ClassA; +diff --git a/tests/baselines/reference/metadataOfClassFromAlias2.js b/tests/baselines/reference/metadataOfClassFromAlias2.js +index 02d2626a9..8b7a2b931 100644 +--- a/tests/baselines/reference/metadataOfClassFromAlias2.js ++++ b/tests/baselines/reference/metadataOfClassFromAlias2.js +@@ -40,7 +40,7 @@ exports.ClassA = void 0; + function annotation() { + return function (target) { }; + } +-var ClassA = exports.ClassA = /** @class */ (function () { ++var ClassA = /** @class */ (function () { + function ClassA() { + } + __decorate([ +@@ -49,3 +49,4 @@ var ClassA = exports.ClassA = /** @class */ (function () { + ], ClassA.prototype, "array", void 0); + return ClassA; + }()); ++exports.ClassA = ClassA; +diff --git a/tests/baselines/reference/metadataOfEventAlias.js b/tests/baselines/reference/metadataOfEventAlias.js +index c4d498295..999396743 100644 +--- a/tests/baselines/reference/metadataOfEventAlias.js ++++ b/tests/baselines/reference/metadataOfEventAlias.js +@@ -28,7 +28,7 @@ var __metadata = (this && this.__metadata) || function (k, v) { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.SomeClass = void 0; + function Input(target, key) { } +-var SomeClass = exports.SomeClass = /** @class */ (function () { ++var SomeClass = /** @class */ (function () { + function SomeClass() { + } + __decorate([ +@@ -37,3 +37,4 @@ var SomeClass = exports.SomeClass = /** @class */ (function () { + ], SomeClass.prototype, "event", void 0); + return SomeClass; + }()); ++exports.SomeClass = SomeClass; +diff --git a/tests/baselines/reference/metadataReferencedWithinFilteredUnion.js b/tests/baselines/reference/metadataReferencedWithinFilteredUnion.js +index 1462af8a6..7c7d70c74 100644 +--- a/tests/baselines/reference/metadataReferencedWithinFilteredUnion.js ++++ b/tests/baselines/reference/metadataReferencedWithinFilteredUnion.js +@@ -42,7 +42,7 @@ exports.Class2 = void 0; + var Class1_1 = require("./Class1"); + function decorate(target, propertyKey) { + } +-var Class2 = exports.Class2 = /** @class */ (function () { ++var Class2 = /** @class */ (function () { + function Class2() { + } + Object.defineProperty(Class2.prototype, "prop", { +@@ -59,3 +59,4 @@ var Class2 = exports.Class2 = /** @class */ (function () { + ], Class2.prototype, "prop", null); + return Class2; + }()); ++exports.Class2 = Class2; +diff --git a/tests/baselines/reference/plainJSGrammarErrors.errors.txt b/tests/baselines/reference/plainJSGrammarErrors.errors.txt +index b855bc6b1..8b015217e 100644 +--- a/tests/baselines/reference/plainJSGrammarErrors.errors.txt ++++ b/tests/baselines/reference/plainJSGrammarErrors.errors.txt +@@ -1,7 +1,7 @@ + plainJSGrammarErrors.js(3,9): error TS1451: Private identifiers are only allowed in class bodies and may only be used as part of a class member declaration, property access, or on the left-hand-side of an 'in' expression + plainJSGrammarErrors.js(5,9): error TS1451: Private identifiers are only allowed in class bodies and may only be used as part of a class member declaration, property access, or on the left-hand-side of an 'in' expression + plainJSGrammarErrors.js(10,15): error TS2803: Cannot assign to private method '#m'. Private methods are not writable. +-plainJSGrammarErrors.js(14,13): error TS18038: 'For await' loops cannot be used inside a class static block. ++plainJSGrammarErrors.js(14,13): error TS18038: 'for await' loops cannot be used inside a class static block. + plainJSGrammarErrors.js(17,9): error TS18041: A 'return' statement cannot be used inside a class static block. + plainJSGrammarErrors.js(20,5): error TS1089: 'static' modifier cannot appear on a constructor declaration. + plainJSGrammarErrors.js(21,5): error TS1089: 'async' modifier cannot appear on a constructor declaration. +@@ -77,7 +77,7 @@ plainJSGrammarErrors.js(120,7): error TS1182: A destructuring declaration must h + plainJSGrammarErrors.js(121,7): error TS1155: 'const' declarations must be initialized. + plainJSGrammarErrors.js(122,5): error TS1214: Identifier expected. 'let' is a reserved word in strict mode. Modules are automatically in strict mode. + plainJSGrammarErrors.js(122,5): error TS2480: 'let' is not allowed to be used as a name in 'let' or 'const' declarations. +-plainJSGrammarErrors.js(124,5): error TS1157: 'let' declarations can only be declared inside a block. ++plainJSGrammarErrors.js(124,5): error TS1156: 'let' declarations can only be declared inside a block. + plainJSGrammarErrors.js(126,5): error TS1156: 'const' declarations can only be declared inside a block. + plainJSGrammarErrors.js(131,6): error TS1106: The left-hand side of a 'for...of' statement may not be 'async'. + plainJSGrammarErrors.js(134,12): error TS1190: The variable declaration of a 'for...of' statement cannot have an initializer. +@@ -124,7 +124,7 @@ plainJSGrammarErrors.js(205,36): error TS1325: Argument of dynamic import cannot + static { + for await (const x of [1,2,3]) { + ~~~~~ +-!!! error TS18038: 'For await' loops cannot be used inside a class static block. ++!!! error TS18038: 'for await' loops cannot be used inside a class static block. + console.log(x) + } + return null +@@ -386,7 +386,7 @@ plainJSGrammarErrors.js(205,36): error TS1325: Argument of dynamic import cannot + if (true) + let onlyBlockLet = 17; + ~~~~~~~~~~~~~~~~~~~~~~ +-!!! error TS1157: 'let' declarations can only be declared inside a block. ++!!! error TS1156: 'let' declarations can only be declared inside a block. + if (true) + const onlyBlockConst = 18; + ~~~~~~~~~~~~~~~~~~~~~~~~~~ +diff --git a/tests/baselines/reference/privacyCannotNameVarTypeDeclFile.js b/tests/baselines/reference/privacyCannotNameVarTypeDeclFile.js +index a95b49ad8..cc61a1f86 100644 +--- a/tests/baselines/reference/privacyCannotNameVarTypeDeclFile.js ++++ b/tests/baselines/reference/privacyCannotNameVarTypeDeclFile.js +@@ -156,7 +156,7 @@ exports.createExportedWidget4 = createExportedWidget4; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.publicVarWithPrivateModulePropertyTypes1 = exports.publicVarWithPrivateModulePropertyTypes = exports.publicClassWithPrivateModulePropertyTypes = exports.publicVarWithPrivatePropertyTypes1 = exports.publicVarWithPrivatePropertyTypes = exports.publicClassWithWithPrivatePropertyTypes = void 0; + var exporter = require("./privacyCannotNameVarTypeDeclFile_exporter"); +-var publicClassWithWithPrivatePropertyTypes = exports.publicClassWithWithPrivatePropertyTypes = /** @class */ (function () { ++var publicClassWithWithPrivatePropertyTypes = /** @class */ (function () { + function publicClassWithWithPrivatePropertyTypes() { + this.myPublicProperty = exporter.createExportedWidget1(); // Error + this.myPrivateProperty = exporter.createExportedWidget1(); +@@ -169,6 +169,7 @@ var publicClassWithWithPrivatePropertyTypes = exports.publicClassWithWithPrivate + publicClassWithWithPrivatePropertyTypes.myPrivateStaticProperty1 = exporter.createExportedWidget3(); + return publicClassWithWithPrivatePropertyTypes; + }()); ++exports.publicClassWithWithPrivatePropertyTypes = publicClassWithWithPrivatePropertyTypes; + var privateClassWithWithPrivatePropertyTypes = /** @class */ (function () { + function privateClassWithWithPrivatePropertyTypes() { + this.myPublicProperty = exporter.createExportedWidget1(); +@@ -186,7 +187,7 @@ exports.publicVarWithPrivatePropertyTypes = exporter.createExportedWidget1(); // + var privateVarWithPrivatePropertyTypes = exporter.createExportedWidget1(); + exports.publicVarWithPrivatePropertyTypes1 = exporter.createExportedWidget3(); // Error + var privateVarWithPrivatePropertyTypes1 = exporter.createExportedWidget3(); +-var publicClassWithPrivateModulePropertyTypes = exports.publicClassWithPrivateModulePropertyTypes = /** @class */ (function () { ++var publicClassWithPrivateModulePropertyTypes = /** @class */ (function () { + function publicClassWithPrivateModulePropertyTypes() { + this.myPublicProperty = exporter.createExportedWidget2(); // Error + this.myPublicProperty1 = exporter.createExportedWidget4(); // Error +@@ -195,6 +196,7 @@ var publicClassWithPrivateModulePropertyTypes = exports.publicClassWithPrivateMo + publicClassWithPrivateModulePropertyTypes.myPublicStaticProperty1 = exporter.createExportedWidget4(); // Error + return publicClassWithPrivateModulePropertyTypes; + }()); ++exports.publicClassWithPrivateModulePropertyTypes = publicClassWithPrivateModulePropertyTypes; + exports.publicVarWithPrivateModulePropertyTypes = exporter.createExportedWidget2(); // Error + exports.publicVarWithPrivateModulePropertyTypes1 = exporter.createExportedWidget4(); // Error + var privateClassWithPrivateModulePropertyTypes = /** @class */ (function () { +diff --git a/tests/baselines/reference/project/emitDecoratorMetadataCommonJSISolatedModules/amd/main.js b/tests/baselines/reference/project/emitDecoratorMetadataCommonJSISolatedModules/amd/main.js +index 523abb131..9ca20dffe 100644 +--- a/tests/baselines/reference/project/emitDecoratorMetadataCommonJSISolatedModules/amd/main.js ++++ b/tests/baselines/reference/project/emitDecoratorMetadataCommonJSISolatedModules/amd/main.js +@@ -11,7 +11,7 @@ define(["require", "exports", "angular2/core"], function (require, exports, ng) + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.MyClass1 = void 0; +- var MyClass1 = exports.MyClass1 = /** @class */ (function () { ++ var MyClass1 = /** @class */ (function () { + function MyClass1(_elementRef) { + this._elementRef = _elementRef; + } +@@ -22,4 +22,5 @@ define(["require", "exports", "angular2/core"], function (require, exports, ng) + ], MyClass1); + return MyClass1; + }()); ++ exports.MyClass1 = MyClass1; + }); +diff --git a/tests/baselines/reference/project/emitDecoratorMetadataCommonJSISolatedModules/node/main.js b/tests/baselines/reference/project/emitDecoratorMetadataCommonJSISolatedModules/node/main.js +index adbff7ffa..7a668087a 100644 +--- a/tests/baselines/reference/project/emitDecoratorMetadataCommonJSISolatedModules/node/main.js ++++ b/tests/baselines/reference/project/emitDecoratorMetadataCommonJSISolatedModules/node/main.js +@@ -11,7 +11,7 @@ var __metadata = (this && this.__metadata) || function (k, v) { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.MyClass1 = void 0; + var ng = require("angular2/core"); +-var MyClass1 = exports.MyClass1 = /** @class */ (function () { ++var MyClass1 = /** @class */ (function () { + function MyClass1(_elementRef) { + this._elementRef = _elementRef; + } +@@ -22,3 +22,4 @@ var MyClass1 = exports.MyClass1 = /** @class */ (function () { + ], MyClass1); + return MyClass1; + }()); ++exports.MyClass1 = MyClass1; +diff --git a/tests/baselines/reference/project/emitDecoratorMetadataCommonJSISolatedModulesNoResolve/amd/main.js b/tests/baselines/reference/project/emitDecoratorMetadataCommonJSISolatedModulesNoResolve/amd/main.js +index 523abb131..9ca20dffe 100644 +--- a/tests/baselines/reference/project/emitDecoratorMetadataCommonJSISolatedModulesNoResolve/amd/main.js ++++ b/tests/baselines/reference/project/emitDecoratorMetadataCommonJSISolatedModulesNoResolve/amd/main.js +@@ -11,7 +11,7 @@ define(["require", "exports", "angular2/core"], function (require, exports, ng) + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.MyClass1 = void 0; +- var MyClass1 = exports.MyClass1 = /** @class */ (function () { ++ var MyClass1 = /** @class */ (function () { + function MyClass1(_elementRef) { + this._elementRef = _elementRef; + } +@@ -22,4 +22,5 @@ define(["require", "exports", "angular2/core"], function (require, exports, ng) + ], MyClass1); + return MyClass1; + }()); ++ exports.MyClass1 = MyClass1; + }); +diff --git a/tests/baselines/reference/project/emitDecoratorMetadataCommonJSISolatedModulesNoResolve/node/main.js b/tests/baselines/reference/project/emitDecoratorMetadataCommonJSISolatedModulesNoResolve/node/main.js +index adbff7ffa..7a668087a 100644 +--- a/tests/baselines/reference/project/emitDecoratorMetadataCommonJSISolatedModulesNoResolve/node/main.js ++++ b/tests/baselines/reference/project/emitDecoratorMetadataCommonJSISolatedModulesNoResolve/node/main.js +@@ -11,7 +11,7 @@ var __metadata = (this && this.__metadata) || function (k, v) { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.MyClass1 = void 0; + var ng = require("angular2/core"); +-var MyClass1 = exports.MyClass1 = /** @class */ (function () { ++var MyClass1 = /** @class */ (function () { + function MyClass1(_elementRef) { + this._elementRef = _elementRef; + } +@@ -22,3 +22,4 @@ var MyClass1 = exports.MyClass1 = /** @class */ (function () { + ], MyClass1); + return MyClass1; + }()); ++exports.MyClass1 = MyClass1; +diff --git a/tests/baselines/reference/project/emitDecoratorMetadataSystemJS/amd/main.js b/tests/baselines/reference/project/emitDecoratorMetadataSystemJS/amd/main.js +index 523abb131..9ca20dffe 100644 +--- a/tests/baselines/reference/project/emitDecoratorMetadataSystemJS/amd/main.js ++++ b/tests/baselines/reference/project/emitDecoratorMetadataSystemJS/amd/main.js +@@ -11,7 +11,7 @@ define(["require", "exports", "angular2/core"], function (require, exports, ng) + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.MyClass1 = void 0; +- var MyClass1 = exports.MyClass1 = /** @class */ (function () { ++ var MyClass1 = /** @class */ (function () { + function MyClass1(_elementRef) { + this._elementRef = _elementRef; + } +@@ -22,4 +22,5 @@ define(["require", "exports", "angular2/core"], function (require, exports, ng) + ], MyClass1); + return MyClass1; + }()); ++ exports.MyClass1 = MyClass1; + }); +diff --git a/tests/baselines/reference/project/emitDecoratorMetadataSystemJS/node/main.js b/tests/baselines/reference/project/emitDecoratorMetadataSystemJS/node/main.js +index adbff7ffa..7a668087a 100644 +--- a/tests/baselines/reference/project/emitDecoratorMetadataSystemJS/node/main.js ++++ b/tests/baselines/reference/project/emitDecoratorMetadataSystemJS/node/main.js +@@ -11,7 +11,7 @@ var __metadata = (this && this.__metadata) || function (k, v) { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.MyClass1 = void 0; + var ng = require("angular2/core"); +-var MyClass1 = exports.MyClass1 = /** @class */ (function () { ++var MyClass1 = /** @class */ (function () { + function MyClass1(_elementRef) { + this._elementRef = _elementRef; + } +@@ -22,3 +22,4 @@ var MyClass1 = exports.MyClass1 = /** @class */ (function () { + ], MyClass1); + return MyClass1; + }()); ++exports.MyClass1 = MyClass1; +diff --git a/tests/baselines/reference/project/emitDecoratorMetadataSystemJSISolatedModules/amd/main.js b/tests/baselines/reference/project/emitDecoratorMetadataSystemJSISolatedModules/amd/main.js +index 523abb131..9ca20dffe 100644 +--- a/tests/baselines/reference/project/emitDecoratorMetadataSystemJSISolatedModules/amd/main.js ++++ b/tests/baselines/reference/project/emitDecoratorMetadataSystemJSISolatedModules/amd/main.js +@@ -11,7 +11,7 @@ define(["require", "exports", "angular2/core"], function (require, exports, ng) + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.MyClass1 = void 0; +- var MyClass1 = exports.MyClass1 = /** @class */ (function () { ++ var MyClass1 = /** @class */ (function () { + function MyClass1(_elementRef) { + this._elementRef = _elementRef; + } +@@ -22,4 +22,5 @@ define(["require", "exports", "angular2/core"], function (require, exports, ng) + ], MyClass1); + return MyClass1; + }()); ++ exports.MyClass1 = MyClass1; + }); +diff --git a/tests/baselines/reference/project/emitDecoratorMetadataSystemJSISolatedModules/node/main.js b/tests/baselines/reference/project/emitDecoratorMetadataSystemJSISolatedModules/node/main.js +index adbff7ffa..7a668087a 100644 +--- a/tests/baselines/reference/project/emitDecoratorMetadataSystemJSISolatedModules/node/main.js ++++ b/tests/baselines/reference/project/emitDecoratorMetadataSystemJSISolatedModules/node/main.js +@@ -11,7 +11,7 @@ var __metadata = (this && this.__metadata) || function (k, v) { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.MyClass1 = void 0; + var ng = require("angular2/core"); +-var MyClass1 = exports.MyClass1 = /** @class */ (function () { ++var MyClass1 = /** @class */ (function () { + function MyClass1(_elementRef) { + this._elementRef = _elementRef; + } +@@ -22,3 +22,4 @@ var MyClass1 = exports.MyClass1 = /** @class */ (function () { + ], MyClass1); + return MyClass1; + }()); ++exports.MyClass1 = MyClass1; +diff --git a/tests/baselines/reference/project/emitDecoratorMetadataSystemJSISolatedModulesNoResolve/amd/main.js b/tests/baselines/reference/project/emitDecoratorMetadataSystemJSISolatedModulesNoResolve/amd/main.js +index 523abb131..9ca20dffe 100644 +--- a/tests/baselines/reference/project/emitDecoratorMetadataSystemJSISolatedModulesNoResolve/amd/main.js ++++ b/tests/baselines/reference/project/emitDecoratorMetadataSystemJSISolatedModulesNoResolve/amd/main.js +@@ -11,7 +11,7 @@ define(["require", "exports", "angular2/core"], function (require, exports, ng) + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.MyClass1 = void 0; +- var MyClass1 = exports.MyClass1 = /** @class */ (function () { ++ var MyClass1 = /** @class */ (function () { + function MyClass1(_elementRef) { + this._elementRef = _elementRef; + } +@@ -22,4 +22,5 @@ define(["require", "exports", "angular2/core"], function (require, exports, ng) + ], MyClass1); + return MyClass1; + }()); ++ exports.MyClass1 = MyClass1; + }); +diff --git a/tests/baselines/reference/project/emitDecoratorMetadataSystemJSISolatedModulesNoResolve/node/main.js b/tests/baselines/reference/project/emitDecoratorMetadataSystemJSISolatedModulesNoResolve/node/main.js +index adbff7ffa..7a668087a 100644 +--- a/tests/baselines/reference/project/emitDecoratorMetadataSystemJSISolatedModulesNoResolve/node/main.js ++++ b/tests/baselines/reference/project/emitDecoratorMetadataSystemJSISolatedModulesNoResolve/node/main.js +@@ -11,7 +11,7 @@ var __metadata = (this && this.__metadata) || function (k, v) { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.MyClass1 = void 0; + var ng = require("angular2/core"); +-var MyClass1 = exports.MyClass1 = /** @class */ (function () { ++var MyClass1 = /** @class */ (function () { + function MyClass1(_elementRef) { + this._elementRef = _elementRef; + } +@@ -22,3 +22,4 @@ var MyClass1 = exports.MyClass1 = /** @class */ (function () { + ], MyClass1); + return MyClass1; + }()); ++exports.MyClass1 = MyClass1; +diff --git a/tests/baselines/reference/staticFieldWithInterfaceContext.js b/tests/baselines/reference/staticFieldWithInterfaceContext.js +index ef805ebc0..fbc525790 100644 +--- a/tests/baselines/reference/staticFieldWithInterfaceContext.js ++++ b/tests/baselines/reference/staticFieldWithInterfaceContext.js +@@ -45,15 +45,15 @@ var c = (_a = /** @class */ (function () { + _a); + c.x = { a: "a" }; + var ex = "x"; +-var c2 = (_c = /** @class */ (function () { ++var c2 = (_b = /** @class */ (function () { + function class_2() { + } + return class_2; + }()), +- _b = ex, +- __setFunctionName(_c, "c2"), +- _c[_b] = { a: "a" }, +- _c); ++ _c = ex, ++ __setFunctionName(_b, "c2"), ++ _b[_c] = { a: "a" }, ++ _b); + c[ex] = { a: "a" }; + function f(c) { + var _a; +diff --git a/tests/baselines/reference/strictModeInConstructor.js b/tests/baselines/reference/strictModeInConstructor.js +index 749e45128..c0cf843fc 100644 +--- a/tests/baselines/reference/strictModeInConstructor.js ++++ b/tests/baselines/reference/strictModeInConstructor.js +@@ -129,8 +129,8 @@ var Bs = /** @class */ (function (_super) { + var Cs = /** @class */ (function (_super) { + __extends(Cs, _super); + function Cs() { +- "use strict"; + var _this = _super.call(this) || this; ++ "use strict"; + return _this; + } + Cs.s = 9; +@@ -139,10 +139,10 @@ var Cs = /** @class */ (function (_super) { + var Ds = /** @class */ (function (_super) { + __extends(Ds, _super); + function Ds() { +- "use strict"; + var _this = this; + var x = 1; // no Error + _this = _super.call(this) || this; ++ "use strict"; + return _this; + } + Ds.s = 9; +diff --git a/tests/baselines/reference/targetEs6DecoratorMetadataImportNotElided.js b/tests/baselines/reference/targetEs6DecoratorMetadataImportNotElided.js +index 891f04581..d4781b57b 100644 +--- a/tests/baselines/reference/targetEs6DecoratorMetadataImportNotElided.js ++++ b/tests/baselines/reference/targetEs6DecoratorMetadataImportNotElided.js +@@ -35,7 +35,7 @@ var __metadata = (this && this.__metadata) || function (k, v) { + if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v); + }; + import { Input, TemplateRef } from './deps'; +-export var MyComponent = /** @class */ (function () { ++var MyComponent = /** @class */ (function () { + function MyComponent() { + } + Object.defineProperty(MyComponent.prototype, "ref", { +@@ -51,3 +51,4 @@ export var MyComponent = /** @class */ (function () { + ], MyComponent.prototype, "ref", null); + return MyComponent; + }()); ++export { MyComponent }; +diff --git a/tests/baselines/reference/templateLiteralsAndDecoratorMetadata.js b/tests/baselines/reference/templateLiteralsAndDecoratorMetadata.js +index 69bdedff6..8b28bb3a8 100644 +--- a/tests/baselines/reference/templateLiteralsAndDecoratorMetadata.js ++++ b/tests/baselines/reference/templateLiteralsAndDecoratorMetadata.js +@@ -20,7 +20,7 @@ var __metadata = (this && this.__metadata) || function (k, v) { + }; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.Greeter = void 0; +-var Greeter = exports.Greeter = /** @class */ (function () { ++var Greeter = /** @class */ (function () { + function Greeter() { + this.greeting = "employee"; //template literals on this line cause the issue + } +@@ -30,3 +30,4 @@ var Greeter = exports.Greeter = /** @class */ (function () { + ], Greeter.prototype, "greeting", void 0); + return Greeter; + }()); ++exports.Greeter = Greeter; +diff --git a/tests/baselines/reference/thisInConstructorParameter2.js b/tests/baselines/reference/thisInConstructorParameter2.js +index b8540253c..61abc7e52 100644 +--- a/tests/baselines/reference/thisInConstructorParameter2.js ++++ b/tests/baselines/reference/thisInConstructorParameter2.js +@@ -16,13 +16,13 @@ class P { + //// [thisInConstructorParameter2.js] + var P = /** @class */ (function () { + function P(z, zz, zzz) { ++ var _this = this; + if (z === void 0) { z = this; } + if (zz === void 0) { zz = this; } + if (zzz === void 0) { zzz = function (p) { + if (p === void 0) { p = _this; } + return _this; + }; } +- var _this = this; + this.z = z; + this.x = this; + zzz = function (p) { +diff --git a/tests/baselines/reference/tsc/runWithoutArgs/does-not-add-color-when-NO_COLOR-is-set.js b/tests/baselines/reference/tsc/runWithoutArgs/does-not-add-color-when-NO_COLOR-is-set.js +index 2fb4a9cc6..878fcc68e 100644 +--- a/tests/baselines/reference/tsc/runWithoutArgs/does-not-add-color-when-NO_COLOR-is-set.js ++++ b/tests/baselines/reference/tsc/runWithoutArgs/does-not-add-color-when-NO_COLOR-is-set.js +@@ -111,7 +111,7 @@ default: undefined + + --lib + Specify a set of bundled library declaration files that describe the target runtime environment. +-one or more: es5, es6/es2015, es7/es2016, es2017, es2018, es2019, es2020, es2021, es2022, es2023, esnext, dom, dom.iterable, webworker, webworker.importscripts, webworker.iterable, scripthost, es2015.core, es2015.collection, es2015.generator, es2015.iterable, es2015.promise, es2015.proxy, es2015.reflect, es2015.symbol, es2015.symbol.wellknown, es2016.array.include, es2017.date, es2017.object, es2017.sharedmemory, es2017.string, es2017.intl, es2017.typedarrays, es2018.asyncgenerator, es2018.asynciterable/esnext.asynciterable, es2018.intl, es2018.promise, es2018.regexp, es2019.array, es2019.object, es2019.string, es2019.symbol/esnext.symbol, es2019.intl, es2020.bigint/esnext.bigint, es2020.date, es2020.promise, es2020.sharedmemory, es2020.string, es2020.symbol.wellknown, es2020.intl, es2020.number, es2021.promise/esnext.promise, es2021.string, es2021.weakref/esnext.weakref, es2021.intl, es2022.array, es2022.error, es2022.intl, es2022.object, es2022.sharedmemory, es2022.string/esnext.string, es2022.regexp, es2023.array/esnext.array, es2023.collection/esnext.collection, esnext.intl, decorators, decorators.legacy ++one or more: es5, es6/es2015, es7/es2016, es2017, es2018, es2019, es2020, es2021, es2022, es2023, esnext, dom, dom.iterable, webworker, webworker.importscripts, webworker.iterable, scripthost, es2015.core, es2015.collection, es2015.generator, es2015.iterable, es2015.promise, es2015.proxy, es2015.reflect, es2015.symbol, es2015.symbol.wellknown, es2016.array.include, es2017.date, es2017.object, es2017.sharedmemory, es2017.string, es2017.intl, es2017.typedarrays, es2018.asyncgenerator, es2018.asynciterable/esnext.asynciterable, es2018.intl, es2018.promise, es2018.regexp, es2019.array, es2019.object, es2019.string, es2019.symbol/esnext.symbol, es2019.intl, es2020.bigint/esnext.bigint, es2020.date, es2020.promise, es2020.sharedmemory, es2020.string, es2020.symbol.wellknown, es2020.intl, es2020.number, es2021.promise/esnext.promise, es2021.string, es2021.weakref/esnext.weakref, es2021.intl, es2022.array, es2022.error, es2022.intl, es2022.object, es2022.sharedmemory, es2022.string/esnext.string, es2022.regexp, es2023.array/esnext.array, es2023.collection/esnext.collection, esnext.intl, esnext.disposable, decorators, decorators.legacy + default: undefined + + --allowJs +diff --git a/tests/baselines/reference/tsc/runWithoutArgs/show-help-with-ExitStatus.DiagnosticsPresent_OutputsSkipped-when-host-can't-provide-terminal-width.js b/tests/baselines/reference/tsc/runWithoutArgs/show-help-with-ExitStatus.DiagnosticsPresent_OutputsSkipped-when-host-can't-provide-terminal-width.js +index 0c77e3ad9..ac9f0f14d 100644 +--- a/tests/baselines/reference/tsc/runWithoutArgs/show-help-with-ExitStatus.DiagnosticsPresent_OutputsSkipped-when-host-can't-provide-terminal-width.js ++++ b/tests/baselines/reference/tsc/runWithoutArgs/show-help-with-ExitStatus.DiagnosticsPresent_OutputsSkipped-when-host-can't-provide-terminal-width.js +@@ -111,7 +111,7 @@ default: undefined + + --lib + Specify a set of bundled library declaration files that describe the target runtime environment. +-one or more: es5, es6/es2015, es7/es2016, es2017, es2018, es2019, es2020, es2021, es2022, es2023, esnext, dom, dom.iterable, webworker, webworker.importscripts, webworker.iterable, scripthost, es2015.core, es2015.collection, es2015.generator, es2015.iterable, es2015.promise, es2015.proxy, es2015.reflect, es2015.symbol, es2015.symbol.wellknown, es2016.array.include, es2017.date, es2017.object, es2017.sharedmemory, es2017.string, es2017.intl, es2017.typedarrays, es2018.asyncgenerator, es2018.asynciterable/esnext.asynciterable, es2018.intl, es2018.promise, es2018.regexp, es2019.array, es2019.object, es2019.string, es2019.symbol/esnext.symbol, es2019.intl, es2020.bigint/esnext.bigint, es2020.date, es2020.promise, es2020.sharedmemory, es2020.string, es2020.symbol.wellknown, es2020.intl, es2020.number, es2021.promise/esnext.promise, es2021.string, es2021.weakref/esnext.weakref, es2021.intl, es2022.array, es2022.error, es2022.intl, es2022.object, es2022.sharedmemory, es2022.string/esnext.string, es2022.regexp, es2023.array/esnext.array, es2023.collection/esnext.collection, esnext.intl, decorators, decorators.legacy ++one or more: es5, es6/es2015, es7/es2016, es2017, es2018, es2019, es2020, es2021, es2022, es2023, esnext, dom, dom.iterable, webworker, webworker.importscripts, webworker.iterable, scripthost, es2015.core, es2015.collection, es2015.generator, es2015.iterable, es2015.promise, es2015.proxy, es2015.reflect, es2015.symbol, es2015.symbol.wellknown, es2016.array.include, es2017.date, es2017.object, es2017.sharedmemory, es2017.string, es2017.intl, es2017.typedarrays, es2018.asyncgenerator, es2018.asynciterable/esnext.asynciterable, es2018.intl, es2018.promise, es2018.regexp, es2019.array, es2019.object, es2019.string, es2019.symbol/esnext.symbol, es2019.intl, es2020.bigint/esnext.bigint, es2020.date, es2020.promise, es2020.sharedmemory, es2020.string, es2020.symbol.wellknown, es2020.intl, es2020.number, es2021.promise/esnext.promise, es2021.string, es2021.weakref/esnext.weakref, es2021.intl, es2022.array, es2022.error, es2022.intl, es2022.object, es2022.sharedmemory, es2022.string/esnext.string, es2022.regexp, es2023.array/esnext.array, es2023.collection/esnext.collection, esnext.intl, esnext.disposable, decorators, decorators.legacy + default: undefined + + --allowJs +diff --git a/tests/baselines/reference/tsc/runWithoutArgs/show-help-with-ExitStatus.DiagnosticsPresent_OutputsSkipped.js b/tests/baselines/reference/tsc/runWithoutArgs/show-help-with-ExitStatus.DiagnosticsPresent_OutputsSkipped.js +index 0c77e3ad9..ac9f0f14d 100644 +--- a/tests/baselines/reference/tsc/runWithoutArgs/show-help-with-ExitStatus.DiagnosticsPresent_OutputsSkipped.js ++++ b/tests/baselines/reference/tsc/runWithoutArgs/show-help-with-ExitStatus.DiagnosticsPresent_OutputsSkipped.js +@@ -111,7 +111,7 @@ default: undefined + + --lib + Specify a set of bundled library declaration files that describe the target runtime environment. +-one or more: es5, es6/es2015, es7/es2016, es2017, es2018, es2019, es2020, es2021, es2022, es2023, esnext, dom, dom.iterable, webworker, webworker.importscripts, webworker.iterable, scripthost, es2015.core, es2015.collection, es2015.generator, es2015.iterable, es2015.promise, es2015.proxy, es2015.reflect, es2015.symbol, es2015.symbol.wellknown, es2016.array.include, es2017.date, es2017.object, es2017.sharedmemory, es2017.string, es2017.intl, es2017.typedarrays, es2018.asyncgenerator, es2018.asynciterable/esnext.asynciterable, es2018.intl, es2018.promise, es2018.regexp, es2019.array, es2019.object, es2019.string, es2019.symbol/esnext.symbol, es2019.intl, es2020.bigint/esnext.bigint, es2020.date, es2020.promise, es2020.sharedmemory, es2020.string, es2020.symbol.wellknown, es2020.intl, es2020.number, es2021.promise/esnext.promise, es2021.string, es2021.weakref/esnext.weakref, es2021.intl, es2022.array, es2022.error, es2022.intl, es2022.object, es2022.sharedmemory, es2022.string/esnext.string, es2022.regexp, es2023.array/esnext.array, es2023.collection/esnext.collection, esnext.intl, decorators, decorators.legacy ++one or more: es5, es6/es2015, es7/es2016, es2017, es2018, es2019, es2020, es2021, es2022, es2023, esnext, dom, dom.iterable, webworker, webworker.importscripts, webworker.iterable, scripthost, es2015.core, es2015.collection, es2015.generator, es2015.iterable, es2015.promise, es2015.proxy, es2015.reflect, es2015.symbol, es2015.symbol.wellknown, es2016.array.include, es2017.date, es2017.object, es2017.sharedmemory, es2017.string, es2017.intl, es2017.typedarrays, es2018.asyncgenerator, es2018.asynciterable/esnext.asynciterable, es2018.intl, es2018.promise, es2018.regexp, es2019.array, es2019.object, es2019.string, es2019.symbol/esnext.symbol, es2019.intl, es2020.bigint/esnext.bigint, es2020.date, es2020.promise, es2020.sharedmemory, es2020.string, es2020.symbol.wellknown, es2020.intl, es2020.number, es2021.promise/esnext.promise, es2021.string, es2021.weakref/esnext.weakref, es2021.intl, es2022.array, es2022.error, es2022.intl, es2022.object, es2022.sharedmemory, es2022.string/esnext.string, es2022.regexp, es2023.array/esnext.array, es2023.collection/esnext.collection, esnext.intl, esnext.disposable, decorators, decorators.legacy + default: undefined + + --allowJs +diff --git a/tests/baselines/reference/tscWatch/programUpdates/updates-diagnostics-and-emit-for-decorators.js b/tests/baselines/reference/tscWatch/programUpdates/updates-diagnostics-and-emit-for-decorators.js +index cc323419f..d0faf0c6d 100644 +--- a/tests/baselines/reference/tscWatch/programUpdates/updates-diagnostics-and-emit-for-decorators.js ++++ b/tests/baselines/reference/tscWatch/programUpdates/updates-diagnostics-and-emit-for-decorators.js +@@ -118,7 +118,7 @@ var __setFunctionName = (this && this.__setFunctionName) || function (f, name, p + return Object.defineProperty(f, "name", { configurable: true, value: prefix ? "".concat(prefix, " ", name) : name }); + }; + import './b'; +-export let A = (() => { ++let A = (() => { + let _classDecorators = [((_) => { })]; + let _classDescriptor; + let _classExtraInitializers = []; +@@ -134,6 +134,7 @@ export let A = (() => { + })(); + return A = _classThis; + })(); ++export { A }; + + + +@@ -184,12 +185,13 @@ var __decorate = (this && this.__decorate) || function (decorators, target, key, + return c > 3 && r && Object.defineProperty(target, key, r), r; + }; + import './b'; +-export let A = class A { ++let A = class A { + constructor(p) { } + }; + A = __decorate([ + ((_) => { }) + ], A); ++export { A }; + + + +@@ -243,12 +245,13 @@ var __metadata = (this && this.__metadata) || function (k, v) { + if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v); + }; + import { B } from './b'; +-export let A = class A { ++let A = class A { + constructor(p) { } + }; + A = __decorate([ + ((_) => { }), + __metadata("design:paramtypes", [B]) + ], A); ++export { A }; + + +diff --git a/tests/baselines/reference/tslibReExportHelpers.js b/tests/baselines/reference/tslibReExportHelpers.js +index 033bd963f..db2f3a48c 100644 +--- a/tests/baselines/reference/tslibReExportHelpers.js ++++ b/tests/baselines/reference/tslibReExportHelpers.js +@@ -29,7 +29,7 @@ export class Foo {} + + //// [index.mjs] + import { __decorate } from "tslib"; +-export var Foo = /** @class */ (function () { ++var Foo = /** @class */ (function () { + function Foo() { + } + Foo = __decorate([ +@@ -37,3 +37,4 @@ export var Foo = /** @class */ (function () { + ], Foo); + return Foo; + }()); ++export { Foo }; +diff --git a/tests/baselines/reference/tsserver/telemetry/does-not-expose-paths.js b/tests/baselines/reference/tsserver/telemetry/does-not-expose-paths.js +index 31410efa3..e3392cc15 100644 +--- a/tests/baselines/reference/tsserver/telemetry/does-not-expose-paths.js ++++ b/tests/baselines/reference/tsserver/telemetry/does-not-expose-paths.js +@@ -430,7 +430,7 @@ Info seq [hh:mm:ss:mss] event: + "line": 1, + "offset": 431 + }, +- "text": "Argument for '--lib' option must be: 'es5', 'es6', 'es2015', 'es7', 'es2016', 'es2017', 'es2018', 'es2019', 'es2020', 'es2021', 'es2022', 'es2023', 'esnext', 'dom', 'dom.iterable', 'webworker', 'webworker.importscripts', 'webworker.iterable', 'scripthost', 'es2015.core', 'es2015.collection', 'es2015.generator', 'es2015.iterable', 'es2015.promise', 'es2015.proxy', 'es2015.reflect', 'es2015.symbol', 'es2015.symbol.wellknown', 'es2016.array.include', 'es2017.date', 'es2017.object', 'es2017.sharedmemory', 'es2017.string', 'es2017.intl', 'es2017.typedarrays', 'es2018.asyncgenerator', 'es2018.asynciterable', 'es2018.intl', 'es2018.promise', 'es2018.regexp', 'es2019.array', 'es2019.object', 'es2019.string', 'es2019.symbol', 'es2019.intl', 'es2020.bigint', 'es2020.date', 'es2020.promise', 'es2020.sharedmemory', 'es2020.string', 'es2020.symbol.wellknown', 'es2020.intl', 'es2020.number', 'es2021.promise', 'es2021.string', 'es2021.weakref', 'es2021.intl', 'es2022.array', 'es2022.error', 'es2022.intl', 'es2022.object', 'es2022.sharedmemory', 'es2022.string', 'es2022.regexp', 'es2023.array', 'es2023.collection', 'esnext.array', 'esnext.collection', 'esnext.symbol', 'esnext.asynciterable', 'esnext.intl', 'esnext.bigint', 'esnext.string', 'esnext.promise', 'esnext.weakref', 'decorators', 'decorators.legacy'.", ++ "text": "Argument for '--lib' option must be: 'es5', 'es6', 'es2015', 'es7', 'es2016', 'es2017', 'es2018', 'es2019', 'es2020', 'es2021', 'es2022', 'es2023', 'esnext', 'dom', 'dom.iterable', 'webworker', 'webworker.importscripts', 'webworker.iterable', 'scripthost', 'es2015.core', 'es2015.collection', 'es2015.generator', 'es2015.iterable', 'es2015.promise', 'es2015.proxy', 'es2015.reflect', 'es2015.symbol', 'es2015.symbol.wellknown', 'es2016.array.include', 'es2017.date', 'es2017.object', 'es2017.sharedmemory', 'es2017.string', 'es2017.intl', 'es2017.typedarrays', 'es2018.asyncgenerator', 'es2018.asynciterable', 'es2018.intl', 'es2018.promise', 'es2018.regexp', 'es2019.array', 'es2019.object', 'es2019.string', 'es2019.symbol', 'es2019.intl', 'es2020.bigint', 'es2020.date', 'es2020.promise', 'es2020.sharedmemory', 'es2020.string', 'es2020.symbol.wellknown', 'es2020.intl', 'es2020.number', 'es2021.promise', 'es2021.string', 'es2021.weakref', 'es2021.intl', 'es2022.array', 'es2022.error', 'es2022.intl', 'es2022.object', 'es2022.sharedmemory', 'es2022.string', 'es2022.regexp', 'es2023.array', 'es2023.collection', 'esnext.array', 'esnext.collection', 'esnext.symbol', 'esnext.asynciterable', 'esnext.intl', 'esnext.disposable', 'esnext.bigint', 'esnext.string', 'esnext.promise', 'esnext.weakref', 'decorators', 'decorators.legacy'.", + "code": 6046, + "category": "error", + "fileName": "/tsconfig.json" +diff --git a/tests/baselines/reference/typesVersions.ambientModules.trace.json b/tests/baselines/reference/typesVersions.ambientModules.trace.json +index 0a410f50e..3adfc2c0d 100644 +--- a/tests/baselines/reference/typesVersions.ambientModules.trace.json ++++ b/tests/baselines/reference/typesVersions.ambientModules.trace.json +@@ -786,6 +786,18 @@ + "Searching all ancestor node_modules directories for fallback extensions: JavaScript.", + "Directory '/node_modules' does not exist, skipping all lookups in it.", + "======== Module name '@typescript/lib-esnext/intl' was not resolved. ========", ++ "======== Resolving module '@typescript/lib-esnext/disposable' from '/.src/__lib_node_modules_lookup_lib.esnext.disposable.d.ts__.ts'. ========", ++ "Explicitly specified module resolution kind: 'Node10'.", ++ "Loading module '@typescript/lib-esnext/disposable' from 'node_modules' folder, target file types: TypeScript, Declaration.", ++ "Searching all ancestor node_modules directories for preferred extensions: TypeScript, Declaration.", ++ "Directory '/.src/node_modules/@types' does not exist, skipping all lookups in it.", ++ "Scoped package detected, looking in 'typescript__lib-esnext/disposable'", ++ "Directory '/node_modules' does not exist, skipping all lookups in it.", ++ "Scoped package detected, looking in 'typescript__lib-esnext/disposable'", ++ "Loading module '@typescript/lib-esnext/disposable' from 'node_modules' folder, target file types: JavaScript.", ++ "Searching all ancestor node_modules directories for fallback extensions: JavaScript.", ++ "Directory '/node_modules' does not exist, skipping all lookups in it.", ++ "======== Module name '@typescript/lib-esnext/disposable' was not resolved. ========", + "======== Resolving module '@typescript/lib-dom' from '/.src/__lib_node_modules_lookup_lib.dom.d.ts__.ts'. ========", + "Explicitly specified module resolution kind: 'Node10'.", + "Loading module '@typescript/lib-dom' from 'node_modules' folder, target file types: TypeScript, Declaration.", +diff --git a/tests/baselines/reference/typesVersions.emptyTypes.trace.json b/tests/baselines/reference/typesVersions.emptyTypes.trace.json +index 8d0744b55..2fd6b050c 100644 +--- a/tests/baselines/reference/typesVersions.emptyTypes.trace.json ++++ b/tests/baselines/reference/typesVersions.emptyTypes.trace.json +@@ -814,6 +814,19 @@ + "Directory '/.src/node_modules' does not exist, skipping all lookups in it.", + "Directory '/node_modules' does not exist, skipping all lookups in it.", + "======== Module name '@typescript/lib-esnext/intl' was not resolved. ========", ++ "======== Resolving module '@typescript/lib-esnext/disposable' from '/.src/__lib_node_modules_lookup_lib.esnext.disposable.d.ts__.ts'. ========", ++ "Explicitly specified module resolution kind: 'Node10'.", ++ "Loading module '@typescript/lib-esnext/disposable' from 'node_modules' folder, target file types: TypeScript, Declaration.", ++ "Searching all ancestor node_modules directories for preferred extensions: TypeScript, Declaration.", ++ "Directory '/.src/node_modules' does not exist, skipping all lookups in it.", ++ "Scoped package detected, looking in 'typescript__lib-esnext/disposable'", ++ "Directory '/node_modules' does not exist, skipping all lookups in it.", ++ "Scoped package detected, looking in 'typescript__lib-esnext/disposable'", ++ "Loading module '@typescript/lib-esnext/disposable' from 'node_modules' folder, target file types: JavaScript.", ++ "Searching all ancestor node_modules directories for fallback extensions: JavaScript.", ++ "Directory '/.src/node_modules' does not exist, skipping all lookups in it.", ++ "Directory '/node_modules' does not exist, skipping all lookups in it.", ++ "======== Module name '@typescript/lib-esnext/disposable' was not resolved. ========", + "======== Resolving module '@typescript/lib-dom' from '/.src/__lib_node_modules_lookup_lib.dom.d.ts__.ts'. ========", + "Explicitly specified module resolution kind: 'Node10'.", + "Loading module '@typescript/lib-dom' from 'node_modules' folder, target file types: TypeScript, Declaration.", +diff --git a/tests/baselines/reference/typesVersions.justIndex.trace.json b/tests/baselines/reference/typesVersions.justIndex.trace.json +index 3ae541cf1..bd509b985 100644 +--- a/tests/baselines/reference/typesVersions.justIndex.trace.json ++++ b/tests/baselines/reference/typesVersions.justIndex.trace.json +@@ -814,6 +814,19 @@ + "Directory '/.src/node_modules' does not exist, skipping all lookups in it.", + "Directory '/node_modules' does not exist, skipping all lookups in it.", + "======== Module name '@typescript/lib-esnext/intl' was not resolved. ========", ++ "======== Resolving module '@typescript/lib-esnext/disposable' from '/.src/__lib_node_modules_lookup_lib.esnext.disposable.d.ts__.ts'. ========", ++ "Explicitly specified module resolution kind: 'Node10'.", ++ "Loading module '@typescript/lib-esnext/disposable' from 'node_modules' folder, target file types: TypeScript, Declaration.", ++ "Searching all ancestor node_modules directories for preferred extensions: TypeScript, Declaration.", ++ "Directory '/.src/node_modules' does not exist, skipping all lookups in it.", ++ "Scoped package detected, looking in 'typescript__lib-esnext/disposable'", ++ "Directory '/node_modules' does not exist, skipping all lookups in it.", ++ "Scoped package detected, looking in 'typescript__lib-esnext/disposable'", ++ "Loading module '@typescript/lib-esnext/disposable' from 'node_modules' folder, target file types: JavaScript.", ++ "Searching all ancestor node_modules directories for fallback extensions: JavaScript.", ++ "Directory '/.src/node_modules' does not exist, skipping all lookups in it.", ++ "Directory '/node_modules' does not exist, skipping all lookups in it.", ++ "======== Module name '@typescript/lib-esnext/disposable' was not resolved. ========", + "======== Resolving module '@typescript/lib-dom' from '/.src/__lib_node_modules_lookup_lib.dom.d.ts__.ts'. ========", + "Explicitly specified module resolution kind: 'Node10'.", + "Loading module '@typescript/lib-dom' from 'node_modules' folder, target file types: TypeScript, Declaration.", +diff --git a/tests/baselines/reference/typesVersions.multiFile.trace.json b/tests/baselines/reference/typesVersions.multiFile.trace.json +index defb376cb..b3f0b7ef2 100644 +--- a/tests/baselines/reference/typesVersions.multiFile.trace.json ++++ b/tests/baselines/reference/typesVersions.multiFile.trace.json +@@ -765,6 +765,18 @@ + "Searching all ancestor node_modules directories for fallback extensions: JavaScript.", + "Directory '/node_modules' does not exist, skipping all lookups in it.", + "======== Module name '@typescript/lib-esnext/intl' was not resolved. ========", ++ "======== Resolving module '@typescript/lib-esnext/disposable' from '/.src/__lib_node_modules_lookup_lib.esnext.disposable.d.ts__.ts'. ========", ++ "Explicitly specified module resolution kind: 'Node10'.", ++ "Loading module '@typescript/lib-esnext/disposable' from 'node_modules' folder, target file types: TypeScript, Declaration.", ++ "Searching all ancestor node_modules directories for preferred extensions: TypeScript, Declaration.", ++ "Directory '/.src/node_modules/@types' does not exist, skipping all lookups in it.", ++ "Scoped package detected, looking in 'typescript__lib-esnext/disposable'", ++ "Directory '/node_modules' does not exist, skipping all lookups in it.", ++ "Scoped package detected, looking in 'typescript__lib-esnext/disposable'", ++ "Loading module '@typescript/lib-esnext/disposable' from 'node_modules' folder, target file types: JavaScript.", ++ "Searching all ancestor node_modules directories for fallback extensions: JavaScript.", ++ "Directory '/node_modules' does not exist, skipping all lookups in it.", ++ "======== Module name '@typescript/lib-esnext/disposable' was not resolved. ========", + "======== Resolving module '@typescript/lib-dom' from '/.src/__lib_node_modules_lookup_lib.dom.d.ts__.ts'. ========", + "Explicitly specified module resolution kind: 'Node10'.", + "Loading module '@typescript/lib-dom' from 'node_modules' folder, target file types: TypeScript, Declaration.", +diff --git a/tests/baselines/reference/typesVersionsDeclarationEmit.ambient.trace.json b/tests/baselines/reference/typesVersionsDeclarationEmit.ambient.trace.json +index 0a410f50e..3adfc2c0d 100644 +--- a/tests/baselines/reference/typesVersionsDeclarationEmit.ambient.trace.json ++++ b/tests/baselines/reference/typesVersionsDeclarationEmit.ambient.trace.json +@@ -786,6 +786,18 @@ + "Searching all ancestor node_modules directories for fallback extensions: JavaScript.", + "Directory '/node_modules' does not exist, skipping all lookups in it.", + "======== Module name '@typescript/lib-esnext/intl' was not resolved. ========", ++ "======== Resolving module '@typescript/lib-esnext/disposable' from '/.src/__lib_node_modules_lookup_lib.esnext.disposable.d.ts__.ts'. ========", ++ "Explicitly specified module resolution kind: 'Node10'.", ++ "Loading module '@typescript/lib-esnext/disposable' from 'node_modules' folder, target file types: TypeScript, Declaration.", ++ "Searching all ancestor node_modules directories for preferred extensions: TypeScript, Declaration.", ++ "Directory '/.src/node_modules/@types' does not exist, skipping all lookups in it.", ++ "Scoped package detected, looking in 'typescript__lib-esnext/disposable'", ++ "Directory '/node_modules' does not exist, skipping all lookups in it.", ++ "Scoped package detected, looking in 'typescript__lib-esnext/disposable'", ++ "Loading module '@typescript/lib-esnext/disposable' from 'node_modules' folder, target file types: JavaScript.", ++ "Searching all ancestor node_modules directories for fallback extensions: JavaScript.", ++ "Directory '/node_modules' does not exist, skipping all lookups in it.", ++ "======== Module name '@typescript/lib-esnext/disposable' was not resolved. ========", + "======== Resolving module '@typescript/lib-dom' from '/.src/__lib_node_modules_lookup_lib.dom.d.ts__.ts'. ========", + "Explicitly specified module resolution kind: 'Node10'.", + "Loading module '@typescript/lib-dom' from 'node_modules' folder, target file types: TypeScript, Declaration.", +diff --git a/tests/baselines/reference/typesVersionsDeclarationEmit.multiFile.trace.json b/tests/baselines/reference/typesVersionsDeclarationEmit.multiFile.trace.json +index defb376cb..b3f0b7ef2 100644 +--- a/tests/baselines/reference/typesVersionsDeclarationEmit.multiFile.trace.json ++++ b/tests/baselines/reference/typesVersionsDeclarationEmit.multiFile.trace.json +@@ -765,6 +765,18 @@ + "Searching all ancestor node_modules directories for fallback extensions: JavaScript.", + "Directory '/node_modules' does not exist, skipping all lookups in it.", + "======== Module name '@typescript/lib-esnext/intl' was not resolved. ========", ++ "======== Resolving module '@typescript/lib-esnext/disposable' from '/.src/__lib_node_modules_lookup_lib.esnext.disposable.d.ts__.ts'. ========", ++ "Explicitly specified module resolution kind: 'Node10'.", ++ "Loading module '@typescript/lib-esnext/disposable' from 'node_modules' folder, target file types: TypeScript, Declaration.", ++ "Searching all ancestor node_modules directories for preferred extensions: TypeScript, Declaration.", ++ "Directory '/.src/node_modules/@types' does not exist, skipping all lookups in it.", ++ "Scoped package detected, looking in 'typescript__lib-esnext/disposable'", ++ "Directory '/node_modules' does not exist, skipping all lookups in it.", ++ "Scoped package detected, looking in 'typescript__lib-esnext/disposable'", ++ "Loading module '@typescript/lib-esnext/disposable' from 'node_modules' folder, target file types: JavaScript.", ++ "Searching all ancestor node_modules directories for fallback extensions: JavaScript.", ++ "Directory '/node_modules' does not exist, skipping all lookups in it.", ++ "======== Module name '@typescript/lib-esnext/disposable' was not resolved. ========", + "======== Resolving module '@typescript/lib-dom' from '/.src/__lib_node_modules_lookup_lib.dom.d.ts__.ts'. ========", + "Explicitly specified module resolution kind: 'Node10'.", + "Loading module '@typescript/lib-dom' from 'node_modules' folder, target file types: TypeScript, Declaration.", +diff --git a/tests/baselines/reference/typesVersionsDeclarationEmit.multiFileBackReferenceToSelf.trace.json b/tests/baselines/reference/typesVersionsDeclarationEmit.multiFileBackReferenceToSelf.trace.json +index 14703ef05..d6eea6bd7 100644 +--- a/tests/baselines/reference/typesVersionsDeclarationEmit.multiFileBackReferenceToSelf.trace.json ++++ b/tests/baselines/reference/typesVersionsDeclarationEmit.multiFileBackReferenceToSelf.trace.json +@@ -788,6 +788,18 @@ + "Searching all ancestor node_modules directories for fallback extensions: JavaScript.", + "Directory '/node_modules' does not exist, skipping all lookups in it.", + "======== Module name '@typescript/lib-esnext/intl' was not resolved. ========", ++ "======== Resolving module '@typescript/lib-esnext/disposable' from '/.src/__lib_node_modules_lookup_lib.esnext.disposable.d.ts__.ts'. ========", ++ "Explicitly specified module resolution kind: 'Node10'.", ++ "Loading module '@typescript/lib-esnext/disposable' from 'node_modules' folder, target file types: TypeScript, Declaration.", ++ "Searching all ancestor node_modules directories for preferred extensions: TypeScript, Declaration.", ++ "Directory '/.src/node_modules/@types' does not exist, skipping all lookups in it.", ++ "Scoped package detected, looking in 'typescript__lib-esnext/disposable'", ++ "Directory '/node_modules' does not exist, skipping all lookups in it.", ++ "Scoped package detected, looking in 'typescript__lib-esnext/disposable'", ++ "Loading module '@typescript/lib-esnext/disposable' from 'node_modules' folder, target file types: JavaScript.", ++ "Searching all ancestor node_modules directories for fallback extensions: JavaScript.", ++ "Directory '/node_modules' does not exist, skipping all lookups in it.", ++ "======== Module name '@typescript/lib-esnext/disposable' was not resolved. ========", + "======== Resolving module '@typescript/lib-dom' from '/.src/__lib_node_modules_lookup_lib.dom.d.ts__.ts'. ========", + "Explicitly specified module resolution kind: 'Node10'.", + "Loading module '@typescript/lib-dom' from 'node_modules' folder, target file types: TypeScript, Declaration.", +diff --git a/tests/baselines/reference/typesVersionsDeclarationEmit.multiFileBackReferenceToUnmapped.trace.json b/tests/baselines/reference/typesVersionsDeclarationEmit.multiFileBackReferenceToUnmapped.trace.json +index 009cab1a5..c8bb8ebcf 100644 +--- a/tests/baselines/reference/typesVersionsDeclarationEmit.multiFileBackReferenceToUnmapped.trace.json ++++ b/tests/baselines/reference/typesVersionsDeclarationEmit.multiFileBackReferenceToUnmapped.trace.json +@@ -771,6 +771,18 @@ + "Searching all ancestor node_modules directories for fallback extensions: JavaScript.", + "Directory '/node_modules' does not exist, skipping all lookups in it.", + "======== Module name '@typescript/lib-esnext/intl' was not resolved. ========", ++ "======== Resolving module '@typescript/lib-esnext/disposable' from '/.src/__lib_node_modules_lookup_lib.esnext.disposable.d.ts__.ts'. ========", ++ "Explicitly specified module resolution kind: 'Node10'.", ++ "Loading module '@typescript/lib-esnext/disposable' from 'node_modules' folder, target file types: TypeScript, Declaration.", ++ "Searching all ancestor node_modules directories for preferred extensions: TypeScript, Declaration.", ++ "Directory '/.src/node_modules/@types' does not exist, skipping all lookups in it.", ++ "Scoped package detected, looking in 'typescript__lib-esnext/disposable'", ++ "Directory '/node_modules' does not exist, skipping all lookups in it.", ++ "Scoped package detected, looking in 'typescript__lib-esnext/disposable'", ++ "Loading module '@typescript/lib-esnext/disposable' from 'node_modules' folder, target file types: JavaScript.", ++ "Searching all ancestor node_modules directories for fallback extensions: JavaScript.", ++ "Directory '/node_modules' does not exist, skipping all lookups in it.", ++ "======== Module name '@typescript/lib-esnext/disposable' was not resolved. ========", + "======== Resolving module '@typescript/lib-dom' from '/.src/__lib_node_modules_lookup_lib.dom.d.ts__.ts'. ========", + "Explicitly specified module resolution kind: 'Node10'.", + "Loading module '@typescript/lib-dom' from 'node_modules' folder, target file types: TypeScript, Declaration.", +diff --git a/tests/baselines/reference/usingDeclarations.1(target=es2015).js b/tests/baselines/reference/usingDeclarations.1(target=es2015).js +new file mode 100644 +index 000000000..c10bc21fb +--- /dev/null ++++ b/tests/baselines/reference/usingDeclarations.1(target=es2015).js +@@ -0,0 +1,665 @@ ++//// [tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarations.1.ts] //// ++ ++//// [usingDeclarations.1.ts] ++using d1 = { [Symbol.dispose]() {} }; ++ ++function f() { ++ using d2 = { [Symbol.dispose]() {} }; ++} ++ ++async function af() { ++ using d3 = { [Symbol.dispose]() {} }; ++ await null; ++} ++ ++function * g() { ++ using d4 = { [Symbol.dispose]() {} }; ++ yield; ++} ++ ++async function * ag() { ++ using d5 = { [Symbol.dispose]() {} }; ++ yield; ++ await null; ++} ++ ++const a = () => { ++ using d6 = { [Symbol.dispose]() {} }; ++} ++ ++class C1 { ++ a = () => { ++ using d7 = { [Symbol.dispose]() {} }; ++ } ++ ++ constructor() { ++ using d8 = { [Symbol.dispose]() {} }; ++ } ++ ++ static { ++ using d9 = { [Symbol.dispose]() {} }; ++ } ++ ++ m() { ++ using d10 = { [Symbol.dispose]() {} }; ++ } ++ ++ get x() { ++ using d11 = { [Symbol.dispose]() {} }; ++ return 0; ++ } ++ ++ set x(v) { ++ using d12 = { [Symbol.dispose]() {} }; ++ } ++ ++ async am() { ++ using d13 = { [Symbol.dispose]() {} }; ++ await null; ++ } ++ ++ * g() { ++ using d14 = { [Symbol.dispose]() {} }; ++ yield; ++ } ++ ++ async * ag() { ++ using d15 = { [Symbol.dispose]() {} }; ++ yield; ++ await null; ++ } ++} ++ ++class C2 extends C1 { ++ constructor() { ++ using d16 = { [Symbol.dispose]() {} }; ++ super(); ++ } ++} ++ ++class C3 extends C1 { ++ y = 1; ++ constructor() { ++ using d17 = { [Symbol.dispose]() {} }; ++ super(); ++ } ++} ++ ++namespace N { ++ using d18 = { [Symbol.dispose]() {} }; ++} ++ ++{ ++ using d19 = { [Symbol.dispose]() {} }; ++} ++ ++switch (Math.random()) { ++ case 0: ++ using d20 = { [Symbol.dispose]() {} }; ++ break; ++ ++ case 1: ++ using d21 = { [Symbol.dispose]() {} }; ++ break; ++} ++ ++if (true) ++ switch (0) { ++ case 0: ++ using d22 = { [Symbol.dispose]() {} }; ++ break; ++ } ++ ++try { ++ using d23 = { [Symbol.dispose]() {} }; ++} ++catch { ++ using d24 = { [Symbol.dispose]() {} }; ++} ++finally { ++ using d25 = { [Symbol.dispose]() {} }; ++} ++ ++if (true) { ++ using d26 = { [Symbol.dispose]() {} }; ++} ++else { ++ using d27 = { [Symbol.dispose]() {} }; ++} ++ ++while (true) { ++ using d28 = { [Symbol.dispose]() {} }; ++ break; ++} ++ ++do { ++ using d29 = { [Symbol.dispose]() {} }; ++ break; ++} ++while (true); ++ ++for (;;) { ++ using d30 = { [Symbol.dispose]() {} }; ++ break; ++} ++ ++for (const x in {}) { ++ using d31 = { [Symbol.dispose]() {} }; ++} ++ ++for (const x of []) { ++ using d32 = { [Symbol.dispose]() {} }; ++} ++ ++export {}; ++ ++//// [usingDeclarations.1.js] ++var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { ++ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } ++ return new (P || (P = Promise))(function (resolve, reject) { ++ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } ++ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } ++ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } ++ step((generator = generator.apply(thisArg, _arguments || [])).next()); ++ }); ++}; ++var __addDisposableResource = (this && this.__addDisposableResource) || function (env, value, async) { ++ if (value !== null && value !== void 0) { ++ if (typeof value !== "object") throw new TypeError("Object expected."); ++ var dispose; ++ if (async) { ++ if (!Symbol.asyncDispose) throw new TypeError("Symbol.asyncDispose is not defined."); ++ dispose = value[Symbol.asyncDispose]; ++ } ++ if (dispose === void 0) { ++ if (!Symbol.dispose) throw new TypeError("Symbol.dispose is not defined."); ++ dispose = value[Symbol.dispose]; ++ } ++ if (typeof dispose !== "function") throw new TypeError("Object not disposable."); ++ env.stack.push({ value: value, dispose: dispose, async: async }); ++ } ++ else if (async) { ++ env.stack.push({ async: true }); ++ } ++ return value; ++}; ++var __disposeResources = (this && this.__disposeResources) || (function (SuppressedError) { ++ return function (env) { ++ function fail(e) { ++ env.error = env.hasError ? new SuppressedError(e, env.error, "An error was suppressed during disposal.") : e; ++ env.hasError = true; ++ } ++ function next() { ++ while (env.stack.length) { ++ var rec = env.stack.pop(); ++ try { ++ var result = rec.dispose && rec.dispose.call(rec.value); ++ if (rec.async) return Promise.resolve(result).then(next, function(e) { fail(e); return next(); }); ++ } ++ catch (e) { ++ fail(e); ++ } ++ } ++ if (env.hasError) throw env.error; ++ } ++ return next(); ++ }; ++})(typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) { ++ var e = new Error(message); ++ return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e; ++}); ++var __await = (this && this.__await) || function (v) { return this instanceof __await ? (this.v = v, this) : new __await(v); } ++var __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _arguments, generator) { ++ if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); ++ var g = generator.apply(thisArg, _arguments || []), i, q = []; ++ return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i; ++ function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; } ++ function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } } ++ function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); } ++ function fulfill(value) { resume("next", value); } ++ function reject(value) { resume("throw", value); } ++ function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); } ++}; ++var _a; ++function f() { ++ const env_15 = { stack: [], error: void 0, hasError: false }; ++ try { ++ const d2 = __addDisposableResource(env_15, { [Symbol.dispose]() { } }, false); ++ } ++ catch (e_15) { ++ env_15.error = e_15; ++ env_15.hasError = true; ++ } ++ finally { ++ __disposeResources(env_15); ++ } ++} ++function af() { ++ return __awaiter(this, void 0, void 0, function* () { ++ const env_16 = { stack: [], error: void 0, hasError: false }; ++ try { ++ const d3 = __addDisposableResource(env_16, { [Symbol.dispose]() { } }, false); ++ yield null; ++ } ++ catch (e_16) { ++ env_16.error = e_16; ++ env_16.hasError = true; ++ } ++ finally { ++ __disposeResources(env_16); ++ } ++ }); ++} ++function* g() { ++ const env_17 = { stack: [], error: void 0, hasError: false }; ++ try { ++ const d4 = __addDisposableResource(env_17, { [Symbol.dispose]() { } }, false); ++ yield; ++ } ++ catch (e_17) { ++ env_17.error = e_17; ++ env_17.hasError = true; ++ } ++ finally { ++ __disposeResources(env_17); ++ } ++} ++function ag() { ++ return __asyncGenerator(this, arguments, function* ag_1() { ++ const env_18 = { stack: [], error: void 0, hasError: false }; ++ try { ++ const d5 = __addDisposableResource(env_18, { [Symbol.dispose]() { } }, false); ++ yield yield __await(void 0); ++ yield __await(null); ++ } ++ catch (e_18) { ++ env_18.error = e_18; ++ env_18.hasError = true; ++ } ++ finally { ++ __disposeResources(env_18); ++ } ++ }); ++} ++var d1, a, C1, C2, C3, N, env_1; ++const env_2 = { stack: [], error: void 0, hasError: false }; ++try { ++ d1 = __addDisposableResource(env_2, { [Symbol.dispose]() { } }, false); ++ a = () => { ++ const env_19 = { stack: [], error: void 0, hasError: false }; ++ try { ++ const d6 = __addDisposableResource(env_19, { [Symbol.dispose]() { } }, false); ++ } ++ catch (e_19) { ++ env_19.error = e_19; ++ env_19.hasError = true; ++ } ++ finally { ++ __disposeResources(env_19); ++ } ++ }; ++ C1 = (_a = class C1 { ++ constructor() { ++ this.a = () => { ++ const env_21 = { stack: [], error: void 0, hasError: false }; ++ try { ++ const d7 = __addDisposableResource(env_21, { [Symbol.dispose]() { } }, false); ++ } ++ catch (e_21) { ++ env_21.error = e_21; ++ env_21.hasError = true; ++ } ++ finally { ++ __disposeResources(env_21); ++ } ++ }; ++ const env_20 = { stack: [], error: void 0, hasError: false }; ++ try { ++ const d8 = __addDisposableResource(env_20, { [Symbol.dispose]() { } }, false); ++ } ++ catch (e_20) { ++ env_20.error = e_20; ++ env_20.hasError = true; ++ } ++ finally { ++ __disposeResources(env_20); ++ } ++ } ++ m() { ++ const env_22 = { stack: [], error: void 0, hasError: false }; ++ try { ++ const d10 = __addDisposableResource(env_22, { [Symbol.dispose]() { } }, false); ++ } ++ catch (e_22) { ++ env_22.error = e_22; ++ env_22.hasError = true; ++ } ++ finally { ++ __disposeResources(env_22); ++ } ++ } ++ get x() { ++ const env_23 = { stack: [], error: void 0, hasError: false }; ++ try { ++ const d11 = __addDisposableResource(env_23, { [Symbol.dispose]() { } }, false); ++ return 0; ++ } ++ catch (e_23) { ++ env_23.error = e_23; ++ env_23.hasError = true; ++ } ++ finally { ++ __disposeResources(env_23); ++ } ++ } ++ set x(v) { ++ const env_24 = { stack: [], error: void 0, hasError: false }; ++ try { ++ const d12 = __addDisposableResource(env_24, { [Symbol.dispose]() { } }, false); ++ } ++ catch (e_24) { ++ env_24.error = e_24; ++ env_24.hasError = true; ++ } ++ finally { ++ __disposeResources(env_24); ++ } ++ } ++ am() { ++ return __awaiter(this, void 0, void 0, function* () { ++ const env_25 = { stack: [], error: void 0, hasError: false }; ++ try { ++ const d13 = __addDisposableResource(env_25, { [Symbol.dispose]() { } }, false); ++ yield null; ++ } ++ catch (e_25) { ++ env_25.error = e_25; ++ env_25.hasError = true; ++ } ++ finally { ++ __disposeResources(env_25); ++ } ++ }); ++ } ++ *g() { ++ const env_26 = { stack: [], error: void 0, hasError: false }; ++ try { ++ const d14 = __addDisposableResource(env_26, { [Symbol.dispose]() { } }, false); ++ yield; ++ } ++ catch (e_26) { ++ env_26.error = e_26; ++ env_26.hasError = true; ++ } ++ finally { ++ __disposeResources(env_26); ++ } ++ } ++ ag() { ++ return __asyncGenerator(this, arguments, function* ag_2() { ++ const env_27 = { stack: [], error: void 0, hasError: false }; ++ try { ++ const d15 = __addDisposableResource(env_27, { [Symbol.dispose]() { } }, false); ++ yield yield __await(void 0); ++ yield __await(null); ++ } ++ catch (e_27) { ++ env_27.error = e_27; ++ env_27.hasError = true; ++ } ++ finally { ++ __disposeResources(env_27); ++ } ++ }); ++ } ++ }, ++ (() => { ++ const env_28 = { stack: [], error: void 0, hasError: false }; ++ try { ++ const d9 = __addDisposableResource(env_28, { [Symbol.dispose]() { } }, false); ++ } ++ catch (e_28) { ++ env_28.error = e_28; ++ env_28.hasError = true; ++ } ++ finally { ++ __disposeResources(env_28); ++ } ++ })(), ++ _a); ++ C2 = class C2 extends C1 { ++ constructor() { ++ const env_29 = { stack: [], error: void 0, hasError: false }; ++ try { ++ const d16 = __addDisposableResource(env_29, { [Symbol.dispose]() { } }, false); ++ super(); ++ } ++ catch (e_29) { ++ env_29.error = e_29; ++ env_29.hasError = true; ++ } ++ finally { ++ __disposeResources(env_29); ++ } ++ } ++ }; ++ C3 = class C3 extends C1 { ++ constructor() { ++ const env_30 = { stack: [], error: void 0, hasError: false }; ++ try { ++ const d17 = __addDisposableResource(env_30, { [Symbol.dispose]() { } }, false); ++ super(); ++ this.y = 1; ++ } ++ catch (e_30) { ++ env_30.error = e_30; ++ env_30.hasError = true; ++ } ++ finally { ++ __disposeResources(env_30); ++ } ++ } ++ }; ++ (function (N) { ++ const env_31 = { stack: [], error: void 0, hasError: false }; ++ try { ++ const d18 = __addDisposableResource(env_31, { [Symbol.dispose]() { } }, false); ++ } ++ catch (e_31) { ++ env_31.error = e_31; ++ env_31.hasError = true; ++ } ++ finally { ++ __disposeResources(env_31); ++ } ++ })(N || (N = {})); ++ { ++ const env_3 = { stack: [], error: void 0, hasError: false }; ++ try { ++ const d19 = __addDisposableResource(env_3, { [Symbol.dispose]() { } }, false); ++ } ++ catch (e_1) { ++ env_3.error = e_1; ++ env_3.hasError = true; ++ } ++ finally { ++ __disposeResources(env_3); ++ } ++ } ++ env_1 = { stack: [], error: void 0, hasError: false }; ++ try { ++ switch (Math.random()) { ++ case 0: ++ const d20 = __addDisposableResource(env_1, { [Symbol.dispose]() { } }, false); ++ break; ++ case 1: ++ const d21 = __addDisposableResource(env_1, { [Symbol.dispose]() { } }, false); ++ break; ++ } ++ } ++ catch (e_2) { ++ env_1.error = e_2; ++ env_1.hasError = true; ++ } ++ finally { ++ __disposeResources(env_1); ++ } ++ if (true) { ++ const env_4 = { stack: [], error: void 0, hasError: false }; ++ try { ++ switch (0) { ++ case 0: ++ const d22 = __addDisposableResource(env_4, { [Symbol.dispose]() { } }, false); ++ break; ++ } ++ } ++ catch (e_3) { ++ env_4.error = e_3; ++ env_4.hasError = true; ++ } ++ finally { ++ __disposeResources(env_4); ++ } ++ } ++ try { ++ const env_5 = { stack: [], error: void 0, hasError: false }; ++ try { ++ const d23 = __addDisposableResource(env_5, { [Symbol.dispose]() { } }, false); ++ } ++ catch (e_4) { ++ env_5.error = e_4; ++ env_5.hasError = true; ++ } ++ finally { ++ __disposeResources(env_5); ++ } ++ } ++ catch (_b) { ++ const env_6 = { stack: [], error: void 0, hasError: false }; ++ try { ++ const d24 = __addDisposableResource(env_6, { [Symbol.dispose]() { } }, false); ++ } ++ catch (e_5) { ++ env_6.error = e_5; ++ env_6.hasError = true; ++ } ++ finally { ++ __disposeResources(env_6); ++ } ++ } ++ finally { ++ const env_7 = { stack: [], error: void 0, hasError: false }; ++ try { ++ const d25 = __addDisposableResource(env_7, { [Symbol.dispose]() { } }, false); ++ } ++ catch (e_6) { ++ env_7.error = e_6; ++ env_7.hasError = true; ++ } ++ finally { ++ __disposeResources(env_7); ++ } ++ } ++ if (true) { ++ const env_8 = { stack: [], error: void 0, hasError: false }; ++ try { ++ const d26 = __addDisposableResource(env_8, { [Symbol.dispose]() { } }, false); ++ } ++ catch (e_7) { ++ env_8.error = e_7; ++ env_8.hasError = true; ++ } ++ finally { ++ __disposeResources(env_8); ++ } ++ } ++ else { ++ const env_9 = { stack: [], error: void 0, hasError: false }; ++ try { ++ const d27 = __addDisposableResource(env_9, { [Symbol.dispose]() { } }, false); ++ } ++ catch (e_8) { ++ env_9.error = e_8; ++ env_9.hasError = true; ++ } ++ finally { ++ __disposeResources(env_9); ++ } ++ } ++ while (true) { ++ const env_10 = { stack: [], error: void 0, hasError: false }; ++ try { ++ const d28 = __addDisposableResource(env_10, { [Symbol.dispose]() { } }, false); ++ break; ++ } ++ catch (e_9) { ++ env_10.error = e_9; ++ env_10.hasError = true; ++ } ++ finally { ++ __disposeResources(env_10); ++ } ++ } ++ do { ++ const env_11 = { stack: [], error: void 0, hasError: false }; ++ try { ++ const d29 = __addDisposableResource(env_11, { [Symbol.dispose]() { } }, false); ++ break; ++ } ++ catch (e_10) { ++ env_11.error = e_10; ++ env_11.hasError = true; ++ } ++ finally { ++ __disposeResources(env_11); ++ } ++ } while (true); ++ for (;;) { ++ const env_12 = { stack: [], error: void 0, hasError: false }; ++ try { ++ const d30 = __addDisposableResource(env_12, { [Symbol.dispose]() { } }, false); ++ break; ++ } ++ catch (e_11) { ++ env_12.error = e_11; ++ env_12.hasError = true; ++ } ++ finally { ++ __disposeResources(env_12); ++ } ++ } ++ for (const x in {}) { ++ const env_13 = { stack: [], error: void 0, hasError: false }; ++ try { ++ const d31 = __addDisposableResource(env_13, { [Symbol.dispose]() { } }, false); ++ } ++ catch (e_12) { ++ env_13.error = e_12; ++ env_13.hasError = true; ++ } ++ finally { ++ __disposeResources(env_13); ++ } ++ } ++ for (const x of []) { ++ const env_14 = { stack: [], error: void 0, hasError: false }; ++ try { ++ const d32 = __addDisposableResource(env_14, { [Symbol.dispose]() { } }, false); ++ } ++ catch (e_13) { ++ env_14.error = e_13; ++ env_14.hasError = true; ++ } ++ finally { ++ __disposeResources(env_14); ++ } ++ } ++} ++catch (e_14) { ++ env_2.error = e_14; ++ env_2.hasError = true; ++} ++finally { ++ __disposeResources(env_2); ++} ++export {}; +diff --git a/tests/baselines/reference/usingDeclarations.1(target=es2017).js b/tests/baselines/reference/usingDeclarations.1(target=es2017).js +new file mode 100644 +index 000000000..f65b33bc9 +--- /dev/null ++++ b/tests/baselines/reference/usingDeclarations.1(target=es2017).js +@@ -0,0 +1,652 @@ ++//// [tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarations.1.ts] //// ++ ++//// [usingDeclarations.1.ts] ++using d1 = { [Symbol.dispose]() {} }; ++ ++function f() { ++ using d2 = { [Symbol.dispose]() {} }; ++} ++ ++async function af() { ++ using d3 = { [Symbol.dispose]() {} }; ++ await null; ++} ++ ++function * g() { ++ using d4 = { [Symbol.dispose]() {} }; ++ yield; ++} ++ ++async function * ag() { ++ using d5 = { [Symbol.dispose]() {} }; ++ yield; ++ await null; ++} ++ ++const a = () => { ++ using d6 = { [Symbol.dispose]() {} }; ++} ++ ++class C1 { ++ a = () => { ++ using d7 = { [Symbol.dispose]() {} }; ++ } ++ ++ constructor() { ++ using d8 = { [Symbol.dispose]() {} }; ++ } ++ ++ static { ++ using d9 = { [Symbol.dispose]() {} }; ++ } ++ ++ m() { ++ using d10 = { [Symbol.dispose]() {} }; ++ } ++ ++ get x() { ++ using d11 = { [Symbol.dispose]() {} }; ++ return 0; ++ } ++ ++ set x(v) { ++ using d12 = { [Symbol.dispose]() {} }; ++ } ++ ++ async am() { ++ using d13 = { [Symbol.dispose]() {} }; ++ await null; ++ } ++ ++ * g() { ++ using d14 = { [Symbol.dispose]() {} }; ++ yield; ++ } ++ ++ async * ag() { ++ using d15 = { [Symbol.dispose]() {} }; ++ yield; ++ await null; ++ } ++} ++ ++class C2 extends C1 { ++ constructor() { ++ using d16 = { [Symbol.dispose]() {} }; ++ super(); ++ } ++} ++ ++class C3 extends C1 { ++ y = 1; ++ constructor() { ++ using d17 = { [Symbol.dispose]() {} }; ++ super(); ++ } ++} ++ ++namespace N { ++ using d18 = { [Symbol.dispose]() {} }; ++} ++ ++{ ++ using d19 = { [Symbol.dispose]() {} }; ++} ++ ++switch (Math.random()) { ++ case 0: ++ using d20 = { [Symbol.dispose]() {} }; ++ break; ++ ++ case 1: ++ using d21 = { [Symbol.dispose]() {} }; ++ break; ++} ++ ++if (true) ++ switch (0) { ++ case 0: ++ using d22 = { [Symbol.dispose]() {} }; ++ break; ++ } ++ ++try { ++ using d23 = { [Symbol.dispose]() {} }; ++} ++catch { ++ using d24 = { [Symbol.dispose]() {} }; ++} ++finally { ++ using d25 = { [Symbol.dispose]() {} }; ++} ++ ++if (true) { ++ using d26 = { [Symbol.dispose]() {} }; ++} ++else { ++ using d27 = { [Symbol.dispose]() {} }; ++} ++ ++while (true) { ++ using d28 = { [Symbol.dispose]() {} }; ++ break; ++} ++ ++do { ++ using d29 = { [Symbol.dispose]() {} }; ++ break; ++} ++while (true); ++ ++for (;;) { ++ using d30 = { [Symbol.dispose]() {} }; ++ break; ++} ++ ++for (const x in {}) { ++ using d31 = { [Symbol.dispose]() {} }; ++} ++ ++for (const x of []) { ++ using d32 = { [Symbol.dispose]() {} }; ++} ++ ++export {}; ++ ++//// [usingDeclarations.1.js] ++var __addDisposableResource = (this && this.__addDisposableResource) || function (env, value, async) { ++ if (value !== null && value !== void 0) { ++ if (typeof value !== "object") throw new TypeError("Object expected."); ++ var dispose; ++ if (async) { ++ if (!Symbol.asyncDispose) throw new TypeError("Symbol.asyncDispose is not defined."); ++ dispose = value[Symbol.asyncDispose]; ++ } ++ if (dispose === void 0) { ++ if (!Symbol.dispose) throw new TypeError("Symbol.dispose is not defined."); ++ dispose = value[Symbol.dispose]; ++ } ++ if (typeof dispose !== "function") throw new TypeError("Object not disposable."); ++ env.stack.push({ value: value, dispose: dispose, async: async }); ++ } ++ else if (async) { ++ env.stack.push({ async: true }); ++ } ++ return value; ++}; ++var __disposeResources = (this && this.__disposeResources) || (function (SuppressedError) { ++ return function (env) { ++ function fail(e) { ++ env.error = env.hasError ? new SuppressedError(e, env.error, "An error was suppressed during disposal.") : e; ++ env.hasError = true; ++ } ++ function next() { ++ while (env.stack.length) { ++ var rec = env.stack.pop(); ++ try { ++ var result = rec.dispose && rec.dispose.call(rec.value); ++ if (rec.async) return Promise.resolve(result).then(next, function(e) { fail(e); return next(); }); ++ } ++ catch (e) { ++ fail(e); ++ } ++ } ++ if (env.hasError) throw env.error; ++ } ++ return next(); ++ }; ++})(typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) { ++ var e = new Error(message); ++ return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e; ++}); ++var __await = (this && this.__await) || function (v) { return this instanceof __await ? (this.v = v, this) : new __await(v); } ++var __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _arguments, generator) { ++ if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); ++ var g = generator.apply(thisArg, _arguments || []), i, q = []; ++ return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i; ++ function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; } ++ function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } } ++ function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); } ++ function fulfill(value) { resume("next", value); } ++ function reject(value) { resume("throw", value); } ++ function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); } ++}; ++var _a; ++function f() { ++ const env_15 = { stack: [], error: void 0, hasError: false }; ++ try { ++ const d2 = __addDisposableResource(env_15, { [Symbol.dispose]() { } }, false); ++ } ++ catch (e_15) { ++ env_15.error = e_15; ++ env_15.hasError = true; ++ } ++ finally { ++ __disposeResources(env_15); ++ } ++} ++async function af() { ++ const env_16 = { stack: [], error: void 0, hasError: false }; ++ try { ++ const d3 = __addDisposableResource(env_16, { [Symbol.dispose]() { } }, false); ++ await null; ++ } ++ catch (e_16) { ++ env_16.error = e_16; ++ env_16.hasError = true; ++ } ++ finally { ++ __disposeResources(env_16); ++ } ++} ++function* g() { ++ const env_17 = { stack: [], error: void 0, hasError: false }; ++ try { ++ const d4 = __addDisposableResource(env_17, { [Symbol.dispose]() { } }, false); ++ yield; ++ } ++ catch (e_17) { ++ env_17.error = e_17; ++ env_17.hasError = true; ++ } ++ finally { ++ __disposeResources(env_17); ++ } ++} ++function ag() { ++ return __asyncGenerator(this, arguments, function* ag_1() { ++ const env_18 = { stack: [], error: void 0, hasError: false }; ++ try { ++ const d5 = __addDisposableResource(env_18, { [Symbol.dispose]() { } }, false); ++ yield yield __await(void 0); ++ yield __await(null); ++ } ++ catch (e_18) { ++ env_18.error = e_18; ++ env_18.hasError = true; ++ } ++ finally { ++ __disposeResources(env_18); ++ } ++ }); ++} ++var d1, a, C1, C2, C3, N, env_1; ++const env_2 = { stack: [], error: void 0, hasError: false }; ++try { ++ d1 = __addDisposableResource(env_2, { [Symbol.dispose]() { } }, false); ++ a = () => { ++ const env_19 = { stack: [], error: void 0, hasError: false }; ++ try { ++ const d6 = __addDisposableResource(env_19, { [Symbol.dispose]() { } }, false); ++ } ++ catch (e_19) { ++ env_19.error = e_19; ++ env_19.hasError = true; ++ } ++ finally { ++ __disposeResources(env_19); ++ } ++ }; ++ C1 = (_a = class C1 { ++ constructor() { ++ this.a = () => { ++ const env_21 = { stack: [], error: void 0, hasError: false }; ++ try { ++ const d7 = __addDisposableResource(env_21, { [Symbol.dispose]() { } }, false); ++ } ++ catch (e_21) { ++ env_21.error = e_21; ++ env_21.hasError = true; ++ } ++ finally { ++ __disposeResources(env_21); ++ } ++ }; ++ const env_20 = { stack: [], error: void 0, hasError: false }; ++ try { ++ const d8 = __addDisposableResource(env_20, { [Symbol.dispose]() { } }, false); ++ } ++ catch (e_20) { ++ env_20.error = e_20; ++ env_20.hasError = true; ++ } ++ finally { ++ __disposeResources(env_20); ++ } ++ } ++ m() { ++ const env_22 = { stack: [], error: void 0, hasError: false }; ++ try { ++ const d10 = __addDisposableResource(env_22, { [Symbol.dispose]() { } }, false); ++ } ++ catch (e_22) { ++ env_22.error = e_22; ++ env_22.hasError = true; ++ } ++ finally { ++ __disposeResources(env_22); ++ } ++ } ++ get x() { ++ const env_23 = { stack: [], error: void 0, hasError: false }; ++ try { ++ const d11 = __addDisposableResource(env_23, { [Symbol.dispose]() { } }, false); ++ return 0; ++ } ++ catch (e_23) { ++ env_23.error = e_23; ++ env_23.hasError = true; ++ } ++ finally { ++ __disposeResources(env_23); ++ } ++ } ++ set x(v) { ++ const env_24 = { stack: [], error: void 0, hasError: false }; ++ try { ++ const d12 = __addDisposableResource(env_24, { [Symbol.dispose]() { } }, false); ++ } ++ catch (e_24) { ++ env_24.error = e_24; ++ env_24.hasError = true; ++ } ++ finally { ++ __disposeResources(env_24); ++ } ++ } ++ async am() { ++ const env_25 = { stack: [], error: void 0, hasError: false }; ++ try { ++ const d13 = __addDisposableResource(env_25, { [Symbol.dispose]() { } }, false); ++ await null; ++ } ++ catch (e_25) { ++ env_25.error = e_25; ++ env_25.hasError = true; ++ } ++ finally { ++ __disposeResources(env_25); ++ } ++ } ++ *g() { ++ const env_26 = { stack: [], error: void 0, hasError: false }; ++ try { ++ const d14 = __addDisposableResource(env_26, { [Symbol.dispose]() { } }, false); ++ yield; ++ } ++ catch (e_26) { ++ env_26.error = e_26; ++ env_26.hasError = true; ++ } ++ finally { ++ __disposeResources(env_26); ++ } ++ } ++ ag() { ++ return __asyncGenerator(this, arguments, function* ag_2() { ++ const env_27 = { stack: [], error: void 0, hasError: false }; ++ try { ++ const d15 = __addDisposableResource(env_27, { [Symbol.dispose]() { } }, false); ++ yield yield __await(void 0); ++ yield __await(null); ++ } ++ catch (e_27) { ++ env_27.error = e_27; ++ env_27.hasError = true; ++ } ++ finally { ++ __disposeResources(env_27); ++ } ++ }); ++ } ++ }, ++ (() => { ++ const env_28 = { stack: [], error: void 0, hasError: false }; ++ try { ++ const d9 = __addDisposableResource(env_28, { [Symbol.dispose]() { } }, false); ++ } ++ catch (e_28) { ++ env_28.error = e_28; ++ env_28.hasError = true; ++ } ++ finally { ++ __disposeResources(env_28); ++ } ++ })(), ++ _a); ++ C2 = class C2 extends C1 { ++ constructor() { ++ const env_29 = { stack: [], error: void 0, hasError: false }; ++ try { ++ const d16 = __addDisposableResource(env_29, { [Symbol.dispose]() { } }, false); ++ super(); ++ } ++ catch (e_29) { ++ env_29.error = e_29; ++ env_29.hasError = true; ++ } ++ finally { ++ __disposeResources(env_29); ++ } ++ } ++ }; ++ C3 = class C3 extends C1 { ++ constructor() { ++ const env_30 = { stack: [], error: void 0, hasError: false }; ++ try { ++ const d17 = __addDisposableResource(env_30, { [Symbol.dispose]() { } }, false); ++ super(); ++ this.y = 1; ++ } ++ catch (e_30) { ++ env_30.error = e_30; ++ env_30.hasError = true; ++ } ++ finally { ++ __disposeResources(env_30); ++ } ++ } ++ }; ++ (function (N) { ++ const env_31 = { stack: [], error: void 0, hasError: false }; ++ try { ++ const d18 = __addDisposableResource(env_31, { [Symbol.dispose]() { } }, false); ++ } ++ catch (e_31) { ++ env_31.error = e_31; ++ env_31.hasError = true; ++ } ++ finally { ++ __disposeResources(env_31); ++ } ++ })(N || (N = {})); ++ { ++ const env_3 = { stack: [], error: void 0, hasError: false }; ++ try { ++ const d19 = __addDisposableResource(env_3, { [Symbol.dispose]() { } }, false); ++ } ++ catch (e_1) { ++ env_3.error = e_1; ++ env_3.hasError = true; ++ } ++ finally { ++ __disposeResources(env_3); ++ } ++ } ++ env_1 = { stack: [], error: void 0, hasError: false }; ++ try { ++ switch (Math.random()) { ++ case 0: ++ const d20 = __addDisposableResource(env_1, { [Symbol.dispose]() { } }, false); ++ break; ++ case 1: ++ const d21 = __addDisposableResource(env_1, { [Symbol.dispose]() { } }, false); ++ break; ++ } ++ } ++ catch (e_2) { ++ env_1.error = e_2; ++ env_1.hasError = true; ++ } ++ finally { ++ __disposeResources(env_1); ++ } ++ if (true) { ++ const env_4 = { stack: [], error: void 0, hasError: false }; ++ try { ++ switch (0) { ++ case 0: ++ const d22 = __addDisposableResource(env_4, { [Symbol.dispose]() { } }, false); ++ break; ++ } ++ } ++ catch (e_3) { ++ env_4.error = e_3; ++ env_4.hasError = true; ++ } ++ finally { ++ __disposeResources(env_4); ++ } ++ } ++ try { ++ const env_5 = { stack: [], error: void 0, hasError: false }; ++ try { ++ const d23 = __addDisposableResource(env_5, { [Symbol.dispose]() { } }, false); ++ } ++ catch (e_4) { ++ env_5.error = e_4; ++ env_5.hasError = true; ++ } ++ finally { ++ __disposeResources(env_5); ++ } ++ } ++ catch (_b) { ++ const env_6 = { stack: [], error: void 0, hasError: false }; ++ try { ++ const d24 = __addDisposableResource(env_6, { [Symbol.dispose]() { } }, false); ++ } ++ catch (e_5) { ++ env_6.error = e_5; ++ env_6.hasError = true; ++ } ++ finally { ++ __disposeResources(env_6); ++ } ++ } ++ finally { ++ const env_7 = { stack: [], error: void 0, hasError: false }; ++ try { ++ const d25 = __addDisposableResource(env_7, { [Symbol.dispose]() { } }, false); ++ } ++ catch (e_6) { ++ env_7.error = e_6; ++ env_7.hasError = true; ++ } ++ finally { ++ __disposeResources(env_7); ++ } ++ } ++ if (true) { ++ const env_8 = { stack: [], error: void 0, hasError: false }; ++ try { ++ const d26 = __addDisposableResource(env_8, { [Symbol.dispose]() { } }, false); ++ } ++ catch (e_7) { ++ env_8.error = e_7; ++ env_8.hasError = true; ++ } ++ finally { ++ __disposeResources(env_8); ++ } ++ } ++ else { ++ const env_9 = { stack: [], error: void 0, hasError: false }; ++ try { ++ const d27 = __addDisposableResource(env_9, { [Symbol.dispose]() { } }, false); ++ } ++ catch (e_8) { ++ env_9.error = e_8; ++ env_9.hasError = true; ++ } ++ finally { ++ __disposeResources(env_9); ++ } ++ } ++ while (true) { ++ const env_10 = { stack: [], error: void 0, hasError: false }; ++ try { ++ const d28 = __addDisposableResource(env_10, { [Symbol.dispose]() { } }, false); ++ break; ++ } ++ catch (e_9) { ++ env_10.error = e_9; ++ env_10.hasError = true; ++ } ++ finally { ++ __disposeResources(env_10); ++ } ++ } ++ do { ++ const env_11 = { stack: [], error: void 0, hasError: false }; ++ try { ++ const d29 = __addDisposableResource(env_11, { [Symbol.dispose]() { } }, false); ++ break; ++ } ++ catch (e_10) { ++ env_11.error = e_10; ++ env_11.hasError = true; ++ } ++ finally { ++ __disposeResources(env_11); ++ } ++ } while (true); ++ for (;;) { ++ const env_12 = { stack: [], error: void 0, hasError: false }; ++ try { ++ const d30 = __addDisposableResource(env_12, { [Symbol.dispose]() { } }, false); ++ break; ++ } ++ catch (e_11) { ++ env_12.error = e_11; ++ env_12.hasError = true; ++ } ++ finally { ++ __disposeResources(env_12); ++ } ++ } ++ for (const x in {}) { ++ const env_13 = { stack: [], error: void 0, hasError: false }; ++ try { ++ const d31 = __addDisposableResource(env_13, { [Symbol.dispose]() { } }, false); ++ } ++ catch (e_12) { ++ env_13.error = e_12; ++ env_13.hasError = true; ++ } ++ finally { ++ __disposeResources(env_13); ++ } ++ } ++ for (const x of []) { ++ const env_14 = { stack: [], error: void 0, hasError: false }; ++ try { ++ const d32 = __addDisposableResource(env_14, { [Symbol.dispose]() { } }, false); ++ } ++ catch (e_13) { ++ env_14.error = e_13; ++ env_14.hasError = true; ++ } ++ finally { ++ __disposeResources(env_14); ++ } ++ } ++} ++catch (e_14) { ++ env_2.error = e_14; ++ env_2.hasError = true; ++} ++finally { ++ __disposeResources(env_2); ++} ++export {}; +diff --git a/tests/baselines/reference/usingDeclarations.1(target=es2022).js b/tests/baselines/reference/usingDeclarations.1(target=es2022).js +new file mode 100644 +index 000000000..f5bf25b81 +--- /dev/null ++++ b/tests/baselines/reference/usingDeclarations.1(target=es2022).js +@@ -0,0 +1,634 @@ ++//// [tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarations.1.ts] //// ++ ++//// [usingDeclarations.1.ts] ++using d1 = { [Symbol.dispose]() {} }; ++ ++function f() { ++ using d2 = { [Symbol.dispose]() {} }; ++} ++ ++async function af() { ++ using d3 = { [Symbol.dispose]() {} }; ++ await null; ++} ++ ++function * g() { ++ using d4 = { [Symbol.dispose]() {} }; ++ yield; ++} ++ ++async function * ag() { ++ using d5 = { [Symbol.dispose]() {} }; ++ yield; ++ await null; ++} ++ ++const a = () => { ++ using d6 = { [Symbol.dispose]() {} }; ++} ++ ++class C1 { ++ a = () => { ++ using d7 = { [Symbol.dispose]() {} }; ++ } ++ ++ constructor() { ++ using d8 = { [Symbol.dispose]() {} }; ++ } ++ ++ static { ++ using d9 = { [Symbol.dispose]() {} }; ++ } ++ ++ m() { ++ using d10 = { [Symbol.dispose]() {} }; ++ } ++ ++ get x() { ++ using d11 = { [Symbol.dispose]() {} }; ++ return 0; ++ } ++ ++ set x(v) { ++ using d12 = { [Symbol.dispose]() {} }; ++ } ++ ++ async am() { ++ using d13 = { [Symbol.dispose]() {} }; ++ await null; ++ } ++ ++ * g() { ++ using d14 = { [Symbol.dispose]() {} }; ++ yield; ++ } ++ ++ async * ag() { ++ using d15 = { [Symbol.dispose]() {} }; ++ yield; ++ await null; ++ } ++} ++ ++class C2 extends C1 { ++ constructor() { ++ using d16 = { [Symbol.dispose]() {} }; ++ super(); ++ } ++} ++ ++class C3 extends C1 { ++ y = 1; ++ constructor() { ++ using d17 = { [Symbol.dispose]() {} }; ++ super(); ++ } ++} ++ ++namespace N { ++ using d18 = { [Symbol.dispose]() {} }; ++} ++ ++{ ++ using d19 = { [Symbol.dispose]() {} }; ++} ++ ++switch (Math.random()) { ++ case 0: ++ using d20 = { [Symbol.dispose]() {} }; ++ break; ++ ++ case 1: ++ using d21 = { [Symbol.dispose]() {} }; ++ break; ++} ++ ++if (true) ++ switch (0) { ++ case 0: ++ using d22 = { [Symbol.dispose]() {} }; ++ break; ++ } ++ ++try { ++ using d23 = { [Symbol.dispose]() {} }; ++} ++catch { ++ using d24 = { [Symbol.dispose]() {} }; ++} ++finally { ++ using d25 = { [Symbol.dispose]() {} }; ++} ++ ++if (true) { ++ using d26 = { [Symbol.dispose]() {} }; ++} ++else { ++ using d27 = { [Symbol.dispose]() {} }; ++} ++ ++while (true) { ++ using d28 = { [Symbol.dispose]() {} }; ++ break; ++} ++ ++do { ++ using d29 = { [Symbol.dispose]() {} }; ++ break; ++} ++while (true); ++ ++for (;;) { ++ using d30 = { [Symbol.dispose]() {} }; ++ break; ++} ++ ++for (const x in {}) { ++ using d31 = { [Symbol.dispose]() {} }; ++} ++ ++for (const x of []) { ++ using d32 = { [Symbol.dispose]() {} }; ++} ++ ++export {}; ++ ++//// [usingDeclarations.1.js] ++var __addDisposableResource = (this && this.__addDisposableResource) || function (env, value, async) { ++ if (value !== null && value !== void 0) { ++ if (typeof value !== "object") throw new TypeError("Object expected."); ++ var dispose; ++ if (async) { ++ if (!Symbol.asyncDispose) throw new TypeError("Symbol.asyncDispose is not defined."); ++ dispose = value[Symbol.asyncDispose]; ++ } ++ if (dispose === void 0) { ++ if (!Symbol.dispose) throw new TypeError("Symbol.dispose is not defined."); ++ dispose = value[Symbol.dispose]; ++ } ++ if (typeof dispose !== "function") throw new TypeError("Object not disposable."); ++ env.stack.push({ value: value, dispose: dispose, async: async }); ++ } ++ else if (async) { ++ env.stack.push({ async: true }); ++ } ++ return value; ++}; ++var __disposeResources = (this && this.__disposeResources) || (function (SuppressedError) { ++ return function (env) { ++ function fail(e) { ++ env.error = env.hasError ? new SuppressedError(e, env.error, "An error was suppressed during disposal.") : e; ++ env.hasError = true; ++ } ++ function next() { ++ while (env.stack.length) { ++ var rec = env.stack.pop(); ++ try { ++ var result = rec.dispose && rec.dispose.call(rec.value); ++ if (rec.async) return Promise.resolve(result).then(next, function(e) { fail(e); return next(); }); ++ } ++ catch (e) { ++ fail(e); ++ } ++ } ++ if (env.hasError) throw env.error; ++ } ++ return next(); ++ }; ++})(typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) { ++ var e = new Error(message); ++ return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e; ++}); ++function f() { ++ const env_15 = { stack: [], error: void 0, hasError: false }; ++ try { ++ const d2 = __addDisposableResource(env_15, { [Symbol.dispose]() { } }, false); ++ } ++ catch (e_15) { ++ env_15.error = e_15; ++ env_15.hasError = true; ++ } ++ finally { ++ __disposeResources(env_15); ++ } ++} ++async function af() { ++ const env_16 = { stack: [], error: void 0, hasError: false }; ++ try { ++ const d3 = __addDisposableResource(env_16, { [Symbol.dispose]() { } }, false); ++ await null; ++ } ++ catch (e_16) { ++ env_16.error = e_16; ++ env_16.hasError = true; ++ } ++ finally { ++ __disposeResources(env_16); ++ } ++} ++function* g() { ++ const env_17 = { stack: [], error: void 0, hasError: false }; ++ try { ++ const d4 = __addDisposableResource(env_17, { [Symbol.dispose]() { } }, false); ++ yield; ++ } ++ catch (e_17) { ++ env_17.error = e_17; ++ env_17.hasError = true; ++ } ++ finally { ++ __disposeResources(env_17); ++ } ++} ++async function* ag() { ++ const env_18 = { stack: [], error: void 0, hasError: false }; ++ try { ++ const d5 = __addDisposableResource(env_18, { [Symbol.dispose]() { } }, false); ++ yield; ++ await null; ++ } ++ catch (e_18) { ++ env_18.error = e_18; ++ env_18.hasError = true; ++ } ++ finally { ++ __disposeResources(env_18); ++ } ++} ++var d1, a, C1, C2, C3, N, env_1; ++const env_2 = { stack: [], error: void 0, hasError: false }; ++try { ++ d1 = __addDisposableResource(env_2, { [Symbol.dispose]() { } }, false); ++ a = () => { ++ const env_19 = { stack: [], error: void 0, hasError: false }; ++ try { ++ const d6 = __addDisposableResource(env_19, { [Symbol.dispose]() { } }, false); ++ } ++ catch (e_19) { ++ env_19.error = e_19; ++ env_19.hasError = true; ++ } ++ finally { ++ __disposeResources(env_19); ++ } ++ }; ++ C1 = class C1 { ++ a = () => { ++ const env_20 = { stack: [], error: void 0, hasError: false }; ++ try { ++ const d7 = __addDisposableResource(env_20, { [Symbol.dispose]() { } }, false); ++ } ++ catch (e_20) { ++ env_20.error = e_20; ++ env_20.hasError = true; ++ } ++ finally { ++ __disposeResources(env_20); ++ } ++ }; ++ constructor() { ++ const env_21 = { stack: [], error: void 0, hasError: false }; ++ try { ++ const d8 = __addDisposableResource(env_21, { [Symbol.dispose]() { } }, false); ++ } ++ catch (e_21) { ++ env_21.error = e_21; ++ env_21.hasError = true; ++ } ++ finally { ++ __disposeResources(env_21); ++ } ++ } ++ static { ++ const env_22 = { stack: [], error: void 0, hasError: false }; ++ try { ++ const d9 = __addDisposableResource(env_22, { [Symbol.dispose]() { } }, false); ++ } ++ catch (e_22) { ++ env_22.error = e_22; ++ env_22.hasError = true; ++ } ++ finally { ++ __disposeResources(env_22); ++ } ++ } ++ m() { ++ const env_23 = { stack: [], error: void 0, hasError: false }; ++ try { ++ const d10 = __addDisposableResource(env_23, { [Symbol.dispose]() { } }, false); ++ } ++ catch (e_23) { ++ env_23.error = e_23; ++ env_23.hasError = true; ++ } ++ finally { ++ __disposeResources(env_23); ++ } ++ } ++ get x() { ++ const env_24 = { stack: [], error: void 0, hasError: false }; ++ try { ++ const d11 = __addDisposableResource(env_24, { [Symbol.dispose]() { } }, false); ++ return 0; ++ } ++ catch (e_24) { ++ env_24.error = e_24; ++ env_24.hasError = true; ++ } ++ finally { ++ __disposeResources(env_24); ++ } ++ } ++ set x(v) { ++ const env_25 = { stack: [], error: void 0, hasError: false }; ++ try { ++ const d12 = __addDisposableResource(env_25, { [Symbol.dispose]() { } }, false); ++ } ++ catch (e_25) { ++ env_25.error = e_25; ++ env_25.hasError = true; ++ } ++ finally { ++ __disposeResources(env_25); ++ } ++ } ++ async am() { ++ const env_26 = { stack: [], error: void 0, hasError: false }; ++ try { ++ const d13 = __addDisposableResource(env_26, { [Symbol.dispose]() { } }, false); ++ await null; ++ } ++ catch (e_26) { ++ env_26.error = e_26; ++ env_26.hasError = true; ++ } ++ finally { ++ __disposeResources(env_26); ++ } ++ } ++ *g() { ++ const env_27 = { stack: [], error: void 0, hasError: false }; ++ try { ++ const d14 = __addDisposableResource(env_27, { [Symbol.dispose]() { } }, false); ++ yield; ++ } ++ catch (e_27) { ++ env_27.error = e_27; ++ env_27.hasError = true; ++ } ++ finally { ++ __disposeResources(env_27); ++ } ++ } ++ async *ag() { ++ const env_28 = { stack: [], error: void 0, hasError: false }; ++ try { ++ const d15 = __addDisposableResource(env_28, { [Symbol.dispose]() { } }, false); ++ yield; ++ await null; ++ } ++ catch (e_28) { ++ env_28.error = e_28; ++ env_28.hasError = true; ++ } ++ finally { ++ __disposeResources(env_28); ++ } ++ } ++ }; ++ C2 = class C2 extends C1 { ++ constructor() { ++ const env_29 = { stack: [], error: void 0, hasError: false }; ++ try { ++ const d16 = __addDisposableResource(env_29, { [Symbol.dispose]() { } }, false); ++ super(); ++ } ++ catch (e_29) { ++ env_29.error = e_29; ++ env_29.hasError = true; ++ } ++ finally { ++ __disposeResources(env_29); ++ } ++ } ++ }; ++ C3 = class C3 extends C1 { ++ y = 1; ++ constructor() { ++ const env_30 = { stack: [], error: void 0, hasError: false }; ++ try { ++ const d17 = __addDisposableResource(env_30, { [Symbol.dispose]() { } }, false); ++ super(); ++ } ++ catch (e_30) { ++ env_30.error = e_30; ++ env_30.hasError = true; ++ } ++ finally { ++ __disposeResources(env_30); ++ } ++ } ++ }; ++ (function (N) { ++ const env_31 = { stack: [], error: void 0, hasError: false }; ++ try { ++ const d18 = __addDisposableResource(env_31, { [Symbol.dispose]() { } }, false); ++ } ++ catch (e_31) { ++ env_31.error = e_31; ++ env_31.hasError = true; ++ } ++ finally { ++ __disposeResources(env_31); ++ } ++ })(N || (N = {})); ++ { ++ const env_3 = { stack: [], error: void 0, hasError: false }; ++ try { ++ const d19 = __addDisposableResource(env_3, { [Symbol.dispose]() { } }, false); ++ } ++ catch (e_1) { ++ env_3.error = e_1; ++ env_3.hasError = true; ++ } ++ finally { ++ __disposeResources(env_3); ++ } ++ } ++ env_1 = { stack: [], error: void 0, hasError: false }; ++ try { ++ switch (Math.random()) { ++ case 0: ++ const d20 = __addDisposableResource(env_1, { [Symbol.dispose]() { } }, false); ++ break; ++ case 1: ++ const d21 = __addDisposableResource(env_1, { [Symbol.dispose]() { } }, false); ++ break; ++ } ++ } ++ catch (e_2) { ++ env_1.error = e_2; ++ env_1.hasError = true; ++ } ++ finally { ++ __disposeResources(env_1); ++ } ++ if (true) { ++ const env_4 = { stack: [], error: void 0, hasError: false }; ++ try { ++ switch (0) { ++ case 0: ++ const d22 = __addDisposableResource(env_4, { [Symbol.dispose]() { } }, false); ++ break; ++ } ++ } ++ catch (e_3) { ++ env_4.error = e_3; ++ env_4.hasError = true; ++ } ++ finally { ++ __disposeResources(env_4); ++ } ++ } ++ try { ++ const env_5 = { stack: [], error: void 0, hasError: false }; ++ try { ++ const d23 = __addDisposableResource(env_5, { [Symbol.dispose]() { } }, false); ++ } ++ catch (e_4) { ++ env_5.error = e_4; ++ env_5.hasError = true; ++ } ++ finally { ++ __disposeResources(env_5); ++ } ++ } ++ catch { ++ const env_6 = { stack: [], error: void 0, hasError: false }; ++ try { ++ const d24 = __addDisposableResource(env_6, { [Symbol.dispose]() { } }, false); ++ } ++ catch (e_5) { ++ env_6.error = e_5; ++ env_6.hasError = true; ++ } ++ finally { ++ __disposeResources(env_6); ++ } ++ } ++ finally { ++ const env_7 = { stack: [], error: void 0, hasError: false }; ++ try { ++ const d25 = __addDisposableResource(env_7, { [Symbol.dispose]() { } }, false); ++ } ++ catch (e_6) { ++ env_7.error = e_6; ++ env_7.hasError = true; ++ } ++ finally { ++ __disposeResources(env_7); ++ } ++ } ++ if (true) { ++ const env_8 = { stack: [], error: void 0, hasError: false }; ++ try { ++ const d26 = __addDisposableResource(env_8, { [Symbol.dispose]() { } }, false); ++ } ++ catch (e_7) { ++ env_8.error = e_7; ++ env_8.hasError = true; ++ } ++ finally { ++ __disposeResources(env_8); ++ } ++ } ++ else { ++ const env_9 = { stack: [], error: void 0, hasError: false }; ++ try { ++ const d27 = __addDisposableResource(env_9, { [Symbol.dispose]() { } }, false); ++ } ++ catch (e_8) { ++ env_9.error = e_8; ++ env_9.hasError = true; ++ } ++ finally { ++ __disposeResources(env_9); ++ } ++ } ++ while (true) { ++ const env_10 = { stack: [], error: void 0, hasError: false }; ++ try { ++ const d28 = __addDisposableResource(env_10, { [Symbol.dispose]() { } }, false); ++ break; ++ } ++ catch (e_9) { ++ env_10.error = e_9; ++ env_10.hasError = true; ++ } ++ finally { ++ __disposeResources(env_10); ++ } ++ } ++ do { ++ const env_11 = { stack: [], error: void 0, hasError: false }; ++ try { ++ const d29 = __addDisposableResource(env_11, { [Symbol.dispose]() { } }, false); ++ break; ++ } ++ catch (e_10) { ++ env_11.error = e_10; ++ env_11.hasError = true; ++ } ++ finally { ++ __disposeResources(env_11); ++ } ++ } while (true); ++ for (;;) { ++ const env_12 = { stack: [], error: void 0, hasError: false }; ++ try { ++ const d30 = __addDisposableResource(env_12, { [Symbol.dispose]() { } }, false); ++ break; ++ } ++ catch (e_11) { ++ env_12.error = e_11; ++ env_12.hasError = true; ++ } ++ finally { ++ __disposeResources(env_12); ++ } ++ } ++ for (const x in {}) { ++ const env_13 = { stack: [], error: void 0, hasError: false }; ++ try { ++ const d31 = __addDisposableResource(env_13, { [Symbol.dispose]() { } }, false); ++ } ++ catch (e_12) { ++ env_13.error = e_12; ++ env_13.hasError = true; ++ } ++ finally { ++ __disposeResources(env_13); ++ } ++ } ++ for (const x of []) { ++ const env_14 = { stack: [], error: void 0, hasError: false }; ++ try { ++ const d32 = __addDisposableResource(env_14, { [Symbol.dispose]() { } }, false); ++ } ++ catch (e_13) { ++ env_14.error = e_13; ++ env_14.hasError = true; ++ } ++ finally { ++ __disposeResources(env_14); ++ } ++ } ++} ++catch (e_14) { ++ env_2.error = e_14; ++ env_2.hasError = true; ++} ++finally { ++ __disposeResources(env_2); ++} ++export {}; +diff --git a/tests/baselines/reference/usingDeclarations.1(target=es5).js b/tests/baselines/reference/usingDeclarations.1(target=es5).js +new file mode 100644 +index 000000000..369559dff +--- /dev/null ++++ b/tests/baselines/reference/usingDeclarations.1(target=es5).js +@@ -0,0 +1,814 @@ ++//// [tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarations.1.ts] //// ++ ++//// [usingDeclarations.1.ts] ++using d1 = { [Symbol.dispose]() {} }; ++ ++function f() { ++ using d2 = { [Symbol.dispose]() {} }; ++} ++ ++async function af() { ++ using d3 = { [Symbol.dispose]() {} }; ++ await null; ++} ++ ++function * g() { ++ using d4 = { [Symbol.dispose]() {} }; ++ yield; ++} ++ ++async function * ag() { ++ using d5 = { [Symbol.dispose]() {} }; ++ yield; ++ await null; ++} ++ ++const a = () => { ++ using d6 = { [Symbol.dispose]() {} }; ++} ++ ++class C1 { ++ a = () => { ++ using d7 = { [Symbol.dispose]() {} }; ++ } ++ ++ constructor() { ++ using d8 = { [Symbol.dispose]() {} }; ++ } ++ ++ static { ++ using d9 = { [Symbol.dispose]() {} }; ++ } ++ ++ m() { ++ using d10 = { [Symbol.dispose]() {} }; ++ } ++ ++ get x() { ++ using d11 = { [Symbol.dispose]() {} }; ++ return 0; ++ } ++ ++ set x(v) { ++ using d12 = { [Symbol.dispose]() {} }; ++ } ++ ++ async am() { ++ using d13 = { [Symbol.dispose]() {} }; ++ await null; ++ } ++ ++ * g() { ++ using d14 = { [Symbol.dispose]() {} }; ++ yield; ++ } ++ ++ async * ag() { ++ using d15 = { [Symbol.dispose]() {} }; ++ yield; ++ await null; ++ } ++} ++ ++class C2 extends C1 { ++ constructor() { ++ using d16 = { [Symbol.dispose]() {} }; ++ super(); ++ } ++} ++ ++class C3 extends C1 { ++ y = 1; ++ constructor() { ++ using d17 = { [Symbol.dispose]() {} }; ++ super(); ++ } ++} ++ ++namespace N { ++ using d18 = { [Symbol.dispose]() {} }; ++} ++ ++{ ++ using d19 = { [Symbol.dispose]() {} }; ++} ++ ++switch (Math.random()) { ++ case 0: ++ using d20 = { [Symbol.dispose]() {} }; ++ break; ++ ++ case 1: ++ using d21 = { [Symbol.dispose]() {} }; ++ break; ++} ++ ++if (true) ++ switch (0) { ++ case 0: ++ using d22 = { [Symbol.dispose]() {} }; ++ break; ++ } ++ ++try { ++ using d23 = { [Symbol.dispose]() {} }; ++} ++catch { ++ using d24 = { [Symbol.dispose]() {} }; ++} ++finally { ++ using d25 = { [Symbol.dispose]() {} }; ++} ++ ++if (true) { ++ using d26 = { [Symbol.dispose]() {} }; ++} ++else { ++ using d27 = { [Symbol.dispose]() {} }; ++} ++ ++while (true) { ++ using d28 = { [Symbol.dispose]() {} }; ++ break; ++} ++ ++do { ++ using d29 = { [Symbol.dispose]() {} }; ++ break; ++} ++while (true); ++ ++for (;;) { ++ using d30 = { [Symbol.dispose]() {} }; ++ break; ++} ++ ++for (const x in {}) { ++ using d31 = { [Symbol.dispose]() {} }; ++} ++ ++for (const x of []) { ++ using d32 = { [Symbol.dispose]() {} }; ++} ++ ++export {}; ++ ++//// [usingDeclarations.1.js] ++var __extends = (this && this.__extends) || (function () { ++ var extendStatics = function (d, b) { ++ extendStatics = Object.setPrototypeOf || ++ ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || ++ function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; ++ return extendStatics(d, b); ++ }; ++ return function (d, b) { ++ if (typeof b !== "function" && b !== null) ++ throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); ++ extendStatics(d, b); ++ function __() { this.constructor = d; } ++ d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); ++ }; ++})(); ++var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { ++ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } ++ return new (P || (P = Promise))(function (resolve, reject) { ++ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } ++ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } ++ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } ++ step((generator = generator.apply(thisArg, _arguments || [])).next()); ++ }); ++}; ++var __generator = (this && this.__generator) || function (thisArg, body) { ++ var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; ++ return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; ++ function verb(n) { return function (v) { return step([n, v]); }; } ++ function step(op) { ++ if (f) throw new TypeError("Generator is already executing."); ++ while (g && (g = 0, op[0] && (_ = 0)), _) try { ++ if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; ++ if (y = 0, t) op = [op[0] & 2, t.value]; ++ switch (op[0]) { ++ case 0: case 1: t = op; break; ++ case 4: _.label++; return { value: op[1], done: false }; ++ case 5: _.label++; y = op[1]; op = [0]; continue; ++ case 7: op = _.ops.pop(); _.trys.pop(); continue; ++ default: ++ if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } ++ if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } ++ if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } ++ if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } ++ if (t[2]) _.ops.pop(); ++ _.trys.pop(); continue; ++ } ++ op = body.call(thisArg, _); ++ } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } ++ if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; ++ } ++}; ++var __addDisposableResource = (this && this.__addDisposableResource) || function (env, value, async) { ++ if (value !== null && value !== void 0) { ++ if (typeof value !== "object") throw new TypeError("Object expected."); ++ var dispose; ++ if (async) { ++ if (!Symbol.asyncDispose) throw new TypeError("Symbol.asyncDispose is not defined."); ++ dispose = value[Symbol.asyncDispose]; ++ } ++ if (dispose === void 0) { ++ if (!Symbol.dispose) throw new TypeError("Symbol.dispose is not defined."); ++ dispose = value[Symbol.dispose]; ++ } ++ if (typeof dispose !== "function") throw new TypeError("Object not disposable."); ++ env.stack.push({ value: value, dispose: dispose, async: async }); ++ } ++ else if (async) { ++ env.stack.push({ async: true }); ++ } ++ return value; ++}; ++var __disposeResources = (this && this.__disposeResources) || (function (SuppressedError) { ++ return function (env) { ++ function fail(e) { ++ env.error = env.hasError ? new SuppressedError(e, env.error, "An error was suppressed during disposal.") : e; ++ env.hasError = true; ++ } ++ function next() { ++ while (env.stack.length) { ++ var rec = env.stack.pop(); ++ try { ++ var result = rec.dispose && rec.dispose.call(rec.value); ++ if (rec.async) return Promise.resolve(result).then(next, function(e) { fail(e); return next(); }); ++ } ++ catch (e) { ++ fail(e); ++ } ++ } ++ if (env.hasError) throw env.error; ++ } ++ return next(); ++ }; ++})(typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) { ++ var e = new Error(message); ++ return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e; ++}); ++var __await = (this && this.__await) || function (v) { return this instanceof __await ? (this.v = v, this) : new __await(v); } ++var __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _arguments, generator) { ++ if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); ++ var g = generator.apply(thisArg, _arguments || []), i, q = []; ++ return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i; ++ function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; } ++ function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } } ++ function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); } ++ function fulfill(value) { resume("next", value); } ++ function reject(value) { resume("throw", value); } ++ function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); } ++}; ++var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q; ++var _r; ++function f() { ++ var _a; ++ var env_15 = { stack: [], error: void 0, hasError: false }; ++ try { ++ var d2 = __addDisposableResource(env_15, (_a = {}, _a[Symbol.dispose] = function () { }, _a), false); ++ } ++ catch (e_15) { ++ env_15.error = e_15; ++ env_15.hasError = true; ++ } ++ finally { ++ __disposeResources(env_15); ++ } ++} ++function af() { ++ return __awaiter(this, void 0, void 0, function () { ++ var env_16, d3, e_16; ++ var _a; ++ return __generator(this, function (_b) { ++ switch (_b.label) { ++ case 0: ++ env_16 = { stack: [], error: void 0, hasError: false }; ++ _b.label = 1; ++ case 1: ++ _b.trys.push([1, 3, 4, 5]); ++ d3 = __addDisposableResource(env_16, (_a = {}, _a[Symbol.dispose] = function () { }, _a), false); ++ return [4 /*yield*/, null]; ++ case 2: ++ _b.sent(); ++ return [3 /*break*/, 5]; ++ case 3: ++ e_16 = _b.sent(); ++ env_16.error = e_16; ++ env_16.hasError = true; ++ return [3 /*break*/, 5]; ++ case 4: ++ __disposeResources(env_16); ++ return [7 /*endfinally*/]; ++ case 5: return [2 /*return*/]; ++ } ++ }); ++ }); ++} ++function g() { ++ var env_17, d4, e_17; ++ var _a; ++ return __generator(this, function (_b) { ++ switch (_b.label) { ++ case 0: ++ env_17 = { stack: [], error: void 0, hasError: false }; ++ _b.label = 1; ++ case 1: ++ _b.trys.push([1, 3, 4, 5]); ++ d4 = __addDisposableResource(env_17, (_a = {}, _a[Symbol.dispose] = function () { }, _a), false); ++ return [4 /*yield*/]; ++ case 2: ++ _b.sent(); ++ return [3 /*break*/, 5]; ++ case 3: ++ e_17 = _b.sent(); ++ env_17.error = e_17; ++ env_17.hasError = true; ++ return [3 /*break*/, 5]; ++ case 4: ++ __disposeResources(env_17); ++ return [7 /*endfinally*/]; ++ case 5: return [2 /*return*/]; ++ } ++ }); ++} ++function ag() { ++ return __asyncGenerator(this, arguments, function ag_1() { ++ var env_18, d5, e_18; ++ var _a; ++ return __generator(this, function (_b) { ++ switch (_b.label) { ++ case 0: ++ env_18 = { stack: [], error: void 0, hasError: false }; ++ _b.label = 1; ++ case 1: ++ _b.trys.push([1, 5, 6, 7]); ++ d5 = __addDisposableResource(env_18, (_a = {}, _a[Symbol.dispose] = function () { }, _a), false); ++ return [4 /*yield*/, __await(void 0)]; ++ case 2: return [4 /*yield*/, _b.sent()]; ++ case 3: ++ _b.sent(); ++ return [4 /*yield*/, __await(null)]; ++ case 4: ++ _b.sent(); ++ return [3 /*break*/, 7]; ++ case 5: ++ e_18 = _b.sent(); ++ env_18.error = e_18; ++ env_18.hasError = true; ++ return [3 /*break*/, 7]; ++ case 6: ++ __disposeResources(env_18); ++ return [7 /*endfinally*/]; ++ case 7: return [2 /*return*/]; ++ } ++ }); ++ }); ++} ++var d1, a, C1, C2, C3, N, env_1; ++var env_2 = { stack: [], error: void 0, hasError: false }; ++try { ++ d1 = __addDisposableResource(env_2, (_a = {}, _a[Symbol.dispose] = function () { }, _a), false); ++ a = function () { ++ var _a; ++ var env_19 = { stack: [], error: void 0, hasError: false }; ++ try { ++ var d6 = __addDisposableResource(env_19, (_a = {}, _a[Symbol.dispose] = function () { }, _a), false); ++ } ++ catch (e_19) { ++ env_19.error = e_19; ++ env_19.hasError = true; ++ } ++ finally { ++ __disposeResources(env_19); ++ } ++ }; ++ C1 = (_r = /** @class */ (function () { ++ function C1() { ++ var _a; ++ this.a = function () { ++ var _a; ++ var env_21 = { stack: [], error: void 0, hasError: false }; ++ try { ++ var d7 = __addDisposableResource(env_21, (_a = {}, _a[Symbol.dispose] = function () { }, _a), false); ++ } ++ catch (e_21) { ++ env_21.error = e_21; ++ env_21.hasError = true; ++ } ++ finally { ++ __disposeResources(env_21); ++ } ++ }; ++ var env_20 = { stack: [], error: void 0, hasError: false }; ++ try { ++ var d8 = __addDisposableResource(env_20, (_a = {}, _a[Symbol.dispose] = function () { }, _a), false); ++ } ++ catch (e_20) { ++ env_20.error = e_20; ++ env_20.hasError = true; ++ } ++ finally { ++ __disposeResources(env_20); ++ } ++ } ++ C1.prototype.m = function () { ++ var _a; ++ var env_22 = { stack: [], error: void 0, hasError: false }; ++ try { ++ var d10 = __addDisposableResource(env_22, (_a = {}, _a[Symbol.dispose] = function () { }, _a), false); ++ } ++ catch (e_22) { ++ env_22.error = e_22; ++ env_22.hasError = true; ++ } ++ finally { ++ __disposeResources(env_22); ++ } ++ }; ++ Object.defineProperty(C1.prototype, "x", { ++ get: function () { ++ var _a; ++ var env_23 = { stack: [], error: void 0, hasError: false }; ++ try { ++ var d11 = __addDisposableResource(env_23, (_a = {}, _a[Symbol.dispose] = function () { }, _a), false); ++ return 0; ++ } ++ catch (e_23) { ++ env_23.error = e_23; ++ env_23.hasError = true; ++ } ++ finally { ++ __disposeResources(env_23); ++ } ++ }, ++ set: function (v) { ++ var _a; ++ var env_24 = { stack: [], error: void 0, hasError: false }; ++ try { ++ var d12 = __addDisposableResource(env_24, (_a = {}, _a[Symbol.dispose] = function () { }, _a), false); ++ } ++ catch (e_24) { ++ env_24.error = e_24; ++ env_24.hasError = true; ++ } ++ finally { ++ __disposeResources(env_24); ++ } ++ }, ++ enumerable: false, ++ configurable: true ++ }); ++ C1.prototype.am = function () { ++ return __awaiter(this, void 0, void 0, function () { ++ var env_25, d13, e_25; ++ var _a; ++ return __generator(this, function (_b) { ++ switch (_b.label) { ++ case 0: ++ env_25 = { stack: [], error: void 0, hasError: false }; ++ _b.label = 1; ++ case 1: ++ _b.trys.push([1, 3, 4, 5]); ++ d13 = __addDisposableResource(env_25, (_a = {}, _a[Symbol.dispose] = function () { }, _a), false); ++ return [4 /*yield*/, null]; ++ case 2: ++ _b.sent(); ++ return [3 /*break*/, 5]; ++ case 3: ++ e_25 = _b.sent(); ++ env_25.error = e_25; ++ env_25.hasError = true; ++ return [3 /*break*/, 5]; ++ case 4: ++ __disposeResources(env_25); ++ return [7 /*endfinally*/]; ++ case 5: return [2 /*return*/]; ++ } ++ }); ++ }); ++ }; ++ C1.prototype.g = function () { ++ var env_26, d14, e_26; ++ var _a; ++ return __generator(this, function (_b) { ++ switch (_b.label) { ++ case 0: ++ env_26 = { stack: [], error: void 0, hasError: false }; ++ _b.label = 1; ++ case 1: ++ _b.trys.push([1, 3, 4, 5]); ++ d14 = __addDisposableResource(env_26, (_a = {}, _a[Symbol.dispose] = function () { }, _a), false); ++ return [4 /*yield*/]; ++ case 2: ++ _b.sent(); ++ return [3 /*break*/, 5]; ++ case 3: ++ e_26 = _b.sent(); ++ env_26.error = e_26; ++ env_26.hasError = true; ++ return [3 /*break*/, 5]; ++ case 4: ++ __disposeResources(env_26); ++ return [7 /*endfinally*/]; ++ case 5: return [2 /*return*/]; ++ } ++ }); ++ }; ++ C1.prototype.ag = function () { ++ return __asyncGenerator(this, arguments, function ag_2() { ++ var env_27, d15, e_27; ++ var _a; ++ return __generator(this, function (_b) { ++ switch (_b.label) { ++ case 0: ++ env_27 = { stack: [], error: void 0, hasError: false }; ++ _b.label = 1; ++ case 1: ++ _b.trys.push([1, 5, 6, 7]); ++ d15 = __addDisposableResource(env_27, (_a = {}, _a[Symbol.dispose] = function () { }, _a), false); ++ return [4 /*yield*/, __await(void 0)]; ++ case 2: return [4 /*yield*/, _b.sent()]; ++ case 3: ++ _b.sent(); ++ return [4 /*yield*/, __await(null)]; ++ case 4: ++ _b.sent(); ++ return [3 /*break*/, 7]; ++ case 5: ++ e_27 = _b.sent(); ++ env_27.error = e_27; ++ env_27.hasError = true; ++ return [3 /*break*/, 7]; ++ case 6: ++ __disposeResources(env_27); ++ return [7 /*endfinally*/]; ++ case 7: return [2 /*return*/]; ++ } ++ }); ++ }); ++ }; ++ return C1; ++ }()), ++ (function () { ++ var _a; ++ var env_28 = { stack: [], error: void 0, hasError: false }; ++ try { ++ var d9 = __addDisposableResource(env_28, (_a = {}, _a[Symbol.dispose] = function () { }, _a), false); ++ } ++ catch (e_28) { ++ env_28.error = e_28; ++ env_28.hasError = true; ++ } ++ finally { ++ __disposeResources(env_28); ++ } ++ })(), ++ _r); ++ C2 = /** @class */ (function (_super) { ++ __extends(C2, _super); ++ function C2() { ++ var _a; ++ var env_29 = { stack: [], error: void 0, hasError: false }; ++ try { ++ var d16 = __addDisposableResource(env_29, (_a = {}, _a[Symbol.dispose] = function () { }, _a), false); ++ return _super.call(this) || this; ++ } ++ catch (e_29) { ++ env_29.error = e_29; ++ env_29.hasError = true; ++ } ++ finally { ++ __disposeResources(env_29); ++ } ++ } ++ return C2; ++ }(C1)); ++ C3 = /** @class */ (function (_super) { ++ __extends(C3, _super); ++ function C3() { ++ var _a; ++ var env_30 = { stack: [], error: void 0, hasError: false }; ++ try { ++ var _this = _super.call(this) || this; ++ var d17 = __addDisposableResource(env_30, (_a = {}, _a[Symbol.dispose] = function () { }, _a), false); ++ _this.y = 1; ++ } ++ catch (e_30) { ++ env_30.error = e_30; ++ env_30.hasError = true; ++ } ++ finally { ++ __disposeResources(env_30); ++ } ++ return _this; ++ } ++ return C3; ++ }(C1)); ++ (function (N) { ++ var _a; ++ var env_31 = { stack: [], error: void 0, hasError: false }; ++ try { ++ var d18 = __addDisposableResource(env_31, (_a = {}, _a[Symbol.dispose] = function () { }, _a), false); ++ } ++ catch (e_31) { ++ env_31.error = e_31; ++ env_31.hasError = true; ++ } ++ finally { ++ __disposeResources(env_31); ++ } ++ })(N || (N = {})); ++ { ++ var env_3 = { stack: [], error: void 0, hasError: false }; ++ try { ++ var d19 = __addDisposableResource(env_3, (_b = {}, _b[Symbol.dispose] = function () { }, _b), false); ++ } ++ catch (e_1) { ++ env_3.error = e_1; ++ env_3.hasError = true; ++ } ++ finally { ++ __disposeResources(env_3); ++ } ++ } ++ env_1 = { stack: [], error: void 0, hasError: false }; ++ try { ++ switch (Math.random()) { ++ case 0: ++ var d20 = __addDisposableResource(env_1, (_c = {}, _c[Symbol.dispose] = function () { }, _c), false); ++ break; ++ case 1: ++ var d21 = __addDisposableResource(env_1, (_d = {}, _d[Symbol.dispose] = function () { }, _d), false); ++ break; ++ } ++ } ++ catch (e_2) { ++ env_1.error = e_2; ++ env_1.hasError = true; ++ } ++ finally { ++ __disposeResources(env_1); ++ } ++ if (true) { ++ var env_4 = { stack: [], error: void 0, hasError: false }; ++ try { ++ switch (0) { ++ case 0: ++ var d22 = __addDisposableResource(env_4, (_e = {}, _e[Symbol.dispose] = function () { }, _e), false); ++ break; ++ } ++ } ++ catch (e_3) { ++ env_4.error = e_3; ++ env_4.hasError = true; ++ } ++ finally { ++ __disposeResources(env_4); ++ } ++ } ++ try { ++ var env_5 = { stack: [], error: void 0, hasError: false }; ++ try { ++ var d23 = __addDisposableResource(env_5, (_f = {}, _f[Symbol.dispose] = function () { }, _f), false); ++ } ++ catch (e_4) { ++ env_5.error = e_4; ++ env_5.hasError = true; ++ } ++ finally { ++ __disposeResources(env_5); ++ } ++ } ++ catch (_s) { ++ var env_6 = { stack: [], error: void 0, hasError: false }; ++ try { ++ var d24 = __addDisposableResource(env_6, (_g = {}, _g[Symbol.dispose] = function () { }, _g), false); ++ } ++ catch (e_5) { ++ env_6.error = e_5; ++ env_6.hasError = true; ++ } ++ finally { ++ __disposeResources(env_6); ++ } ++ } ++ finally { ++ var env_7 = { stack: [], error: void 0, hasError: false }; ++ try { ++ var d25 = __addDisposableResource(env_7, (_h = {}, _h[Symbol.dispose] = function () { }, _h), false); ++ } ++ catch (e_6) { ++ env_7.error = e_6; ++ env_7.hasError = true; ++ } ++ finally { ++ __disposeResources(env_7); ++ } ++ } ++ if (true) { ++ var env_8 = { stack: [], error: void 0, hasError: false }; ++ try { ++ var d26 = __addDisposableResource(env_8, (_j = {}, _j[Symbol.dispose] = function () { }, _j), false); ++ } ++ catch (e_7) { ++ env_8.error = e_7; ++ env_8.hasError = true; ++ } ++ finally { ++ __disposeResources(env_8); ++ } ++ } ++ else { ++ var env_9 = { stack: [], error: void 0, hasError: false }; ++ try { ++ var d27 = __addDisposableResource(env_9, (_k = {}, _k[Symbol.dispose] = function () { }, _k), false); ++ } ++ catch (e_8) { ++ env_9.error = e_8; ++ env_9.hasError = true; ++ } ++ finally { ++ __disposeResources(env_9); ++ } ++ } ++ while (true) { ++ var env_10 = { stack: [], error: void 0, hasError: false }; ++ try { ++ var d28 = __addDisposableResource(env_10, (_l = {}, _l[Symbol.dispose] = function () { }, _l), false); ++ break; ++ } ++ catch (e_9) { ++ env_10.error = e_9; ++ env_10.hasError = true; ++ } ++ finally { ++ __disposeResources(env_10); ++ } ++ } ++ do { ++ var env_11 = { stack: [], error: void 0, hasError: false }; ++ try { ++ var d29 = __addDisposableResource(env_11, (_m = {}, _m[Symbol.dispose] = function () { }, _m), false); ++ break; ++ } ++ catch (e_10) { ++ env_11.error = e_10; ++ env_11.hasError = true; ++ } ++ finally { ++ __disposeResources(env_11); ++ } ++ } while (true); ++ for (;;) { ++ var env_12 = { stack: [], error: void 0, hasError: false }; ++ try { ++ var d30 = __addDisposableResource(env_12, (_o = {}, _o[Symbol.dispose] = function () { }, _o), false); ++ break; ++ } ++ catch (e_11) { ++ env_12.error = e_11; ++ env_12.hasError = true; ++ } ++ finally { ++ __disposeResources(env_12); ++ } ++ } ++ for (var x in {}) { ++ var env_13 = { stack: [], error: void 0, hasError: false }; ++ try { ++ var d31 = __addDisposableResource(env_13, (_p = {}, _p[Symbol.dispose] = function () { }, _p), false); ++ } ++ catch (e_12) { ++ env_13.error = e_12; ++ env_13.hasError = true; ++ } ++ finally { ++ __disposeResources(env_13); ++ } ++ } ++ for (var _i = 0, _t = []; _i < _t.length; _i++) { ++ var x = _t[_i]; ++ var env_14 = { stack: [], error: void 0, hasError: false }; ++ try { ++ var d32 = __addDisposableResource(env_14, (_q = {}, _q[Symbol.dispose] = function () { }, _q), false); ++ } ++ catch (e_13) { ++ env_14.error = e_13; ++ env_14.hasError = true; ++ } ++ finally { ++ __disposeResources(env_14); ++ } ++ } ++} ++catch (e_14) { ++ env_2.error = e_14; ++ env_2.hasError = true; ++} ++finally { ++ __disposeResources(env_2); ++} ++export {}; +diff --git a/tests/baselines/reference/usingDeclarations.1(target=esnext).js b/tests/baselines/reference/usingDeclarations.1(target=esnext).js +new file mode 100644 +index 000000000..7f52b6f35 +--- /dev/null ++++ b/tests/baselines/reference/usingDeclarations.1(target=esnext).js +@@ -0,0 +1,278 @@ ++//// [tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarations.1.ts] //// ++ ++//// [usingDeclarations.1.ts] ++using d1 = { [Symbol.dispose]() {} }; ++ ++function f() { ++ using d2 = { [Symbol.dispose]() {} }; ++} ++ ++async function af() { ++ using d3 = { [Symbol.dispose]() {} }; ++ await null; ++} ++ ++function * g() { ++ using d4 = { [Symbol.dispose]() {} }; ++ yield; ++} ++ ++async function * ag() { ++ using d5 = { [Symbol.dispose]() {} }; ++ yield; ++ await null; ++} ++ ++const a = () => { ++ using d6 = { [Symbol.dispose]() {} }; ++} ++ ++class C1 { ++ a = () => { ++ using d7 = { [Symbol.dispose]() {} }; ++ } ++ ++ constructor() { ++ using d8 = { [Symbol.dispose]() {} }; ++ } ++ ++ static { ++ using d9 = { [Symbol.dispose]() {} }; ++ } ++ ++ m() { ++ using d10 = { [Symbol.dispose]() {} }; ++ } ++ ++ get x() { ++ using d11 = { [Symbol.dispose]() {} }; ++ return 0; ++ } ++ ++ set x(v) { ++ using d12 = { [Symbol.dispose]() {} }; ++ } ++ ++ async am() { ++ using d13 = { [Symbol.dispose]() {} }; ++ await null; ++ } ++ ++ * g() { ++ using d14 = { [Symbol.dispose]() {} }; ++ yield; ++ } ++ ++ async * ag() { ++ using d15 = { [Symbol.dispose]() {} }; ++ yield; ++ await null; ++ } ++} ++ ++class C2 extends C1 { ++ constructor() { ++ using d16 = { [Symbol.dispose]() {} }; ++ super(); ++ } ++} ++ ++class C3 extends C1 { ++ y = 1; ++ constructor() { ++ using d17 = { [Symbol.dispose]() {} }; ++ super(); ++ } ++} ++ ++namespace N { ++ using d18 = { [Symbol.dispose]() {} }; ++} ++ ++{ ++ using d19 = { [Symbol.dispose]() {} }; ++} ++ ++switch (Math.random()) { ++ case 0: ++ using d20 = { [Symbol.dispose]() {} }; ++ break; ++ ++ case 1: ++ using d21 = { [Symbol.dispose]() {} }; ++ break; ++} ++ ++if (true) ++ switch (0) { ++ case 0: ++ using d22 = { [Symbol.dispose]() {} }; ++ break; ++ } ++ ++try { ++ using d23 = { [Symbol.dispose]() {} }; ++} ++catch { ++ using d24 = { [Symbol.dispose]() {} }; ++} ++finally { ++ using d25 = { [Symbol.dispose]() {} }; ++} ++ ++if (true) { ++ using d26 = { [Symbol.dispose]() {} }; ++} ++else { ++ using d27 = { [Symbol.dispose]() {} }; ++} ++ ++while (true) { ++ using d28 = { [Symbol.dispose]() {} }; ++ break; ++} ++ ++do { ++ using d29 = { [Symbol.dispose]() {} }; ++ break; ++} ++while (true); ++ ++for (;;) { ++ using d30 = { [Symbol.dispose]() {} }; ++ break; ++} ++ ++for (const x in {}) { ++ using d31 = { [Symbol.dispose]() {} }; ++} ++ ++for (const x of []) { ++ using d32 = { [Symbol.dispose]() {} }; ++} ++ ++export {}; ++ ++//// [usingDeclarations.1.js] ++using d1 = { [Symbol.dispose]() { } }; ++function f() { ++ using d2 = { [Symbol.dispose]() { } }; ++} ++async function af() { ++ using d3 = { [Symbol.dispose]() { } }; ++ await null; ++} ++function* g() { ++ using d4 = { [Symbol.dispose]() { } }; ++ yield; ++} ++async function* ag() { ++ using d5 = { [Symbol.dispose]() { } }; ++ yield; ++ await null; ++} ++const a = () => { ++ using d6 = { [Symbol.dispose]() { } }; ++}; ++class C1 { ++ a = () => { ++ using d7 = { [Symbol.dispose]() { } }; ++ }; ++ constructor() { ++ using d8 = { [Symbol.dispose]() { } }; ++ } ++ static { ++ using d9 = { [Symbol.dispose]() { } }; ++ } ++ m() { ++ using d10 = { [Symbol.dispose]() { } }; ++ } ++ get x() { ++ using d11 = { [Symbol.dispose]() { } }; ++ return 0; ++ } ++ set x(v) { ++ using d12 = { [Symbol.dispose]() { } }; ++ } ++ async am() { ++ using d13 = { [Symbol.dispose]() { } }; ++ await null; ++ } ++ *g() { ++ using d14 = { [Symbol.dispose]() { } }; ++ yield; ++ } ++ async *ag() { ++ using d15 = { [Symbol.dispose]() { } }; ++ yield; ++ await null; ++ } ++} ++class C2 extends C1 { ++ constructor() { ++ using d16 = { [Symbol.dispose]() { } }; ++ super(); ++ } ++} ++class C3 extends C1 { ++ y = 1; ++ constructor() { ++ using d17 = { [Symbol.dispose]() { } }; ++ super(); ++ } ++} ++var N; ++(function (N) { ++ using d18 = { [Symbol.dispose]() { } }; ++})(N || (N = {})); ++{ ++ using d19 = { [Symbol.dispose]() { } }; ++} ++switch (Math.random()) { ++ case 0: ++ using d20 = { [Symbol.dispose]() { } }; ++ break; ++ case 1: ++ using d21 = { [Symbol.dispose]() { } }; ++ break; ++} ++if (true) ++ switch (0) { ++ case 0: ++ using d22 = { [Symbol.dispose]() { } }; ++ break; ++ } ++try { ++ using d23 = { [Symbol.dispose]() { } }; ++} ++catch { ++ using d24 = { [Symbol.dispose]() { } }; ++} ++finally { ++ using d25 = { [Symbol.dispose]() { } }; ++} ++if (true) { ++ using d26 = { [Symbol.dispose]() { } }; ++} ++else { ++ using d27 = { [Symbol.dispose]() { } }; ++} ++while (true) { ++ using d28 = { [Symbol.dispose]() { } }; ++ break; ++} ++do { ++ using d29 = { [Symbol.dispose]() { } }; ++ break; ++} while (true); ++for (;;) { ++ using d30 = { [Symbol.dispose]() { } }; ++ break; ++} ++for (const x in {}) { ++ using d31 = { [Symbol.dispose]() { } }; ++} ++for (const x of []) { ++ using d32 = { [Symbol.dispose]() { } }; ++} ++export {}; +diff --git a/tests/baselines/reference/usingDeclarations.10.errors.txt b/tests/baselines/reference/usingDeclarations.10.errors.txt +new file mode 100644 +index 000000000..b53dd1896 +--- /dev/null ++++ b/tests/baselines/reference/usingDeclarations.10.errors.txt +@@ -0,0 +1,9 @@ ++usingDeclarations.10.ts(2,8): error TS1156: 'using' declarations can only be declared inside a block. ++ ++ ++==== usingDeclarations.10.ts (1 errors) ==== ++ declare var x: any; ++ if (x) using a = null; ++ ~~~~~~~~~~~~~~~ ++!!! error TS1156: 'using' declarations can only be declared inside a block. ++ +\ No newline at end of file +diff --git a/tests/baselines/reference/usingDeclarations.10.js b/tests/baselines/reference/usingDeclarations.10.js +new file mode 100644 +index 000000000..91c2e067a +--- /dev/null ++++ b/tests/baselines/reference/usingDeclarations.10.js +@@ -0,0 +1,10 @@ ++//// [tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarations.10.ts] //// ++ ++//// [usingDeclarations.10.ts] ++declare var x: any; ++if (x) using a = null; ++ ++ ++//// [usingDeclarations.10.js] ++if (x) ++ using a = null; +diff --git a/tests/baselines/reference/usingDeclarations.11.js b/tests/baselines/reference/usingDeclarations.11.js +new file mode 100644 +index 000000000..3cce2dda6 +--- /dev/null ++++ b/tests/baselines/reference/usingDeclarations.11.js +@@ -0,0 +1,202 @@ ++//// [tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarations.11.ts] //// ++ ++//// [usingDeclarations.11.ts] ++class A {} ++class C1 extends A { ++ constructor() { ++ using x = null; ++ super(); ++ } ++} ++class C2 extends A { ++ constructor() { ++ super(); ++ using x = null; ++ } ++} ++class C3 extends A { ++ y = 1; ++ constructor() { ++ using x = null; ++ super(); ++ } ++} ++class C4 extends A { ++ constructor(public y: number) { ++ using x = null; ++ super(); ++ } ++} ++class C5 extends A { ++ z = 1; ++ constructor(public y: number) { ++ using x = null; ++ super(); ++ } ++} ++ ++ ++//// [usingDeclarations.11.js] ++var __extends = (this && this.__extends) || (function () { ++ var extendStatics = function (d, b) { ++ extendStatics = Object.setPrototypeOf || ++ ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || ++ function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; ++ return extendStatics(d, b); ++ }; ++ return function (d, b) { ++ if (typeof b !== "function" && b !== null) ++ throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); ++ extendStatics(d, b); ++ function __() { this.constructor = d; } ++ d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); ++ }; ++})(); ++var __addDisposableResource = (this && this.__addDisposableResource) || function (env, value, async) { ++ if (value !== null && value !== void 0) { ++ if (typeof value !== "object") throw new TypeError("Object expected."); ++ var dispose; ++ if (async) { ++ if (!Symbol.asyncDispose) throw new TypeError("Symbol.asyncDispose is not defined."); ++ dispose = value[Symbol.asyncDispose]; ++ } ++ if (dispose === void 0) { ++ if (!Symbol.dispose) throw new TypeError("Symbol.dispose is not defined."); ++ dispose = value[Symbol.dispose]; ++ } ++ if (typeof dispose !== "function") throw new TypeError("Object not disposable."); ++ env.stack.push({ value: value, dispose: dispose, async: async }); ++ } ++ else if (async) { ++ env.stack.push({ async: true }); ++ } ++ return value; ++}; ++var __disposeResources = (this && this.__disposeResources) || (function (SuppressedError) { ++ return function (env) { ++ function fail(e) { ++ env.error = env.hasError ? new SuppressedError(e, env.error, "An error was suppressed during disposal.") : e; ++ env.hasError = true; ++ } ++ function next() { ++ while (env.stack.length) { ++ var rec = env.stack.pop(); ++ try { ++ var result = rec.dispose && rec.dispose.call(rec.value); ++ if (rec.async) return Promise.resolve(result).then(next, function(e) { fail(e); return next(); }); ++ } ++ catch (e) { ++ fail(e); ++ } ++ } ++ if (env.hasError) throw env.error; ++ } ++ return next(); ++ }; ++})(typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) { ++ var e = new Error(message); ++ return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e; ++}); ++var A = /** @class */ (function () { ++ function A() { ++ } ++ return A; ++}()); ++var C1 = /** @class */ (function (_super) { ++ __extends(C1, _super); ++ function C1() { ++ var env_1 = { stack: [], error: void 0, hasError: false }; ++ try { ++ var x = __addDisposableResource(env_1, null, false); ++ return _super.call(this) || this; ++ } ++ catch (e_1) { ++ env_1.error = e_1; ++ env_1.hasError = true; ++ } ++ finally { ++ __disposeResources(env_1); ++ } ++ } ++ return C1; ++}(A)); ++var C2 = /** @class */ (function (_super) { ++ __extends(C2, _super); ++ function C2() { ++ var env_2 = { stack: [], error: void 0, hasError: false }; ++ try { ++ var _this = _super.call(this) || this; ++ var x = __addDisposableResource(env_2, null, false); ++ } ++ catch (e_2) { ++ env_2.error = e_2; ++ env_2.hasError = true; ++ } ++ finally { ++ __disposeResources(env_2); ++ } ++ return _this; ++ } ++ return C2; ++}(A)); ++var C3 = /** @class */ (function (_super) { ++ __extends(C3, _super); ++ function C3() { ++ var env_3 = { stack: [], error: void 0, hasError: false }; ++ try { ++ var _this = _super.call(this) || this; ++ var x = __addDisposableResource(env_3, null, false); ++ _this.y = 1; ++ } ++ catch (e_3) { ++ env_3.error = e_3; ++ env_3.hasError = true; ++ } ++ finally { ++ __disposeResources(env_3); ++ } ++ return _this; ++ } ++ return C3; ++}(A)); ++var C4 = /** @class */ (function (_super) { ++ __extends(C4, _super); ++ function C4(y) { ++ var env_4 = { stack: [], error: void 0, hasError: false }; ++ try { ++ var _this = _super.call(this) || this; ++ var x = __addDisposableResource(env_4, null, false); ++ _this.y = y; ++ } ++ catch (e_4) { ++ env_4.error = e_4; ++ env_4.hasError = true; ++ } ++ finally { ++ __disposeResources(env_4); ++ } ++ return _this; ++ } ++ return C4; ++}(A)); ++var C5 = /** @class */ (function (_super) { ++ __extends(C5, _super); ++ function C5(y) { ++ var env_5 = { stack: [], error: void 0, hasError: false }; ++ try { ++ var _this = _super.call(this) || this; ++ var x = __addDisposableResource(env_5, null, false); ++ _this.y = y; ++ _this.z = 1; ++ } ++ catch (e_5) { ++ env_5.error = e_5; ++ env_5.hasError = true; ++ } ++ finally { ++ __disposeResources(env_5); ++ } ++ return _this; ++ } ++ return C5; ++}(A)); +diff --git a/tests/baselines/reference/usingDeclarations.12(usedefineforclassfields=false).js b/tests/baselines/reference/usingDeclarations.12(usedefineforclassfields=false).js +new file mode 100644 +index 000000000..768b5142f +--- /dev/null ++++ b/tests/baselines/reference/usingDeclarations.12(usedefineforclassfields=false).js +@@ -0,0 +1,81 @@ ++//// [tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarations.12.ts] //// ++ ++//// [usingDeclarations.12.ts] ++class C1 { ++ constructor() {} ++} ++ ++class C2 extends C1 { ++ y = 1; ++ constructor() { ++ super(); ++ using d17 = { [Symbol.dispose]() {} }; ++ } ++} ++ ++//// [usingDeclarations.12.js] ++var __addDisposableResource = (this && this.__addDisposableResource) || function (env, value, async) { ++ if (value !== null && value !== void 0) { ++ if (typeof value !== "object") throw new TypeError("Object expected."); ++ var dispose; ++ if (async) { ++ if (!Symbol.asyncDispose) throw new TypeError("Symbol.asyncDispose is not defined."); ++ dispose = value[Symbol.asyncDispose]; ++ } ++ if (dispose === void 0) { ++ if (!Symbol.dispose) throw new TypeError("Symbol.dispose is not defined."); ++ dispose = value[Symbol.dispose]; ++ } ++ if (typeof dispose !== "function") throw new TypeError("Object not disposable."); ++ env.stack.push({ value: value, dispose: dispose, async: async }); ++ } ++ else if (async) { ++ env.stack.push({ async: true }); ++ } ++ return value; ++}; ++var __disposeResources = (this && this.__disposeResources) || (function (SuppressedError) { ++ return function (env) { ++ function fail(e) { ++ env.error = env.hasError ? new SuppressedError(e, env.error, "An error was suppressed during disposal.") : e; ++ env.hasError = true; ++ } ++ function next() { ++ while (env.stack.length) { ++ var rec = env.stack.pop(); ++ try { ++ var result = rec.dispose && rec.dispose.call(rec.value); ++ if (rec.async) return Promise.resolve(result).then(next, function(e) { fail(e); return next(); }); ++ } ++ catch (e) { ++ fail(e); ++ } ++ } ++ if (env.hasError) throw env.error; ++ } ++ return next(); ++ }; ++})(typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) { ++ var e = new Error(message); ++ return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e; ++}); ++class C1 { ++ constructor() { } ++} ++class C2 extends C1 { ++ constructor() { ++ const env_1 = { stack: [], error: void 0, hasError: false }; ++ try { ++ super(); ++ this.y = 1; ++ const d17 = __addDisposableResource(env_1, { [Symbol.dispose]() { } }, false); ++ } ++ catch (e_1) { ++ env_1.error = e_1; ++ env_1.hasError = true; ++ } ++ finally { ++ __disposeResources(env_1); ++ } ++ } ++} +diff --git a/tests/baselines/reference/usingDeclarations.12(usedefineforclassfields=true).js b/tests/baselines/reference/usingDeclarations.12(usedefineforclassfields=true).js +new file mode 100644 +index 000000000..641d086c1 +--- /dev/null ++++ b/tests/baselines/reference/usingDeclarations.12(usedefineforclassfields=true).js +@@ -0,0 +1,86 @@ ++//// [tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarations.12.ts] //// ++ ++//// [usingDeclarations.12.ts] ++class C1 { ++ constructor() {} ++} ++ ++class C2 extends C1 { ++ y = 1; ++ constructor() { ++ super(); ++ using d17 = { [Symbol.dispose]() {} }; ++ } ++} ++ ++//// [usingDeclarations.12.js] ++var __addDisposableResource = (this && this.__addDisposableResource) || function (env, value, async) { ++ if (value !== null && value !== void 0) { ++ if (typeof value !== "object") throw new TypeError("Object expected."); ++ var dispose; ++ if (async) { ++ if (!Symbol.asyncDispose) throw new TypeError("Symbol.asyncDispose is not defined."); ++ dispose = value[Symbol.asyncDispose]; ++ } ++ if (dispose === void 0) { ++ if (!Symbol.dispose) throw new TypeError("Symbol.dispose is not defined."); ++ dispose = value[Symbol.dispose]; ++ } ++ if (typeof dispose !== "function") throw new TypeError("Object not disposable."); ++ env.stack.push({ value: value, dispose: dispose, async: async }); ++ } ++ else if (async) { ++ env.stack.push({ async: true }); ++ } ++ return value; ++}; ++var __disposeResources = (this && this.__disposeResources) || (function (SuppressedError) { ++ return function (env) { ++ function fail(e) { ++ env.error = env.hasError ? new SuppressedError(e, env.error, "An error was suppressed during disposal.") : e; ++ env.hasError = true; ++ } ++ function next() { ++ while (env.stack.length) { ++ var rec = env.stack.pop(); ++ try { ++ var result = rec.dispose && rec.dispose.call(rec.value); ++ if (rec.async) return Promise.resolve(result).then(next, function(e) { fail(e); return next(); }); ++ } ++ catch (e) { ++ fail(e); ++ } ++ } ++ if (env.hasError) throw env.error; ++ } ++ return next(); ++ }; ++})(typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) { ++ var e = new Error(message); ++ return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e; ++}); ++class C1 { ++ constructor() { } ++} ++class C2 extends C1 { ++ constructor() { ++ const env_1 = { stack: [], error: void 0, hasError: false }; ++ try { ++ super(); ++ Object.defineProperty(this, "y", { ++ enumerable: true, ++ configurable: true, ++ writable: true, ++ value: 1 ++ }); ++ const d17 = __addDisposableResource(env_1, { [Symbol.dispose]() { } }, false); ++ } ++ catch (e_1) { ++ env_1.error = e_1; ++ env_1.hasError = true; ++ } ++ finally { ++ __disposeResources(env_1); ++ } ++ } ++} +diff --git a/tests/baselines/reference/usingDeclarations.13.errors.txt b/tests/baselines/reference/usingDeclarations.13.errors.txt +new file mode 100644 +index 000000000..b121a1570 +--- /dev/null ++++ b/tests/baselines/reference/usingDeclarations.13.errors.txt +@@ -0,0 +1,12 @@ ++usingDeclarations.13.ts(1,1): error TS1491: 'export' modifier cannot appear on a 'using' declaration. ++usingDeclarations.13.ts(2,1): error TS1491: 'declare' modifier cannot appear on a 'using' declaration. ++ ++ ++==== usingDeclarations.13.ts (2 errors) ==== ++ export using x = null; ++ ~~~~~~ ++!!! error TS1491: 'export' modifier cannot appear on a 'using' declaration. ++ declare using y: null; ++ ~~~~~~~ ++!!! error TS1491: 'declare' modifier cannot appear on a 'using' declaration. ++ +\ No newline at end of file +diff --git a/tests/baselines/reference/usingDeclarations.13.js b/tests/baselines/reference/usingDeclarations.13.js +new file mode 100644 +index 000000000..4b6587a99 +--- /dev/null ++++ b/tests/baselines/reference/usingDeclarations.13.js +@@ -0,0 +1,9 @@ ++//// [tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarations.13.ts] //// ++ ++//// [usingDeclarations.13.ts] ++export using x = null; ++declare using y: null; ++ ++ ++//// [usingDeclarations.13.js] ++export using x = null; +diff --git a/tests/baselines/reference/usingDeclarations.14.errors.txt b/tests/baselines/reference/usingDeclarations.14.errors.txt +new file mode 100644 +index 000000000..5d3e1507f +--- /dev/null ++++ b/tests/baselines/reference/usingDeclarations.14.errors.txt +@@ -0,0 +1,10 @@ ++usingDeclarations.14.ts(1,11): error TS2850: The initializer of a 'using' declaration must be either an object with a '[Symbol.dispose]()' method, or be 'null' or 'undefined'. ++ Property '[Symbol.dispose]' is missing in type '{}' but required in type 'Disposable'. ++ ++ ++==== usingDeclarations.14.ts (1 errors) ==== ++ using x = {}; ++ ~~ ++!!! error TS2850: The initializer of a 'using' declaration must be either an object with a '[Symbol.dispose]()' method, or be 'null' or 'undefined'. ++!!! error TS2850: Property '[Symbol.dispose]' is missing in type '{}' but required in type 'Disposable'. ++!!! related TS2728 lib.esnext.disposable.d.ts:--:--: '[Symbol.dispose]' is declared here. +\ No newline at end of file +diff --git a/tests/baselines/reference/usingDeclarations.14.js b/tests/baselines/reference/usingDeclarations.14.js +new file mode 100644 +index 000000000..600af3d71 +--- /dev/null ++++ b/tests/baselines/reference/usingDeclarations.14.js +@@ -0,0 +1,7 @@ ++//// [tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarations.14.ts] //// ++ ++//// [usingDeclarations.14.ts] ++using x = {}; ++ ++//// [usingDeclarations.14.js] ++using x = {}; +diff --git a/tests/baselines/reference/usingDeclarations.15.js b/tests/baselines/reference/usingDeclarations.15.js +new file mode 100644 +index 000000000..aeab9a383 +--- /dev/null ++++ b/tests/baselines/reference/usingDeclarations.15.js +@@ -0,0 +1,10 @@ ++//// [tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarations.15.ts] //// ++ ++//// [usingDeclarations.15.ts] ++export {}; ++ ++using _ = { [Symbol.dispose]() {} }; ++ ++//// [usingDeclarations.15.js] ++using _ = { [Symbol.dispose]() { } }; ++export {}; +diff --git a/tests/baselines/reference/usingDeclarations.2(target=es2015).js b/tests/baselines/reference/usingDeclarations.2(target=es2015).js +new file mode 100644 +index 000000000..66c7f0b96 +--- /dev/null ++++ b/tests/baselines/reference/usingDeclarations.2(target=es2015).js +@@ -0,0 +1,68 @@ ++//// [tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarations.2.ts] //// ++ ++//// [usingDeclarations.2.ts] ++{ ++ using d1 = { [Symbol.dispose]() {} }, ++ d2 = { [Symbol.dispose]() {} }; ++} ++ ++ ++//// [usingDeclarations.2.js] ++var __addDisposableResource = (this && this.__addDisposableResource) || function (env, value, async) { ++ if (value !== null && value !== void 0) { ++ if (typeof value !== "object") throw new TypeError("Object expected."); ++ var dispose; ++ if (async) { ++ if (!Symbol.asyncDispose) throw new TypeError("Symbol.asyncDispose is not defined."); ++ dispose = value[Symbol.asyncDispose]; ++ } ++ if (dispose === void 0) { ++ if (!Symbol.dispose) throw new TypeError("Symbol.dispose is not defined."); ++ dispose = value[Symbol.dispose]; ++ } ++ if (typeof dispose !== "function") throw new TypeError("Object not disposable."); ++ env.stack.push({ value: value, dispose: dispose, async: async }); ++ } ++ else if (async) { ++ env.stack.push({ async: true }); ++ } ++ return value; ++}; ++var __disposeResources = (this && this.__disposeResources) || (function (SuppressedError) { ++ return function (env) { ++ function fail(e) { ++ env.error = env.hasError ? new SuppressedError(e, env.error, "An error was suppressed during disposal.") : e; ++ env.hasError = true; ++ } ++ function next() { ++ while (env.stack.length) { ++ var rec = env.stack.pop(); ++ try { ++ var result = rec.dispose && rec.dispose.call(rec.value); ++ if (rec.async) return Promise.resolve(result).then(next, function(e) { fail(e); return next(); }); ++ } ++ catch (e) { ++ fail(e); ++ } ++ } ++ if (env.hasError) throw env.error; ++ } ++ return next(); ++ }; ++})(typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) { ++ var e = new Error(message); ++ return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e; ++}); ++{ ++ const env_1 = { stack: [], error: void 0, hasError: false }; ++ try { ++ const d1 = __addDisposableResource(env_1, { [Symbol.dispose]() { } }, false), d2 = __addDisposableResource(env_1, { [Symbol.dispose]() { } }, false); ++ } ++ catch (e_1) { ++ env_1.error = e_1; ++ env_1.hasError = true; ++ } ++ finally { ++ __disposeResources(env_1); ++ } ++} +diff --git a/tests/baselines/reference/usingDeclarations.2(target=es2017).js b/tests/baselines/reference/usingDeclarations.2(target=es2017).js +new file mode 100644 +index 000000000..66c7f0b96 +--- /dev/null ++++ b/tests/baselines/reference/usingDeclarations.2(target=es2017).js +@@ -0,0 +1,68 @@ ++//// [tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarations.2.ts] //// ++ ++//// [usingDeclarations.2.ts] ++{ ++ using d1 = { [Symbol.dispose]() {} }, ++ d2 = { [Symbol.dispose]() {} }; ++} ++ ++ ++//// [usingDeclarations.2.js] ++var __addDisposableResource = (this && this.__addDisposableResource) || function (env, value, async) { ++ if (value !== null && value !== void 0) { ++ if (typeof value !== "object") throw new TypeError("Object expected."); ++ var dispose; ++ if (async) { ++ if (!Symbol.asyncDispose) throw new TypeError("Symbol.asyncDispose is not defined."); ++ dispose = value[Symbol.asyncDispose]; ++ } ++ if (dispose === void 0) { ++ if (!Symbol.dispose) throw new TypeError("Symbol.dispose is not defined."); ++ dispose = value[Symbol.dispose]; ++ } ++ if (typeof dispose !== "function") throw new TypeError("Object not disposable."); ++ env.stack.push({ value: value, dispose: dispose, async: async }); ++ } ++ else if (async) { ++ env.stack.push({ async: true }); ++ } ++ return value; ++}; ++var __disposeResources = (this && this.__disposeResources) || (function (SuppressedError) { ++ return function (env) { ++ function fail(e) { ++ env.error = env.hasError ? new SuppressedError(e, env.error, "An error was suppressed during disposal.") : e; ++ env.hasError = true; ++ } ++ function next() { ++ while (env.stack.length) { ++ var rec = env.stack.pop(); ++ try { ++ var result = rec.dispose && rec.dispose.call(rec.value); ++ if (rec.async) return Promise.resolve(result).then(next, function(e) { fail(e); return next(); }); ++ } ++ catch (e) { ++ fail(e); ++ } ++ } ++ if (env.hasError) throw env.error; ++ } ++ return next(); ++ }; ++})(typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) { ++ var e = new Error(message); ++ return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e; ++}); ++{ ++ const env_1 = { stack: [], error: void 0, hasError: false }; ++ try { ++ const d1 = __addDisposableResource(env_1, { [Symbol.dispose]() { } }, false), d2 = __addDisposableResource(env_1, { [Symbol.dispose]() { } }, false); ++ } ++ catch (e_1) { ++ env_1.error = e_1; ++ env_1.hasError = true; ++ } ++ finally { ++ __disposeResources(env_1); ++ } ++} +diff --git a/tests/baselines/reference/usingDeclarations.2(target=es2022).js b/tests/baselines/reference/usingDeclarations.2(target=es2022).js +new file mode 100644 +index 000000000..66c7f0b96 +--- /dev/null ++++ b/tests/baselines/reference/usingDeclarations.2(target=es2022).js +@@ -0,0 +1,68 @@ ++//// [tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarations.2.ts] //// ++ ++//// [usingDeclarations.2.ts] ++{ ++ using d1 = { [Symbol.dispose]() {} }, ++ d2 = { [Symbol.dispose]() {} }; ++} ++ ++ ++//// [usingDeclarations.2.js] ++var __addDisposableResource = (this && this.__addDisposableResource) || function (env, value, async) { ++ if (value !== null && value !== void 0) { ++ if (typeof value !== "object") throw new TypeError("Object expected."); ++ var dispose; ++ if (async) { ++ if (!Symbol.asyncDispose) throw new TypeError("Symbol.asyncDispose is not defined."); ++ dispose = value[Symbol.asyncDispose]; ++ } ++ if (dispose === void 0) { ++ if (!Symbol.dispose) throw new TypeError("Symbol.dispose is not defined."); ++ dispose = value[Symbol.dispose]; ++ } ++ if (typeof dispose !== "function") throw new TypeError("Object not disposable."); ++ env.stack.push({ value: value, dispose: dispose, async: async }); ++ } ++ else if (async) { ++ env.stack.push({ async: true }); ++ } ++ return value; ++}; ++var __disposeResources = (this && this.__disposeResources) || (function (SuppressedError) { ++ return function (env) { ++ function fail(e) { ++ env.error = env.hasError ? new SuppressedError(e, env.error, "An error was suppressed during disposal.") : e; ++ env.hasError = true; ++ } ++ function next() { ++ while (env.stack.length) { ++ var rec = env.stack.pop(); ++ try { ++ var result = rec.dispose && rec.dispose.call(rec.value); ++ if (rec.async) return Promise.resolve(result).then(next, function(e) { fail(e); return next(); }); ++ } ++ catch (e) { ++ fail(e); ++ } ++ } ++ if (env.hasError) throw env.error; ++ } ++ return next(); ++ }; ++})(typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) { ++ var e = new Error(message); ++ return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e; ++}); ++{ ++ const env_1 = { stack: [], error: void 0, hasError: false }; ++ try { ++ const d1 = __addDisposableResource(env_1, { [Symbol.dispose]() { } }, false), d2 = __addDisposableResource(env_1, { [Symbol.dispose]() { } }, false); ++ } ++ catch (e_1) { ++ env_1.error = e_1; ++ env_1.hasError = true; ++ } ++ finally { ++ __disposeResources(env_1); ++ } ++} +diff --git a/tests/baselines/reference/usingDeclarations.2(target=es5).js b/tests/baselines/reference/usingDeclarations.2(target=es5).js +new file mode 100644 +index 000000000..cb89d9fb7 +--- /dev/null ++++ b/tests/baselines/reference/usingDeclarations.2(target=es5).js +@@ -0,0 +1,69 @@ ++//// [tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarations.2.ts] //// ++ ++//// [usingDeclarations.2.ts] ++{ ++ using d1 = { [Symbol.dispose]() {} }, ++ d2 = { [Symbol.dispose]() {} }; ++} ++ ++ ++//// [usingDeclarations.2.js] ++var __addDisposableResource = (this && this.__addDisposableResource) || function (env, value, async) { ++ if (value !== null && value !== void 0) { ++ if (typeof value !== "object") throw new TypeError("Object expected."); ++ var dispose; ++ if (async) { ++ if (!Symbol.asyncDispose) throw new TypeError("Symbol.asyncDispose is not defined."); ++ dispose = value[Symbol.asyncDispose]; ++ } ++ if (dispose === void 0) { ++ if (!Symbol.dispose) throw new TypeError("Symbol.dispose is not defined."); ++ dispose = value[Symbol.dispose]; ++ } ++ if (typeof dispose !== "function") throw new TypeError("Object not disposable."); ++ env.stack.push({ value: value, dispose: dispose, async: async }); ++ } ++ else if (async) { ++ env.stack.push({ async: true }); ++ } ++ return value; ++}; ++var __disposeResources = (this && this.__disposeResources) || (function (SuppressedError) { ++ return function (env) { ++ function fail(e) { ++ env.error = env.hasError ? new SuppressedError(e, env.error, "An error was suppressed during disposal.") : e; ++ env.hasError = true; ++ } ++ function next() { ++ while (env.stack.length) { ++ var rec = env.stack.pop(); ++ try { ++ var result = rec.dispose && rec.dispose.call(rec.value); ++ if (rec.async) return Promise.resolve(result).then(next, function(e) { fail(e); return next(); }); ++ } ++ catch (e) { ++ fail(e); ++ } ++ } ++ if (env.hasError) throw env.error; ++ } ++ return next(); ++ }; ++})(typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) { ++ var e = new Error(message); ++ return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e; ++}); ++var _a, _b; ++{ ++ var env_1 = { stack: [], error: void 0, hasError: false }; ++ try { ++ var d1 = __addDisposableResource(env_1, (_a = {}, _a[Symbol.dispose] = function () { }, _a), false), d2 = __addDisposableResource(env_1, (_b = {}, _b[Symbol.dispose] = function () { }, _b), false); ++ } ++ catch (e_1) { ++ env_1.error = e_1; ++ env_1.hasError = true; ++ } ++ finally { ++ __disposeResources(env_1); ++ } ++} +diff --git a/tests/baselines/reference/usingDeclarations.2(target=esnext).js b/tests/baselines/reference/usingDeclarations.2(target=esnext).js +new file mode 100644 +index 000000000..ad15c171c +--- /dev/null ++++ b/tests/baselines/reference/usingDeclarations.2(target=esnext).js +@@ -0,0 +1,13 @@ ++//// [tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarations.2.ts] //// ++ ++//// [usingDeclarations.2.ts] ++{ ++ using d1 = { [Symbol.dispose]() {} }, ++ d2 = { [Symbol.dispose]() {} }; ++} ++ ++ ++//// [usingDeclarations.2.js] ++{ ++ using d1 = { [Symbol.dispose]() { } }, d2 = { [Symbol.dispose]() { } }; ++} +diff --git a/tests/baselines/reference/usingDeclarations.3(target=es2015).js b/tests/baselines/reference/usingDeclarations.3(target=es2015).js +new file mode 100644 +index 000000000..061c93eba +--- /dev/null ++++ b/tests/baselines/reference/usingDeclarations.3(target=es2015).js +@@ -0,0 +1,70 @@ ++//// [tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarations.3.ts] //// ++ ++//// [usingDeclarations.3.ts] ++{ ++ using d1 = { [Symbol.dispose]() {} }, ++ d2 = null, ++ d3 = undefined, ++ d4 = { [Symbol.dispose]() {} }; ++} ++ ++ ++//// [usingDeclarations.3.js] ++var __addDisposableResource = (this && this.__addDisposableResource) || function (env, value, async) { ++ if (value !== null && value !== void 0) { ++ if (typeof value !== "object") throw new TypeError("Object expected."); ++ var dispose; ++ if (async) { ++ if (!Symbol.asyncDispose) throw new TypeError("Symbol.asyncDispose is not defined."); ++ dispose = value[Symbol.asyncDispose]; ++ } ++ if (dispose === void 0) { ++ if (!Symbol.dispose) throw new TypeError("Symbol.dispose is not defined."); ++ dispose = value[Symbol.dispose]; ++ } ++ if (typeof dispose !== "function") throw new TypeError("Object not disposable."); ++ env.stack.push({ value: value, dispose: dispose, async: async }); ++ } ++ else if (async) { ++ env.stack.push({ async: true }); ++ } ++ return value; ++}; ++var __disposeResources = (this && this.__disposeResources) || (function (SuppressedError) { ++ return function (env) { ++ function fail(e) { ++ env.error = env.hasError ? new SuppressedError(e, env.error, "An error was suppressed during disposal.") : e; ++ env.hasError = true; ++ } ++ function next() { ++ while (env.stack.length) { ++ var rec = env.stack.pop(); ++ try { ++ var result = rec.dispose && rec.dispose.call(rec.value); ++ if (rec.async) return Promise.resolve(result).then(next, function(e) { fail(e); return next(); }); ++ } ++ catch (e) { ++ fail(e); ++ } ++ } ++ if (env.hasError) throw env.error; ++ } ++ return next(); ++ }; ++})(typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) { ++ var e = new Error(message); ++ return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e; ++}); ++{ ++ const env_1 = { stack: [], error: void 0, hasError: false }; ++ try { ++ const d1 = __addDisposableResource(env_1, { [Symbol.dispose]() { } }, false), d2 = __addDisposableResource(env_1, null, false), d3 = __addDisposableResource(env_1, undefined, false), d4 = __addDisposableResource(env_1, { [Symbol.dispose]() { } }, false); ++ } ++ catch (e_1) { ++ env_1.error = e_1; ++ env_1.hasError = true; ++ } ++ finally { ++ __disposeResources(env_1); ++ } ++} +diff --git a/tests/baselines/reference/usingDeclarations.3(target=es2017).js b/tests/baselines/reference/usingDeclarations.3(target=es2017).js +new file mode 100644 +index 000000000..061c93eba +--- /dev/null ++++ b/tests/baselines/reference/usingDeclarations.3(target=es2017).js +@@ -0,0 +1,70 @@ ++//// [tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarations.3.ts] //// ++ ++//// [usingDeclarations.3.ts] ++{ ++ using d1 = { [Symbol.dispose]() {} }, ++ d2 = null, ++ d3 = undefined, ++ d4 = { [Symbol.dispose]() {} }; ++} ++ ++ ++//// [usingDeclarations.3.js] ++var __addDisposableResource = (this && this.__addDisposableResource) || function (env, value, async) { ++ if (value !== null && value !== void 0) { ++ if (typeof value !== "object") throw new TypeError("Object expected."); ++ var dispose; ++ if (async) { ++ if (!Symbol.asyncDispose) throw new TypeError("Symbol.asyncDispose is not defined."); ++ dispose = value[Symbol.asyncDispose]; ++ } ++ if (dispose === void 0) { ++ if (!Symbol.dispose) throw new TypeError("Symbol.dispose is not defined."); ++ dispose = value[Symbol.dispose]; ++ } ++ if (typeof dispose !== "function") throw new TypeError("Object not disposable."); ++ env.stack.push({ value: value, dispose: dispose, async: async }); ++ } ++ else if (async) { ++ env.stack.push({ async: true }); ++ } ++ return value; ++}; ++var __disposeResources = (this && this.__disposeResources) || (function (SuppressedError) { ++ return function (env) { ++ function fail(e) { ++ env.error = env.hasError ? new SuppressedError(e, env.error, "An error was suppressed during disposal.") : e; ++ env.hasError = true; ++ } ++ function next() { ++ while (env.stack.length) { ++ var rec = env.stack.pop(); ++ try { ++ var result = rec.dispose && rec.dispose.call(rec.value); ++ if (rec.async) return Promise.resolve(result).then(next, function(e) { fail(e); return next(); }); ++ } ++ catch (e) { ++ fail(e); ++ } ++ } ++ if (env.hasError) throw env.error; ++ } ++ return next(); ++ }; ++})(typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) { ++ var e = new Error(message); ++ return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e; ++}); ++{ ++ const env_1 = { stack: [], error: void 0, hasError: false }; ++ try { ++ const d1 = __addDisposableResource(env_1, { [Symbol.dispose]() { } }, false), d2 = __addDisposableResource(env_1, null, false), d3 = __addDisposableResource(env_1, undefined, false), d4 = __addDisposableResource(env_1, { [Symbol.dispose]() { } }, false); ++ } ++ catch (e_1) { ++ env_1.error = e_1; ++ env_1.hasError = true; ++ } ++ finally { ++ __disposeResources(env_1); ++ } ++} +diff --git a/tests/baselines/reference/usingDeclarations.3(target=es2022).js b/tests/baselines/reference/usingDeclarations.3(target=es2022).js +new file mode 100644 +index 000000000..061c93eba +--- /dev/null ++++ b/tests/baselines/reference/usingDeclarations.3(target=es2022).js +@@ -0,0 +1,70 @@ ++//// [tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarations.3.ts] //// ++ ++//// [usingDeclarations.3.ts] ++{ ++ using d1 = { [Symbol.dispose]() {} }, ++ d2 = null, ++ d3 = undefined, ++ d4 = { [Symbol.dispose]() {} }; ++} ++ ++ ++//// [usingDeclarations.3.js] ++var __addDisposableResource = (this && this.__addDisposableResource) || function (env, value, async) { ++ if (value !== null && value !== void 0) { ++ if (typeof value !== "object") throw new TypeError("Object expected."); ++ var dispose; ++ if (async) { ++ if (!Symbol.asyncDispose) throw new TypeError("Symbol.asyncDispose is not defined."); ++ dispose = value[Symbol.asyncDispose]; ++ } ++ if (dispose === void 0) { ++ if (!Symbol.dispose) throw new TypeError("Symbol.dispose is not defined."); ++ dispose = value[Symbol.dispose]; ++ } ++ if (typeof dispose !== "function") throw new TypeError("Object not disposable."); ++ env.stack.push({ value: value, dispose: dispose, async: async }); ++ } ++ else if (async) { ++ env.stack.push({ async: true }); ++ } ++ return value; ++}; ++var __disposeResources = (this && this.__disposeResources) || (function (SuppressedError) { ++ return function (env) { ++ function fail(e) { ++ env.error = env.hasError ? new SuppressedError(e, env.error, "An error was suppressed during disposal.") : e; ++ env.hasError = true; ++ } ++ function next() { ++ while (env.stack.length) { ++ var rec = env.stack.pop(); ++ try { ++ var result = rec.dispose && rec.dispose.call(rec.value); ++ if (rec.async) return Promise.resolve(result).then(next, function(e) { fail(e); return next(); }); ++ } ++ catch (e) { ++ fail(e); ++ } ++ } ++ if (env.hasError) throw env.error; ++ } ++ return next(); ++ }; ++})(typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) { ++ var e = new Error(message); ++ return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e; ++}); ++{ ++ const env_1 = { stack: [], error: void 0, hasError: false }; ++ try { ++ const d1 = __addDisposableResource(env_1, { [Symbol.dispose]() { } }, false), d2 = __addDisposableResource(env_1, null, false), d3 = __addDisposableResource(env_1, undefined, false), d4 = __addDisposableResource(env_1, { [Symbol.dispose]() { } }, false); ++ } ++ catch (e_1) { ++ env_1.error = e_1; ++ env_1.hasError = true; ++ } ++ finally { ++ __disposeResources(env_1); ++ } ++} +diff --git a/tests/baselines/reference/usingDeclarations.3(target=es5).js b/tests/baselines/reference/usingDeclarations.3(target=es5).js +new file mode 100644 +index 000000000..baf9f2096 +--- /dev/null ++++ b/tests/baselines/reference/usingDeclarations.3(target=es5).js +@@ -0,0 +1,71 @@ ++//// [tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarations.3.ts] //// ++ ++//// [usingDeclarations.3.ts] ++{ ++ using d1 = { [Symbol.dispose]() {} }, ++ d2 = null, ++ d3 = undefined, ++ d4 = { [Symbol.dispose]() {} }; ++} ++ ++ ++//// [usingDeclarations.3.js] ++var __addDisposableResource = (this && this.__addDisposableResource) || function (env, value, async) { ++ if (value !== null && value !== void 0) { ++ if (typeof value !== "object") throw new TypeError("Object expected."); ++ var dispose; ++ if (async) { ++ if (!Symbol.asyncDispose) throw new TypeError("Symbol.asyncDispose is not defined."); ++ dispose = value[Symbol.asyncDispose]; ++ } ++ if (dispose === void 0) { ++ if (!Symbol.dispose) throw new TypeError("Symbol.dispose is not defined."); ++ dispose = value[Symbol.dispose]; ++ } ++ if (typeof dispose !== "function") throw new TypeError("Object not disposable."); ++ env.stack.push({ value: value, dispose: dispose, async: async }); ++ } ++ else if (async) { ++ env.stack.push({ async: true }); ++ } ++ return value; ++}; ++var __disposeResources = (this && this.__disposeResources) || (function (SuppressedError) { ++ return function (env) { ++ function fail(e) { ++ env.error = env.hasError ? new SuppressedError(e, env.error, "An error was suppressed during disposal.") : e; ++ env.hasError = true; ++ } ++ function next() { ++ while (env.stack.length) { ++ var rec = env.stack.pop(); ++ try { ++ var result = rec.dispose && rec.dispose.call(rec.value); ++ if (rec.async) return Promise.resolve(result).then(next, function(e) { fail(e); return next(); }); ++ } ++ catch (e) { ++ fail(e); ++ } ++ } ++ if (env.hasError) throw env.error; ++ } ++ return next(); ++ }; ++})(typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) { ++ var e = new Error(message); ++ return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e; ++}); ++var _a, _b; ++{ ++ var env_1 = { stack: [], error: void 0, hasError: false }; ++ try { ++ var d1 = __addDisposableResource(env_1, (_a = {}, _a[Symbol.dispose] = function () { }, _a), false), d2 = __addDisposableResource(env_1, null, false), d3 = __addDisposableResource(env_1, undefined, false), d4 = __addDisposableResource(env_1, (_b = {}, _b[Symbol.dispose] = function () { }, _b), false); ++ } ++ catch (e_1) { ++ env_1.error = e_1; ++ env_1.hasError = true; ++ } ++ finally { ++ __disposeResources(env_1); ++ } ++} +diff --git a/tests/baselines/reference/usingDeclarations.3(target=esnext).js b/tests/baselines/reference/usingDeclarations.3(target=esnext).js +new file mode 100644 +index 000000000..7b5896595 +--- /dev/null ++++ b/tests/baselines/reference/usingDeclarations.3(target=esnext).js +@@ -0,0 +1,15 @@ ++//// [tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarations.3.ts] //// ++ ++//// [usingDeclarations.3.ts] ++{ ++ using d1 = { [Symbol.dispose]() {} }, ++ d2 = null, ++ d3 = undefined, ++ d4 = { [Symbol.dispose]() {} }; ++} ++ ++ ++//// [usingDeclarations.3.js] ++{ ++ using d1 = { [Symbol.dispose]() { } }, d2 = null, d3 = undefined, d4 = { [Symbol.dispose]() { } }; ++} +diff --git a/tests/baselines/reference/usingDeclarations.4.errors.txt b/tests/baselines/reference/usingDeclarations.4.errors.txt +new file mode 100644 +index 000000000..649ee1af9 +--- /dev/null ++++ b/tests/baselines/reference/usingDeclarations.4.errors.txt +@@ -0,0 +1,12 @@ ++usingDeclarations.4.ts(2,5): error TS2304: Cannot find name 'using'. ++usingDeclarations.4.ts(2,12): error TS2304: Cannot find name 'a'. ++ ++ ++==== usingDeclarations.4.ts (2 errors) ==== ++ { ++ using [a] = null; ++ ~~~~~ ++!!! error TS2304: Cannot find name 'using'. ++ ~ ++!!! error TS2304: Cannot find name 'a'. ++ } +\ No newline at end of file +diff --git a/tests/baselines/reference/usingDeclarations.4.js b/tests/baselines/reference/usingDeclarations.4.js +new file mode 100644 +index 000000000..38ca6b16c +--- /dev/null ++++ b/tests/baselines/reference/usingDeclarations.4.js +@@ -0,0 +1,11 @@ ++//// [tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarations.4.ts] //// ++ ++//// [usingDeclarations.4.ts] ++{ ++ using [a] = null; ++} ++ ++//// [usingDeclarations.4.js] ++{ ++ using[a] = null; ++} +diff --git a/tests/baselines/reference/usingDeclarations.5.errors.txt b/tests/baselines/reference/usingDeclarations.5.errors.txt +new file mode 100644 +index 000000000..ddb56031a +--- /dev/null ++++ b/tests/baselines/reference/usingDeclarations.5.errors.txt +@@ -0,0 +1,15 @@ ++usingDeclarations.5.ts(3,11): error TS1492: 'using' declarations may not have binding patterns. ++usingDeclarations.5.ts(3,11): error TS2488: Type 'null' must have a '[Symbol.iterator]()' method that returns an iterator. ++ ++ ++==== usingDeclarations.5.ts (2 errors) ==== ++ { ++ using a = null, ++ [b] = null, ++ ~~~ ++!!! error TS1492: 'using' declarations may not have binding patterns. ++ ~~~ ++!!! error TS2488: Type 'null' must have a '[Symbol.iterator]()' method that returns an iterator. ++ c = null; ++ } ++ +\ No newline at end of file +diff --git a/tests/baselines/reference/usingDeclarations.5.js b/tests/baselines/reference/usingDeclarations.5.js +new file mode 100644 +index 000000000..310622461 +--- /dev/null ++++ b/tests/baselines/reference/usingDeclarations.5.js +@@ -0,0 +1,14 @@ ++//// [tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarations.5.ts] //// ++ ++//// [usingDeclarations.5.ts] ++{ ++ using a = null, ++ [b] = null, ++ c = null; ++} ++ ++ ++//// [usingDeclarations.5.js] ++{ ++ using a = null, [b] = null, c = null; ++} +diff --git a/tests/baselines/reference/usingDeclarations.6.errors.txt b/tests/baselines/reference/usingDeclarations.6.errors.txt +new file mode 100644 +index 000000000..b03116526 +--- /dev/null ++++ b/tests/baselines/reference/usingDeclarations.6.errors.txt +@@ -0,0 +1,13 @@ ++usingDeclarations.6.ts(2,11): error TS1492: 'using' declarations may not have binding patterns. ++usingDeclarations.6.ts(2,12): error TS2339: Property 'a' does not exist on type 'null'. ++ ++ ++==== usingDeclarations.6.ts (2 errors) ==== ++ { ++ using {a} = null; ++ ~~~ ++!!! error TS1492: 'using' declarations may not have binding patterns. ++ ~ ++!!! error TS2339: Property 'a' does not exist on type 'null'. ++ } ++ +\ No newline at end of file +diff --git a/tests/baselines/reference/usingDeclarations.6.js b/tests/baselines/reference/usingDeclarations.6.js +new file mode 100644 +index 000000000..c7fef3335 +--- /dev/null ++++ b/tests/baselines/reference/usingDeclarations.6.js +@@ -0,0 +1,12 @@ ++//// [tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarations.6.ts] //// ++ ++//// [usingDeclarations.6.ts] ++{ ++ using {a} = null; ++} ++ ++ ++//// [usingDeclarations.6.js] ++{ ++ using { a } = null; ++} +diff --git a/tests/baselines/reference/usingDeclarations.7.errors.txt b/tests/baselines/reference/usingDeclarations.7.errors.txt +new file mode 100644 +index 000000000..78bb1f905 +--- /dev/null ++++ b/tests/baselines/reference/usingDeclarations.7.errors.txt +@@ -0,0 +1,14 @@ ++usingDeclarations.7.ts(3,11): error TS1492: 'using' declarations may not have binding patterns. ++usingDeclarations.7.ts(3,12): error TS2339: Property 'b' does not exist on type 'null'. ++ ++ ++==== usingDeclarations.7.ts (2 errors) ==== ++ { ++ using a = null, ++ {b} = null, ++ ~~~ ++!!! error TS1492: 'using' declarations may not have binding patterns. ++ ~ ++!!! error TS2339: Property 'b' does not exist on type 'null'. ++ c = null; ++ } +\ No newline at end of file +diff --git a/tests/baselines/reference/usingDeclarations.7.js b/tests/baselines/reference/usingDeclarations.7.js +new file mode 100644 +index 000000000..c92c8929a +--- /dev/null ++++ b/tests/baselines/reference/usingDeclarations.7.js +@@ -0,0 +1,13 @@ ++//// [tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarations.7.ts] //// ++ ++//// [usingDeclarations.7.ts] ++{ ++ using a = null, ++ {b} = null, ++ c = null; ++} ++ ++//// [usingDeclarations.7.js] ++{ ++ using a = null, { b } = null, c = null; ++} +diff --git a/tests/baselines/reference/usingDeclarations.8.errors.txt b/tests/baselines/reference/usingDeclarations.8.errors.txt +new file mode 100644 +index 000000000..4ed183efe +--- /dev/null ++++ b/tests/baselines/reference/usingDeclarations.8.errors.txt +@@ -0,0 +1,9 @@ ++usingDeclarations.8.ts(2,11): error TS1155: 'using' declarations must be initialized. ++ ++ ++==== usingDeclarations.8.ts (1 errors) ==== ++ { ++ using a; ++ ~ ++!!! error TS1155: 'using' declarations must be initialized. ++ } +\ No newline at end of file +diff --git a/tests/baselines/reference/usingDeclarations.8.js b/tests/baselines/reference/usingDeclarations.8.js +new file mode 100644 +index 000000000..3bfabea2c +--- /dev/null ++++ b/tests/baselines/reference/usingDeclarations.8.js +@@ -0,0 +1,11 @@ ++//// [tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarations.8.ts] //// ++ ++//// [usingDeclarations.8.ts] ++{ ++ using a; ++} ++ ++//// [usingDeclarations.8.js] ++{ ++ using a; ++} +diff --git a/tests/baselines/reference/usingDeclarations.9.errors.txt b/tests/baselines/reference/usingDeclarations.9.errors.txt +new file mode 100644 +index 000000000..9fec9843d +--- /dev/null ++++ b/tests/baselines/reference/usingDeclarations.9.errors.txt +@@ -0,0 +1,8 @@ ++error TS2318: Cannot find global type 'Disposable'. ++ ++ ++!!! error TS2318: Cannot find global type 'Disposable'. ++==== usingDeclarations.9.ts (0 errors) ==== ++ { ++ using a = null; ++ } +\ No newline at end of file +diff --git a/tests/baselines/reference/usingDeclarations.9.js b/tests/baselines/reference/usingDeclarations.9.js +new file mode 100644 +index 000000000..d423904e8 +--- /dev/null ++++ b/tests/baselines/reference/usingDeclarations.9.js +@@ -0,0 +1,11 @@ ++//// [tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarations.9.ts] //// ++ ++//// [usingDeclarations.9.ts] ++{ ++ using a = null; ++} ++ ++//// [usingDeclarations.9.js] ++{ ++ using a = null; ++} +diff --git a/tests/baselines/reference/usingDeclarationsDeclarationEmit.1.js b/tests/baselines/reference/usingDeclarationsDeclarationEmit.1.js +new file mode 100644 +index 000000000..8148df031 +--- /dev/null ++++ b/tests/baselines/reference/usingDeclarationsDeclarationEmit.1.js +@@ -0,0 +1,26 @@ ++//// [tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsDeclarationEmit.1.ts] //// ++ ++//// [usingDeclarationsDeclarationEmit.1.ts] ++using r1 = { [Symbol.dispose]() {} }; ++export { r1 }; ++ ++await using r2 = { async [Symbol.asyncDispose]() {} }; ++export { r2 }; ++ ++ ++//// [usingDeclarationsDeclarationEmit.1.js] ++using r1 = { [Symbol.dispose]() { } }; ++export { r1 }; ++await using r2 = { async [Symbol.asyncDispose]() { } }; ++export { r2 }; ++ ++ ++//// [usingDeclarationsDeclarationEmit.1.d.ts] ++declare const r1: { ++ [Symbol.dispose](): void; ++}; ++export { r1 }; ++declare const r2: { ++ [Symbol.asyncDispose](): Promise; ++}; ++export { r2 }; +diff --git a/tests/baselines/reference/usingDeclarationsDeclarationEmit.2.js b/tests/baselines/reference/usingDeclarationsDeclarationEmit.2.js +new file mode 100644 +index 000000000..f65f38ed8 +--- /dev/null ++++ b/tests/baselines/reference/usingDeclarationsDeclarationEmit.2.js +@@ -0,0 +1,26 @@ ++//// [tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsDeclarationEmit.2.ts] //// ++ ++//// [usingDeclarationsDeclarationEmit.2.ts] ++using r1 = { [Symbol.dispose]() {} }; ++export type R1 = typeof r1; ++ ++await using r2 = { async [Symbol.asyncDispose]() {} }; ++export type R2 = typeof r2; ++ ++ ++//// [usingDeclarationsDeclarationEmit.2.js] ++using r1 = { [Symbol.dispose]() { } }; ++await using r2 = { async [Symbol.asyncDispose]() { } }; ++export {}; ++ ++ ++//// [usingDeclarationsDeclarationEmit.2.d.ts] ++declare const r1: { ++ [Symbol.dispose](): void; ++}; ++export type R1 = typeof r1; ++declare const r2: { ++ [Symbol.asyncDispose](): Promise; ++}; ++export type R2 = typeof r2; ++export {}; +diff --git a/tests/baselines/reference/usingDeclarationsInFor(target=es2015).js b/tests/baselines/reference/usingDeclarationsInFor(target=es2015).js +new file mode 100644 +index 000000000..7138c3078 +--- /dev/null ++++ b/tests/baselines/reference/usingDeclarationsInFor(target=es2015).js +@@ -0,0 +1,68 @@ ++//// [tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsInFor.ts] //// ++ ++//// [usingDeclarationsInFor.ts] ++for (using d1 = { [Symbol.dispose]() {} }, d2 = null, d3 = undefined;;) { ++} ++ ++ ++//// [usingDeclarationsInFor.js] ++var __addDisposableResource = (this && this.__addDisposableResource) || function (env, value, async) { ++ if (value !== null && value !== void 0) { ++ if (typeof value !== "object") throw new TypeError("Object expected."); ++ var dispose; ++ if (async) { ++ if (!Symbol.asyncDispose) throw new TypeError("Symbol.asyncDispose is not defined."); ++ dispose = value[Symbol.asyncDispose]; ++ } ++ if (dispose === void 0) { ++ if (!Symbol.dispose) throw new TypeError("Symbol.dispose is not defined."); ++ dispose = value[Symbol.dispose]; ++ } ++ if (typeof dispose !== "function") throw new TypeError("Object not disposable."); ++ env.stack.push({ value: value, dispose: dispose, async: async }); ++ } ++ else if (async) { ++ env.stack.push({ async: true }); ++ } ++ return value; ++}; ++var __disposeResources = (this && this.__disposeResources) || (function (SuppressedError) { ++ return function (env) { ++ function fail(e) { ++ env.error = env.hasError ? new SuppressedError(e, env.error, "An error was suppressed during disposal.") : e; ++ env.hasError = true; ++ } ++ function next() { ++ while (env.stack.length) { ++ var rec = env.stack.pop(); ++ try { ++ var result = rec.dispose && rec.dispose.call(rec.value); ++ if (rec.async) return Promise.resolve(result).then(next, function(e) { fail(e); return next(); }); ++ } ++ catch (e) { ++ fail(e); ++ } ++ } ++ if (env.hasError) throw env.error; ++ } ++ return next(); ++ }; ++})(typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) { ++ var e = new Error(message); ++ return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e; ++}); ++{ ++ const env_1 = { stack: [], error: void 0, hasError: false }; ++ try { ++ const d1 = __addDisposableResource(env_1, { [Symbol.dispose]() { } }, false), d2 = __addDisposableResource(env_1, null, false), d3 = __addDisposableResource(env_1, undefined, false); ++ for (;;) { ++ } ++ } ++ catch (e_1) { ++ env_1.error = e_1; ++ env_1.hasError = true; ++ } ++ finally { ++ __disposeResources(env_1); ++ } ++} +diff --git a/tests/baselines/reference/usingDeclarationsInFor(target=es2017).js b/tests/baselines/reference/usingDeclarationsInFor(target=es2017).js +new file mode 100644 +index 000000000..7138c3078 +--- /dev/null ++++ b/tests/baselines/reference/usingDeclarationsInFor(target=es2017).js +@@ -0,0 +1,68 @@ ++//// [tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsInFor.ts] //// ++ ++//// [usingDeclarationsInFor.ts] ++for (using d1 = { [Symbol.dispose]() {} }, d2 = null, d3 = undefined;;) { ++} ++ ++ ++//// [usingDeclarationsInFor.js] ++var __addDisposableResource = (this && this.__addDisposableResource) || function (env, value, async) { ++ if (value !== null && value !== void 0) { ++ if (typeof value !== "object") throw new TypeError("Object expected."); ++ var dispose; ++ if (async) { ++ if (!Symbol.asyncDispose) throw new TypeError("Symbol.asyncDispose is not defined."); ++ dispose = value[Symbol.asyncDispose]; ++ } ++ if (dispose === void 0) { ++ if (!Symbol.dispose) throw new TypeError("Symbol.dispose is not defined."); ++ dispose = value[Symbol.dispose]; ++ } ++ if (typeof dispose !== "function") throw new TypeError("Object not disposable."); ++ env.stack.push({ value: value, dispose: dispose, async: async }); ++ } ++ else if (async) { ++ env.stack.push({ async: true }); ++ } ++ return value; ++}; ++var __disposeResources = (this && this.__disposeResources) || (function (SuppressedError) { ++ return function (env) { ++ function fail(e) { ++ env.error = env.hasError ? new SuppressedError(e, env.error, "An error was suppressed during disposal.") : e; ++ env.hasError = true; ++ } ++ function next() { ++ while (env.stack.length) { ++ var rec = env.stack.pop(); ++ try { ++ var result = rec.dispose && rec.dispose.call(rec.value); ++ if (rec.async) return Promise.resolve(result).then(next, function(e) { fail(e); return next(); }); ++ } ++ catch (e) { ++ fail(e); ++ } ++ } ++ if (env.hasError) throw env.error; ++ } ++ return next(); ++ }; ++})(typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) { ++ var e = new Error(message); ++ return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e; ++}); ++{ ++ const env_1 = { stack: [], error: void 0, hasError: false }; ++ try { ++ const d1 = __addDisposableResource(env_1, { [Symbol.dispose]() { } }, false), d2 = __addDisposableResource(env_1, null, false), d3 = __addDisposableResource(env_1, undefined, false); ++ for (;;) { ++ } ++ } ++ catch (e_1) { ++ env_1.error = e_1; ++ env_1.hasError = true; ++ } ++ finally { ++ __disposeResources(env_1); ++ } ++} +diff --git a/tests/baselines/reference/usingDeclarationsInFor(target=es2022).js b/tests/baselines/reference/usingDeclarationsInFor(target=es2022).js +new file mode 100644 +index 000000000..7138c3078 +--- /dev/null ++++ b/tests/baselines/reference/usingDeclarationsInFor(target=es2022).js +@@ -0,0 +1,68 @@ ++//// [tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsInFor.ts] //// ++ ++//// [usingDeclarationsInFor.ts] ++for (using d1 = { [Symbol.dispose]() {} }, d2 = null, d3 = undefined;;) { ++} ++ ++ ++//// [usingDeclarationsInFor.js] ++var __addDisposableResource = (this && this.__addDisposableResource) || function (env, value, async) { ++ if (value !== null && value !== void 0) { ++ if (typeof value !== "object") throw new TypeError("Object expected."); ++ var dispose; ++ if (async) { ++ if (!Symbol.asyncDispose) throw new TypeError("Symbol.asyncDispose is not defined."); ++ dispose = value[Symbol.asyncDispose]; ++ } ++ if (dispose === void 0) { ++ if (!Symbol.dispose) throw new TypeError("Symbol.dispose is not defined."); ++ dispose = value[Symbol.dispose]; ++ } ++ if (typeof dispose !== "function") throw new TypeError("Object not disposable."); ++ env.stack.push({ value: value, dispose: dispose, async: async }); ++ } ++ else if (async) { ++ env.stack.push({ async: true }); ++ } ++ return value; ++}; ++var __disposeResources = (this && this.__disposeResources) || (function (SuppressedError) { ++ return function (env) { ++ function fail(e) { ++ env.error = env.hasError ? new SuppressedError(e, env.error, "An error was suppressed during disposal.") : e; ++ env.hasError = true; ++ } ++ function next() { ++ while (env.stack.length) { ++ var rec = env.stack.pop(); ++ try { ++ var result = rec.dispose && rec.dispose.call(rec.value); ++ if (rec.async) return Promise.resolve(result).then(next, function(e) { fail(e); return next(); }); ++ } ++ catch (e) { ++ fail(e); ++ } ++ } ++ if (env.hasError) throw env.error; ++ } ++ return next(); ++ }; ++})(typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) { ++ var e = new Error(message); ++ return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e; ++}); ++{ ++ const env_1 = { stack: [], error: void 0, hasError: false }; ++ try { ++ const d1 = __addDisposableResource(env_1, { [Symbol.dispose]() { } }, false), d2 = __addDisposableResource(env_1, null, false), d3 = __addDisposableResource(env_1, undefined, false); ++ for (;;) { ++ } ++ } ++ catch (e_1) { ++ env_1.error = e_1; ++ env_1.hasError = true; ++ } ++ finally { ++ __disposeResources(env_1); ++ } ++} +diff --git a/tests/baselines/reference/usingDeclarationsInFor(target=es5).js b/tests/baselines/reference/usingDeclarationsInFor(target=es5).js +new file mode 100644 +index 000000000..c8cff8bb8 +--- /dev/null ++++ b/tests/baselines/reference/usingDeclarationsInFor(target=es5).js +@@ -0,0 +1,69 @@ ++//// [tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsInFor.ts] //// ++ ++//// [usingDeclarationsInFor.ts] ++for (using d1 = { [Symbol.dispose]() {} }, d2 = null, d3 = undefined;;) { ++} ++ ++ ++//// [usingDeclarationsInFor.js] ++var __addDisposableResource = (this && this.__addDisposableResource) || function (env, value, async) { ++ if (value !== null && value !== void 0) { ++ if (typeof value !== "object") throw new TypeError("Object expected."); ++ var dispose; ++ if (async) { ++ if (!Symbol.asyncDispose) throw new TypeError("Symbol.asyncDispose is not defined."); ++ dispose = value[Symbol.asyncDispose]; ++ } ++ if (dispose === void 0) { ++ if (!Symbol.dispose) throw new TypeError("Symbol.dispose is not defined."); ++ dispose = value[Symbol.dispose]; ++ } ++ if (typeof dispose !== "function") throw new TypeError("Object not disposable."); ++ env.stack.push({ value: value, dispose: dispose, async: async }); ++ } ++ else if (async) { ++ env.stack.push({ async: true }); ++ } ++ return value; ++}; ++var __disposeResources = (this && this.__disposeResources) || (function (SuppressedError) { ++ return function (env) { ++ function fail(e) { ++ env.error = env.hasError ? new SuppressedError(e, env.error, "An error was suppressed during disposal.") : e; ++ env.hasError = true; ++ } ++ function next() { ++ while (env.stack.length) { ++ var rec = env.stack.pop(); ++ try { ++ var result = rec.dispose && rec.dispose.call(rec.value); ++ if (rec.async) return Promise.resolve(result).then(next, function(e) { fail(e); return next(); }); ++ } ++ catch (e) { ++ fail(e); ++ } ++ } ++ if (env.hasError) throw env.error; ++ } ++ return next(); ++ }; ++})(typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) { ++ var e = new Error(message); ++ return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e; ++}); ++var _a; ++{ ++ var env_1 = { stack: [], error: void 0, hasError: false }; ++ try { ++ var d1 = __addDisposableResource(env_1, (_a = {}, _a[Symbol.dispose] = function () { }, _a), false), d2 = __addDisposableResource(env_1, null, false), d3 = __addDisposableResource(env_1, undefined, false); ++ for (;;) { ++ } ++ } ++ catch (e_1) { ++ env_1.error = e_1; ++ env_1.hasError = true; ++ } ++ finally { ++ __disposeResources(env_1); ++ } ++} +diff --git a/tests/baselines/reference/usingDeclarationsInFor(target=esnext).js b/tests/baselines/reference/usingDeclarationsInFor(target=esnext).js +new file mode 100644 +index 000000000..f279fdb59 +--- /dev/null ++++ b/tests/baselines/reference/usingDeclarationsInFor(target=esnext).js +@@ -0,0 +1,10 @@ ++//// [tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsInFor.ts] //// ++ ++//// [usingDeclarationsInFor.ts] ++for (using d1 = { [Symbol.dispose]() {} }, d2 = null, d3 = undefined;;) { ++} ++ ++ ++//// [usingDeclarationsInFor.js] ++for (using d1 = { [Symbol.dispose]() { } }, d2 = null, d3 = undefined;;) { ++} +diff --git a/tests/baselines/reference/usingDeclarationsInForAwaitOf(target=es2015).js b/tests/baselines/reference/usingDeclarationsInForAwaitOf(target=es2015).js +new file mode 100644 +index 000000000..24f12546a +--- /dev/null ++++ b/tests/baselines/reference/usingDeclarationsInForAwaitOf(target=es2015).js +@@ -0,0 +1,101 @@ ++//// [tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsInForAwaitOf.ts] //// ++ ++//// [usingDeclarationsInForAwaitOf.ts] ++async function main() { ++ for await (using d1 of [{ [Symbol.dispose]() {} }, null, undefined]) { ++ } ++} ++ ++ ++//// [usingDeclarationsInForAwaitOf.js] ++var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { ++ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } ++ return new (P || (P = Promise))(function (resolve, reject) { ++ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } ++ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } ++ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } ++ step((generator = generator.apply(thisArg, _arguments || [])).next()); ++ }); ++}; ++var __addDisposableResource = (this && this.__addDisposableResource) || function (env, value, async) { ++ if (value !== null && value !== void 0) { ++ if (typeof value !== "object") throw new TypeError("Object expected."); ++ var dispose; ++ if (async) { ++ if (!Symbol.asyncDispose) throw new TypeError("Symbol.asyncDispose is not defined."); ++ dispose = value[Symbol.asyncDispose]; ++ } ++ if (dispose === void 0) { ++ if (!Symbol.dispose) throw new TypeError("Symbol.dispose is not defined."); ++ dispose = value[Symbol.dispose]; ++ } ++ if (typeof dispose !== "function") throw new TypeError("Object not disposable."); ++ env.stack.push({ value: value, dispose: dispose, async: async }); ++ } ++ else if (async) { ++ env.stack.push({ async: true }); ++ } ++ return value; ++}; ++var __disposeResources = (this && this.__disposeResources) || (function (SuppressedError) { ++ return function (env) { ++ function fail(e) { ++ env.error = env.hasError ? new SuppressedError(e, env.error, "An error was suppressed during disposal.") : e; ++ env.hasError = true; ++ } ++ function next() { ++ while (env.stack.length) { ++ var rec = env.stack.pop(); ++ try { ++ var result = rec.dispose && rec.dispose.call(rec.value); ++ if (rec.async) return Promise.resolve(result).then(next, function(e) { fail(e); return next(); }); ++ } ++ catch (e) { ++ fail(e); ++ } ++ } ++ if (env.hasError) throw env.error; ++ } ++ return next(); ++ }; ++})(typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) { ++ var e = new Error(message); ++ return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e; ++}); ++var __asyncValues = (this && this.__asyncValues) || function (o) { ++ if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); ++ var m = o[Symbol.asyncIterator], i; ++ return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i); ++ function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; } ++ function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); } ++}; ++function main() { ++ var _a, e_1, _b, _c; ++ return __awaiter(this, void 0, void 0, function* () { ++ try { ++ for (var _d = true, _e = __asyncValues([{ [Symbol.dispose]() { } }, null, undefined]), _f; _f = yield _e.next(), _a = _f.done, !_a; _d = true) { ++ _c = _f.value; ++ _d = false; ++ const d1_1 = _c; ++ const env_1 = { stack: [], error: void 0, hasError: false }; ++ try { ++ const d1 = __addDisposableResource(env_1, d1_1, false); ++ } ++ catch (e_2) { ++ env_1.error = e_2; ++ env_1.hasError = true; ++ } ++ finally { ++ __disposeResources(env_1); ++ } ++ } ++ } ++ catch (e_1_1) { e_1 = { error: e_1_1 }; } ++ finally { ++ try { ++ if (!_d && !_a && (_b = _e.return)) yield _b.call(_e); ++ } ++ finally { if (e_1) throw e_1.error; } ++ } ++ }); ++} +diff --git a/tests/baselines/reference/usingDeclarationsInForAwaitOf(target=es2017).js b/tests/baselines/reference/usingDeclarationsInForAwaitOf(target=es2017).js +new file mode 100644 +index 000000000..988c9fbea +--- /dev/null ++++ b/tests/baselines/reference/usingDeclarationsInForAwaitOf(target=es2017).js +@@ -0,0 +1,90 @@ ++//// [tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsInForAwaitOf.ts] //// ++ ++//// [usingDeclarationsInForAwaitOf.ts] ++async function main() { ++ for await (using d1 of [{ [Symbol.dispose]() {} }, null, undefined]) { ++ } ++} ++ ++ ++//// [usingDeclarationsInForAwaitOf.js] ++var __addDisposableResource = (this && this.__addDisposableResource) || function (env, value, async) { ++ if (value !== null && value !== void 0) { ++ if (typeof value !== "object") throw new TypeError("Object expected."); ++ var dispose; ++ if (async) { ++ if (!Symbol.asyncDispose) throw new TypeError("Symbol.asyncDispose is not defined."); ++ dispose = value[Symbol.asyncDispose]; ++ } ++ if (dispose === void 0) { ++ if (!Symbol.dispose) throw new TypeError("Symbol.dispose is not defined."); ++ dispose = value[Symbol.dispose]; ++ } ++ if (typeof dispose !== "function") throw new TypeError("Object not disposable."); ++ env.stack.push({ value: value, dispose: dispose, async: async }); ++ } ++ else if (async) { ++ env.stack.push({ async: true }); ++ } ++ return value; ++}; ++var __disposeResources = (this && this.__disposeResources) || (function (SuppressedError) { ++ return function (env) { ++ function fail(e) { ++ env.error = env.hasError ? new SuppressedError(e, env.error, "An error was suppressed during disposal.") : e; ++ env.hasError = true; ++ } ++ function next() { ++ while (env.stack.length) { ++ var rec = env.stack.pop(); ++ try { ++ var result = rec.dispose && rec.dispose.call(rec.value); ++ if (rec.async) return Promise.resolve(result).then(next, function(e) { fail(e); return next(); }); ++ } ++ catch (e) { ++ fail(e); ++ } ++ } ++ if (env.hasError) throw env.error; ++ } ++ return next(); ++ }; ++})(typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) { ++ var e = new Error(message); ++ return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e; ++}); ++var __asyncValues = (this && this.__asyncValues) || function (o) { ++ if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); ++ var m = o[Symbol.asyncIterator], i; ++ return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i); ++ function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; } ++ function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); } ++}; ++async function main() { ++ var _a, e_1, _b, _c; ++ try { ++ for (var _d = true, _e = __asyncValues([{ [Symbol.dispose]() { } }, null, undefined]), _f; _f = await _e.next(), _a = _f.done, !_a; _d = true) { ++ _c = _f.value; ++ _d = false; ++ const d1_1 = _c; ++ const env_1 = { stack: [], error: void 0, hasError: false }; ++ try { ++ const d1 = __addDisposableResource(env_1, d1_1, false); ++ } ++ catch (e_2) { ++ env_1.error = e_2; ++ env_1.hasError = true; ++ } ++ finally { ++ __disposeResources(env_1); ++ } ++ } ++ } ++ catch (e_1_1) { e_1 = { error: e_1_1 }; } ++ finally { ++ try { ++ if (!_d && !_a && (_b = _e.return)) await _b.call(_e); ++ } ++ finally { if (e_1) throw e_1.error; } ++ } ++} +diff --git a/tests/baselines/reference/usingDeclarationsInForAwaitOf(target=es2022).js b/tests/baselines/reference/usingDeclarationsInForAwaitOf(target=es2022).js +new file mode 100644 +index 000000000..00737468c +--- /dev/null ++++ b/tests/baselines/reference/usingDeclarationsInForAwaitOf(target=es2022).js +@@ -0,0 +1,70 @@ ++//// [tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsInForAwaitOf.ts] //// ++ ++//// [usingDeclarationsInForAwaitOf.ts] ++async function main() { ++ for await (using d1 of [{ [Symbol.dispose]() {} }, null, undefined]) { ++ } ++} ++ ++ ++//// [usingDeclarationsInForAwaitOf.js] ++var __addDisposableResource = (this && this.__addDisposableResource) || function (env, value, async) { ++ if (value !== null && value !== void 0) { ++ if (typeof value !== "object") throw new TypeError("Object expected."); ++ var dispose; ++ if (async) { ++ if (!Symbol.asyncDispose) throw new TypeError("Symbol.asyncDispose is not defined."); ++ dispose = value[Symbol.asyncDispose]; ++ } ++ if (dispose === void 0) { ++ if (!Symbol.dispose) throw new TypeError("Symbol.dispose is not defined."); ++ dispose = value[Symbol.dispose]; ++ } ++ if (typeof dispose !== "function") throw new TypeError("Object not disposable."); ++ env.stack.push({ value: value, dispose: dispose, async: async }); ++ } ++ else if (async) { ++ env.stack.push({ async: true }); ++ } ++ return value; ++}; ++var __disposeResources = (this && this.__disposeResources) || (function (SuppressedError) { ++ return function (env) { ++ function fail(e) { ++ env.error = env.hasError ? new SuppressedError(e, env.error, "An error was suppressed during disposal.") : e; ++ env.hasError = true; ++ } ++ function next() { ++ while (env.stack.length) { ++ var rec = env.stack.pop(); ++ try { ++ var result = rec.dispose && rec.dispose.call(rec.value); ++ if (rec.async) return Promise.resolve(result).then(next, function(e) { fail(e); return next(); }); ++ } ++ catch (e) { ++ fail(e); ++ } ++ } ++ if (env.hasError) throw env.error; ++ } ++ return next(); ++ }; ++})(typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) { ++ var e = new Error(message); ++ return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e; ++}); ++async function main() { ++ for await (const d1_1 of [{ [Symbol.dispose]() { } }, null, undefined]) { ++ const env_1 = { stack: [], error: void 0, hasError: false }; ++ try { ++ const d1 = __addDisposableResource(env_1, d1_1, false); ++ } ++ catch (e_1) { ++ env_1.error = e_1; ++ env_1.hasError = true; ++ } ++ finally { ++ __disposeResources(env_1); ++ } ++ } ++} +diff --git a/tests/baselines/reference/usingDeclarationsInForAwaitOf(target=es5).js b/tests/baselines/reference/usingDeclarationsInForAwaitOf(target=es5).js +new file mode 100644 +index 000000000..0ad207f75 +--- /dev/null ++++ b/tests/baselines/reference/usingDeclarationsInForAwaitOf(target=es5).js +@@ -0,0 +1,152 @@ ++//// [tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsInForAwaitOf.ts] //// ++ ++//// [usingDeclarationsInForAwaitOf.ts] ++async function main() { ++ for await (using d1 of [{ [Symbol.dispose]() {} }, null, undefined]) { ++ } ++} ++ ++ ++//// [usingDeclarationsInForAwaitOf.js] ++var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { ++ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } ++ return new (P || (P = Promise))(function (resolve, reject) { ++ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } ++ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } ++ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } ++ step((generator = generator.apply(thisArg, _arguments || [])).next()); ++ }); ++}; ++var __generator = (this && this.__generator) || function (thisArg, body) { ++ var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; ++ return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; ++ function verb(n) { return function (v) { return step([n, v]); }; } ++ function step(op) { ++ if (f) throw new TypeError("Generator is already executing."); ++ while (g && (g = 0, op[0] && (_ = 0)), _) try { ++ if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; ++ if (y = 0, t) op = [op[0] & 2, t.value]; ++ switch (op[0]) { ++ case 0: case 1: t = op; break; ++ case 4: _.label++; return { value: op[1], done: false }; ++ case 5: _.label++; y = op[1]; op = [0]; continue; ++ case 7: op = _.ops.pop(); _.trys.pop(); continue; ++ default: ++ if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } ++ if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } ++ if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } ++ if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } ++ if (t[2]) _.ops.pop(); ++ _.trys.pop(); continue; ++ } ++ op = body.call(thisArg, _); ++ } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } ++ if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; ++ } ++}; ++var __addDisposableResource = (this && this.__addDisposableResource) || function (env, value, async) { ++ if (value !== null && value !== void 0) { ++ if (typeof value !== "object") throw new TypeError("Object expected."); ++ var dispose; ++ if (async) { ++ if (!Symbol.asyncDispose) throw new TypeError("Symbol.asyncDispose is not defined."); ++ dispose = value[Symbol.asyncDispose]; ++ } ++ if (dispose === void 0) { ++ if (!Symbol.dispose) throw new TypeError("Symbol.dispose is not defined."); ++ dispose = value[Symbol.dispose]; ++ } ++ if (typeof dispose !== "function") throw new TypeError("Object not disposable."); ++ env.stack.push({ value: value, dispose: dispose, async: async }); ++ } ++ else if (async) { ++ env.stack.push({ async: true }); ++ } ++ return value; ++}; ++var __disposeResources = (this && this.__disposeResources) || (function (SuppressedError) { ++ return function (env) { ++ function fail(e) { ++ env.error = env.hasError ? new SuppressedError(e, env.error, "An error was suppressed during disposal.") : e; ++ env.hasError = true; ++ } ++ function next() { ++ while (env.stack.length) { ++ var rec = env.stack.pop(); ++ try { ++ var result = rec.dispose && rec.dispose.call(rec.value); ++ if (rec.async) return Promise.resolve(result).then(next, function(e) { fail(e); return next(); }); ++ } ++ catch (e) { ++ fail(e); ++ } ++ } ++ if (env.hasError) throw env.error; ++ } ++ return next(); ++ }; ++})(typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) { ++ var e = new Error(message); ++ return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e; ++}); ++var __asyncValues = (this && this.__asyncValues) || function (o) { ++ if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); ++ var m = o[Symbol.asyncIterator], i; ++ return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i); ++ function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; } ++ function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); } ++}; ++function main() { ++ var _a, e_1, _b, _c; ++ return __awaiter(this, void 0, void 0, function () { ++ var _d, _e, _f, d1_1, env_1, d1, e_1_1; ++ var _g; ++ return __generator(this, function (_h) { ++ switch (_h.label) { ++ case 0: ++ _h.trys.push([0, 5, 6, 11]); ++ _d = true, _e = __asyncValues([(_g = {}, _g[Symbol.dispose] = function () { }, _g), null, undefined]); ++ _h.label = 1; ++ case 1: return [4 /*yield*/, _e.next()]; ++ case 2: ++ if (!(_f = _h.sent(), _a = _f.done, !_a)) return [3 /*break*/, 4]; ++ _c = _f.value; ++ _d = false; ++ d1_1 = _c; ++ env_1 = { stack: [], error: void 0, hasError: false }; ++ try { ++ d1 = __addDisposableResource(env_1, d1_1, false); ++ } ++ catch (e_2) { ++ env_1.error = e_2; ++ env_1.hasError = true; ++ } ++ finally { ++ __disposeResources(env_1); ++ } ++ _h.label = 3; ++ case 3: ++ _d = true; ++ return [3 /*break*/, 1]; ++ case 4: return [3 /*break*/, 11]; ++ case 5: ++ e_1_1 = _h.sent(); ++ e_1 = { error: e_1_1 }; ++ return [3 /*break*/, 11]; ++ case 6: ++ _h.trys.push([6, , 9, 10]); ++ if (!(!_d && !_a && (_b = _e.return))) return [3 /*break*/, 8]; ++ return [4 /*yield*/, _b.call(_e)]; ++ case 7: ++ _h.sent(); ++ _h.label = 8; ++ case 8: return [3 /*break*/, 10]; ++ case 9: ++ if (e_1) throw e_1.error; ++ return [7 /*endfinally*/]; ++ case 10: return [7 /*endfinally*/]; ++ case 11: return [2 /*return*/]; ++ } ++ }); ++ }); ++} +diff --git a/tests/baselines/reference/usingDeclarationsInForAwaitOf(target=esnext).js b/tests/baselines/reference/usingDeclarationsInForAwaitOf(target=esnext).js +new file mode 100644 +index 000000000..c17e98d6a +--- /dev/null ++++ b/tests/baselines/reference/usingDeclarationsInForAwaitOf(target=esnext).js +@@ -0,0 +1,14 @@ ++//// [tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsInForAwaitOf.ts] //// ++ ++//// [usingDeclarationsInForAwaitOf.ts] ++async function main() { ++ for await (using d1 of [{ [Symbol.dispose]() {} }, null, undefined]) { ++ } ++} ++ ++ ++//// [usingDeclarationsInForAwaitOf.js] ++async function main() { ++ for await (using d1 of [{ [Symbol.dispose]() { } }, null, undefined]) { ++ } ++} +diff --git a/tests/baselines/reference/usingDeclarationsInForIn.errors.txt b/tests/baselines/reference/usingDeclarationsInForIn.errors.txt +new file mode 100644 +index 000000000..123b33719 +--- /dev/null ++++ b/tests/baselines/reference/usingDeclarationsInForIn.errors.txt +@@ -0,0 +1,9 @@ ++usingDeclarationsInForIn.ts(1,6): error TS1493: The left-hand side of a 'for...in' statement cannot be a 'using' declaration. ++ ++ ++==== usingDeclarationsInForIn.ts (1 errors) ==== ++ for (using x in {}) { ++ ~~~~~~~ ++!!! error TS1493: The left-hand side of a 'for...in' statement cannot be a 'using' declaration. ++ } ++ +\ No newline at end of file +diff --git a/tests/baselines/reference/usingDeclarationsInForIn.js b/tests/baselines/reference/usingDeclarationsInForIn.js +new file mode 100644 +index 000000000..fce8a93bb +--- /dev/null ++++ b/tests/baselines/reference/usingDeclarationsInForIn.js +@@ -0,0 +1,10 @@ ++//// [tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsInForIn.ts] //// ++ ++//// [usingDeclarationsInForIn.ts] ++for (using x in {}) { ++} ++ ++ ++//// [usingDeclarationsInForIn.js] ++for (using x in {}) { ++} +diff --git a/tests/baselines/reference/usingDeclarationsInForOf.1(target=es2015).js b/tests/baselines/reference/usingDeclarationsInForOf.1(target=es2015).js +new file mode 100644 +index 000000000..bf993d5fb +--- /dev/null ++++ b/tests/baselines/reference/usingDeclarationsInForOf.1(target=es2015).js +@@ -0,0 +1,66 @@ ++//// [tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsInForOf.1.ts] //// ++ ++//// [usingDeclarationsInForOf.1.ts] ++for (using d1 of [{ [Symbol.dispose]() {} }, null, undefined]) { ++} ++ ++ ++//// [usingDeclarationsInForOf.1.js] ++var __addDisposableResource = (this && this.__addDisposableResource) || function (env, value, async) { ++ if (value !== null && value !== void 0) { ++ if (typeof value !== "object") throw new TypeError("Object expected."); ++ var dispose; ++ if (async) { ++ if (!Symbol.asyncDispose) throw new TypeError("Symbol.asyncDispose is not defined."); ++ dispose = value[Symbol.asyncDispose]; ++ } ++ if (dispose === void 0) { ++ if (!Symbol.dispose) throw new TypeError("Symbol.dispose is not defined."); ++ dispose = value[Symbol.dispose]; ++ } ++ if (typeof dispose !== "function") throw new TypeError("Object not disposable."); ++ env.stack.push({ value: value, dispose: dispose, async: async }); ++ } ++ else if (async) { ++ env.stack.push({ async: true }); ++ } ++ return value; ++}; ++var __disposeResources = (this && this.__disposeResources) || (function (SuppressedError) { ++ return function (env) { ++ function fail(e) { ++ env.error = env.hasError ? new SuppressedError(e, env.error, "An error was suppressed during disposal.") : e; ++ env.hasError = true; ++ } ++ function next() { ++ while (env.stack.length) { ++ var rec = env.stack.pop(); ++ try { ++ var result = rec.dispose && rec.dispose.call(rec.value); ++ if (rec.async) return Promise.resolve(result).then(next, function(e) { fail(e); return next(); }); ++ } ++ catch (e) { ++ fail(e); ++ } ++ } ++ if (env.hasError) throw env.error; ++ } ++ return next(); ++ }; ++})(typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) { ++ var e = new Error(message); ++ return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e; ++}); ++for (const d1_1 of [{ [Symbol.dispose]() { } }, null, undefined]) { ++ const env_1 = { stack: [], error: void 0, hasError: false }; ++ try { ++ const d1 = __addDisposableResource(env_1, d1_1, false); ++ } ++ catch (e_1) { ++ env_1.error = e_1; ++ env_1.hasError = true; ++ } ++ finally { ++ __disposeResources(env_1); ++ } ++} +diff --git a/tests/baselines/reference/usingDeclarationsInForOf.1(target=es2017).js b/tests/baselines/reference/usingDeclarationsInForOf.1(target=es2017).js +new file mode 100644 +index 000000000..bf993d5fb +--- /dev/null ++++ b/tests/baselines/reference/usingDeclarationsInForOf.1(target=es2017).js +@@ -0,0 +1,66 @@ ++//// [tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsInForOf.1.ts] //// ++ ++//// [usingDeclarationsInForOf.1.ts] ++for (using d1 of [{ [Symbol.dispose]() {} }, null, undefined]) { ++} ++ ++ ++//// [usingDeclarationsInForOf.1.js] ++var __addDisposableResource = (this && this.__addDisposableResource) || function (env, value, async) { ++ if (value !== null && value !== void 0) { ++ if (typeof value !== "object") throw new TypeError("Object expected."); ++ var dispose; ++ if (async) { ++ if (!Symbol.asyncDispose) throw new TypeError("Symbol.asyncDispose is not defined."); ++ dispose = value[Symbol.asyncDispose]; ++ } ++ if (dispose === void 0) { ++ if (!Symbol.dispose) throw new TypeError("Symbol.dispose is not defined."); ++ dispose = value[Symbol.dispose]; ++ } ++ if (typeof dispose !== "function") throw new TypeError("Object not disposable."); ++ env.stack.push({ value: value, dispose: dispose, async: async }); ++ } ++ else if (async) { ++ env.stack.push({ async: true }); ++ } ++ return value; ++}; ++var __disposeResources = (this && this.__disposeResources) || (function (SuppressedError) { ++ return function (env) { ++ function fail(e) { ++ env.error = env.hasError ? new SuppressedError(e, env.error, "An error was suppressed during disposal.") : e; ++ env.hasError = true; ++ } ++ function next() { ++ while (env.stack.length) { ++ var rec = env.stack.pop(); ++ try { ++ var result = rec.dispose && rec.dispose.call(rec.value); ++ if (rec.async) return Promise.resolve(result).then(next, function(e) { fail(e); return next(); }); ++ } ++ catch (e) { ++ fail(e); ++ } ++ } ++ if (env.hasError) throw env.error; ++ } ++ return next(); ++ }; ++})(typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) { ++ var e = new Error(message); ++ return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e; ++}); ++for (const d1_1 of [{ [Symbol.dispose]() { } }, null, undefined]) { ++ const env_1 = { stack: [], error: void 0, hasError: false }; ++ try { ++ const d1 = __addDisposableResource(env_1, d1_1, false); ++ } ++ catch (e_1) { ++ env_1.error = e_1; ++ env_1.hasError = true; ++ } ++ finally { ++ __disposeResources(env_1); ++ } ++} +diff --git a/tests/baselines/reference/usingDeclarationsInForOf.1(target=es2022).js b/tests/baselines/reference/usingDeclarationsInForOf.1(target=es2022).js +new file mode 100644 +index 000000000..bf993d5fb +--- /dev/null ++++ b/tests/baselines/reference/usingDeclarationsInForOf.1(target=es2022).js +@@ -0,0 +1,66 @@ ++//// [tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsInForOf.1.ts] //// ++ ++//// [usingDeclarationsInForOf.1.ts] ++for (using d1 of [{ [Symbol.dispose]() {} }, null, undefined]) { ++} ++ ++ ++//// [usingDeclarationsInForOf.1.js] ++var __addDisposableResource = (this && this.__addDisposableResource) || function (env, value, async) { ++ if (value !== null && value !== void 0) { ++ if (typeof value !== "object") throw new TypeError("Object expected."); ++ var dispose; ++ if (async) { ++ if (!Symbol.asyncDispose) throw new TypeError("Symbol.asyncDispose is not defined."); ++ dispose = value[Symbol.asyncDispose]; ++ } ++ if (dispose === void 0) { ++ if (!Symbol.dispose) throw new TypeError("Symbol.dispose is not defined."); ++ dispose = value[Symbol.dispose]; ++ } ++ if (typeof dispose !== "function") throw new TypeError("Object not disposable."); ++ env.stack.push({ value: value, dispose: dispose, async: async }); ++ } ++ else if (async) { ++ env.stack.push({ async: true }); ++ } ++ return value; ++}; ++var __disposeResources = (this && this.__disposeResources) || (function (SuppressedError) { ++ return function (env) { ++ function fail(e) { ++ env.error = env.hasError ? new SuppressedError(e, env.error, "An error was suppressed during disposal.") : e; ++ env.hasError = true; ++ } ++ function next() { ++ while (env.stack.length) { ++ var rec = env.stack.pop(); ++ try { ++ var result = rec.dispose && rec.dispose.call(rec.value); ++ if (rec.async) return Promise.resolve(result).then(next, function(e) { fail(e); return next(); }); ++ } ++ catch (e) { ++ fail(e); ++ } ++ } ++ if (env.hasError) throw env.error; ++ } ++ return next(); ++ }; ++})(typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) { ++ var e = new Error(message); ++ return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e; ++}); ++for (const d1_1 of [{ [Symbol.dispose]() { } }, null, undefined]) { ++ const env_1 = { stack: [], error: void 0, hasError: false }; ++ try { ++ const d1 = __addDisposableResource(env_1, d1_1, false); ++ } ++ catch (e_1) { ++ env_1.error = e_1; ++ env_1.hasError = true; ++ } ++ finally { ++ __disposeResources(env_1); ++ } ++} +diff --git a/tests/baselines/reference/usingDeclarationsInForOf.1(target=es5).js b/tests/baselines/reference/usingDeclarationsInForOf.1(target=es5).js +new file mode 100644 +index 000000000..f80303d1c +--- /dev/null ++++ b/tests/baselines/reference/usingDeclarationsInForOf.1(target=es5).js +@@ -0,0 +1,68 @@ ++//// [tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsInForOf.1.ts] //// ++ ++//// [usingDeclarationsInForOf.1.ts] ++for (using d1 of [{ [Symbol.dispose]() {} }, null, undefined]) { ++} ++ ++ ++//// [usingDeclarationsInForOf.1.js] ++var __addDisposableResource = (this && this.__addDisposableResource) || function (env, value, async) { ++ if (value !== null && value !== void 0) { ++ if (typeof value !== "object") throw new TypeError("Object expected."); ++ var dispose; ++ if (async) { ++ if (!Symbol.asyncDispose) throw new TypeError("Symbol.asyncDispose is not defined."); ++ dispose = value[Symbol.asyncDispose]; ++ } ++ if (dispose === void 0) { ++ if (!Symbol.dispose) throw new TypeError("Symbol.dispose is not defined."); ++ dispose = value[Symbol.dispose]; ++ } ++ if (typeof dispose !== "function") throw new TypeError("Object not disposable."); ++ env.stack.push({ value: value, dispose: dispose, async: async }); ++ } ++ else if (async) { ++ env.stack.push({ async: true }); ++ } ++ return value; ++}; ++var __disposeResources = (this && this.__disposeResources) || (function (SuppressedError) { ++ return function (env) { ++ function fail(e) { ++ env.error = env.hasError ? new SuppressedError(e, env.error, "An error was suppressed during disposal.") : e; ++ env.hasError = true; ++ } ++ function next() { ++ while (env.stack.length) { ++ var rec = env.stack.pop(); ++ try { ++ var result = rec.dispose && rec.dispose.call(rec.value); ++ if (rec.async) return Promise.resolve(result).then(next, function(e) { fail(e); return next(); }); ++ } ++ catch (e) { ++ fail(e); ++ } ++ } ++ if (env.hasError) throw env.error; ++ } ++ return next(); ++ }; ++})(typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) { ++ var e = new Error(message); ++ return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e; ++}); ++var _a; ++for (var _i = 0, _b = [(_a = {}, _a[Symbol.dispose] = function () { }, _a), null, undefined]; _i < _b.length; _i++) { ++ var d1_1 = _b[_i]; ++ var env_1 = { stack: [], error: void 0, hasError: false }; ++ try { ++ var d1 = __addDisposableResource(env_1, d1_1, false); ++ } ++ catch (e_1) { ++ env_1.error = e_1; ++ env_1.hasError = true; ++ } ++ finally { ++ __disposeResources(env_1); ++ } ++} +diff --git a/tests/baselines/reference/usingDeclarationsInForOf.1(target=esnext).js b/tests/baselines/reference/usingDeclarationsInForOf.1(target=esnext).js +new file mode 100644 +index 000000000..aaebb8948 +--- /dev/null ++++ b/tests/baselines/reference/usingDeclarationsInForOf.1(target=esnext).js +@@ -0,0 +1,10 @@ ++//// [tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsInForOf.1.ts] //// ++ ++//// [usingDeclarationsInForOf.1.ts] ++for (using d1 of [{ [Symbol.dispose]() {} }, null, undefined]) { ++} ++ ++ ++//// [usingDeclarationsInForOf.1.js] ++for (using d1 of [{ [Symbol.dispose]() { } }, null, undefined]) { ++} +diff --git a/tests/baselines/reference/usingDeclarationsInForOf.2.errors.txt b/tests/baselines/reference/usingDeclarationsInForOf.2.errors.txt +new file mode 100644 +index 000000000..2e5ee586e +--- /dev/null ++++ b/tests/baselines/reference/usingDeclarationsInForOf.2.errors.txt +@@ -0,0 +1,15 @@ ++usingDeclarationsInForOf.2.ts(1,6): error TS2304: Cannot find name 'using'. ++usingDeclarationsInForOf.2.ts(1,15): error TS2304: Cannot find name 'of'. ++usingDeclarationsInForOf.2.ts(1,19): error TS1011: An element access expression should take an argument. ++ ++ ++==== usingDeclarationsInForOf.2.ts (3 errors) ==== ++ for (using of of []) { ++ ~~~~~ ++!!! error TS2304: Cannot find name 'using'. ++ ~~ ++!!! error TS2304: Cannot find name 'of'. ++ ++!!! error TS1011: An element access expression should take an argument. ++ } ++ +\ No newline at end of file +diff --git a/tests/baselines/reference/usingDeclarationsInForOf.2.js b/tests/baselines/reference/usingDeclarationsInForOf.2.js +new file mode 100644 +index 000000000..d965d7aa4 +--- /dev/null ++++ b/tests/baselines/reference/usingDeclarationsInForOf.2.js +@@ -0,0 +1,10 @@ ++//// [tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsInForOf.2.ts] //// ++ ++//// [usingDeclarationsInForOf.2.ts] ++for (using of of []) { ++} ++ ++ ++//// [usingDeclarationsInForOf.2.js] ++for (using of of[]) { ++} +diff --git a/tests/baselines/reference/usingDeclarationsInForOf.3.errors.txt b/tests/baselines/reference/usingDeclarationsInForOf.3.errors.txt +new file mode 100644 +index 000000000..3af402cdc +--- /dev/null ++++ b/tests/baselines/reference/usingDeclarationsInForOf.3.errors.txt +@@ -0,0 +1,9 @@ ++usingDeclarationsInForOf.3.ts(1,12): error TS1492: 'using' declarations may not have binding patterns. ++ ++ ++==== usingDeclarationsInForOf.3.ts (1 errors) ==== ++ for (using {} of []) { ++ ~~ ++!!! error TS1492: 'using' declarations may not have binding patterns. ++ } ++ +\ No newline at end of file +diff --git a/tests/baselines/reference/usingDeclarationsInForOf.3.js b/tests/baselines/reference/usingDeclarationsInForOf.3.js +new file mode 100644 +index 000000000..877a26032 +--- /dev/null ++++ b/tests/baselines/reference/usingDeclarationsInForOf.3.js +@@ -0,0 +1,10 @@ ++//// [tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsInForOf.3.ts] //// ++ ++//// [usingDeclarationsInForOf.3.ts] ++for (using {} of []) { ++} ++ ++ ++//// [usingDeclarationsInForOf.3.js] ++for (using {} of []) { ++} +diff --git a/tests/baselines/reference/usingDeclarationsNamedEvaluationDecoratorsAndClassFields.js b/tests/baselines/reference/usingDeclarationsNamedEvaluationDecoratorsAndClassFields.js +new file mode 100644 +index 000000000..a08e0c7f6 +--- /dev/null ++++ b/tests/baselines/reference/usingDeclarationsNamedEvaluationDecoratorsAndClassFields.js +@@ -0,0 +1,171 @@ ++//// [tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsNamedEvaluationDecoratorsAndClassFields.ts] //// ++ ++//// [usingDeclarationsNamedEvaluationDecoratorsAndClassFields.ts] ++export {}; ++ ++declare var dec: any; ++ ++using C1 = class { ++ static [Symbol.dispose]() {} ++}; ++ ++using C2 = class { ++ static x = 1; ++ static [Symbol.dispose]() {} ++}; ++ ++using C3 = @dec class { ++ static [Symbol.dispose]() {} ++}; ++ ++using C4 = @dec class { ++ static x = 1; ++ static [Symbol.dispose]() {} ++}; ++ ++ ++//// [usingDeclarationsNamedEvaluationDecoratorsAndClassFields.js] ++var __esDecorate = (this && this.__esDecorate) || function (ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) { ++ function accept(f) { if (f !== void 0 && typeof f !== "function") throw new TypeError("Function expected"); return f; } ++ var kind = contextIn.kind, key = kind === "getter" ? "get" : kind === "setter" ? "set" : "value"; ++ var target = !descriptorIn && ctor ? contextIn["static"] ? ctor : ctor.prototype : null; ++ var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {}); ++ var _, done = false; ++ for (var i = decorators.length - 1; i >= 0; i--) { ++ var context = {}; ++ for (var p in contextIn) context[p] = p === "access" ? {} : contextIn[p]; ++ for (var p in contextIn.access) context.access[p] = contextIn.access[p]; ++ context.addInitializer = function (f) { if (done) throw new TypeError("Cannot add initializers after decoration has completed"); extraInitializers.push(accept(f || null)); }; ++ var result = (0, decorators[i])(kind === "accessor" ? { get: descriptor.get, set: descriptor.set } : descriptor[key], context); ++ if (kind === "accessor") { ++ if (result === void 0) continue; ++ if (result === null || typeof result !== "object") throw new TypeError("Object expected"); ++ if (_ = accept(result.get)) descriptor.get = _; ++ if (_ = accept(result.set)) descriptor.set = _; ++ if (_ = accept(result.init)) initializers.unshift(_); ++ } ++ else if (_ = accept(result)) { ++ if (kind === "field") initializers.unshift(_); ++ else descriptor[key] = _; ++ } ++ } ++ if (target) Object.defineProperty(target, contextIn.name, descriptor); ++ done = true; ++}; ++var __runInitializers = (this && this.__runInitializers) || function (thisArg, initializers, value) { ++ var useValue = arguments.length > 2; ++ for (var i = 0; i < initializers.length; i++) { ++ value = useValue ? initializers[i].call(thisArg, value) : initializers[i].call(thisArg); ++ } ++ return useValue ? value : void 0; ++}; ++var __setFunctionName = (this && this.__setFunctionName) || function (f, name, prefix) { ++ if (typeof name === "symbol") name = name.description ? "[".concat(name.description, "]") : ""; ++ return Object.defineProperty(f, "name", { configurable: true, value: prefix ? "".concat(prefix, " ", name) : name }); ++}; ++var __addDisposableResource = (this && this.__addDisposableResource) || function (env, value, async) { ++ if (value !== null && value !== void 0) { ++ if (typeof value !== "object") throw new TypeError("Object expected."); ++ var dispose; ++ if (async) { ++ if (!Symbol.asyncDispose) throw new TypeError("Symbol.asyncDispose is not defined."); ++ dispose = value[Symbol.asyncDispose]; ++ } ++ if (dispose === void 0) { ++ if (!Symbol.dispose) throw new TypeError("Symbol.dispose is not defined."); ++ dispose = value[Symbol.dispose]; ++ } ++ if (typeof dispose !== "function") throw new TypeError("Object not disposable."); ++ env.stack.push({ value: value, dispose: dispose, async: async }); ++ } ++ else if (async) { ++ env.stack.push({ async: true }); ++ } ++ return value; ++}; ++var __disposeResources = (this && this.__disposeResources) || (function (SuppressedError) { ++ return function (env) { ++ function fail(e) { ++ env.error = env.hasError ? new SuppressedError(e, env.error, "An error was suppressed during disposal.") : e; ++ env.hasError = true; ++ } ++ function next() { ++ while (env.stack.length) { ++ var rec = env.stack.pop(); ++ try { ++ var result = rec.dispose && rec.dispose.call(rec.value); ++ if (rec.async) return Promise.resolve(result).then(next, function(e) { fail(e); return next(); }); ++ } ++ catch (e) { ++ fail(e); ++ } ++ } ++ if (env.hasError) throw env.error; ++ } ++ return next(); ++ }; ++})(typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) { ++ var e = new Error(message); ++ return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e; ++}); ++var _a, _b; ++var C1, C2, C3, C4; ++const env_1 = { stack: [], error: void 0, hasError: false }; ++try { ++ C1 = __addDisposableResource(env_1, (_a = class { ++ static [Symbol.dispose]() { } ++ }, ++ __setFunctionName(_a, "C1"), ++ _a), false); ++ C2 = __addDisposableResource(env_1, (_b = class { ++ static [Symbol.dispose]() { } ++ }, ++ __setFunctionName(_b, "C2"), ++ _b.x = 1, ++ _b), false); ++ C3 = __addDisposableResource(env_1, (() => { ++ let _classDecorators = [dec]; ++ let _classDescriptor; ++ let _classExtraInitializers = []; ++ let _classThis; ++ var class_1 = (_classThis = class { ++ static [Symbol.dispose]() { } ++ }, ++ __setFunctionName(_classThis, "C3"), ++ (() => { ++ __esDecorate(null, _classDescriptor = { value: _classThis }, _classDecorators, { kind: "class", name: _classThis.name }, null, _classExtraInitializers); ++ class_1 = _classThis = _classDescriptor.value; ++ __runInitializers(_classThis, _classExtraInitializers); ++ })(), ++ _classThis); ++ return class_1 = _classThis; ++ })(), false); ++ C4 = __addDisposableResource(env_1, (() => { ++ let _classDecorators = [dec]; ++ let _classDescriptor; ++ let _classExtraInitializers = []; ++ let _classThis; ++ var class_2 = (_classThis = class { ++ static [Symbol.dispose]() { } ++ }, ++ __setFunctionName(_classThis, "C4"), ++ (() => { ++ __esDecorate(null, _classDescriptor = { value: _classThis }, _classDecorators, { kind: "class", name: _classThis.name }, null, _classExtraInitializers); ++ class_2 = _classThis = _classDescriptor.value; ++ })(), ++ _classThis.x = 1, ++ (() => { ++ __runInitializers(_classThis, _classExtraInitializers); ++ })(), ++ _classThis); ++ return class_2 = _classThis; ++ })(), false); ++} ++catch (e_1) { ++ env_1.error = e_1; ++ env_1.hasError = true; ++} ++finally { ++ __disposeResources(env_1); ++} ++export {}; +diff --git a/tests/baselines/reference/usingDeclarationsTopLevelOfModule.1(module=amd).js b/tests/baselines/reference/usingDeclarationsTopLevelOfModule.1(module=amd).js +new file mode 100644 +index 000000000..395532fcb +--- /dev/null ++++ b/tests/baselines/reference/usingDeclarationsTopLevelOfModule.1(module=amd).js +@@ -0,0 +1,40 @@ ++//// [tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsTopLevelOfModule.1.ts] //// ++ ++//// [usingDeclarationsTopLevelOfModule.1.ts] ++export const x = 1; ++export { y }; ++ ++using z = { [Symbol.dispose]() {} }; ++ ++const y = 2; ++ ++export const w = 3; ++ ++export default 4; ++ ++console.log(w, x, y, z); ++ ++ ++//// [usingDeclarationsTopLevelOfModule.1.js] ++define(["require", "exports"], function (require, exports) { ++ "use strict"; ++ Object.defineProperty(exports, "__esModule", { value: true }); ++ exports.w = exports.default = exports.y = exports.x = void 0; ++ exports.x = 1; ++ var z, y, _default; ++ const env_1 = { stack: [], error: void 0, hasError: false }; ++ try { ++ z = __addDisposableResource(env_1, { [Symbol.dispose]() { } }, false); ++ exports.y = y = 2; ++ exports.w = 3; ++ exports.default = _default = 4; ++ console.log(exports.w, exports.x, y, z); ++ } ++ catch (e_1) { ++ env_1.error = e_1; ++ env_1.hasError = true; ++ } ++ finally { ++ __disposeResources(env_1); ++ } ++}); +diff --git a/tests/baselines/reference/usingDeclarationsTopLevelOfModule.1(module=commonjs).js b/tests/baselines/reference/usingDeclarationsTopLevelOfModule.1(module=commonjs).js +new file mode 100644 +index 000000000..a5f84cfaf +--- /dev/null ++++ b/tests/baselines/reference/usingDeclarationsTopLevelOfModule.1(module=commonjs).js +@@ -0,0 +1,38 @@ ++//// [tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsTopLevelOfModule.1.ts] //// ++ ++//// [usingDeclarationsTopLevelOfModule.1.ts] ++export const x = 1; ++export { y }; ++ ++using z = { [Symbol.dispose]() {} }; ++ ++const y = 2; ++ ++export const w = 3; ++ ++export default 4; ++ ++console.log(w, x, y, z); ++ ++ ++//// [usingDeclarationsTopLevelOfModule.1.js] ++"use strict"; ++Object.defineProperty(exports, "__esModule", { value: true }); ++exports.w = exports.default = exports.y = exports.x = void 0; ++exports.x = 1; ++var z, y, _default; ++const env_1 = { stack: [], error: void 0, hasError: false }; ++try { ++ z = __addDisposableResource(env_1, { [Symbol.dispose]() { } }, false); ++ exports.y = y = 2; ++ exports.w = 3; ++ exports.default = _default = 4; ++ console.log(exports.w, exports.x, y, z); ++} ++catch (e_1) { ++ env_1.error = e_1; ++ env_1.hasError = true; ++} ++finally { ++ __disposeResources(env_1); ++} +diff --git a/tests/baselines/reference/usingDeclarationsTopLevelOfModule.1(module=esnext).js b/tests/baselines/reference/usingDeclarationsTopLevelOfModule.1(module=esnext).js +new file mode 100644 +index 000000000..7d293d965 +--- /dev/null ++++ b/tests/baselines/reference/usingDeclarationsTopLevelOfModule.1(module=esnext).js +@@ -0,0 +1,38 @@ ++//// [tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsTopLevelOfModule.1.ts] //// ++ ++//// [usingDeclarationsTopLevelOfModule.1.ts] ++export const x = 1; ++export { y }; ++ ++using z = { [Symbol.dispose]() {} }; ++ ++const y = 2; ++ ++export const w = 3; ++ ++export default 4; ++ ++console.log(w, x, y, z); ++ ++ ++//// [usingDeclarationsTopLevelOfModule.1.js] ++export const x = 1; ++export { y }; ++export { _default as default }; ++var z, y, _default; ++export let w; ++const env_1 = { stack: [], error: void 0, hasError: false }; ++try { ++ z = __addDisposableResource(env_1, { [Symbol.dispose]() { } }, false); ++ y = 2; ++ w = 3; ++ _default = 4; ++ console.log(w, x, y, z); ++} ++catch (e_1) { ++ env_1.error = e_1; ++ env_1.hasError = true; ++} ++finally { ++ __disposeResources(env_1); ++} +diff --git a/tests/baselines/reference/usingDeclarationsTopLevelOfModule.1(module=system).js b/tests/baselines/reference/usingDeclarationsTopLevelOfModule.1(module=system).js +new file mode 100644 +index 000000000..27ac41800 +--- /dev/null ++++ b/tests/baselines/reference/usingDeclarationsTopLevelOfModule.1(module=system).js +@@ -0,0 +1,44 @@ ++//// [tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsTopLevelOfModule.1.ts] //// ++ ++//// [usingDeclarationsTopLevelOfModule.1.ts] ++export const x = 1; ++export { y }; ++ ++using z = { [Symbol.dispose]() {} }; ++ ++const y = 2; ++ ++export const w = 3; ++ ++export default 4; ++ ++console.log(w, x, y, z); ++ ++ ++//// [usingDeclarationsTopLevelOfModule.1.js] ++System.register([], function (exports_1, context_1) { ++ "use strict"; ++ var x, z, y, _default, w, env_1; ++ var __moduleName = context_1 && context_1.id; ++ return { ++ setters: [], ++ execute: function () { ++ exports_1("x", x = 1); ++ env_1 = { stack: [], error: void 0, hasError: false }; ++ try { ++ z = __addDisposableResource(env_1, { [Symbol.dispose]() { } }, false); ++ exports_1("y", y = 2); ++ exports_1("w", w = 3); ++ exports_1("default", _default = 4); ++ console.log(w, x, y, z); ++ } ++ catch (e_1) { ++ env_1.error = e_1; ++ env_1.hasError = true; ++ } ++ finally { ++ __disposeResources(env_1); ++ } ++ } ++ }; ++}); +diff --git a/tests/baselines/reference/usingDeclarationsTopLevelOfModule.2(module=amd).js b/tests/baselines/reference/usingDeclarationsTopLevelOfModule.2(module=amd).js +new file mode 100644 +index 000000000..e93cbc963 +--- /dev/null ++++ b/tests/baselines/reference/usingDeclarationsTopLevelOfModule.2(module=amd).js +@@ -0,0 +1,31 @@ ++//// [tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsTopLevelOfModule.2.ts] //// ++ ++//// [usingDeclarationsTopLevelOfModule.2.ts] ++using z = { [Symbol.dispose]() {} }; ++ ++const y = 2; ++ ++console.log(y, z); ++export = 4; ++ ++ ++//// [usingDeclarationsTopLevelOfModule.2.js] ++define(["require", "exports"], function (require, exports) { ++ "use strict"; ++ var z, y, _default; ++ const env_1 = { stack: [], error: void 0, hasError: false }; ++ try { ++ z = __addDisposableResource(env_1, { [Symbol.dispose]() { } }, false); ++ y = 2; ++ console.log(y, z); ++ _default = 4; ++ } ++ catch (e_1) { ++ env_1.error = e_1; ++ env_1.hasError = true; ++ } ++ finally { ++ __disposeResources(env_1); ++ } ++ return _default; ++}); +diff --git a/tests/baselines/reference/usingDeclarationsTopLevelOfModule.2(module=commonjs).js b/tests/baselines/reference/usingDeclarationsTopLevelOfModule.2(module=commonjs).js +new file mode 100644 +index 000000000..f9e214766 +--- /dev/null ++++ b/tests/baselines/reference/usingDeclarationsTopLevelOfModule.2(module=commonjs).js +@@ -0,0 +1,29 @@ ++//// [tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsTopLevelOfModule.2.ts] //// ++ ++//// [usingDeclarationsTopLevelOfModule.2.ts] ++using z = { [Symbol.dispose]() {} }; ++ ++const y = 2; ++ ++console.log(y, z); ++export = 4; ++ ++ ++//// [usingDeclarationsTopLevelOfModule.2.js] ++"use strict"; ++var z, y, _default; ++const env_1 = { stack: [], error: void 0, hasError: false }; ++try { ++ z = __addDisposableResource(env_1, { [Symbol.dispose]() { } }, false); ++ y = 2; ++ console.log(y, z); ++ _default = 4; ++} ++catch (e_1) { ++ env_1.error = e_1; ++ env_1.hasError = true; ++} ++finally { ++ __disposeResources(env_1); ++} ++module.exports = _default; +diff --git a/tests/baselines/reference/usingDeclarationsTopLevelOfModule.3(module=amd).js b/tests/baselines/reference/usingDeclarationsTopLevelOfModule.3(module=amd).js +new file mode 100644 +index 000000000..9d52c8edf +--- /dev/null ++++ b/tests/baselines/reference/usingDeclarationsTopLevelOfModule.3(module=amd).js +@@ -0,0 +1,42 @@ ++//// [tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsTopLevelOfModule.3.ts] //// ++ ++//// [usingDeclarationsTopLevelOfModule.3.ts] ++export { y }; ++ ++using z = { [Symbol.dispose]() {} }; ++ ++if (false) { ++ var y = 1; ++} ++ ++function f() { ++ console.log(y, z); ++} ++ ++ ++ ++//// [usingDeclarationsTopLevelOfModule.3.js] ++define(["require", "exports"], function (require, exports) { ++ "use strict"; ++ Object.defineProperty(exports, "__esModule", { value: true }); ++ exports.y = void 0; ++ function f() { ++ console.log(y, z); ++ } ++ var z; ++ const env_1 = { stack: [], error: void 0, hasError: false }; ++ try { ++ z = __addDisposableResource(env_1, { [Symbol.dispose]() { } }, false); ++ if (false) { ++ var y = 1; ++ exports.y = y; ++ } ++ } ++ catch (e_1) { ++ env_1.error = e_1; ++ env_1.hasError = true; ++ } ++ finally { ++ __disposeResources(env_1); ++ } ++}); +diff --git a/tests/baselines/reference/usingDeclarationsTopLevelOfModule.3(module=commonjs).js b/tests/baselines/reference/usingDeclarationsTopLevelOfModule.3(module=commonjs).js +new file mode 100644 +index 000000000..ac9dc368e +--- /dev/null ++++ b/tests/baselines/reference/usingDeclarationsTopLevelOfModule.3(module=commonjs).js +@@ -0,0 +1,40 @@ ++//// [tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsTopLevelOfModule.3.ts] //// ++ ++//// [usingDeclarationsTopLevelOfModule.3.ts] ++export { y }; ++ ++using z = { [Symbol.dispose]() {} }; ++ ++if (false) { ++ var y = 1; ++} ++ ++function f() { ++ console.log(y, z); ++} ++ ++ ++ ++//// [usingDeclarationsTopLevelOfModule.3.js] ++"use strict"; ++Object.defineProperty(exports, "__esModule", { value: true }); ++exports.y = void 0; ++function f() { ++ console.log(y, z); ++} ++var z; ++const env_1 = { stack: [], error: void 0, hasError: false }; ++try { ++ z = __addDisposableResource(env_1, { [Symbol.dispose]() { } }, false); ++ if (false) { ++ var y = 1; ++ exports.y = y; ++ } ++} ++catch (e_1) { ++ env_1.error = e_1; ++ env_1.hasError = true; ++} ++finally { ++ __disposeResources(env_1); ++} +diff --git a/tests/baselines/reference/usingDeclarationsTopLevelOfModule.3(module=esnext).js b/tests/baselines/reference/usingDeclarationsTopLevelOfModule.3(module=esnext).js +new file mode 100644 +index 000000000..2e7482a37 +--- /dev/null ++++ b/tests/baselines/reference/usingDeclarationsTopLevelOfModule.3(module=esnext).js +@@ -0,0 +1,37 @@ ++//// [tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsTopLevelOfModule.3.ts] //// ++ ++//// [usingDeclarationsTopLevelOfModule.3.ts] ++export { y }; ++ ++using z = { [Symbol.dispose]() {} }; ++ ++if (false) { ++ var y = 1; ++} ++ ++function f() { ++ console.log(y, z); ++} ++ ++ ++ ++//// [usingDeclarationsTopLevelOfModule.3.js] ++export { y }; ++function f() { ++ console.log(y, z); ++} ++var z; ++const env_1 = { stack: [], error: void 0, hasError: false }; ++try { ++ z = __addDisposableResource(env_1, { [Symbol.dispose]() { } }, false); ++ if (false) { ++ var y = 1; ++ } ++} ++catch (e_1) { ++ env_1.error = e_1; ++ env_1.hasError = true; ++} ++finally { ++ __disposeResources(env_1); ++} +diff --git a/tests/baselines/reference/usingDeclarationsTopLevelOfModule.3(module=system).js b/tests/baselines/reference/usingDeclarationsTopLevelOfModule.3(module=system).js +new file mode 100644 +index 000000000..7cdecf655 +--- /dev/null ++++ b/tests/baselines/reference/usingDeclarationsTopLevelOfModule.3(module=system).js +@@ -0,0 +1,46 @@ ++//// [tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsTopLevelOfModule.3.ts] //// ++ ++//// [usingDeclarationsTopLevelOfModule.3.ts] ++export { y }; ++ ++using z = { [Symbol.dispose]() {} }; ++ ++if (false) { ++ var y = 1; ++} ++ ++function f() { ++ console.log(y, z); ++} ++ ++ ++ ++//// [usingDeclarationsTopLevelOfModule.3.js] ++System.register([], function (exports_1, context_1) { ++ "use strict"; ++ var z, env_1, y; ++ var __moduleName = context_1 && context_1.id; ++ function f() { ++ console.log(y, z); ++ } ++ return { ++ setters: [], ++ execute: function () { ++ env_1 = { stack: [], error: void 0, hasError: false }; ++ try { ++ z = __addDisposableResource(env_1, { [Symbol.dispose]() { } }, false); ++ if (false) { ++ y = 1; ++ exports_1("y", y); ++ } ++ } ++ catch (e_1) { ++ env_1.error = e_1; ++ env_1.hasError = true; ++ } ++ finally { ++ __disposeResources(env_1); ++ } ++ } ++ }; ++}); +diff --git a/tests/baselines/reference/usingDeclarationsWithESClassDecorators.1(module=commonjs,target=es2015).js b/tests/baselines/reference/usingDeclarationsWithESClassDecorators.1(module=commonjs,target=es2015).js +new file mode 100644 +index 000000000..1e01f9ad8 +--- /dev/null ++++ b/tests/baselines/reference/usingDeclarationsWithESClassDecorators.1(module=commonjs,target=es2015).js +@@ -0,0 +1,44 @@ ++//// [tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsWithESClassDecorators.1.ts] //// ++ ++//// [usingDeclarationsWithESClassDecorators.1.ts] ++export {}; ++ ++declare var dec: any; ++ ++using before = null; ++ ++@dec ++class C { ++} ++ ++ ++//// [usingDeclarationsWithESClassDecorators.1.js] ++"use strict"; ++Object.defineProperty(exports, "__esModule", { value: true }); ++var before, C; ++const env_1 = { stack: [], error: void 0, hasError: false }; ++try { ++ before = __addDisposableResource(env_1, null, false); ++ C = (() => { ++ let _classDecorators = [dec]; ++ let _classDescriptor; ++ let _classExtraInitializers = []; ++ let _classThis; ++ var C = _classThis = class { ++ }; ++ __setFunctionName(_classThis, "C"); ++ (() => { ++ __esDecorate(null, _classDescriptor = { value: _classThis }, _classDecorators, { kind: "class", name: _classThis.name }, null, _classExtraInitializers); ++ C = _classThis = _classDescriptor.value; ++ __runInitializers(_classThis, _classExtraInitializers); ++ })(); ++ return C = _classThis; ++ })(); ++} ++catch (e_1) { ++ env_1.error = e_1; ++ env_1.hasError = true; ++} ++finally { ++ __disposeResources(env_1); ++} +diff --git a/tests/baselines/reference/usingDeclarationsWithESClassDecorators.1(module=commonjs,target=es5).js b/tests/baselines/reference/usingDeclarationsWithESClassDecorators.1(module=commonjs,target=es5).js +new file mode 100644 +index 000000000..4bef68fef +--- /dev/null ++++ b/tests/baselines/reference/usingDeclarationsWithESClassDecorators.1(module=commonjs,target=es5).js +@@ -0,0 +1,47 @@ ++//// [tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsWithESClassDecorators.1.ts] //// ++ ++//// [usingDeclarationsWithESClassDecorators.1.ts] ++export {}; ++ ++declare var dec: any; ++ ++using before = null; ++ ++@dec ++class C { ++} ++ ++ ++//// [usingDeclarationsWithESClassDecorators.1.js] ++"use strict"; ++Object.defineProperty(exports, "__esModule", { value: true }); ++var before, C; ++var env_1 = { stack: [], error: void 0, hasError: false }; ++try { ++ before = __addDisposableResource(env_1, null, false); ++ C = function () { ++ var _classDecorators = [dec]; ++ var _classDescriptor; ++ var _classExtraInitializers = []; ++ var _classThis; ++ var C = _classThis = /** @class */ (function () { ++ function C_1() { ++ } ++ return C_1; ++ }()); ++ __setFunctionName(_classThis, "C"); ++ (function () { ++ __esDecorate(null, _classDescriptor = { value: _classThis }, _classDecorators, { kind: "class", name: _classThis.name }, null, _classExtraInitializers); ++ C = _classThis = _classDescriptor.value; ++ __runInitializers(_classThis, _classExtraInitializers); ++ })(); ++ return C = _classThis; ++ }(); ++} ++catch (e_1) { ++ env_1.error = e_1; ++ env_1.hasError = true; ++} ++finally { ++ __disposeResources(env_1); ++} +diff --git a/tests/baselines/reference/usingDeclarationsWithESClassDecorators.1(module=commonjs,target=esnext).js b/tests/baselines/reference/usingDeclarationsWithESClassDecorators.1(module=commonjs,target=esnext).js +new file mode 100644 +index 000000000..f439d2535 +--- /dev/null ++++ b/tests/baselines/reference/usingDeclarationsWithESClassDecorators.1(module=commonjs,target=esnext).js +@@ -0,0 +1,21 @@ ++//// [tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsWithESClassDecorators.1.ts] //// ++ ++//// [usingDeclarationsWithESClassDecorators.1.ts] ++export {}; ++ ++declare var dec: any; ++ ++using before = null; ++ ++@dec ++class C { ++} ++ ++ ++//// [usingDeclarationsWithESClassDecorators.1.js] ++"use strict"; ++Object.defineProperty(exports, "__esModule", { value: true }); ++using before = null; ++@dec ++class C { ++} +diff --git a/tests/baselines/reference/usingDeclarationsWithESClassDecorators.1(module=esnext,target=es2015).js b/tests/baselines/reference/usingDeclarationsWithESClassDecorators.1(module=esnext,target=es2015).js +new file mode 100644 +index 000000000..159a29316 +--- /dev/null ++++ b/tests/baselines/reference/usingDeclarationsWithESClassDecorators.1(module=esnext,target=es2015).js +@@ -0,0 +1,43 @@ ++//// [tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsWithESClassDecorators.1.ts] //// ++ ++//// [usingDeclarationsWithESClassDecorators.1.ts] ++export {}; ++ ++declare var dec: any; ++ ++using before = null; ++ ++@dec ++class C { ++} ++ ++ ++//// [usingDeclarationsWithESClassDecorators.1.js] ++var before, C; ++const env_1 = { stack: [], error: void 0, hasError: false }; ++try { ++ before = __addDisposableResource(env_1, null, false); ++ C = (() => { ++ let _classDecorators = [dec]; ++ let _classDescriptor; ++ let _classExtraInitializers = []; ++ let _classThis; ++ var C = _classThis = class { ++ }; ++ __setFunctionName(_classThis, "C"); ++ (() => { ++ __esDecorate(null, _classDescriptor = { value: _classThis }, _classDecorators, { kind: "class", name: _classThis.name }, null, _classExtraInitializers); ++ C = _classThis = _classDescriptor.value; ++ __runInitializers(_classThis, _classExtraInitializers); ++ })(); ++ return C = _classThis; ++ })(); ++} ++catch (e_1) { ++ env_1.error = e_1; ++ env_1.hasError = true; ++} ++finally { ++ __disposeResources(env_1); ++} ++export {}; +diff --git a/tests/baselines/reference/usingDeclarationsWithESClassDecorators.1(module=esnext,target=es5).js b/tests/baselines/reference/usingDeclarationsWithESClassDecorators.1(module=esnext,target=es5).js +new file mode 100644 +index 000000000..5d78d53be +--- /dev/null ++++ b/tests/baselines/reference/usingDeclarationsWithESClassDecorators.1(module=esnext,target=es5).js +@@ -0,0 +1,46 @@ ++//// [tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsWithESClassDecorators.1.ts] //// ++ ++//// [usingDeclarationsWithESClassDecorators.1.ts] ++export {}; ++ ++declare var dec: any; ++ ++using before = null; ++ ++@dec ++class C { ++} ++ ++ ++//// [usingDeclarationsWithESClassDecorators.1.js] ++var before, C; ++var env_1 = { stack: [], error: void 0, hasError: false }; ++try { ++ before = __addDisposableResource(env_1, null, false); ++ C = function () { ++ var _classDecorators = [dec]; ++ var _classDescriptor; ++ var _classExtraInitializers = []; ++ var _classThis; ++ var C = _classThis = /** @class */ (function () { ++ function C_1() { ++ } ++ return C_1; ++ }()); ++ __setFunctionName(_classThis, "C"); ++ (function () { ++ __esDecorate(null, _classDescriptor = { value: _classThis }, _classDecorators, { kind: "class", name: _classThis.name }, null, _classExtraInitializers); ++ C = _classThis = _classDescriptor.value; ++ __runInitializers(_classThis, _classExtraInitializers); ++ })(); ++ return C = _classThis; ++ }(); ++} ++catch (e_1) { ++ env_1.error = e_1; ++ env_1.hasError = true; ++} ++finally { ++ __disposeResources(env_1); ++} ++export {}; +diff --git a/tests/baselines/reference/usingDeclarationsWithESClassDecorators.1(module=esnext,target=esnext).js b/tests/baselines/reference/usingDeclarationsWithESClassDecorators.1(module=esnext,target=esnext).js +new file mode 100644 +index 000000000..13d651149 +--- /dev/null ++++ b/tests/baselines/reference/usingDeclarationsWithESClassDecorators.1(module=esnext,target=esnext).js +@@ -0,0 +1,20 @@ ++//// [tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsWithESClassDecorators.1.ts] //// ++ ++//// [usingDeclarationsWithESClassDecorators.1.ts] ++export {}; ++ ++declare var dec: any; ++ ++using before = null; ++ ++@dec ++class C { ++} ++ ++ ++//// [usingDeclarationsWithESClassDecorators.1.js] ++using before = null; ++@dec ++class C { ++} ++export {}; +diff --git a/tests/baselines/reference/usingDeclarationsWithESClassDecorators.1(module=system,target=es2015).js b/tests/baselines/reference/usingDeclarationsWithESClassDecorators.1(module=system,target=es2015).js +new file mode 100644 +index 000000000..0370cae3d +--- /dev/null ++++ b/tests/baselines/reference/usingDeclarationsWithESClassDecorators.1(module=system,target=es2015).js +@@ -0,0 +1,51 @@ ++//// [tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsWithESClassDecorators.1.ts] //// ++ ++//// [usingDeclarationsWithESClassDecorators.1.ts] ++export {}; ++ ++declare var dec: any; ++ ++using before = null; ++ ++@dec ++class C { ++} ++ ++ ++//// [usingDeclarationsWithESClassDecorators.1.js] ++System.register([], function (exports_1, context_1) { ++ "use strict"; ++ var before, C, env_1; ++ var __moduleName = context_1 && context_1.id; ++ return { ++ setters: [], ++ execute: function () { ++ env_1 = { stack: [], error: void 0, hasError: false }; ++ try { ++ before = __addDisposableResource(env_1, null, false); ++ C = (() => { ++ let _classDecorators = [dec]; ++ let _classDescriptor; ++ let _classExtraInitializers = []; ++ let _classThis; ++ var C = _classThis = class { ++ }; ++ __setFunctionName(_classThis, "C"); ++ (() => { ++ __esDecorate(null, _classDescriptor = { value: _classThis }, _classDecorators, { kind: "class", name: _classThis.name }, null, _classExtraInitializers); ++ C = _classThis = _classDescriptor.value; ++ __runInitializers(_classThis, _classExtraInitializers); ++ })(); ++ return C = _classThis; ++ })(); ++ } ++ catch (e_1) { ++ env_1.error = e_1; ++ env_1.hasError = true; ++ } ++ finally { ++ __disposeResources(env_1); ++ } ++ } ++ }; ++}); +diff --git a/tests/baselines/reference/usingDeclarationsWithESClassDecorators.1(module=system,target=es5).js b/tests/baselines/reference/usingDeclarationsWithESClassDecorators.1(module=system,target=es5).js +new file mode 100644 +index 000000000..50be8899c +--- /dev/null ++++ b/tests/baselines/reference/usingDeclarationsWithESClassDecorators.1(module=system,target=es5).js +@@ -0,0 +1,54 @@ ++//// [tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsWithESClassDecorators.1.ts] //// ++ ++//// [usingDeclarationsWithESClassDecorators.1.ts] ++export {}; ++ ++declare var dec: any; ++ ++using before = null; ++ ++@dec ++class C { ++} ++ ++ ++//// [usingDeclarationsWithESClassDecorators.1.js] ++System.register([], function (exports_1, context_1) { ++ "use strict"; ++ var before, C, env_1; ++ var __moduleName = context_1 && context_1.id; ++ return { ++ setters: [], ++ execute: function () { ++ env_1 = { stack: [], error: void 0, hasError: false }; ++ try { ++ before = __addDisposableResource(env_1, null, false); ++ C = function () { ++ var _classDecorators = [dec]; ++ var _classDescriptor; ++ var _classExtraInitializers = []; ++ var _classThis; ++ var C = _classThis = /** @class */ (function () { ++ function C_1() { ++ } ++ return C_1; ++ }()); ++ __setFunctionName(_classThis, "C"); ++ (function () { ++ __esDecorate(null, _classDescriptor = { value: _classThis }, _classDecorators, { kind: "class", name: _classThis.name }, null, _classExtraInitializers); ++ C = _classThis = _classDescriptor.value; ++ __runInitializers(_classThis, _classExtraInitializers); ++ })(); ++ return C = _classThis; ++ }(); ++ } ++ catch (e_1) { ++ env_1.error = e_1; ++ env_1.hasError = true; ++ } ++ finally { ++ __disposeResources(env_1); ++ } ++ } ++ }; ++}); +diff --git a/tests/baselines/reference/usingDeclarationsWithESClassDecorators.1(module=system,target=esnext).js b/tests/baselines/reference/usingDeclarationsWithESClassDecorators.1(module=system,target=esnext).js +new file mode 100644 +index 000000000..2bcd0e780 +--- /dev/null ++++ b/tests/baselines/reference/usingDeclarationsWithESClassDecorators.1(module=system,target=esnext).js +@@ -0,0 +1,30 @@ ++//// [tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsWithESClassDecorators.1.ts] //// ++ ++//// [usingDeclarationsWithESClassDecorators.1.ts] ++export {}; ++ ++declare var dec: any; ++ ++using before = null; ++ ++@dec ++class C { ++} ++ ++ ++//// [usingDeclarationsWithESClassDecorators.1.js] ++System.register([], function (exports_1, context_1) { ++ "use strict"; ++ var before, C; ++ var __moduleName = context_1 && context_1.id; ++ return { ++ setters: [], ++ execute: function () { ++ using before_1 = before = null; ++ C = ++ @dec ++ class C { ++ }; ++ } ++ }; ++}); +diff --git a/tests/baselines/reference/usingDeclarationsWithESClassDecorators.10(module=commonjs,target=es2015).js b/tests/baselines/reference/usingDeclarationsWithESClassDecorators.10(module=commonjs,target=es2015).js +new file mode 100644 +index 000000000..65a229c79 +--- /dev/null ++++ b/tests/baselines/reference/usingDeclarationsWithESClassDecorators.10(module=commonjs,target=es2015).js +@@ -0,0 +1,44 @@ ++//// [tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsWithESClassDecorators.10.ts] //// ++ ++//// [usingDeclarationsWithESClassDecorators.10.ts] ++export {}; ++ ++declare var dec: any; ++ ++@dec ++export default class { ++} ++ ++using after = null; ++ ++ ++//// [usingDeclarationsWithESClassDecorators.10.js] ++"use strict"; ++Object.defineProperty(exports, "__esModule", { value: true }); ++exports.default = (() => { ++ let _classDecorators = [dec]; ++ let _classDescriptor; ++ let _classExtraInitializers = []; ++ let _classThis; ++ var default_1 = _classThis = class { ++ }; ++ __setFunctionName(_classThis, "default"); ++ (() => { ++ __esDecorate(null, _classDescriptor = { value: _classThis }, _classDecorators, { kind: "class", name: _classThis.name }, null, _classExtraInitializers); ++ default_1 = _classThis = _classDescriptor.value; ++ __runInitializers(_classThis, _classExtraInitializers); ++ })(); ++ return default_1 = _classThis; ++})(); ++var after; ++const env_1 = { stack: [], error: void 0, hasError: false }; ++try { ++ after = __addDisposableResource(env_1, null, false); ++} ++catch (e_1) { ++ env_1.error = e_1; ++ env_1.hasError = true; ++} ++finally { ++ __disposeResources(env_1); ++} +diff --git a/tests/baselines/reference/usingDeclarationsWithESClassDecorators.10(module=commonjs,target=es5).js b/tests/baselines/reference/usingDeclarationsWithESClassDecorators.10(module=commonjs,target=es5).js +new file mode 100644 +index 000000000..413a5784b +--- /dev/null ++++ b/tests/baselines/reference/usingDeclarationsWithESClassDecorators.10(module=commonjs,target=es5).js +@@ -0,0 +1,48 @@ ++//// [tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsWithESClassDecorators.10.ts] //// ++ ++//// [usingDeclarationsWithESClassDecorators.10.ts] ++export {}; ++ ++declare var dec: any; ++ ++@dec ++export default class { ++} ++ ++using after = null; ++ ++ ++//// [usingDeclarationsWithESClassDecorators.10.js] ++"use strict"; ++Object.defineProperty(exports, "__esModule", { value: true }); ++var default_1 = function () { ++ var _classDecorators = [dec]; ++ var _classDescriptor; ++ var _classExtraInitializers = []; ++ var _classThis; ++ var default_1 = _classThis = /** @class */ (function () { ++ function default_1() { ++ } ++ return default_1; ++ }()); ++ __setFunctionName(_classThis, "default"); ++ (function () { ++ __esDecorate(null, _classDescriptor = { value: _classThis }, _classDecorators, { kind: "class", name: _classThis.name }, null, _classExtraInitializers); ++ default_1 = _classThis = _classDescriptor.value; ++ __runInitializers(_classThis, _classExtraInitializers); ++ })(); ++ return default_1 = _classThis; ++}(); ++exports.default = default_1; ++var after; ++var env_1 = { stack: [], error: void 0, hasError: false }; ++try { ++ after = __addDisposableResource(env_1, null, false); ++} ++catch (e_1) { ++ env_1.error = e_1; ++ env_1.hasError = true; ++} ++finally { ++ __disposeResources(env_1); ++} +diff --git a/tests/baselines/reference/usingDeclarationsWithESClassDecorators.10(module=commonjs,target=esnext).js b/tests/baselines/reference/usingDeclarationsWithESClassDecorators.10(module=commonjs,target=esnext).js +new file mode 100644 +index 000000000..31ab02877 +--- /dev/null ++++ b/tests/baselines/reference/usingDeclarationsWithESClassDecorators.10(module=commonjs,target=esnext).js +@@ -0,0 +1,22 @@ ++//// [tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsWithESClassDecorators.10.ts] //// ++ ++//// [usingDeclarationsWithESClassDecorators.10.ts] ++export {}; ++ ++declare var dec: any; ++ ++@dec ++export default class { ++} ++ ++using after = null; ++ ++ ++//// [usingDeclarationsWithESClassDecorators.10.js] ++"use strict"; ++Object.defineProperty(exports, "__esModule", { value: true }); ++@dec ++class default_1 { ++} ++exports.default = default_1; ++using after = null; +diff --git a/tests/baselines/reference/usingDeclarationsWithESClassDecorators.10(module=esnext,target=es2015).js b/tests/baselines/reference/usingDeclarationsWithESClassDecorators.10(module=esnext,target=es2015).js +new file mode 100644 +index 000000000..23f62a922 +--- /dev/null ++++ b/tests/baselines/reference/usingDeclarationsWithESClassDecorators.10(module=esnext,target=es2015).js +@@ -0,0 +1,42 @@ ++//// [tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsWithESClassDecorators.10.ts] //// ++ ++//// [usingDeclarationsWithESClassDecorators.10.ts] ++export {}; ++ ++declare var dec: any; ++ ++@dec ++export default class { ++} ++ ++using after = null; ++ ++ ++//// [usingDeclarationsWithESClassDecorators.10.js] ++export default (() => { ++ let _classDecorators = [dec]; ++ let _classDescriptor; ++ let _classExtraInitializers = []; ++ let _classThis; ++ var default_1 = _classThis = class { ++ }; ++ __setFunctionName(_classThis, "default"); ++ (() => { ++ __esDecorate(null, _classDescriptor = { value: _classThis }, _classDecorators, { kind: "class", name: _classThis.name }, null, _classExtraInitializers); ++ default_1 = _classThis = _classDescriptor.value; ++ __runInitializers(_classThis, _classExtraInitializers); ++ })(); ++ return default_1 = _classThis; ++})(); ++var after; ++const env_1 = { stack: [], error: void 0, hasError: false }; ++try { ++ after = __addDisposableResource(env_1, null, false); ++} ++catch (e_1) { ++ env_1.error = e_1; ++ env_1.hasError = true; ++} ++finally { ++ __disposeResources(env_1); ++} +diff --git a/tests/baselines/reference/usingDeclarationsWithESClassDecorators.10(module=esnext,target=es5).js b/tests/baselines/reference/usingDeclarationsWithESClassDecorators.10(module=esnext,target=es5).js +new file mode 100644 +index 000000000..595556129 +--- /dev/null ++++ b/tests/baselines/reference/usingDeclarationsWithESClassDecorators.10(module=esnext,target=es5).js +@@ -0,0 +1,46 @@ ++//// [tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsWithESClassDecorators.10.ts] //// ++ ++//// [usingDeclarationsWithESClassDecorators.10.ts] ++export {}; ++ ++declare var dec: any; ++ ++@dec ++export default class { ++} ++ ++using after = null; ++ ++ ++//// [usingDeclarationsWithESClassDecorators.10.js] ++var default_1 = function () { ++ var _classDecorators = [dec]; ++ var _classDescriptor; ++ var _classExtraInitializers = []; ++ var _classThis; ++ var default_1 = _classThis = /** @class */ (function () { ++ function default_1() { ++ } ++ return default_1; ++ }()); ++ __setFunctionName(_classThis, "default"); ++ (function () { ++ __esDecorate(null, _classDescriptor = { value: _classThis }, _classDecorators, { kind: "class", name: _classThis.name }, null, _classExtraInitializers); ++ default_1 = _classThis = _classDescriptor.value; ++ __runInitializers(_classThis, _classExtraInitializers); ++ })(); ++ return default_1 = _classThis; ++}(); ++export default default_1; ++var after; ++var env_1 = { stack: [], error: void 0, hasError: false }; ++try { ++ after = __addDisposableResource(env_1, null, false); ++} ++catch (e_1) { ++ env_1.error = e_1; ++ env_1.hasError = true; ++} ++finally { ++ __disposeResources(env_1); ++} +diff --git a/tests/baselines/reference/usingDeclarationsWithESClassDecorators.10(module=esnext,target=esnext).js b/tests/baselines/reference/usingDeclarationsWithESClassDecorators.10(module=esnext,target=esnext).js +new file mode 100644 +index 000000000..bef146721 +--- /dev/null ++++ b/tests/baselines/reference/usingDeclarationsWithESClassDecorators.10(module=esnext,target=esnext).js +@@ -0,0 +1,19 @@ ++//// [tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsWithESClassDecorators.10.ts] //// ++ ++//// [usingDeclarationsWithESClassDecorators.10.ts] ++export {}; ++ ++declare var dec: any; ++ ++@dec ++export default class { ++} ++ ++using after = null; ++ ++ ++//// [usingDeclarationsWithESClassDecorators.10.js] ++@dec ++export default class { ++} ++using after = null; +diff --git a/tests/baselines/reference/usingDeclarationsWithESClassDecorators.10(module=system,target=es2015).js b/tests/baselines/reference/usingDeclarationsWithESClassDecorators.10(module=system,target=es2015).js +new file mode 100644 +index 000000000..885c757f0 +--- /dev/null ++++ b/tests/baselines/reference/usingDeclarationsWithESClassDecorators.10(module=system,target=es2015).js +@@ -0,0 +1,51 @@ ++//// [tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsWithESClassDecorators.10.ts] //// ++ ++//// [usingDeclarationsWithESClassDecorators.10.ts] ++export {}; ++ ++declare var dec: any; ++ ++@dec ++export default class { ++} ++ ++using after = null; ++ ++ ++//// [usingDeclarationsWithESClassDecorators.10.js] ++System.register([], function (exports_1, context_1) { ++ "use strict"; ++ var after, env_1; ++ var __moduleName = context_1 && context_1.id; ++ return { ++ setters: [], ++ execute: function () { ++ exports_1("default", (() => { ++ let _classDecorators = [dec]; ++ let _classDescriptor; ++ let _classExtraInitializers = []; ++ let _classThis; ++ var default_1 = _classThis = class { ++ }; ++ __setFunctionName(_classThis, "default"); ++ (() => { ++ __esDecorate(null, _classDescriptor = { value: _classThis }, _classDecorators, { kind: "class", name: _classThis.name }, null, _classExtraInitializers); ++ default_1 = _classThis = _classDescriptor.value; ++ __runInitializers(_classThis, _classExtraInitializers); ++ })(); ++ return default_1 = _classThis; ++ })()); ++ env_1 = { stack: [], error: void 0, hasError: false }; ++ try { ++ after = __addDisposableResource(env_1, null, false); ++ } ++ catch (e_1) { ++ env_1.error = e_1; ++ env_1.hasError = true; ++ } ++ finally { ++ __disposeResources(env_1); ++ } ++ } ++ }; ++}); +diff --git a/tests/baselines/reference/usingDeclarationsWithESClassDecorators.10(module=system,target=es5).js b/tests/baselines/reference/usingDeclarationsWithESClassDecorators.10(module=system,target=es5).js +new file mode 100644 +index 000000000..f6c7d8509 +--- /dev/null ++++ b/tests/baselines/reference/usingDeclarationsWithESClassDecorators.10(module=system,target=es5).js +@@ -0,0 +1,55 @@ ++//// [tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsWithESClassDecorators.10.ts] //// ++ ++//// [usingDeclarationsWithESClassDecorators.10.ts] ++export {}; ++ ++declare var dec: any; ++ ++@dec ++export default class { ++} ++ ++using after = null; ++ ++ ++//// [usingDeclarationsWithESClassDecorators.10.js] ++System.register([], function (exports_1, context_1) { ++ "use strict"; ++ var default_1, after, env_1; ++ var __moduleName = context_1 && context_1.id; ++ return { ++ setters: [], ++ execute: function () { ++ default_1 = function () { ++ var _classDecorators = [dec]; ++ var _classDescriptor; ++ var _classExtraInitializers = []; ++ var _classThis; ++ var default_1 = _classThis = /** @class */ (function () { ++ function default_1() { ++ } ++ return default_1; ++ }()); ++ __setFunctionName(_classThis, "default"); ++ (function () { ++ __esDecorate(null, _classDescriptor = { value: _classThis }, _classDecorators, { kind: "class", name: _classThis.name }, null, _classExtraInitializers); ++ default_1 = _classThis = _classDescriptor.value; ++ __runInitializers(_classThis, _classExtraInitializers); ++ })(); ++ return default_1 = _classThis; ++ }(); ++ exports_1("default", default_1); ++ env_1 = { stack: [], error: void 0, hasError: false }; ++ try { ++ after = __addDisposableResource(env_1, null, false); ++ } ++ catch (e_1) { ++ env_1.error = e_1; ++ env_1.hasError = true; ++ } ++ finally { ++ __disposeResources(env_1); ++ } ++ } ++ }; ++}); +diff --git a/tests/baselines/reference/usingDeclarationsWithESClassDecorators.10(module=system,target=esnext).js b/tests/baselines/reference/usingDeclarationsWithESClassDecorators.10(module=system,target=esnext).js +new file mode 100644 +index 000000000..e50d6155d +--- /dev/null ++++ b/tests/baselines/reference/usingDeclarationsWithESClassDecorators.10(module=system,target=esnext).js +@@ -0,0 +1,31 @@ ++//// [tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsWithESClassDecorators.10.ts] //// ++ ++//// [usingDeclarationsWithESClassDecorators.10.ts] ++export {}; ++ ++declare var dec: any; ++ ++@dec ++export default class { ++} ++ ++using after = null; ++ ++ ++//// [usingDeclarationsWithESClassDecorators.10.js] ++System.register([], function (exports_1, context_1) { ++ "use strict"; ++ var default_1, after; ++ var __moduleName = context_1 && context_1.id; ++ return { ++ setters: [], ++ execute: function () { ++ default_1 = ++ @dec ++ class { ++ }; ++ exports_1("default", default_1); ++ using after_1 = after = null; ++ } ++ }; ++}); +diff --git a/tests/baselines/reference/usingDeclarationsWithESClassDecorators.11(module=commonjs,target=es2015).js b/tests/baselines/reference/usingDeclarationsWithESClassDecorators.11(module=commonjs,target=es2015).js +new file mode 100644 +index 000000000..730ec08a4 +--- /dev/null ++++ b/tests/baselines/reference/usingDeclarationsWithESClassDecorators.11(module=commonjs,target=es2015).js +@@ -0,0 +1,48 @@ ++//// [tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsWithESClassDecorators.11.ts] //// ++ ++//// [usingDeclarationsWithESClassDecorators.11.ts] ++export {}; ++ ++declare var dec: any; ++ ++@dec ++class C { ++} ++ ++export { C }; ++ ++using after = null; ++ ++ ++//// [usingDeclarationsWithESClassDecorators.11.js] ++"use strict"; ++Object.defineProperty(exports, "__esModule", { value: true }); ++exports.C = void 0; ++let C = (() => { ++ let _classDecorators = [dec]; ++ let _classDescriptor; ++ let _classExtraInitializers = []; ++ let _classThis; ++ var C = _classThis = class { ++ }; ++ __setFunctionName(_classThis, "C"); ++ (() => { ++ __esDecorate(null, _classDescriptor = { value: _classThis }, _classDecorators, { kind: "class", name: _classThis.name }, null, _classExtraInitializers); ++ C = _classThis = _classDescriptor.value; ++ __runInitializers(_classThis, _classExtraInitializers); ++ })(); ++ return C = _classThis; ++})(); ++exports.C = C; ++var after; ++const env_1 = { stack: [], error: void 0, hasError: false }; ++try { ++ after = __addDisposableResource(env_1, null, false); ++} ++catch (e_1) { ++ env_1.error = e_1; ++ env_1.hasError = true; ++} ++finally { ++ __disposeResources(env_1); ++} +diff --git a/tests/baselines/reference/usingDeclarationsWithESClassDecorators.11(module=commonjs,target=es5).js b/tests/baselines/reference/usingDeclarationsWithESClassDecorators.11(module=commonjs,target=es5).js +new file mode 100644 +index 000000000..46157431f +--- /dev/null ++++ b/tests/baselines/reference/usingDeclarationsWithESClassDecorators.11(module=commonjs,target=es5).js +@@ -0,0 +1,51 @@ ++//// [tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsWithESClassDecorators.11.ts] //// ++ ++//// [usingDeclarationsWithESClassDecorators.11.ts] ++export {}; ++ ++declare var dec: any; ++ ++@dec ++class C { ++} ++ ++export { C }; ++ ++using after = null; ++ ++ ++//// [usingDeclarationsWithESClassDecorators.11.js] ++"use strict"; ++Object.defineProperty(exports, "__esModule", { value: true }); ++exports.C = void 0; ++var C = function () { ++ var _classDecorators = [dec]; ++ var _classDescriptor; ++ var _classExtraInitializers = []; ++ var _classThis; ++ var C = _classThis = /** @class */ (function () { ++ function C_1() { ++ } ++ return C_1; ++ }()); ++ __setFunctionName(_classThis, "C"); ++ (function () { ++ __esDecorate(null, _classDescriptor = { value: _classThis }, _classDecorators, { kind: "class", name: _classThis.name }, null, _classExtraInitializers); ++ C = _classThis = _classDescriptor.value; ++ __runInitializers(_classThis, _classExtraInitializers); ++ })(); ++ return C = _classThis; ++}(); ++exports.C = C; ++var after; ++var env_1 = { stack: [], error: void 0, hasError: false }; ++try { ++ after = __addDisposableResource(env_1, null, false); ++} ++catch (e_1) { ++ env_1.error = e_1; ++ env_1.hasError = true; ++} ++finally { ++ __disposeResources(env_1); ++} +diff --git a/tests/baselines/reference/usingDeclarationsWithESClassDecorators.11(module=commonjs,target=esnext).js b/tests/baselines/reference/usingDeclarationsWithESClassDecorators.11(module=commonjs,target=esnext).js +new file mode 100644 +index 000000000..afd994944 +--- /dev/null ++++ b/tests/baselines/reference/usingDeclarationsWithESClassDecorators.11(module=commonjs,target=esnext).js +@@ -0,0 +1,25 @@ ++//// [tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsWithESClassDecorators.11.ts] //// ++ ++//// [usingDeclarationsWithESClassDecorators.11.ts] ++export {}; ++ ++declare var dec: any; ++ ++@dec ++class C { ++} ++ ++export { C }; ++ ++using after = null; ++ ++ ++//// [usingDeclarationsWithESClassDecorators.11.js] ++"use strict"; ++Object.defineProperty(exports, "__esModule", { value: true }); ++exports.C = void 0; ++@dec ++class C { ++} ++exports.C = C; ++using after = null; +diff --git a/tests/baselines/reference/usingDeclarationsWithESClassDecorators.11(module=esnext,target=es2015).js b/tests/baselines/reference/usingDeclarationsWithESClassDecorators.11(module=esnext,target=es2015).js +new file mode 100644 +index 000000000..562444595 +--- /dev/null ++++ b/tests/baselines/reference/usingDeclarationsWithESClassDecorators.11(module=esnext,target=es2015).js +@@ -0,0 +1,45 @@ ++//// [tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsWithESClassDecorators.11.ts] //// ++ ++//// [usingDeclarationsWithESClassDecorators.11.ts] ++export {}; ++ ++declare var dec: any; ++ ++@dec ++class C { ++} ++ ++export { C }; ++ ++using after = null; ++ ++ ++//// [usingDeclarationsWithESClassDecorators.11.js] ++let C = (() => { ++ let _classDecorators = [dec]; ++ let _classDescriptor; ++ let _classExtraInitializers = []; ++ let _classThis; ++ var C = _classThis = class { ++ }; ++ __setFunctionName(_classThis, "C"); ++ (() => { ++ __esDecorate(null, _classDescriptor = { value: _classThis }, _classDecorators, { kind: "class", name: _classThis.name }, null, _classExtraInitializers); ++ C = _classThis = _classDescriptor.value; ++ __runInitializers(_classThis, _classExtraInitializers); ++ })(); ++ return C = _classThis; ++})(); ++export { C }; ++var after; ++const env_1 = { stack: [], error: void 0, hasError: false }; ++try { ++ after = __addDisposableResource(env_1, null, false); ++} ++catch (e_1) { ++ env_1.error = e_1; ++ env_1.hasError = true; ++} ++finally { ++ __disposeResources(env_1); ++} +diff --git a/tests/baselines/reference/usingDeclarationsWithESClassDecorators.11(module=esnext,target=es5).js b/tests/baselines/reference/usingDeclarationsWithESClassDecorators.11(module=esnext,target=es5).js +new file mode 100644 +index 000000000..0f59cf196 +--- /dev/null ++++ b/tests/baselines/reference/usingDeclarationsWithESClassDecorators.11(module=esnext,target=es5).js +@@ -0,0 +1,48 @@ ++//// [tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsWithESClassDecorators.11.ts] //// ++ ++//// [usingDeclarationsWithESClassDecorators.11.ts] ++export {}; ++ ++declare var dec: any; ++ ++@dec ++class C { ++} ++ ++export { C }; ++ ++using after = null; ++ ++ ++//// [usingDeclarationsWithESClassDecorators.11.js] ++var C = function () { ++ var _classDecorators = [dec]; ++ var _classDescriptor; ++ var _classExtraInitializers = []; ++ var _classThis; ++ var C = _classThis = /** @class */ (function () { ++ function C_1() { ++ } ++ return C_1; ++ }()); ++ __setFunctionName(_classThis, "C"); ++ (function () { ++ __esDecorate(null, _classDescriptor = { value: _classThis }, _classDecorators, { kind: "class", name: _classThis.name }, null, _classExtraInitializers); ++ C = _classThis = _classDescriptor.value; ++ __runInitializers(_classThis, _classExtraInitializers); ++ })(); ++ return C = _classThis; ++}(); ++export { C }; ++var after; ++var env_1 = { stack: [], error: void 0, hasError: false }; ++try { ++ after = __addDisposableResource(env_1, null, false); ++} ++catch (e_1) { ++ env_1.error = e_1; ++ env_1.hasError = true; ++} ++finally { ++ __disposeResources(env_1); ++} +diff --git a/tests/baselines/reference/usingDeclarationsWithESClassDecorators.11(module=esnext,target=esnext).js b/tests/baselines/reference/usingDeclarationsWithESClassDecorators.11(module=esnext,target=esnext).js +new file mode 100644 +index 000000000..ae5cb9de7 +--- /dev/null ++++ b/tests/baselines/reference/usingDeclarationsWithESClassDecorators.11(module=esnext,target=esnext).js +@@ -0,0 +1,22 @@ ++//// [tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsWithESClassDecorators.11.ts] //// ++ ++//// [usingDeclarationsWithESClassDecorators.11.ts] ++export {}; ++ ++declare var dec: any; ++ ++@dec ++class C { ++} ++ ++export { C }; ++ ++using after = null; ++ ++ ++//// [usingDeclarationsWithESClassDecorators.11.js] ++@dec ++class C { ++} ++export { C }; ++using after = null; +diff --git a/tests/baselines/reference/usingDeclarationsWithESClassDecorators.11(module=system,target=es2015).js b/tests/baselines/reference/usingDeclarationsWithESClassDecorators.11(module=system,target=es2015).js +new file mode 100644 +index 000000000..c8f244dda +--- /dev/null ++++ b/tests/baselines/reference/usingDeclarationsWithESClassDecorators.11(module=system,target=es2015).js +@@ -0,0 +1,54 @@ ++//// [tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsWithESClassDecorators.11.ts] //// ++ ++//// [usingDeclarationsWithESClassDecorators.11.ts] ++export {}; ++ ++declare var dec: any; ++ ++@dec ++class C { ++} ++ ++export { C }; ++ ++using after = null; ++ ++ ++//// [usingDeclarationsWithESClassDecorators.11.js] ++System.register([], function (exports_1, context_1) { ++ "use strict"; ++ var C, after, env_1; ++ var __moduleName = context_1 && context_1.id; ++ return { ++ setters: [], ++ execute: function () { ++ C = (() => { ++ let _classDecorators = [dec]; ++ let _classDescriptor; ++ let _classExtraInitializers = []; ++ let _classThis; ++ var C = _classThis = class { ++ }; ++ __setFunctionName(_classThis, "C"); ++ (() => { ++ __esDecorate(null, _classDescriptor = { value: _classThis }, _classDecorators, { kind: "class", name: _classThis.name }, null, _classExtraInitializers); ++ C = _classThis = _classDescriptor.value; ++ __runInitializers(_classThis, _classExtraInitializers); ++ })(); ++ return C = _classThis; ++ })(); ++ exports_1("C", C); ++ env_1 = { stack: [], error: void 0, hasError: false }; ++ try { ++ after = __addDisposableResource(env_1, null, false); ++ } ++ catch (e_1) { ++ env_1.error = e_1; ++ env_1.hasError = true; ++ } ++ finally { ++ __disposeResources(env_1); ++ } ++ } ++ }; ++}); +diff --git a/tests/baselines/reference/usingDeclarationsWithESClassDecorators.11(module=system,target=es5).js b/tests/baselines/reference/usingDeclarationsWithESClassDecorators.11(module=system,target=es5).js +new file mode 100644 +index 000000000..990cca574 +--- /dev/null ++++ b/tests/baselines/reference/usingDeclarationsWithESClassDecorators.11(module=system,target=es5).js +@@ -0,0 +1,57 @@ ++//// [tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsWithESClassDecorators.11.ts] //// ++ ++//// [usingDeclarationsWithESClassDecorators.11.ts] ++export {}; ++ ++declare var dec: any; ++ ++@dec ++class C { ++} ++ ++export { C }; ++ ++using after = null; ++ ++ ++//// [usingDeclarationsWithESClassDecorators.11.js] ++System.register([], function (exports_1, context_1) { ++ "use strict"; ++ var C, after, env_1; ++ var __moduleName = context_1 && context_1.id; ++ return { ++ setters: [], ++ execute: function () { ++ C = function () { ++ var _classDecorators = [dec]; ++ var _classDescriptor; ++ var _classExtraInitializers = []; ++ var _classThis; ++ var C = _classThis = /** @class */ (function () { ++ function C_1() { ++ } ++ return C_1; ++ }()); ++ __setFunctionName(_classThis, "C"); ++ (function () { ++ __esDecorate(null, _classDescriptor = { value: _classThis }, _classDecorators, { kind: "class", name: _classThis.name }, null, _classExtraInitializers); ++ C = _classThis = _classDescriptor.value; ++ __runInitializers(_classThis, _classExtraInitializers); ++ })(); ++ return C = _classThis; ++ }(); ++ exports_1("C", C); ++ env_1 = { stack: [], error: void 0, hasError: false }; ++ try { ++ after = __addDisposableResource(env_1, null, false); ++ } ++ catch (e_1) { ++ env_1.error = e_1; ++ env_1.hasError = true; ++ } ++ finally { ++ __disposeResources(env_1); ++ } ++ } ++ }; ++}); +diff --git a/tests/baselines/reference/usingDeclarationsWithESClassDecorators.11(module=system,target=esnext).js b/tests/baselines/reference/usingDeclarationsWithESClassDecorators.11(module=system,target=esnext).js +new file mode 100644 +index 000000000..de982a12d +--- /dev/null ++++ b/tests/baselines/reference/usingDeclarationsWithESClassDecorators.11(module=system,target=esnext).js +@@ -0,0 +1,33 @@ ++//// [tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsWithESClassDecorators.11.ts] //// ++ ++//// [usingDeclarationsWithESClassDecorators.11.ts] ++export {}; ++ ++declare var dec: any; ++ ++@dec ++class C { ++} ++ ++export { C }; ++ ++using after = null; ++ ++ ++//// [usingDeclarationsWithESClassDecorators.11.js] ++System.register([], function (exports_1, context_1) { ++ "use strict"; ++ var C, after; ++ var __moduleName = context_1 && context_1.id; ++ return { ++ setters: [], ++ execute: function () { ++ C = ++ @dec ++ class C { ++ }; ++ exports_1("C", C); ++ using after_1 = after = null; ++ } ++ }; ++}); +diff --git a/tests/baselines/reference/usingDeclarationsWithESClassDecorators.12(module=commonjs,target=es2015).js b/tests/baselines/reference/usingDeclarationsWithESClassDecorators.12(module=commonjs,target=es2015).js +new file mode 100644 +index 000000000..700b49c59 +--- /dev/null ++++ b/tests/baselines/reference/usingDeclarationsWithESClassDecorators.12(module=commonjs,target=es2015).js +@@ -0,0 +1,48 @@ ++//// [tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsWithESClassDecorators.12.ts] //// ++ ++//// [usingDeclarationsWithESClassDecorators.12.ts] ++export {}; ++ ++declare var dec: any; ++ ++@dec ++class C { ++} ++ ++export { C as D }; ++ ++using after = null; ++ ++ ++//// [usingDeclarationsWithESClassDecorators.12.js] ++"use strict"; ++Object.defineProperty(exports, "__esModule", { value: true }); ++exports.D = void 0; ++let C = (() => { ++ let _classDecorators = [dec]; ++ let _classDescriptor; ++ let _classExtraInitializers = []; ++ let _classThis; ++ var C = _classThis = class { ++ }; ++ __setFunctionName(_classThis, "C"); ++ (() => { ++ __esDecorate(null, _classDescriptor = { value: _classThis }, _classDecorators, { kind: "class", name: _classThis.name }, null, _classExtraInitializers); ++ C = _classThis = _classDescriptor.value; ++ __runInitializers(_classThis, _classExtraInitializers); ++ })(); ++ return C = _classThis; ++})(); ++exports.D = C; ++var after; ++const env_1 = { stack: [], error: void 0, hasError: false }; ++try { ++ after = __addDisposableResource(env_1, null, false); ++} ++catch (e_1) { ++ env_1.error = e_1; ++ env_1.hasError = true; ++} ++finally { ++ __disposeResources(env_1); ++} +diff --git a/tests/baselines/reference/usingDeclarationsWithESClassDecorators.12(module=commonjs,target=es5).js b/tests/baselines/reference/usingDeclarationsWithESClassDecorators.12(module=commonjs,target=es5).js +new file mode 100644 +index 000000000..2f420f06e +--- /dev/null ++++ b/tests/baselines/reference/usingDeclarationsWithESClassDecorators.12(module=commonjs,target=es5).js +@@ -0,0 +1,51 @@ ++//// [tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsWithESClassDecorators.12.ts] //// ++ ++//// [usingDeclarationsWithESClassDecorators.12.ts] ++export {}; ++ ++declare var dec: any; ++ ++@dec ++class C { ++} ++ ++export { C as D }; ++ ++using after = null; ++ ++ ++//// [usingDeclarationsWithESClassDecorators.12.js] ++"use strict"; ++Object.defineProperty(exports, "__esModule", { value: true }); ++exports.D = void 0; ++var C = function () { ++ var _classDecorators = [dec]; ++ var _classDescriptor; ++ var _classExtraInitializers = []; ++ var _classThis; ++ var C = _classThis = /** @class */ (function () { ++ function C_1() { ++ } ++ return C_1; ++ }()); ++ __setFunctionName(_classThis, "C"); ++ (function () { ++ __esDecorate(null, _classDescriptor = { value: _classThis }, _classDecorators, { kind: "class", name: _classThis.name }, null, _classExtraInitializers); ++ C = _classThis = _classDescriptor.value; ++ __runInitializers(_classThis, _classExtraInitializers); ++ })(); ++ return C = _classThis; ++}(); ++exports.D = C; ++var after; ++var env_1 = { stack: [], error: void 0, hasError: false }; ++try { ++ after = __addDisposableResource(env_1, null, false); ++} ++catch (e_1) { ++ env_1.error = e_1; ++ env_1.hasError = true; ++} ++finally { ++ __disposeResources(env_1); ++} +diff --git a/tests/baselines/reference/usingDeclarationsWithESClassDecorators.12(module=commonjs,target=esnext).js b/tests/baselines/reference/usingDeclarationsWithESClassDecorators.12(module=commonjs,target=esnext).js +new file mode 100644 +index 000000000..264a0b9e6 +--- /dev/null ++++ b/tests/baselines/reference/usingDeclarationsWithESClassDecorators.12(module=commonjs,target=esnext).js +@@ -0,0 +1,25 @@ ++//// [tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsWithESClassDecorators.12.ts] //// ++ ++//// [usingDeclarationsWithESClassDecorators.12.ts] ++export {}; ++ ++declare var dec: any; ++ ++@dec ++class C { ++} ++ ++export { C as D }; ++ ++using after = null; ++ ++ ++//// [usingDeclarationsWithESClassDecorators.12.js] ++"use strict"; ++Object.defineProperty(exports, "__esModule", { value: true }); ++exports.D = void 0; ++@dec ++class C { ++} ++exports.D = C; ++using after = null; +diff --git a/tests/baselines/reference/usingDeclarationsWithESClassDecorators.12(module=esnext,target=es2015).js b/tests/baselines/reference/usingDeclarationsWithESClassDecorators.12(module=esnext,target=es2015).js +new file mode 100644 +index 000000000..5f654d1d5 +--- /dev/null ++++ b/tests/baselines/reference/usingDeclarationsWithESClassDecorators.12(module=esnext,target=es2015).js +@@ -0,0 +1,45 @@ ++//// [tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsWithESClassDecorators.12.ts] //// ++ ++//// [usingDeclarationsWithESClassDecorators.12.ts] ++export {}; ++ ++declare var dec: any; ++ ++@dec ++class C { ++} ++ ++export { C as D }; ++ ++using after = null; ++ ++ ++//// [usingDeclarationsWithESClassDecorators.12.js] ++let C = (() => { ++ let _classDecorators = [dec]; ++ let _classDescriptor; ++ let _classExtraInitializers = []; ++ let _classThis; ++ var C = _classThis = class { ++ }; ++ __setFunctionName(_classThis, "C"); ++ (() => { ++ __esDecorate(null, _classDescriptor = { value: _classThis }, _classDecorators, { kind: "class", name: _classThis.name }, null, _classExtraInitializers); ++ C = _classThis = _classDescriptor.value; ++ __runInitializers(_classThis, _classExtraInitializers); ++ })(); ++ return C = _classThis; ++})(); ++export { C as D }; ++var after; ++const env_1 = { stack: [], error: void 0, hasError: false }; ++try { ++ after = __addDisposableResource(env_1, null, false); ++} ++catch (e_1) { ++ env_1.error = e_1; ++ env_1.hasError = true; ++} ++finally { ++ __disposeResources(env_1); ++} +diff --git a/tests/baselines/reference/usingDeclarationsWithESClassDecorators.12(module=esnext,target=es5).js b/tests/baselines/reference/usingDeclarationsWithESClassDecorators.12(module=esnext,target=es5).js +new file mode 100644 +index 000000000..c16abc977 +--- /dev/null ++++ b/tests/baselines/reference/usingDeclarationsWithESClassDecorators.12(module=esnext,target=es5).js +@@ -0,0 +1,48 @@ ++//// [tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsWithESClassDecorators.12.ts] //// ++ ++//// [usingDeclarationsWithESClassDecorators.12.ts] ++export {}; ++ ++declare var dec: any; ++ ++@dec ++class C { ++} ++ ++export { C as D }; ++ ++using after = null; ++ ++ ++//// [usingDeclarationsWithESClassDecorators.12.js] ++var C = function () { ++ var _classDecorators = [dec]; ++ var _classDescriptor; ++ var _classExtraInitializers = []; ++ var _classThis; ++ var C = _classThis = /** @class */ (function () { ++ function C_1() { ++ } ++ return C_1; ++ }()); ++ __setFunctionName(_classThis, "C"); ++ (function () { ++ __esDecorate(null, _classDescriptor = { value: _classThis }, _classDecorators, { kind: "class", name: _classThis.name }, null, _classExtraInitializers); ++ C = _classThis = _classDescriptor.value; ++ __runInitializers(_classThis, _classExtraInitializers); ++ })(); ++ return C = _classThis; ++}(); ++export { C as D }; ++var after; ++var env_1 = { stack: [], error: void 0, hasError: false }; ++try { ++ after = __addDisposableResource(env_1, null, false); ++} ++catch (e_1) { ++ env_1.error = e_1; ++ env_1.hasError = true; ++} ++finally { ++ __disposeResources(env_1); ++} +diff --git a/tests/baselines/reference/usingDeclarationsWithESClassDecorators.12(module=esnext,target=esnext).js b/tests/baselines/reference/usingDeclarationsWithESClassDecorators.12(module=esnext,target=esnext).js +new file mode 100644 +index 000000000..88e96a557 +--- /dev/null ++++ b/tests/baselines/reference/usingDeclarationsWithESClassDecorators.12(module=esnext,target=esnext).js +@@ -0,0 +1,22 @@ ++//// [tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsWithESClassDecorators.12.ts] //// ++ ++//// [usingDeclarationsWithESClassDecorators.12.ts] ++export {}; ++ ++declare var dec: any; ++ ++@dec ++class C { ++} ++ ++export { C as D }; ++ ++using after = null; ++ ++ ++//// [usingDeclarationsWithESClassDecorators.12.js] ++@dec ++class C { ++} ++export { C as D }; ++using after = null; +diff --git a/tests/baselines/reference/usingDeclarationsWithESClassDecorators.12(module=system,target=es2015).js b/tests/baselines/reference/usingDeclarationsWithESClassDecorators.12(module=system,target=es2015).js +new file mode 100644 +index 000000000..703dbd4a0 +--- /dev/null ++++ b/tests/baselines/reference/usingDeclarationsWithESClassDecorators.12(module=system,target=es2015).js +@@ -0,0 +1,54 @@ ++//// [tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsWithESClassDecorators.12.ts] //// ++ ++//// [usingDeclarationsWithESClassDecorators.12.ts] ++export {}; ++ ++declare var dec: any; ++ ++@dec ++class C { ++} ++ ++export { C as D }; ++ ++using after = null; ++ ++ ++//// [usingDeclarationsWithESClassDecorators.12.js] ++System.register([], function (exports_1, context_1) { ++ "use strict"; ++ var C, after, env_1; ++ var __moduleName = context_1 && context_1.id; ++ return { ++ setters: [], ++ execute: function () { ++ C = (() => { ++ let _classDecorators = [dec]; ++ let _classDescriptor; ++ let _classExtraInitializers = []; ++ let _classThis; ++ var C = _classThis = class { ++ }; ++ __setFunctionName(_classThis, "C"); ++ (() => { ++ __esDecorate(null, _classDescriptor = { value: _classThis }, _classDecorators, { kind: "class", name: _classThis.name }, null, _classExtraInitializers); ++ C = _classThis = _classDescriptor.value; ++ __runInitializers(_classThis, _classExtraInitializers); ++ })(); ++ return C = _classThis; ++ })(); ++ exports_1("D", C); ++ env_1 = { stack: [], error: void 0, hasError: false }; ++ try { ++ after = __addDisposableResource(env_1, null, false); ++ } ++ catch (e_1) { ++ env_1.error = e_1; ++ env_1.hasError = true; ++ } ++ finally { ++ __disposeResources(env_1); ++ } ++ } ++ }; ++}); +diff --git a/tests/baselines/reference/usingDeclarationsWithESClassDecorators.12(module=system,target=es5).js b/tests/baselines/reference/usingDeclarationsWithESClassDecorators.12(module=system,target=es5).js +new file mode 100644 +index 000000000..47721a55f +--- /dev/null ++++ b/tests/baselines/reference/usingDeclarationsWithESClassDecorators.12(module=system,target=es5).js +@@ -0,0 +1,57 @@ ++//// [tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsWithESClassDecorators.12.ts] //// ++ ++//// [usingDeclarationsWithESClassDecorators.12.ts] ++export {}; ++ ++declare var dec: any; ++ ++@dec ++class C { ++} ++ ++export { C as D }; ++ ++using after = null; ++ ++ ++//// [usingDeclarationsWithESClassDecorators.12.js] ++System.register([], function (exports_1, context_1) { ++ "use strict"; ++ var C, after, env_1; ++ var __moduleName = context_1 && context_1.id; ++ return { ++ setters: [], ++ execute: function () { ++ C = function () { ++ var _classDecorators = [dec]; ++ var _classDescriptor; ++ var _classExtraInitializers = []; ++ var _classThis; ++ var C = _classThis = /** @class */ (function () { ++ function C_1() { ++ } ++ return C_1; ++ }()); ++ __setFunctionName(_classThis, "C"); ++ (function () { ++ __esDecorate(null, _classDescriptor = { value: _classThis }, _classDecorators, { kind: "class", name: _classThis.name }, null, _classExtraInitializers); ++ C = _classThis = _classDescriptor.value; ++ __runInitializers(_classThis, _classExtraInitializers); ++ })(); ++ return C = _classThis; ++ }(); ++ exports_1("D", C); ++ env_1 = { stack: [], error: void 0, hasError: false }; ++ try { ++ after = __addDisposableResource(env_1, null, false); ++ } ++ catch (e_1) { ++ env_1.error = e_1; ++ env_1.hasError = true; ++ } ++ finally { ++ __disposeResources(env_1); ++ } ++ } ++ }; ++}); +diff --git a/tests/baselines/reference/usingDeclarationsWithESClassDecorators.12(module=system,target=esnext).js b/tests/baselines/reference/usingDeclarationsWithESClassDecorators.12(module=system,target=esnext).js +new file mode 100644 +index 000000000..3469e409b +--- /dev/null ++++ b/tests/baselines/reference/usingDeclarationsWithESClassDecorators.12(module=system,target=esnext).js +@@ -0,0 +1,33 @@ ++//// [tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsWithESClassDecorators.12.ts] //// ++ ++//// [usingDeclarationsWithESClassDecorators.12.ts] ++export {}; ++ ++declare var dec: any; ++ ++@dec ++class C { ++} ++ ++export { C as D }; ++ ++using after = null; ++ ++ ++//// [usingDeclarationsWithESClassDecorators.12.js] ++System.register([], function (exports_1, context_1) { ++ "use strict"; ++ var C, after; ++ var __moduleName = context_1 && context_1.id; ++ return { ++ setters: [], ++ execute: function () { ++ C = ++ @dec ++ class C { ++ }; ++ exports_1("D", C); ++ using after_1 = after = null; ++ } ++ }; ++}); +diff --git a/tests/baselines/reference/usingDeclarationsWithESClassDecorators.2(module=commonjs,target=es2015).js b/tests/baselines/reference/usingDeclarationsWithESClassDecorators.2(module=commonjs,target=es2015).js +new file mode 100644 +index 000000000..2118bb61d +--- /dev/null ++++ b/tests/baselines/reference/usingDeclarationsWithESClassDecorators.2(module=commonjs,target=es2015).js +@@ -0,0 +1,45 @@ ++//// [tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsWithESClassDecorators.2.ts] //// ++ ++//// [usingDeclarationsWithESClassDecorators.2.ts] ++export {}; ++ ++declare var dec: any; ++ ++using before = null; ++ ++@dec ++export class C { ++} ++ ++ ++//// [usingDeclarationsWithESClassDecorators.2.js] ++"use strict"; ++Object.defineProperty(exports, "__esModule", { value: true }); ++exports.C = void 0; ++var before, C; ++const env_1 = { stack: [], error: void 0, hasError: false }; ++try { ++ before = __addDisposableResource(env_1, null, false); ++ exports.C = C = (() => { ++ let _classDecorators = [dec]; ++ let _classDescriptor; ++ let _classExtraInitializers = []; ++ let _classThis; ++ var C = _classThis = class { ++ }; ++ __setFunctionName(_classThis, "C"); ++ (() => { ++ __esDecorate(null, _classDescriptor = { value: _classThis }, _classDecorators, { kind: "class", name: _classThis.name }, null, _classExtraInitializers); ++ C = _classThis = _classDescriptor.value; ++ __runInitializers(_classThis, _classExtraInitializers); ++ })(); ++ return C = _classThis; ++ })(); ++} ++catch (e_1) { ++ env_1.error = e_1; ++ env_1.hasError = true; ++} ++finally { ++ __disposeResources(env_1); ++} +diff --git a/tests/baselines/reference/usingDeclarationsWithESClassDecorators.2(module=commonjs,target=es5).js b/tests/baselines/reference/usingDeclarationsWithESClassDecorators.2(module=commonjs,target=es5).js +new file mode 100644 +index 000000000..7a770d361 +--- /dev/null ++++ b/tests/baselines/reference/usingDeclarationsWithESClassDecorators.2(module=commonjs,target=es5).js +@@ -0,0 +1,48 @@ ++//// [tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsWithESClassDecorators.2.ts] //// ++ ++//// [usingDeclarationsWithESClassDecorators.2.ts] ++export {}; ++ ++declare var dec: any; ++ ++using before = null; ++ ++@dec ++export class C { ++} ++ ++ ++//// [usingDeclarationsWithESClassDecorators.2.js] ++"use strict"; ++Object.defineProperty(exports, "__esModule", { value: true }); ++exports.C = void 0; ++var before, C; ++var env_1 = { stack: [], error: void 0, hasError: false }; ++try { ++ before = __addDisposableResource(env_1, null, false); ++ exports.C = C = function () { ++ var _classDecorators = [dec]; ++ var _classDescriptor; ++ var _classExtraInitializers = []; ++ var _classThis; ++ var C = _classThis = /** @class */ (function () { ++ function C_1() { ++ } ++ return C_1; ++ }()); ++ __setFunctionName(_classThis, "C"); ++ (function () { ++ __esDecorate(null, _classDescriptor = { value: _classThis }, _classDecorators, { kind: "class", name: _classThis.name }, null, _classExtraInitializers); ++ C = _classThis = _classDescriptor.value; ++ __runInitializers(_classThis, _classExtraInitializers); ++ })(); ++ return C = _classThis; ++ }(); ++} ++catch (e_1) { ++ env_1.error = e_1; ++ env_1.hasError = true; ++} ++finally { ++ __disposeResources(env_1); ++} +diff --git a/tests/baselines/reference/usingDeclarationsWithESClassDecorators.2(module=commonjs,target=esnext).js b/tests/baselines/reference/usingDeclarationsWithESClassDecorators.2(module=commonjs,target=esnext).js +new file mode 100644 +index 000000000..938b226e0 +--- /dev/null ++++ b/tests/baselines/reference/usingDeclarationsWithESClassDecorators.2(module=commonjs,target=esnext).js +@@ -0,0 +1,23 @@ ++//// [tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsWithESClassDecorators.2.ts] //// ++ ++//// [usingDeclarationsWithESClassDecorators.2.ts] ++export {}; ++ ++declare var dec: any; ++ ++using before = null; ++ ++@dec ++export class C { ++} ++ ++ ++//// [usingDeclarationsWithESClassDecorators.2.js] ++"use strict"; ++Object.defineProperty(exports, "__esModule", { value: true }); ++exports.C = void 0; ++using before = null; ++@dec ++class C { ++} ++exports.C = C; +diff --git a/tests/baselines/reference/usingDeclarationsWithESClassDecorators.2(module=esnext,target=es2015).js b/tests/baselines/reference/usingDeclarationsWithESClassDecorators.2(module=esnext,target=es2015).js +new file mode 100644 +index 000000000..447e4016d +--- /dev/null ++++ b/tests/baselines/reference/usingDeclarationsWithESClassDecorators.2(module=esnext,target=es2015).js +@@ -0,0 +1,43 @@ ++//// [tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsWithESClassDecorators.2.ts] //// ++ ++//// [usingDeclarationsWithESClassDecorators.2.ts] ++export {}; ++ ++declare var dec: any; ++ ++using before = null; ++ ++@dec ++export class C { ++} ++ ++ ++//// [usingDeclarationsWithESClassDecorators.2.js] ++export { C }; ++var before, C; ++const env_1 = { stack: [], error: void 0, hasError: false }; ++try { ++ before = __addDisposableResource(env_1, null, false); ++ C = (() => { ++ let _classDecorators = [dec]; ++ let _classDescriptor; ++ let _classExtraInitializers = []; ++ let _classThis; ++ var C = _classThis = class { ++ }; ++ __setFunctionName(_classThis, "C"); ++ (() => { ++ __esDecorate(null, _classDescriptor = { value: _classThis }, _classDecorators, { kind: "class", name: _classThis.name }, null, _classExtraInitializers); ++ C = _classThis = _classDescriptor.value; ++ __runInitializers(_classThis, _classExtraInitializers); ++ })(); ++ return C = _classThis; ++ })(); ++} ++catch (e_1) { ++ env_1.error = e_1; ++ env_1.hasError = true; ++} ++finally { ++ __disposeResources(env_1); ++} +diff --git a/tests/baselines/reference/usingDeclarationsWithESClassDecorators.2(module=esnext,target=es5).js b/tests/baselines/reference/usingDeclarationsWithESClassDecorators.2(module=esnext,target=es5).js +new file mode 100644 +index 000000000..d53fe23c7 +--- /dev/null ++++ b/tests/baselines/reference/usingDeclarationsWithESClassDecorators.2(module=esnext,target=es5).js +@@ -0,0 +1,46 @@ ++//// [tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsWithESClassDecorators.2.ts] //// ++ ++//// [usingDeclarationsWithESClassDecorators.2.ts] ++export {}; ++ ++declare var dec: any; ++ ++using before = null; ++ ++@dec ++export class C { ++} ++ ++ ++//// [usingDeclarationsWithESClassDecorators.2.js] ++export { C }; ++var before, C; ++var env_1 = { stack: [], error: void 0, hasError: false }; ++try { ++ before = __addDisposableResource(env_1, null, false); ++ C = function () { ++ var _classDecorators = [dec]; ++ var _classDescriptor; ++ var _classExtraInitializers = []; ++ var _classThis; ++ var C = _classThis = /** @class */ (function () { ++ function C_1() { ++ } ++ return C_1; ++ }()); ++ __setFunctionName(_classThis, "C"); ++ (function () { ++ __esDecorate(null, _classDescriptor = { value: _classThis }, _classDecorators, { kind: "class", name: _classThis.name }, null, _classExtraInitializers); ++ C = _classThis = _classDescriptor.value; ++ __runInitializers(_classThis, _classExtraInitializers); ++ })(); ++ return C = _classThis; ++ }(); ++} ++catch (e_1) { ++ env_1.error = e_1; ++ env_1.hasError = true; ++} ++finally { ++ __disposeResources(env_1); ++} +diff --git a/tests/baselines/reference/usingDeclarationsWithESClassDecorators.2(module=esnext,target=esnext).js b/tests/baselines/reference/usingDeclarationsWithESClassDecorators.2(module=esnext,target=esnext).js +new file mode 100644 +index 000000000..a410a3d05 +--- /dev/null ++++ b/tests/baselines/reference/usingDeclarationsWithESClassDecorators.2(module=esnext,target=esnext).js +@@ -0,0 +1,19 @@ ++//// [tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsWithESClassDecorators.2.ts] //// ++ ++//// [usingDeclarationsWithESClassDecorators.2.ts] ++export {}; ++ ++declare var dec: any; ++ ++using before = null; ++ ++@dec ++export class C { ++} ++ ++ ++//// [usingDeclarationsWithESClassDecorators.2.js] ++using before = null; ++@dec ++export class C { ++} +diff --git a/tests/baselines/reference/usingDeclarationsWithESClassDecorators.2(module=system,target=es2015).js b/tests/baselines/reference/usingDeclarationsWithESClassDecorators.2(module=system,target=es2015).js +new file mode 100644 +index 000000000..c220e494b +--- /dev/null ++++ b/tests/baselines/reference/usingDeclarationsWithESClassDecorators.2(module=system,target=es2015).js +@@ -0,0 +1,51 @@ ++//// [tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsWithESClassDecorators.2.ts] //// ++ ++//// [usingDeclarationsWithESClassDecorators.2.ts] ++export {}; ++ ++declare var dec: any; ++ ++using before = null; ++ ++@dec ++export class C { ++} ++ ++ ++//// [usingDeclarationsWithESClassDecorators.2.js] ++System.register([], function (exports_1, context_1) { ++ "use strict"; ++ var before, C, env_1; ++ var __moduleName = context_1 && context_1.id; ++ return { ++ setters: [], ++ execute: function () { ++ env_1 = { stack: [], error: void 0, hasError: false }; ++ try { ++ before = __addDisposableResource(env_1, null, false); ++ exports_1("C", C = (() => { ++ let _classDecorators = [dec]; ++ let _classDescriptor; ++ let _classExtraInitializers = []; ++ let _classThis; ++ var C = _classThis = class { ++ }; ++ __setFunctionName(_classThis, "C"); ++ (() => { ++ __esDecorate(null, _classDescriptor = { value: _classThis }, _classDecorators, { kind: "class", name: _classThis.name }, null, _classExtraInitializers); ++ C = _classThis = _classDescriptor.value; ++ __runInitializers(_classThis, _classExtraInitializers); ++ })(); ++ return C = _classThis; ++ })()); ++ } ++ catch (e_1) { ++ env_1.error = e_1; ++ env_1.hasError = true; ++ } ++ finally { ++ __disposeResources(env_1); ++ } ++ } ++ }; ++}); +diff --git a/tests/baselines/reference/usingDeclarationsWithESClassDecorators.2(module=system,target=es5).js b/tests/baselines/reference/usingDeclarationsWithESClassDecorators.2(module=system,target=es5).js +new file mode 100644 +index 000000000..7d4c0543a +--- /dev/null ++++ b/tests/baselines/reference/usingDeclarationsWithESClassDecorators.2(module=system,target=es5).js +@@ -0,0 +1,54 @@ ++//// [tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsWithESClassDecorators.2.ts] //// ++ ++//// [usingDeclarationsWithESClassDecorators.2.ts] ++export {}; ++ ++declare var dec: any; ++ ++using before = null; ++ ++@dec ++export class C { ++} ++ ++ ++//// [usingDeclarationsWithESClassDecorators.2.js] ++System.register([], function (exports_1, context_1) { ++ "use strict"; ++ var before, C, env_1; ++ var __moduleName = context_1 && context_1.id; ++ return { ++ setters: [], ++ execute: function () { ++ env_1 = { stack: [], error: void 0, hasError: false }; ++ try { ++ before = __addDisposableResource(env_1, null, false); ++ exports_1("C", C = function () { ++ var _classDecorators = [dec]; ++ var _classDescriptor; ++ var _classExtraInitializers = []; ++ var _classThis; ++ var C = _classThis = /** @class */ (function () { ++ function C_1() { ++ } ++ return C_1; ++ }()); ++ __setFunctionName(_classThis, "C"); ++ (function () { ++ __esDecorate(null, _classDescriptor = { value: _classThis }, _classDecorators, { kind: "class", name: _classThis.name }, null, _classExtraInitializers); ++ C = _classThis = _classDescriptor.value; ++ __runInitializers(_classThis, _classExtraInitializers); ++ })(); ++ return C = _classThis; ++ }()); ++ } ++ catch (e_1) { ++ env_1.error = e_1; ++ env_1.hasError = true; ++ } ++ finally { ++ __disposeResources(env_1); ++ } ++ } ++ }; ++}); +diff --git a/tests/baselines/reference/usingDeclarationsWithESClassDecorators.2(module=system,target=esnext).js b/tests/baselines/reference/usingDeclarationsWithESClassDecorators.2(module=system,target=esnext).js +new file mode 100644 +index 000000000..99beb5190 +--- /dev/null ++++ b/tests/baselines/reference/usingDeclarationsWithESClassDecorators.2(module=system,target=esnext).js +@@ -0,0 +1,31 @@ ++//// [tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsWithESClassDecorators.2.ts] //// ++ ++//// [usingDeclarationsWithESClassDecorators.2.ts] ++export {}; ++ ++declare var dec: any; ++ ++using before = null; ++ ++@dec ++export class C { ++} ++ ++ ++//// [usingDeclarationsWithESClassDecorators.2.js] ++System.register([], function (exports_1, context_1) { ++ "use strict"; ++ var before, C; ++ var __moduleName = context_1 && context_1.id; ++ return { ++ setters: [], ++ execute: function () { ++ using before_1 = before = null; ++ C = ++ @dec ++ class C { ++ }; ++ exports_1("C", C); ++ } ++ }; ++}); +diff --git a/tests/baselines/reference/usingDeclarationsWithESClassDecorators.3(module=commonjs,target=es2015).js b/tests/baselines/reference/usingDeclarationsWithESClassDecorators.3(module=commonjs,target=es2015).js +new file mode 100644 +index 000000000..3370d3f11 +--- /dev/null ++++ b/tests/baselines/reference/usingDeclarationsWithESClassDecorators.3(module=commonjs,target=es2015).js +@@ -0,0 +1,47 @@ ++//// [tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsWithESClassDecorators.3.ts] //// ++ ++//// [usingDeclarationsWithESClassDecorators.3.ts] ++export {}; ++ ++declare var dec: any; ++ ++using before = null; ++ ++@dec ++export default class C { ++} ++ ++void C; ++ ++//// [usingDeclarationsWithESClassDecorators.3.js] ++"use strict"; ++Object.defineProperty(exports, "__esModule", { value: true }); ++exports.default = void 0; ++var before, C, _default; ++const env_1 = { stack: [], error: void 0, hasError: false }; ++try { ++ before = __addDisposableResource(env_1, null, false); ++ exports.default = _default = C = (() => { ++ let _classDecorators = [dec]; ++ let _classDescriptor; ++ let _classExtraInitializers = []; ++ let _classThis; ++ var C = _classThis = class { ++ }; ++ __setFunctionName(_classThis, "C"); ++ (() => { ++ __esDecorate(null, _classDescriptor = { value: _classThis }, _classDecorators, { kind: "class", name: _classThis.name }, null, _classExtraInitializers); ++ C = _classThis = _classDescriptor.value; ++ __runInitializers(_classThis, _classExtraInitializers); ++ })(); ++ return C = _classThis; ++ })(); ++ void C; ++} ++catch (e_1) { ++ env_1.error = e_1; ++ env_1.hasError = true; ++} ++finally { ++ __disposeResources(env_1); ++} +diff --git a/tests/baselines/reference/usingDeclarationsWithESClassDecorators.3(module=commonjs,target=es5).js b/tests/baselines/reference/usingDeclarationsWithESClassDecorators.3(module=commonjs,target=es5).js +new file mode 100644 +index 000000000..d3c27dd43 +--- /dev/null ++++ b/tests/baselines/reference/usingDeclarationsWithESClassDecorators.3(module=commonjs,target=es5).js +@@ -0,0 +1,51 @@ ++//// [tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsWithESClassDecorators.3.ts] //// ++ ++//// [usingDeclarationsWithESClassDecorators.3.ts] ++export {}; ++ ++declare var dec: any; ++ ++using before = null; ++ ++@dec ++export default class C { ++} ++ ++void C; ++ ++//// [usingDeclarationsWithESClassDecorators.3.js] ++"use strict"; ++Object.defineProperty(exports, "__esModule", { value: true }); ++exports.default = void 0; ++var before, C, _default; ++var env_1 = { stack: [], error: void 0, hasError: false }; ++try { ++ before = __addDisposableResource(env_1, null, false); ++ C = function () { ++ var _classDecorators = [dec]; ++ var _classDescriptor; ++ var _classExtraInitializers = []; ++ var _classThis; ++ var C = _classThis = /** @class */ (function () { ++ function C_1() { ++ } ++ return C_1; ++ }()); ++ __setFunctionName(_classThis, "C"); ++ (function () { ++ __esDecorate(null, _classDescriptor = { value: _classThis }, _classDecorators, { kind: "class", name: _classThis.name }, null, _classExtraInitializers); ++ C = _classThis = _classDescriptor.value; ++ __runInitializers(_classThis, _classExtraInitializers); ++ })(); ++ return C = _classThis; ++ }(); ++ exports.default = _default = C; ++ void C; ++} ++catch (e_1) { ++ env_1.error = e_1; ++ env_1.hasError = true; ++} ++finally { ++ __disposeResources(env_1); ++} +diff --git a/tests/baselines/reference/usingDeclarationsWithESClassDecorators.3(module=commonjs,target=esnext).js b/tests/baselines/reference/usingDeclarationsWithESClassDecorators.3(module=commonjs,target=esnext).js +new file mode 100644 +index 000000000..a21525344 +--- /dev/null ++++ b/tests/baselines/reference/usingDeclarationsWithESClassDecorators.3(module=commonjs,target=esnext).js +@@ -0,0 +1,24 @@ ++//// [tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsWithESClassDecorators.3.ts] //// ++ ++//// [usingDeclarationsWithESClassDecorators.3.ts] ++export {}; ++ ++declare var dec: any; ++ ++using before = null; ++ ++@dec ++export default class C { ++} ++ ++void C; ++ ++//// [usingDeclarationsWithESClassDecorators.3.js] ++"use strict"; ++Object.defineProperty(exports, "__esModule", { value: true }); ++using before = null; ++@dec ++class C { ++} ++exports.default = C; ++void C; +diff --git a/tests/baselines/reference/usingDeclarationsWithESClassDecorators.3(module=esnext,target=es2015).js b/tests/baselines/reference/usingDeclarationsWithESClassDecorators.3(module=esnext,target=es2015).js +new file mode 100644 +index 000000000..a44858f1d +--- /dev/null ++++ b/tests/baselines/reference/usingDeclarationsWithESClassDecorators.3(module=esnext,target=es2015).js +@@ -0,0 +1,45 @@ ++//// [tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsWithESClassDecorators.3.ts] //// ++ ++//// [usingDeclarationsWithESClassDecorators.3.ts] ++export {}; ++ ++declare var dec: any; ++ ++using before = null; ++ ++@dec ++export default class C { ++} ++ ++void C; ++ ++//// [usingDeclarationsWithESClassDecorators.3.js] ++export { _default as default }; ++var before, C, _default; ++const env_1 = { stack: [], error: void 0, hasError: false }; ++try { ++ before = __addDisposableResource(env_1, null, false); ++ _default = C = (() => { ++ let _classDecorators = [dec]; ++ let _classDescriptor; ++ let _classExtraInitializers = []; ++ let _classThis; ++ var C = _classThis = class { ++ }; ++ __setFunctionName(_classThis, "C"); ++ (() => { ++ __esDecorate(null, _classDescriptor = { value: _classThis }, _classDecorators, { kind: "class", name: _classThis.name }, null, _classExtraInitializers); ++ C = _classThis = _classDescriptor.value; ++ __runInitializers(_classThis, _classExtraInitializers); ++ })(); ++ return C = _classThis; ++ })(); ++ void C; ++} ++catch (e_1) { ++ env_1.error = e_1; ++ env_1.hasError = true; ++} ++finally { ++ __disposeResources(env_1); ++} +diff --git a/tests/baselines/reference/usingDeclarationsWithESClassDecorators.3(module=esnext,target=es5).js b/tests/baselines/reference/usingDeclarationsWithESClassDecorators.3(module=esnext,target=es5).js +new file mode 100644 +index 000000000..b7d521c92 +--- /dev/null ++++ b/tests/baselines/reference/usingDeclarationsWithESClassDecorators.3(module=esnext,target=es5).js +@@ -0,0 +1,49 @@ ++//// [tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsWithESClassDecorators.3.ts] //// ++ ++//// [usingDeclarationsWithESClassDecorators.3.ts] ++export {}; ++ ++declare var dec: any; ++ ++using before = null; ++ ++@dec ++export default class C { ++} ++ ++void C; ++ ++//// [usingDeclarationsWithESClassDecorators.3.js] ++export { _default as default }; ++var before, C, _default; ++var env_1 = { stack: [], error: void 0, hasError: false }; ++try { ++ before = __addDisposableResource(env_1, null, false); ++ C = function () { ++ var _classDecorators = [dec]; ++ var _classDescriptor; ++ var _classExtraInitializers = []; ++ var _classThis; ++ var C = _classThis = /** @class */ (function () { ++ function C_1() { ++ } ++ return C_1; ++ }()); ++ __setFunctionName(_classThis, "C"); ++ (function () { ++ __esDecorate(null, _classDescriptor = { value: _classThis }, _classDecorators, { kind: "class", name: _classThis.name }, null, _classExtraInitializers); ++ C = _classThis = _classDescriptor.value; ++ __runInitializers(_classThis, _classExtraInitializers); ++ })(); ++ return C = _classThis; ++ }(); ++ _default = C; ++ void C; ++} ++catch (e_1) { ++ env_1.error = e_1; ++ env_1.hasError = true; ++} ++finally { ++ __disposeResources(env_1); ++} +diff --git a/tests/baselines/reference/usingDeclarationsWithESClassDecorators.3(module=esnext,target=esnext).js b/tests/baselines/reference/usingDeclarationsWithESClassDecorators.3(module=esnext,target=esnext).js +new file mode 100644 +index 000000000..03c4b9ce3 +--- /dev/null ++++ b/tests/baselines/reference/usingDeclarationsWithESClassDecorators.3(module=esnext,target=esnext).js +@@ -0,0 +1,21 @@ ++//// [tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsWithESClassDecorators.3.ts] //// ++ ++//// [usingDeclarationsWithESClassDecorators.3.ts] ++export {}; ++ ++declare var dec: any; ++ ++using before = null; ++ ++@dec ++export default class C { ++} ++ ++void C; ++ ++//// [usingDeclarationsWithESClassDecorators.3.js] ++using before = null; ++@dec ++export default class C { ++} ++void C; +diff --git a/tests/baselines/reference/usingDeclarationsWithESClassDecorators.3(module=system,target=es2015).js b/tests/baselines/reference/usingDeclarationsWithESClassDecorators.3(module=system,target=es2015).js +new file mode 100644 +index 000000000..dafe5eade +--- /dev/null ++++ b/tests/baselines/reference/usingDeclarationsWithESClassDecorators.3(module=system,target=es2015).js +@@ -0,0 +1,53 @@ ++//// [tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsWithESClassDecorators.3.ts] //// ++ ++//// [usingDeclarationsWithESClassDecorators.3.ts] ++export {}; ++ ++declare var dec: any; ++ ++using before = null; ++ ++@dec ++export default class C { ++} ++ ++void C; ++ ++//// [usingDeclarationsWithESClassDecorators.3.js] ++System.register([], function (exports_1, context_1) { ++ "use strict"; ++ var before, C, _default, env_1; ++ var __moduleName = context_1 && context_1.id; ++ return { ++ setters: [], ++ execute: function () { ++ env_1 = { stack: [], error: void 0, hasError: false }; ++ try { ++ before = __addDisposableResource(env_1, null, false); ++ exports_1("default", _default = C = (() => { ++ let _classDecorators = [dec]; ++ let _classDescriptor; ++ let _classExtraInitializers = []; ++ let _classThis; ++ var C = _classThis = class { ++ }; ++ __setFunctionName(_classThis, "C"); ++ (() => { ++ __esDecorate(null, _classDescriptor = { value: _classThis }, _classDecorators, { kind: "class", name: _classThis.name }, null, _classExtraInitializers); ++ C = _classThis = _classDescriptor.value; ++ __runInitializers(_classThis, _classExtraInitializers); ++ })(); ++ return C = _classThis; ++ })()); ++ void C; ++ } ++ catch (e_1) { ++ env_1.error = e_1; ++ env_1.hasError = true; ++ } ++ finally { ++ __disposeResources(env_1); ++ } ++ } ++ }; ++}); +diff --git a/tests/baselines/reference/usingDeclarationsWithESClassDecorators.3(module=system,target=es5).js b/tests/baselines/reference/usingDeclarationsWithESClassDecorators.3(module=system,target=es5).js +new file mode 100644 +index 000000000..b30c4565c +--- /dev/null ++++ b/tests/baselines/reference/usingDeclarationsWithESClassDecorators.3(module=system,target=es5).js +@@ -0,0 +1,57 @@ ++//// [tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsWithESClassDecorators.3.ts] //// ++ ++//// [usingDeclarationsWithESClassDecorators.3.ts] ++export {}; ++ ++declare var dec: any; ++ ++using before = null; ++ ++@dec ++export default class C { ++} ++ ++void C; ++ ++//// [usingDeclarationsWithESClassDecorators.3.js] ++System.register([], function (exports_1, context_1) { ++ "use strict"; ++ var before, C, _default, env_1; ++ var __moduleName = context_1 && context_1.id; ++ return { ++ setters: [], ++ execute: function () { ++ env_1 = { stack: [], error: void 0, hasError: false }; ++ try { ++ before = __addDisposableResource(env_1, null, false); ++ C = function () { ++ var _classDecorators = [dec]; ++ var _classDescriptor; ++ var _classExtraInitializers = []; ++ var _classThis; ++ var C = _classThis = /** @class */ (function () { ++ function C_1() { ++ } ++ return C_1; ++ }()); ++ __setFunctionName(_classThis, "C"); ++ (function () { ++ __esDecorate(null, _classDescriptor = { value: _classThis }, _classDecorators, { kind: "class", name: _classThis.name }, null, _classExtraInitializers); ++ C = _classThis = _classDescriptor.value; ++ __runInitializers(_classThis, _classExtraInitializers); ++ })(); ++ return C = _classThis; ++ }(); ++ exports_1("default", _default = C); ++ void C; ++ } ++ catch (e_1) { ++ env_1.error = e_1; ++ env_1.hasError = true; ++ } ++ finally { ++ __disposeResources(env_1); ++ } ++ } ++ }; ++}); +diff --git a/tests/baselines/reference/usingDeclarationsWithESClassDecorators.3(module=system,target=esnext).js b/tests/baselines/reference/usingDeclarationsWithESClassDecorators.3(module=system,target=esnext).js +new file mode 100644 +index 000000000..d15eef891 +--- /dev/null ++++ b/tests/baselines/reference/usingDeclarationsWithESClassDecorators.3(module=system,target=esnext).js +@@ -0,0 +1,33 @@ ++//// [tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsWithESClassDecorators.3.ts] //// ++ ++//// [usingDeclarationsWithESClassDecorators.3.ts] ++export {}; ++ ++declare var dec: any; ++ ++using before = null; ++ ++@dec ++export default class C { ++} ++ ++void C; ++ ++//// [usingDeclarationsWithESClassDecorators.3.js] ++System.register([], function (exports_1, context_1) { ++ "use strict"; ++ var before, C; ++ var __moduleName = context_1 && context_1.id; ++ return { ++ setters: [], ++ execute: function () { ++ using before_1 = before = null; ++ C = ++ @dec ++ class C { ++ }; ++ exports_1("default", C); ++ void C; ++ } ++ }; ++}); +diff --git a/tests/baselines/reference/usingDeclarationsWithESClassDecorators.4(module=commonjs,target=es2015).js b/tests/baselines/reference/usingDeclarationsWithESClassDecorators.4(module=commonjs,target=es2015).js +new file mode 100644 +index 000000000..58f36d54b +--- /dev/null ++++ b/tests/baselines/reference/usingDeclarationsWithESClassDecorators.4(module=commonjs,target=es2015).js +@@ -0,0 +1,45 @@ ++//// [tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsWithESClassDecorators.4.ts] //// ++ ++//// [usingDeclarationsWithESClassDecorators.4.ts] ++export {}; ++ ++declare var dec: any; ++ ++using before = null; ++ ++@dec ++export default class { ++} ++ ++ ++//// [usingDeclarationsWithESClassDecorators.4.js] ++"use strict"; ++Object.defineProperty(exports, "__esModule", { value: true }); ++exports.default = void 0; ++var before, _default; ++const env_1 = { stack: [], error: void 0, hasError: false }; ++try { ++ before = __addDisposableResource(env_1, null, false); ++ exports.default = _default = (() => { ++ let _classDecorators = [dec]; ++ let _classDescriptor; ++ let _classExtraInitializers = []; ++ let _classThis; ++ var default_1 = _classThis = class { ++ }; ++ __setFunctionName(_classThis, "default"); ++ (() => { ++ __esDecorate(null, _classDescriptor = { value: _classThis }, _classDecorators, { kind: "class", name: _classThis.name }, null, _classExtraInitializers); ++ default_1 = _classThis = _classDescriptor.value; ++ __runInitializers(_classThis, _classExtraInitializers); ++ })(); ++ return default_1 = _classThis; ++ })(); ++} ++catch (e_1) { ++ env_1.error = e_1; ++ env_1.hasError = true; ++} ++finally { ++ __disposeResources(env_1); ++} +diff --git a/tests/baselines/reference/usingDeclarationsWithESClassDecorators.4(module=commonjs,target=es5).js b/tests/baselines/reference/usingDeclarationsWithESClassDecorators.4(module=commonjs,target=es5).js +new file mode 100644 +index 000000000..c7937553b +--- /dev/null ++++ b/tests/baselines/reference/usingDeclarationsWithESClassDecorators.4(module=commonjs,target=es5).js +@@ -0,0 +1,49 @@ ++//// [tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsWithESClassDecorators.4.ts] //// ++ ++//// [usingDeclarationsWithESClassDecorators.4.ts] ++export {}; ++ ++declare var dec: any; ++ ++using before = null; ++ ++@dec ++export default class { ++} ++ ++ ++//// [usingDeclarationsWithESClassDecorators.4.js] ++"use strict"; ++Object.defineProperty(exports, "__esModule", { value: true }); ++exports.default = void 0; ++var before, default_1, _default; ++var env_1 = { stack: [], error: void 0, hasError: false }; ++try { ++ before = __addDisposableResource(env_1, null, false); ++ default_1 = function () { ++ var _classDecorators = [dec]; ++ var _classDescriptor; ++ var _classExtraInitializers = []; ++ var _classThis; ++ var default_1 = _classThis = /** @class */ (function () { ++ function default_1() { ++ } ++ return default_1; ++ }()); ++ __setFunctionName(_classThis, "default"); ++ (function () { ++ __esDecorate(null, _classDescriptor = { value: _classThis }, _classDecorators, { kind: "class", name: _classThis.name }, null, _classExtraInitializers); ++ default_1 = _classThis = _classDescriptor.value; ++ __runInitializers(_classThis, _classExtraInitializers); ++ })(); ++ return default_1 = _classThis; ++ }(); ++ exports.default = _default = default_1; ++} ++catch (e_1) { ++ env_1.error = e_1; ++ env_1.hasError = true; ++} ++finally { ++ __disposeResources(env_1); ++} +diff --git a/tests/baselines/reference/usingDeclarationsWithESClassDecorators.4(module=commonjs,target=esnext).js b/tests/baselines/reference/usingDeclarationsWithESClassDecorators.4(module=commonjs,target=esnext).js +new file mode 100644 +index 000000000..a30e9b1a1 +--- /dev/null ++++ b/tests/baselines/reference/usingDeclarationsWithESClassDecorators.4(module=commonjs,target=esnext).js +@@ -0,0 +1,22 @@ ++//// [tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsWithESClassDecorators.4.ts] //// ++ ++//// [usingDeclarationsWithESClassDecorators.4.ts] ++export {}; ++ ++declare var dec: any; ++ ++using before = null; ++ ++@dec ++export default class { ++} ++ ++ ++//// [usingDeclarationsWithESClassDecorators.4.js] ++"use strict"; ++Object.defineProperty(exports, "__esModule", { value: true }); ++using before = null; ++@dec ++class default_1 { ++} ++exports.default = default_1; +diff --git a/tests/baselines/reference/usingDeclarationsWithESClassDecorators.4(module=esnext,target=es2015).js b/tests/baselines/reference/usingDeclarationsWithESClassDecorators.4(module=esnext,target=es2015).js +new file mode 100644 +index 000000000..aa3057d8a +--- /dev/null ++++ b/tests/baselines/reference/usingDeclarationsWithESClassDecorators.4(module=esnext,target=es2015).js +@@ -0,0 +1,43 @@ ++//// [tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsWithESClassDecorators.4.ts] //// ++ ++//// [usingDeclarationsWithESClassDecorators.4.ts] ++export {}; ++ ++declare var dec: any; ++ ++using before = null; ++ ++@dec ++export default class { ++} ++ ++ ++//// [usingDeclarationsWithESClassDecorators.4.js] ++export { _default as default }; ++var before, _default; ++const env_1 = { stack: [], error: void 0, hasError: false }; ++try { ++ before = __addDisposableResource(env_1, null, false); ++ _default = (() => { ++ let _classDecorators = [dec]; ++ let _classDescriptor; ++ let _classExtraInitializers = []; ++ let _classThis; ++ var default_1 = _classThis = class { ++ }; ++ __setFunctionName(_classThis, "default"); ++ (() => { ++ __esDecorate(null, _classDescriptor = { value: _classThis }, _classDecorators, { kind: "class", name: _classThis.name }, null, _classExtraInitializers); ++ default_1 = _classThis = _classDescriptor.value; ++ __runInitializers(_classThis, _classExtraInitializers); ++ })(); ++ return default_1 = _classThis; ++ })(); ++} ++catch (e_1) { ++ env_1.error = e_1; ++ env_1.hasError = true; ++} ++finally { ++ __disposeResources(env_1); ++} +diff --git a/tests/baselines/reference/usingDeclarationsWithESClassDecorators.4(module=esnext,target=es5).js b/tests/baselines/reference/usingDeclarationsWithESClassDecorators.4(module=esnext,target=es5).js +new file mode 100644 +index 000000000..27216ba80 +--- /dev/null ++++ b/tests/baselines/reference/usingDeclarationsWithESClassDecorators.4(module=esnext,target=es5).js +@@ -0,0 +1,47 @@ ++//// [tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsWithESClassDecorators.4.ts] //// ++ ++//// [usingDeclarationsWithESClassDecorators.4.ts] ++export {}; ++ ++declare var dec: any; ++ ++using before = null; ++ ++@dec ++export default class { ++} ++ ++ ++//// [usingDeclarationsWithESClassDecorators.4.js] ++export { _default as default }; ++var before, default_1, _default; ++var env_1 = { stack: [], error: void 0, hasError: false }; ++try { ++ before = __addDisposableResource(env_1, null, false); ++ default_1 = function () { ++ var _classDecorators = [dec]; ++ var _classDescriptor; ++ var _classExtraInitializers = []; ++ var _classThis; ++ var default_1 = _classThis = /** @class */ (function () { ++ function default_1() { ++ } ++ return default_1; ++ }()); ++ __setFunctionName(_classThis, "default"); ++ (function () { ++ __esDecorate(null, _classDescriptor = { value: _classThis }, _classDecorators, { kind: "class", name: _classThis.name }, null, _classExtraInitializers); ++ default_1 = _classThis = _classDescriptor.value; ++ __runInitializers(_classThis, _classExtraInitializers); ++ })(); ++ return default_1 = _classThis; ++ }(); ++ _default = default_1; ++} ++catch (e_1) { ++ env_1.error = e_1; ++ env_1.hasError = true; ++} ++finally { ++ __disposeResources(env_1); ++} +diff --git a/tests/baselines/reference/usingDeclarationsWithESClassDecorators.4(module=esnext,target=esnext).js b/tests/baselines/reference/usingDeclarationsWithESClassDecorators.4(module=esnext,target=esnext).js +new file mode 100644 +index 000000000..274e10833 +--- /dev/null ++++ b/tests/baselines/reference/usingDeclarationsWithESClassDecorators.4(module=esnext,target=esnext).js +@@ -0,0 +1,19 @@ ++//// [tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsWithESClassDecorators.4.ts] //// ++ ++//// [usingDeclarationsWithESClassDecorators.4.ts] ++export {}; ++ ++declare var dec: any; ++ ++using before = null; ++ ++@dec ++export default class { ++} ++ ++ ++//// [usingDeclarationsWithESClassDecorators.4.js] ++using before = null; ++@dec ++export default class { ++} +diff --git a/tests/baselines/reference/usingDeclarationsWithESClassDecorators.4(module=system,target=es2015).js b/tests/baselines/reference/usingDeclarationsWithESClassDecorators.4(module=system,target=es2015).js +new file mode 100644 +index 000000000..10c0557cd +--- /dev/null ++++ b/tests/baselines/reference/usingDeclarationsWithESClassDecorators.4(module=system,target=es2015).js +@@ -0,0 +1,51 @@ ++//// [tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsWithESClassDecorators.4.ts] //// ++ ++//// [usingDeclarationsWithESClassDecorators.4.ts] ++export {}; ++ ++declare var dec: any; ++ ++using before = null; ++ ++@dec ++export default class { ++} ++ ++ ++//// [usingDeclarationsWithESClassDecorators.4.js] ++System.register([], function (exports_1, context_1) { ++ "use strict"; ++ var before, _default, env_1; ++ var __moduleName = context_1 && context_1.id; ++ return { ++ setters: [], ++ execute: function () { ++ env_1 = { stack: [], error: void 0, hasError: false }; ++ try { ++ before = __addDisposableResource(env_1, null, false); ++ exports_1("default", _default = (() => { ++ let _classDecorators = [dec]; ++ let _classDescriptor; ++ let _classExtraInitializers = []; ++ let _classThis; ++ var default_1 = _classThis = class { ++ }; ++ __setFunctionName(_classThis, "default"); ++ (() => { ++ __esDecorate(null, _classDescriptor = { value: _classThis }, _classDecorators, { kind: "class", name: _classThis.name }, null, _classExtraInitializers); ++ default_1 = _classThis = _classDescriptor.value; ++ __runInitializers(_classThis, _classExtraInitializers); ++ })(); ++ return default_1 = _classThis; ++ })()); ++ } ++ catch (e_1) { ++ env_1.error = e_1; ++ env_1.hasError = true; ++ } ++ finally { ++ __disposeResources(env_1); ++ } ++ } ++ }; ++}); +diff --git a/tests/baselines/reference/usingDeclarationsWithESClassDecorators.4(module=system,target=es5).js b/tests/baselines/reference/usingDeclarationsWithESClassDecorators.4(module=system,target=es5).js +new file mode 100644 +index 000000000..6bbc3b09e +--- /dev/null ++++ b/tests/baselines/reference/usingDeclarationsWithESClassDecorators.4(module=system,target=es5).js +@@ -0,0 +1,55 @@ ++//// [tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsWithESClassDecorators.4.ts] //// ++ ++//// [usingDeclarationsWithESClassDecorators.4.ts] ++export {}; ++ ++declare var dec: any; ++ ++using before = null; ++ ++@dec ++export default class { ++} ++ ++ ++//// [usingDeclarationsWithESClassDecorators.4.js] ++System.register([], function (exports_1, context_1) { ++ "use strict"; ++ var before, default_1, _default, env_1; ++ var __moduleName = context_1 && context_1.id; ++ return { ++ setters: [], ++ execute: function () { ++ env_1 = { stack: [], error: void 0, hasError: false }; ++ try { ++ before = __addDisposableResource(env_1, null, false); ++ default_1 = function () { ++ var _classDecorators = [dec]; ++ var _classDescriptor; ++ var _classExtraInitializers = []; ++ var _classThis; ++ var default_1 = _classThis = /** @class */ (function () { ++ function default_1() { ++ } ++ return default_1; ++ }()); ++ __setFunctionName(_classThis, "default"); ++ (function () { ++ __esDecorate(null, _classDescriptor = { value: _classThis }, _classDecorators, { kind: "class", name: _classThis.name }, null, _classExtraInitializers); ++ default_1 = _classThis = _classDescriptor.value; ++ __runInitializers(_classThis, _classExtraInitializers); ++ })(); ++ return default_1 = _classThis; ++ }(); ++ exports_1("default", _default = default_1); ++ } ++ catch (e_1) { ++ env_1.error = e_1; ++ env_1.hasError = true; ++ } ++ finally { ++ __disposeResources(env_1); ++ } ++ } ++ }; ++}); +diff --git a/tests/baselines/reference/usingDeclarationsWithESClassDecorators.4(module=system,target=esnext).js b/tests/baselines/reference/usingDeclarationsWithESClassDecorators.4(module=system,target=esnext).js +new file mode 100644 +index 000000000..e1a2db0a6 +--- /dev/null ++++ b/tests/baselines/reference/usingDeclarationsWithESClassDecorators.4(module=system,target=esnext).js +@@ -0,0 +1,31 @@ ++//// [tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsWithESClassDecorators.4.ts] //// ++ ++//// [usingDeclarationsWithESClassDecorators.4.ts] ++export {}; ++ ++declare var dec: any; ++ ++using before = null; ++ ++@dec ++export default class { ++} ++ ++ ++//// [usingDeclarationsWithESClassDecorators.4.js] ++System.register([], function (exports_1, context_1) { ++ "use strict"; ++ var before, default_1; ++ var __moduleName = context_1 && context_1.id; ++ return { ++ setters: [], ++ execute: function () { ++ using before_1 = before = null; ++ default_1 = ++ @dec ++ class { ++ }; ++ exports_1("default", default_1); ++ } ++ }; ++}); +diff --git a/tests/baselines/reference/usingDeclarationsWithESClassDecorators.5(module=commonjs,target=es2015).js b/tests/baselines/reference/usingDeclarationsWithESClassDecorators.5(module=commonjs,target=es2015).js +new file mode 100644 +index 000000000..69ad55ba7 +--- /dev/null ++++ b/tests/baselines/reference/usingDeclarationsWithESClassDecorators.5(module=commonjs,target=es2015).js +@@ -0,0 +1,46 @@ ++//// [tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsWithESClassDecorators.5.ts] //// ++ ++//// [usingDeclarationsWithESClassDecorators.5.ts] ++export {}; ++ ++declare var dec: any; ++ ++using before = null; ++ ++@dec ++class C { ++} ++ ++export { C }; ++ ++//// [usingDeclarationsWithESClassDecorators.5.js] ++"use strict"; ++Object.defineProperty(exports, "__esModule", { value: true }); ++exports.C = void 0; ++var before, C; ++const env_1 = { stack: [], error: void 0, hasError: false }; ++try { ++ before = __addDisposableResource(env_1, null, false); ++ exports.C = C = (() => { ++ let _classDecorators = [dec]; ++ let _classDescriptor; ++ let _classExtraInitializers = []; ++ let _classThis; ++ var C = _classThis = class { ++ }; ++ __setFunctionName(_classThis, "C"); ++ (() => { ++ __esDecorate(null, _classDescriptor = { value: _classThis }, _classDecorators, { kind: "class", name: _classThis.name }, null, _classExtraInitializers); ++ C = _classThis = _classDescriptor.value; ++ __runInitializers(_classThis, _classExtraInitializers); ++ })(); ++ return C = _classThis; ++ })(); ++} ++catch (e_1) { ++ env_1.error = e_1; ++ env_1.hasError = true; ++} ++finally { ++ __disposeResources(env_1); ++} +diff --git a/tests/baselines/reference/usingDeclarationsWithESClassDecorators.5(module=commonjs,target=es5).js b/tests/baselines/reference/usingDeclarationsWithESClassDecorators.5(module=commonjs,target=es5).js +new file mode 100644 +index 000000000..426fa87fc +--- /dev/null ++++ b/tests/baselines/reference/usingDeclarationsWithESClassDecorators.5(module=commonjs,target=es5).js +@@ -0,0 +1,49 @@ ++//// [tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsWithESClassDecorators.5.ts] //// ++ ++//// [usingDeclarationsWithESClassDecorators.5.ts] ++export {}; ++ ++declare var dec: any; ++ ++using before = null; ++ ++@dec ++class C { ++} ++ ++export { C }; ++ ++//// [usingDeclarationsWithESClassDecorators.5.js] ++"use strict"; ++Object.defineProperty(exports, "__esModule", { value: true }); ++exports.C = void 0; ++var before, C; ++var env_1 = { stack: [], error: void 0, hasError: false }; ++try { ++ before = __addDisposableResource(env_1, null, false); ++ exports.C = C = function () { ++ var _classDecorators = [dec]; ++ var _classDescriptor; ++ var _classExtraInitializers = []; ++ var _classThis; ++ var C = _classThis = /** @class */ (function () { ++ function C_1() { ++ } ++ return C_1; ++ }()); ++ __setFunctionName(_classThis, "C"); ++ (function () { ++ __esDecorate(null, _classDescriptor = { value: _classThis }, _classDecorators, { kind: "class", name: _classThis.name }, null, _classExtraInitializers); ++ C = _classThis = _classDescriptor.value; ++ __runInitializers(_classThis, _classExtraInitializers); ++ })(); ++ return C = _classThis; ++ }(); ++} ++catch (e_1) { ++ env_1.error = e_1; ++ env_1.hasError = true; ++} ++finally { ++ __disposeResources(env_1); ++} +diff --git a/tests/baselines/reference/usingDeclarationsWithESClassDecorators.5(module=commonjs,target=esnext).js b/tests/baselines/reference/usingDeclarationsWithESClassDecorators.5(module=commonjs,target=esnext).js +new file mode 100644 +index 000000000..0f139aa39 +--- /dev/null ++++ b/tests/baselines/reference/usingDeclarationsWithESClassDecorators.5(module=commonjs,target=esnext).js +@@ -0,0 +1,24 @@ ++//// [tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsWithESClassDecorators.5.ts] //// ++ ++//// [usingDeclarationsWithESClassDecorators.5.ts] ++export {}; ++ ++declare var dec: any; ++ ++using before = null; ++ ++@dec ++class C { ++} ++ ++export { C }; ++ ++//// [usingDeclarationsWithESClassDecorators.5.js] ++"use strict"; ++Object.defineProperty(exports, "__esModule", { value: true }); ++exports.C = void 0; ++using before = null; ++@dec ++class C { ++} ++exports.C = C; +diff --git a/tests/baselines/reference/usingDeclarationsWithESClassDecorators.5(module=esnext,target=es2015).js b/tests/baselines/reference/usingDeclarationsWithESClassDecorators.5(module=esnext,target=es2015).js +new file mode 100644 +index 000000000..18733b5de +--- /dev/null ++++ b/tests/baselines/reference/usingDeclarationsWithESClassDecorators.5(module=esnext,target=es2015).js +@@ -0,0 +1,44 @@ ++//// [tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsWithESClassDecorators.5.ts] //// ++ ++//// [usingDeclarationsWithESClassDecorators.5.ts] ++export {}; ++ ++declare var dec: any; ++ ++using before = null; ++ ++@dec ++class C { ++} ++ ++export { C }; ++ ++//// [usingDeclarationsWithESClassDecorators.5.js] ++export { C }; ++var before, C; ++const env_1 = { stack: [], error: void 0, hasError: false }; ++try { ++ before = __addDisposableResource(env_1, null, false); ++ C = (() => { ++ let _classDecorators = [dec]; ++ let _classDescriptor; ++ let _classExtraInitializers = []; ++ let _classThis; ++ var C = _classThis = class { ++ }; ++ __setFunctionName(_classThis, "C"); ++ (() => { ++ __esDecorate(null, _classDescriptor = { value: _classThis }, _classDecorators, { kind: "class", name: _classThis.name }, null, _classExtraInitializers); ++ C = _classThis = _classDescriptor.value; ++ __runInitializers(_classThis, _classExtraInitializers); ++ })(); ++ return C = _classThis; ++ })(); ++} ++catch (e_1) { ++ env_1.error = e_1; ++ env_1.hasError = true; ++} ++finally { ++ __disposeResources(env_1); ++} +diff --git a/tests/baselines/reference/usingDeclarationsWithESClassDecorators.5(module=esnext,target=es5).js b/tests/baselines/reference/usingDeclarationsWithESClassDecorators.5(module=esnext,target=es5).js +new file mode 100644 +index 000000000..67fd4a4ed +--- /dev/null ++++ b/tests/baselines/reference/usingDeclarationsWithESClassDecorators.5(module=esnext,target=es5).js +@@ -0,0 +1,47 @@ ++//// [tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsWithESClassDecorators.5.ts] //// ++ ++//// [usingDeclarationsWithESClassDecorators.5.ts] ++export {}; ++ ++declare var dec: any; ++ ++using before = null; ++ ++@dec ++class C { ++} ++ ++export { C }; ++ ++//// [usingDeclarationsWithESClassDecorators.5.js] ++export { C }; ++var before, C; ++var env_1 = { stack: [], error: void 0, hasError: false }; ++try { ++ before = __addDisposableResource(env_1, null, false); ++ C = function () { ++ var _classDecorators = [dec]; ++ var _classDescriptor; ++ var _classExtraInitializers = []; ++ var _classThis; ++ var C = _classThis = /** @class */ (function () { ++ function C_1() { ++ } ++ return C_1; ++ }()); ++ __setFunctionName(_classThis, "C"); ++ (function () { ++ __esDecorate(null, _classDescriptor = { value: _classThis }, _classDecorators, { kind: "class", name: _classThis.name }, null, _classExtraInitializers); ++ C = _classThis = _classDescriptor.value; ++ __runInitializers(_classThis, _classExtraInitializers); ++ })(); ++ return C = _classThis; ++ }(); ++} ++catch (e_1) { ++ env_1.error = e_1; ++ env_1.hasError = true; ++} ++finally { ++ __disposeResources(env_1); ++} +diff --git a/tests/baselines/reference/usingDeclarationsWithESClassDecorators.5(module=esnext,target=esnext).js b/tests/baselines/reference/usingDeclarationsWithESClassDecorators.5(module=esnext,target=esnext).js +new file mode 100644 +index 000000000..10a24f2f7 +--- /dev/null ++++ b/tests/baselines/reference/usingDeclarationsWithESClassDecorators.5(module=esnext,target=esnext).js +@@ -0,0 +1,21 @@ ++//// [tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsWithESClassDecorators.5.ts] //// ++ ++//// [usingDeclarationsWithESClassDecorators.5.ts] ++export {}; ++ ++declare var dec: any; ++ ++using before = null; ++ ++@dec ++class C { ++} ++ ++export { C }; ++ ++//// [usingDeclarationsWithESClassDecorators.5.js] ++using before = null; ++@dec ++class C { ++} ++export { C }; +diff --git a/tests/baselines/reference/usingDeclarationsWithESClassDecorators.5(module=system,target=es2015).js b/tests/baselines/reference/usingDeclarationsWithESClassDecorators.5(module=system,target=es2015).js +new file mode 100644 +index 000000000..bf9770ac3 +--- /dev/null ++++ b/tests/baselines/reference/usingDeclarationsWithESClassDecorators.5(module=system,target=es2015).js +@@ -0,0 +1,52 @@ ++//// [tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsWithESClassDecorators.5.ts] //// ++ ++//// [usingDeclarationsWithESClassDecorators.5.ts] ++export {}; ++ ++declare var dec: any; ++ ++using before = null; ++ ++@dec ++class C { ++} ++ ++export { C }; ++ ++//// [usingDeclarationsWithESClassDecorators.5.js] ++System.register([], function (exports_1, context_1) { ++ "use strict"; ++ var before, C, env_1; ++ var __moduleName = context_1 && context_1.id; ++ return { ++ setters: [], ++ execute: function () { ++ env_1 = { stack: [], error: void 0, hasError: false }; ++ try { ++ before = __addDisposableResource(env_1, null, false); ++ exports_1("C", C = (() => { ++ let _classDecorators = [dec]; ++ let _classDescriptor; ++ let _classExtraInitializers = []; ++ let _classThis; ++ var C = _classThis = class { ++ }; ++ __setFunctionName(_classThis, "C"); ++ (() => { ++ __esDecorate(null, _classDescriptor = { value: _classThis }, _classDecorators, { kind: "class", name: _classThis.name }, null, _classExtraInitializers); ++ C = _classThis = _classDescriptor.value; ++ __runInitializers(_classThis, _classExtraInitializers); ++ })(); ++ return C = _classThis; ++ })()); ++ } ++ catch (e_1) { ++ env_1.error = e_1; ++ env_1.hasError = true; ++ } ++ finally { ++ __disposeResources(env_1); ++ } ++ } ++ }; ++}); +diff --git a/tests/baselines/reference/usingDeclarationsWithESClassDecorators.5(module=system,target=es5).js b/tests/baselines/reference/usingDeclarationsWithESClassDecorators.5(module=system,target=es5).js +new file mode 100644 +index 000000000..c90bf63c6 +--- /dev/null ++++ b/tests/baselines/reference/usingDeclarationsWithESClassDecorators.5(module=system,target=es5).js +@@ -0,0 +1,55 @@ ++//// [tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsWithESClassDecorators.5.ts] //// ++ ++//// [usingDeclarationsWithESClassDecorators.5.ts] ++export {}; ++ ++declare var dec: any; ++ ++using before = null; ++ ++@dec ++class C { ++} ++ ++export { C }; ++ ++//// [usingDeclarationsWithESClassDecorators.5.js] ++System.register([], function (exports_1, context_1) { ++ "use strict"; ++ var before, C, env_1; ++ var __moduleName = context_1 && context_1.id; ++ return { ++ setters: [], ++ execute: function () { ++ env_1 = { stack: [], error: void 0, hasError: false }; ++ try { ++ before = __addDisposableResource(env_1, null, false); ++ exports_1("C", C = function () { ++ var _classDecorators = [dec]; ++ var _classDescriptor; ++ var _classExtraInitializers = []; ++ var _classThis; ++ var C = _classThis = /** @class */ (function () { ++ function C_1() { ++ } ++ return C_1; ++ }()); ++ __setFunctionName(_classThis, "C"); ++ (function () { ++ __esDecorate(null, _classDescriptor = { value: _classThis }, _classDecorators, { kind: "class", name: _classThis.name }, null, _classExtraInitializers); ++ C = _classThis = _classDescriptor.value; ++ __runInitializers(_classThis, _classExtraInitializers); ++ })(); ++ return C = _classThis; ++ }()); ++ } ++ catch (e_1) { ++ env_1.error = e_1; ++ env_1.hasError = true; ++ } ++ finally { ++ __disposeResources(env_1); ++ } ++ } ++ }; ++}); +diff --git a/tests/baselines/reference/usingDeclarationsWithESClassDecorators.5(module=system,target=esnext).js b/tests/baselines/reference/usingDeclarationsWithESClassDecorators.5(module=system,target=esnext).js +new file mode 100644 +index 000000000..bd6e0ecf0 +--- /dev/null ++++ b/tests/baselines/reference/usingDeclarationsWithESClassDecorators.5(module=system,target=esnext).js +@@ -0,0 +1,32 @@ ++//// [tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsWithESClassDecorators.5.ts] //// ++ ++//// [usingDeclarationsWithESClassDecorators.5.ts] ++export {}; ++ ++declare var dec: any; ++ ++using before = null; ++ ++@dec ++class C { ++} ++ ++export { C }; ++ ++//// [usingDeclarationsWithESClassDecorators.5.js] ++System.register([], function (exports_1, context_1) { ++ "use strict"; ++ var before, C; ++ var __moduleName = context_1 && context_1.id; ++ return { ++ setters: [], ++ execute: function () { ++ using before_1 = before = null; ++ C = ++ @dec ++ class C { ++ }; ++ exports_1("C", C); ++ } ++ }; ++}); +diff --git a/tests/baselines/reference/usingDeclarationsWithESClassDecorators.6(module=commonjs,target=es2015).js b/tests/baselines/reference/usingDeclarationsWithESClassDecorators.6(module=commonjs,target=es2015).js +new file mode 100644 +index 000000000..76192f102 +--- /dev/null ++++ b/tests/baselines/reference/usingDeclarationsWithESClassDecorators.6(module=commonjs,target=es2015).js +@@ -0,0 +1,46 @@ ++//// [tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsWithESClassDecorators.6.ts] //// ++ ++//// [usingDeclarationsWithESClassDecorators.6.ts] ++export {}; ++ ++declare var dec: any; ++ ++using before = null; ++ ++@dec ++class C { ++} ++ ++export { C as D }; ++ ++//// [usingDeclarationsWithESClassDecorators.6.js] ++"use strict"; ++Object.defineProperty(exports, "__esModule", { value: true }); ++exports.D = void 0; ++var before, C; ++const env_1 = { stack: [], error: void 0, hasError: false }; ++try { ++ before = __addDisposableResource(env_1, null, false); ++ exports.D = C = (() => { ++ let _classDecorators = [dec]; ++ let _classDescriptor; ++ let _classExtraInitializers = []; ++ let _classThis; ++ var C = _classThis = class { ++ }; ++ __setFunctionName(_classThis, "C"); ++ (() => { ++ __esDecorate(null, _classDescriptor = { value: _classThis }, _classDecorators, { kind: "class", name: _classThis.name }, null, _classExtraInitializers); ++ C = _classThis = _classDescriptor.value; ++ __runInitializers(_classThis, _classExtraInitializers); ++ })(); ++ return C = _classThis; ++ })(); ++} ++catch (e_1) { ++ env_1.error = e_1; ++ env_1.hasError = true; ++} ++finally { ++ __disposeResources(env_1); ++} +diff --git a/tests/baselines/reference/usingDeclarationsWithESClassDecorators.6(module=commonjs,target=es5).js b/tests/baselines/reference/usingDeclarationsWithESClassDecorators.6(module=commonjs,target=es5).js +new file mode 100644 +index 000000000..f2cf7297b +--- /dev/null ++++ b/tests/baselines/reference/usingDeclarationsWithESClassDecorators.6(module=commonjs,target=es5).js +@@ -0,0 +1,49 @@ ++//// [tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsWithESClassDecorators.6.ts] //// ++ ++//// [usingDeclarationsWithESClassDecorators.6.ts] ++export {}; ++ ++declare var dec: any; ++ ++using before = null; ++ ++@dec ++class C { ++} ++ ++export { C as D }; ++ ++//// [usingDeclarationsWithESClassDecorators.6.js] ++"use strict"; ++Object.defineProperty(exports, "__esModule", { value: true }); ++exports.D = void 0; ++var before, C; ++var env_1 = { stack: [], error: void 0, hasError: false }; ++try { ++ before = __addDisposableResource(env_1, null, false); ++ exports.D = C = function () { ++ var _classDecorators = [dec]; ++ var _classDescriptor; ++ var _classExtraInitializers = []; ++ var _classThis; ++ var C = _classThis = /** @class */ (function () { ++ function C_1() { ++ } ++ return C_1; ++ }()); ++ __setFunctionName(_classThis, "C"); ++ (function () { ++ __esDecorate(null, _classDescriptor = { value: _classThis }, _classDecorators, { kind: "class", name: _classThis.name }, null, _classExtraInitializers); ++ C = _classThis = _classDescriptor.value; ++ __runInitializers(_classThis, _classExtraInitializers); ++ })(); ++ return C = _classThis; ++ }(); ++} ++catch (e_1) { ++ env_1.error = e_1; ++ env_1.hasError = true; ++} ++finally { ++ __disposeResources(env_1); ++} +diff --git a/tests/baselines/reference/usingDeclarationsWithESClassDecorators.6(module=commonjs,target=esnext).js b/tests/baselines/reference/usingDeclarationsWithESClassDecorators.6(module=commonjs,target=esnext).js +new file mode 100644 +index 000000000..71d7f1e7d +--- /dev/null ++++ b/tests/baselines/reference/usingDeclarationsWithESClassDecorators.6(module=commonjs,target=esnext).js +@@ -0,0 +1,24 @@ ++//// [tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsWithESClassDecorators.6.ts] //// ++ ++//// [usingDeclarationsWithESClassDecorators.6.ts] ++export {}; ++ ++declare var dec: any; ++ ++using before = null; ++ ++@dec ++class C { ++} ++ ++export { C as D }; ++ ++//// [usingDeclarationsWithESClassDecorators.6.js] ++"use strict"; ++Object.defineProperty(exports, "__esModule", { value: true }); ++exports.D = void 0; ++using before = null; ++@dec ++class C { ++} ++exports.D = C; +diff --git a/tests/baselines/reference/usingDeclarationsWithESClassDecorators.6(module=esnext,target=es2015).js b/tests/baselines/reference/usingDeclarationsWithESClassDecorators.6(module=esnext,target=es2015).js +new file mode 100644 +index 000000000..45e9ae25a +--- /dev/null ++++ b/tests/baselines/reference/usingDeclarationsWithESClassDecorators.6(module=esnext,target=es2015).js +@@ -0,0 +1,44 @@ ++//// [tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsWithESClassDecorators.6.ts] //// ++ ++//// [usingDeclarationsWithESClassDecorators.6.ts] ++export {}; ++ ++declare var dec: any; ++ ++using before = null; ++ ++@dec ++class C { ++} ++ ++export { C as D }; ++ ++//// [usingDeclarationsWithESClassDecorators.6.js] ++export { C as D }; ++var before, C; ++const env_1 = { stack: [], error: void 0, hasError: false }; ++try { ++ before = __addDisposableResource(env_1, null, false); ++ C = (() => { ++ let _classDecorators = [dec]; ++ let _classDescriptor; ++ let _classExtraInitializers = []; ++ let _classThis; ++ var C = _classThis = class { ++ }; ++ __setFunctionName(_classThis, "C"); ++ (() => { ++ __esDecorate(null, _classDescriptor = { value: _classThis }, _classDecorators, { kind: "class", name: _classThis.name }, null, _classExtraInitializers); ++ C = _classThis = _classDescriptor.value; ++ __runInitializers(_classThis, _classExtraInitializers); ++ })(); ++ return C = _classThis; ++ })(); ++} ++catch (e_1) { ++ env_1.error = e_1; ++ env_1.hasError = true; ++} ++finally { ++ __disposeResources(env_1); ++} +diff --git a/tests/baselines/reference/usingDeclarationsWithESClassDecorators.6(module=esnext,target=es5).js b/tests/baselines/reference/usingDeclarationsWithESClassDecorators.6(module=esnext,target=es5).js +new file mode 100644 +index 000000000..2ec9c11a8 +--- /dev/null ++++ b/tests/baselines/reference/usingDeclarationsWithESClassDecorators.6(module=esnext,target=es5).js +@@ -0,0 +1,47 @@ ++//// [tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsWithESClassDecorators.6.ts] //// ++ ++//// [usingDeclarationsWithESClassDecorators.6.ts] ++export {}; ++ ++declare var dec: any; ++ ++using before = null; ++ ++@dec ++class C { ++} ++ ++export { C as D }; ++ ++//// [usingDeclarationsWithESClassDecorators.6.js] ++export { C as D }; ++var before, C; ++var env_1 = { stack: [], error: void 0, hasError: false }; ++try { ++ before = __addDisposableResource(env_1, null, false); ++ C = function () { ++ var _classDecorators = [dec]; ++ var _classDescriptor; ++ var _classExtraInitializers = []; ++ var _classThis; ++ var C = _classThis = /** @class */ (function () { ++ function C_1() { ++ } ++ return C_1; ++ }()); ++ __setFunctionName(_classThis, "C"); ++ (function () { ++ __esDecorate(null, _classDescriptor = { value: _classThis }, _classDecorators, { kind: "class", name: _classThis.name }, null, _classExtraInitializers); ++ C = _classThis = _classDescriptor.value; ++ __runInitializers(_classThis, _classExtraInitializers); ++ })(); ++ return C = _classThis; ++ }(); ++} ++catch (e_1) { ++ env_1.error = e_1; ++ env_1.hasError = true; ++} ++finally { ++ __disposeResources(env_1); ++} +diff --git a/tests/baselines/reference/usingDeclarationsWithESClassDecorators.6(module=esnext,target=esnext).js b/tests/baselines/reference/usingDeclarationsWithESClassDecorators.6(module=esnext,target=esnext).js +new file mode 100644 +index 000000000..641f53fd9 +--- /dev/null ++++ b/tests/baselines/reference/usingDeclarationsWithESClassDecorators.6(module=esnext,target=esnext).js +@@ -0,0 +1,21 @@ ++//// [tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsWithESClassDecorators.6.ts] //// ++ ++//// [usingDeclarationsWithESClassDecorators.6.ts] ++export {}; ++ ++declare var dec: any; ++ ++using before = null; ++ ++@dec ++class C { ++} ++ ++export { C as D }; ++ ++//// [usingDeclarationsWithESClassDecorators.6.js] ++using before = null; ++@dec ++class C { ++} ++export { C as D }; +diff --git a/tests/baselines/reference/usingDeclarationsWithESClassDecorators.6(module=system,target=es2015).js b/tests/baselines/reference/usingDeclarationsWithESClassDecorators.6(module=system,target=es2015).js +new file mode 100644 +index 000000000..166ea0b80 +--- /dev/null ++++ b/tests/baselines/reference/usingDeclarationsWithESClassDecorators.6(module=system,target=es2015).js +@@ -0,0 +1,52 @@ ++//// [tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsWithESClassDecorators.6.ts] //// ++ ++//// [usingDeclarationsWithESClassDecorators.6.ts] ++export {}; ++ ++declare var dec: any; ++ ++using before = null; ++ ++@dec ++class C { ++} ++ ++export { C as D }; ++ ++//// [usingDeclarationsWithESClassDecorators.6.js] ++System.register([], function (exports_1, context_1) { ++ "use strict"; ++ var before, C, env_1; ++ var __moduleName = context_1 && context_1.id; ++ return { ++ setters: [], ++ execute: function () { ++ env_1 = { stack: [], error: void 0, hasError: false }; ++ try { ++ before = __addDisposableResource(env_1, null, false); ++ exports_1("D", C = (() => { ++ let _classDecorators = [dec]; ++ let _classDescriptor; ++ let _classExtraInitializers = []; ++ let _classThis; ++ var C = _classThis = class { ++ }; ++ __setFunctionName(_classThis, "C"); ++ (() => { ++ __esDecorate(null, _classDescriptor = { value: _classThis }, _classDecorators, { kind: "class", name: _classThis.name }, null, _classExtraInitializers); ++ C = _classThis = _classDescriptor.value; ++ __runInitializers(_classThis, _classExtraInitializers); ++ })(); ++ return C = _classThis; ++ })()); ++ } ++ catch (e_1) { ++ env_1.error = e_1; ++ env_1.hasError = true; ++ } ++ finally { ++ __disposeResources(env_1); ++ } ++ } ++ }; ++}); +diff --git a/tests/baselines/reference/usingDeclarationsWithESClassDecorators.6(module=system,target=es5).js b/tests/baselines/reference/usingDeclarationsWithESClassDecorators.6(module=system,target=es5).js +new file mode 100644 +index 000000000..78f5826eb +--- /dev/null ++++ b/tests/baselines/reference/usingDeclarationsWithESClassDecorators.6(module=system,target=es5).js +@@ -0,0 +1,55 @@ ++//// [tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsWithESClassDecorators.6.ts] //// ++ ++//// [usingDeclarationsWithESClassDecorators.6.ts] ++export {}; ++ ++declare var dec: any; ++ ++using before = null; ++ ++@dec ++class C { ++} ++ ++export { C as D }; ++ ++//// [usingDeclarationsWithESClassDecorators.6.js] ++System.register([], function (exports_1, context_1) { ++ "use strict"; ++ var before, C, env_1; ++ var __moduleName = context_1 && context_1.id; ++ return { ++ setters: [], ++ execute: function () { ++ env_1 = { stack: [], error: void 0, hasError: false }; ++ try { ++ before = __addDisposableResource(env_1, null, false); ++ exports_1("D", C = function () { ++ var _classDecorators = [dec]; ++ var _classDescriptor; ++ var _classExtraInitializers = []; ++ var _classThis; ++ var C = _classThis = /** @class */ (function () { ++ function C_1() { ++ } ++ return C_1; ++ }()); ++ __setFunctionName(_classThis, "C"); ++ (function () { ++ __esDecorate(null, _classDescriptor = { value: _classThis }, _classDecorators, { kind: "class", name: _classThis.name }, null, _classExtraInitializers); ++ C = _classThis = _classDescriptor.value; ++ __runInitializers(_classThis, _classExtraInitializers); ++ })(); ++ return C = _classThis; ++ }()); ++ } ++ catch (e_1) { ++ env_1.error = e_1; ++ env_1.hasError = true; ++ } ++ finally { ++ __disposeResources(env_1); ++ } ++ } ++ }; ++}); +diff --git a/tests/baselines/reference/usingDeclarationsWithESClassDecorators.6(module=system,target=esnext).js b/tests/baselines/reference/usingDeclarationsWithESClassDecorators.6(module=system,target=esnext).js +new file mode 100644 +index 000000000..b350dd05b +--- /dev/null ++++ b/tests/baselines/reference/usingDeclarationsWithESClassDecorators.6(module=system,target=esnext).js +@@ -0,0 +1,32 @@ ++//// [tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsWithESClassDecorators.6.ts] //// ++ ++//// [usingDeclarationsWithESClassDecorators.6.ts] ++export {}; ++ ++declare var dec: any; ++ ++using before = null; ++ ++@dec ++class C { ++} ++ ++export { C as D }; ++ ++//// [usingDeclarationsWithESClassDecorators.6.js] ++System.register([], function (exports_1, context_1) { ++ "use strict"; ++ var before, C; ++ var __moduleName = context_1 && context_1.id; ++ return { ++ setters: [], ++ execute: function () { ++ using before_1 = before = null; ++ C = ++ @dec ++ class C { ++ }; ++ exports_1("D", C); ++ } ++ }; ++}); +diff --git a/tests/baselines/reference/usingDeclarationsWithESClassDecorators.7(module=commonjs,target=es2015).js b/tests/baselines/reference/usingDeclarationsWithESClassDecorators.7(module=commonjs,target=es2015).js +new file mode 100644 +index 000000000..3c4b4dda5 +--- /dev/null ++++ b/tests/baselines/reference/usingDeclarationsWithESClassDecorators.7(module=commonjs,target=es2015).js +@@ -0,0 +1,45 @@ ++//// [tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsWithESClassDecorators.7.ts] //// ++ ++//// [usingDeclarationsWithESClassDecorators.7.ts] ++export {}; ++ ++declare var dec: any; ++ ++@dec ++class C { ++} ++ ++using after = null; ++ ++ ++ ++//// [usingDeclarationsWithESClassDecorators.7.js] ++"use strict"; ++Object.defineProperty(exports, "__esModule", { value: true }); ++let C = (() => { ++ let _classDecorators = [dec]; ++ let _classDescriptor; ++ let _classExtraInitializers = []; ++ let _classThis; ++ var C = _classThis = class { ++ }; ++ __setFunctionName(_classThis, "C"); ++ (() => { ++ __esDecorate(null, _classDescriptor = { value: _classThis }, _classDecorators, { kind: "class", name: _classThis.name }, null, _classExtraInitializers); ++ C = _classThis = _classDescriptor.value; ++ __runInitializers(_classThis, _classExtraInitializers); ++ })(); ++ return C = _classThis; ++})(); ++var after; ++const env_1 = { stack: [], error: void 0, hasError: false }; ++try { ++ after = __addDisposableResource(env_1, null, false); ++} ++catch (e_1) { ++ env_1.error = e_1; ++ env_1.hasError = true; ++} ++finally { ++ __disposeResources(env_1); ++} +diff --git a/tests/baselines/reference/usingDeclarationsWithESClassDecorators.7(module=commonjs,target=es5).js b/tests/baselines/reference/usingDeclarationsWithESClassDecorators.7(module=commonjs,target=es5).js +new file mode 100644 +index 000000000..08af55964 +--- /dev/null ++++ b/tests/baselines/reference/usingDeclarationsWithESClassDecorators.7(module=commonjs,target=es5).js +@@ -0,0 +1,48 @@ ++//// [tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsWithESClassDecorators.7.ts] //// ++ ++//// [usingDeclarationsWithESClassDecorators.7.ts] ++export {}; ++ ++declare var dec: any; ++ ++@dec ++class C { ++} ++ ++using after = null; ++ ++ ++ ++//// [usingDeclarationsWithESClassDecorators.7.js] ++"use strict"; ++Object.defineProperty(exports, "__esModule", { value: true }); ++var C = function () { ++ var _classDecorators = [dec]; ++ var _classDescriptor; ++ var _classExtraInitializers = []; ++ var _classThis; ++ var C = _classThis = /** @class */ (function () { ++ function C_1() { ++ } ++ return C_1; ++ }()); ++ __setFunctionName(_classThis, "C"); ++ (function () { ++ __esDecorate(null, _classDescriptor = { value: _classThis }, _classDecorators, { kind: "class", name: _classThis.name }, null, _classExtraInitializers); ++ C = _classThis = _classDescriptor.value; ++ __runInitializers(_classThis, _classExtraInitializers); ++ })(); ++ return C = _classThis; ++}(); ++var after; ++var env_1 = { stack: [], error: void 0, hasError: false }; ++try { ++ after = __addDisposableResource(env_1, null, false); ++} ++catch (e_1) { ++ env_1.error = e_1; ++ env_1.hasError = true; ++} ++finally { ++ __disposeResources(env_1); ++} +diff --git a/tests/baselines/reference/usingDeclarationsWithESClassDecorators.7(module=commonjs,target=esnext).js b/tests/baselines/reference/usingDeclarationsWithESClassDecorators.7(module=commonjs,target=esnext).js +new file mode 100644 +index 000000000..007c1012f +--- /dev/null ++++ b/tests/baselines/reference/usingDeclarationsWithESClassDecorators.7(module=commonjs,target=esnext).js +@@ -0,0 +1,22 @@ ++//// [tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsWithESClassDecorators.7.ts] //// ++ ++//// [usingDeclarationsWithESClassDecorators.7.ts] ++export {}; ++ ++declare var dec: any; ++ ++@dec ++class C { ++} ++ ++using after = null; ++ ++ ++ ++//// [usingDeclarationsWithESClassDecorators.7.js] ++"use strict"; ++Object.defineProperty(exports, "__esModule", { value: true }); ++@dec ++class C { ++} ++using after = null; +diff --git a/tests/baselines/reference/usingDeclarationsWithESClassDecorators.7(module=esnext,target=es2015).js b/tests/baselines/reference/usingDeclarationsWithESClassDecorators.7(module=esnext,target=es2015).js +new file mode 100644 +index 000000000..1968891ff +--- /dev/null ++++ b/tests/baselines/reference/usingDeclarationsWithESClassDecorators.7(module=esnext,target=es2015).js +@@ -0,0 +1,44 @@ ++//// [tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsWithESClassDecorators.7.ts] //// ++ ++//// [usingDeclarationsWithESClassDecorators.7.ts] ++export {}; ++ ++declare var dec: any; ++ ++@dec ++class C { ++} ++ ++using after = null; ++ ++ ++ ++//// [usingDeclarationsWithESClassDecorators.7.js] ++let C = (() => { ++ let _classDecorators = [dec]; ++ let _classDescriptor; ++ let _classExtraInitializers = []; ++ let _classThis; ++ var C = _classThis = class { ++ }; ++ __setFunctionName(_classThis, "C"); ++ (() => { ++ __esDecorate(null, _classDescriptor = { value: _classThis }, _classDecorators, { kind: "class", name: _classThis.name }, null, _classExtraInitializers); ++ C = _classThis = _classDescriptor.value; ++ __runInitializers(_classThis, _classExtraInitializers); ++ })(); ++ return C = _classThis; ++})(); ++var after; ++const env_1 = { stack: [], error: void 0, hasError: false }; ++try { ++ after = __addDisposableResource(env_1, null, false); ++} ++catch (e_1) { ++ env_1.error = e_1; ++ env_1.hasError = true; ++} ++finally { ++ __disposeResources(env_1); ++} ++export {}; +diff --git a/tests/baselines/reference/usingDeclarationsWithESClassDecorators.7(module=esnext,target=es5).js b/tests/baselines/reference/usingDeclarationsWithESClassDecorators.7(module=esnext,target=es5).js +new file mode 100644 +index 000000000..41f9acca1 +--- /dev/null ++++ b/tests/baselines/reference/usingDeclarationsWithESClassDecorators.7(module=esnext,target=es5).js +@@ -0,0 +1,47 @@ ++//// [tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsWithESClassDecorators.7.ts] //// ++ ++//// [usingDeclarationsWithESClassDecorators.7.ts] ++export {}; ++ ++declare var dec: any; ++ ++@dec ++class C { ++} ++ ++using after = null; ++ ++ ++ ++//// [usingDeclarationsWithESClassDecorators.7.js] ++var C = function () { ++ var _classDecorators = [dec]; ++ var _classDescriptor; ++ var _classExtraInitializers = []; ++ var _classThis; ++ var C = _classThis = /** @class */ (function () { ++ function C_1() { ++ } ++ return C_1; ++ }()); ++ __setFunctionName(_classThis, "C"); ++ (function () { ++ __esDecorate(null, _classDescriptor = { value: _classThis }, _classDecorators, { kind: "class", name: _classThis.name }, null, _classExtraInitializers); ++ C = _classThis = _classDescriptor.value; ++ __runInitializers(_classThis, _classExtraInitializers); ++ })(); ++ return C = _classThis; ++}(); ++var after; ++var env_1 = { stack: [], error: void 0, hasError: false }; ++try { ++ after = __addDisposableResource(env_1, null, false); ++} ++catch (e_1) { ++ env_1.error = e_1; ++ env_1.hasError = true; ++} ++finally { ++ __disposeResources(env_1); ++} ++export {}; +diff --git a/tests/baselines/reference/usingDeclarationsWithESClassDecorators.7(module=esnext,target=esnext).js b/tests/baselines/reference/usingDeclarationsWithESClassDecorators.7(module=esnext,target=esnext).js +new file mode 100644 +index 000000000..aa6ea6c83 +--- /dev/null ++++ b/tests/baselines/reference/usingDeclarationsWithESClassDecorators.7(module=esnext,target=esnext).js +@@ -0,0 +1,21 @@ ++//// [tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsWithESClassDecorators.7.ts] //// ++ ++//// [usingDeclarationsWithESClassDecorators.7.ts] ++export {}; ++ ++declare var dec: any; ++ ++@dec ++class C { ++} ++ ++using after = null; ++ ++ ++ ++//// [usingDeclarationsWithESClassDecorators.7.js] ++@dec ++class C { ++} ++using after = null; ++export {}; +diff --git a/tests/baselines/reference/usingDeclarationsWithESClassDecorators.7(module=system,target=es2015).js b/tests/baselines/reference/usingDeclarationsWithESClassDecorators.7(module=system,target=es2015).js +new file mode 100644 +index 000000000..d0dc61887 +--- /dev/null ++++ b/tests/baselines/reference/usingDeclarationsWithESClassDecorators.7(module=system,target=es2015).js +@@ -0,0 +1,52 @@ ++//// [tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsWithESClassDecorators.7.ts] //// ++ ++//// [usingDeclarationsWithESClassDecorators.7.ts] ++export {}; ++ ++declare var dec: any; ++ ++@dec ++class C { ++} ++ ++using after = null; ++ ++ ++ ++//// [usingDeclarationsWithESClassDecorators.7.js] ++System.register([], function (exports_1, context_1) { ++ "use strict"; ++ var C, after, env_1; ++ var __moduleName = context_1 && context_1.id; ++ return { ++ setters: [], ++ execute: function () { ++ C = (() => { ++ let _classDecorators = [dec]; ++ let _classDescriptor; ++ let _classExtraInitializers = []; ++ let _classThis; ++ var C = _classThis = class { ++ }; ++ __setFunctionName(_classThis, "C"); ++ (() => { ++ __esDecorate(null, _classDescriptor = { value: _classThis }, _classDecorators, { kind: "class", name: _classThis.name }, null, _classExtraInitializers); ++ C = _classThis = _classDescriptor.value; ++ __runInitializers(_classThis, _classExtraInitializers); ++ })(); ++ return C = _classThis; ++ })(); ++ env_1 = { stack: [], error: void 0, hasError: false }; ++ try { ++ after = __addDisposableResource(env_1, null, false); ++ } ++ catch (e_1) { ++ env_1.error = e_1; ++ env_1.hasError = true; ++ } ++ finally { ++ __disposeResources(env_1); ++ } ++ } ++ }; ++}); +diff --git a/tests/baselines/reference/usingDeclarationsWithESClassDecorators.7(module=system,target=es5).js b/tests/baselines/reference/usingDeclarationsWithESClassDecorators.7(module=system,target=es5).js +new file mode 100644 +index 000000000..34ddb575c +--- /dev/null ++++ b/tests/baselines/reference/usingDeclarationsWithESClassDecorators.7(module=system,target=es5).js +@@ -0,0 +1,55 @@ ++//// [tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsWithESClassDecorators.7.ts] //// ++ ++//// [usingDeclarationsWithESClassDecorators.7.ts] ++export {}; ++ ++declare var dec: any; ++ ++@dec ++class C { ++} ++ ++using after = null; ++ ++ ++ ++//// [usingDeclarationsWithESClassDecorators.7.js] ++System.register([], function (exports_1, context_1) { ++ "use strict"; ++ var C, after, env_1; ++ var __moduleName = context_1 && context_1.id; ++ return { ++ setters: [], ++ execute: function () { ++ C = function () { ++ var _classDecorators = [dec]; ++ var _classDescriptor; ++ var _classExtraInitializers = []; ++ var _classThis; ++ var C = _classThis = /** @class */ (function () { ++ function C_1() { ++ } ++ return C_1; ++ }()); ++ __setFunctionName(_classThis, "C"); ++ (function () { ++ __esDecorate(null, _classDescriptor = { value: _classThis }, _classDecorators, { kind: "class", name: _classThis.name }, null, _classExtraInitializers); ++ C = _classThis = _classDescriptor.value; ++ __runInitializers(_classThis, _classExtraInitializers); ++ })(); ++ return C = _classThis; ++ }(); ++ env_1 = { stack: [], error: void 0, hasError: false }; ++ try { ++ after = __addDisposableResource(env_1, null, false); ++ } ++ catch (e_1) { ++ env_1.error = e_1; ++ env_1.hasError = true; ++ } ++ finally { ++ __disposeResources(env_1); ++ } ++ } ++ }; ++}); +diff --git a/tests/baselines/reference/usingDeclarationsWithESClassDecorators.7(module=system,target=esnext).js b/tests/baselines/reference/usingDeclarationsWithESClassDecorators.7(module=system,target=esnext).js +new file mode 100644 +index 000000000..6ee74dea8 +--- /dev/null ++++ b/tests/baselines/reference/usingDeclarationsWithESClassDecorators.7(module=system,target=esnext).js +@@ -0,0 +1,31 @@ ++//// [tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsWithESClassDecorators.7.ts] //// ++ ++//// [usingDeclarationsWithESClassDecorators.7.ts] ++export {}; ++ ++declare var dec: any; ++ ++@dec ++class C { ++} ++ ++using after = null; ++ ++ ++ ++//// [usingDeclarationsWithESClassDecorators.7.js] ++System.register([], function (exports_1, context_1) { ++ "use strict"; ++ var C, after; ++ var __moduleName = context_1 && context_1.id; ++ return { ++ setters: [], ++ execute: function () { ++ C = ++ @dec ++ class C { ++ }; ++ using after_1 = after = null; ++ } ++ }; ++}); +diff --git a/tests/baselines/reference/usingDeclarationsWithESClassDecorators.8(module=commonjs,target=es2015).js b/tests/baselines/reference/usingDeclarationsWithESClassDecorators.8(module=commonjs,target=es2015).js +new file mode 100644 +index 000000000..6f89e98a5 +--- /dev/null ++++ b/tests/baselines/reference/usingDeclarationsWithESClassDecorators.8(module=commonjs,target=es2015).js +@@ -0,0 +1,46 @@ ++//// [tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsWithESClassDecorators.8.ts] //// ++ ++//// [usingDeclarationsWithESClassDecorators.8.ts] ++export {}; ++ ++declare var dec: any; ++ ++@dec ++export class C { ++} ++ ++using after = null; ++ ++ ++//// [usingDeclarationsWithESClassDecorators.8.js] ++"use strict"; ++Object.defineProperty(exports, "__esModule", { value: true }); ++exports.C = void 0; ++let C = (() => { ++ let _classDecorators = [dec]; ++ let _classDescriptor; ++ let _classExtraInitializers = []; ++ let _classThis; ++ var C = _classThis = class { ++ }; ++ __setFunctionName(_classThis, "C"); ++ (() => { ++ __esDecorate(null, _classDescriptor = { value: _classThis }, _classDecorators, { kind: "class", name: _classThis.name }, null, _classExtraInitializers); ++ C = _classThis = _classDescriptor.value; ++ __runInitializers(_classThis, _classExtraInitializers); ++ })(); ++ return C = _classThis; ++})(); ++exports.C = C; ++var after; ++const env_1 = { stack: [], error: void 0, hasError: false }; ++try { ++ after = __addDisposableResource(env_1, null, false); ++} ++catch (e_1) { ++ env_1.error = e_1; ++ env_1.hasError = true; ++} ++finally { ++ __disposeResources(env_1); ++} +diff --git a/tests/baselines/reference/usingDeclarationsWithESClassDecorators.8(module=commonjs,target=es5).js b/tests/baselines/reference/usingDeclarationsWithESClassDecorators.8(module=commonjs,target=es5).js +new file mode 100644 +index 000000000..7a6ea5d91 +--- /dev/null ++++ b/tests/baselines/reference/usingDeclarationsWithESClassDecorators.8(module=commonjs,target=es5).js +@@ -0,0 +1,49 @@ ++//// [tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsWithESClassDecorators.8.ts] //// ++ ++//// [usingDeclarationsWithESClassDecorators.8.ts] ++export {}; ++ ++declare var dec: any; ++ ++@dec ++export class C { ++} ++ ++using after = null; ++ ++ ++//// [usingDeclarationsWithESClassDecorators.8.js] ++"use strict"; ++Object.defineProperty(exports, "__esModule", { value: true }); ++exports.C = void 0; ++var C = function () { ++ var _classDecorators = [dec]; ++ var _classDescriptor; ++ var _classExtraInitializers = []; ++ var _classThis; ++ var C = _classThis = /** @class */ (function () { ++ function C_1() { ++ } ++ return C_1; ++ }()); ++ __setFunctionName(_classThis, "C"); ++ (function () { ++ __esDecorate(null, _classDescriptor = { value: _classThis }, _classDecorators, { kind: "class", name: _classThis.name }, null, _classExtraInitializers); ++ C = _classThis = _classDescriptor.value; ++ __runInitializers(_classThis, _classExtraInitializers); ++ })(); ++ return C = _classThis; ++}(); ++exports.C = C; ++var after; ++var env_1 = { stack: [], error: void 0, hasError: false }; ++try { ++ after = __addDisposableResource(env_1, null, false); ++} ++catch (e_1) { ++ env_1.error = e_1; ++ env_1.hasError = true; ++} ++finally { ++ __disposeResources(env_1); ++} +diff --git a/tests/baselines/reference/usingDeclarationsWithESClassDecorators.8(module=commonjs,target=esnext).js b/tests/baselines/reference/usingDeclarationsWithESClassDecorators.8(module=commonjs,target=esnext).js +new file mode 100644 +index 000000000..89ecf5ebc +--- /dev/null ++++ b/tests/baselines/reference/usingDeclarationsWithESClassDecorators.8(module=commonjs,target=esnext).js +@@ -0,0 +1,23 @@ ++//// [tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsWithESClassDecorators.8.ts] //// ++ ++//// [usingDeclarationsWithESClassDecorators.8.ts] ++export {}; ++ ++declare var dec: any; ++ ++@dec ++export class C { ++} ++ ++using after = null; ++ ++ ++//// [usingDeclarationsWithESClassDecorators.8.js] ++"use strict"; ++Object.defineProperty(exports, "__esModule", { value: true }); ++exports.C = void 0; ++@dec ++class C { ++} ++exports.C = C; ++using after = null; +diff --git a/tests/baselines/reference/usingDeclarationsWithESClassDecorators.8(module=esnext,target=es2015).js b/tests/baselines/reference/usingDeclarationsWithESClassDecorators.8(module=esnext,target=es2015).js +new file mode 100644 +index 000000000..3d9f65648 +--- /dev/null ++++ b/tests/baselines/reference/usingDeclarationsWithESClassDecorators.8(module=esnext,target=es2015).js +@@ -0,0 +1,43 @@ ++//// [tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsWithESClassDecorators.8.ts] //// ++ ++//// [usingDeclarationsWithESClassDecorators.8.ts] ++export {}; ++ ++declare var dec: any; ++ ++@dec ++export class C { ++} ++ ++using after = null; ++ ++ ++//// [usingDeclarationsWithESClassDecorators.8.js] ++let C = (() => { ++ let _classDecorators = [dec]; ++ let _classDescriptor; ++ let _classExtraInitializers = []; ++ let _classThis; ++ var C = _classThis = class { ++ }; ++ __setFunctionName(_classThis, "C"); ++ (() => { ++ __esDecorate(null, _classDescriptor = { value: _classThis }, _classDecorators, { kind: "class", name: _classThis.name }, null, _classExtraInitializers); ++ C = _classThis = _classDescriptor.value; ++ __runInitializers(_classThis, _classExtraInitializers); ++ })(); ++ return C = _classThis; ++})(); ++export { C }; ++var after; ++const env_1 = { stack: [], error: void 0, hasError: false }; ++try { ++ after = __addDisposableResource(env_1, null, false); ++} ++catch (e_1) { ++ env_1.error = e_1; ++ env_1.hasError = true; ++} ++finally { ++ __disposeResources(env_1); ++} +diff --git a/tests/baselines/reference/usingDeclarationsWithESClassDecorators.8(module=esnext,target=es5).js b/tests/baselines/reference/usingDeclarationsWithESClassDecorators.8(module=esnext,target=es5).js +new file mode 100644 +index 000000000..4d2d866f2 +--- /dev/null ++++ b/tests/baselines/reference/usingDeclarationsWithESClassDecorators.8(module=esnext,target=es5).js +@@ -0,0 +1,46 @@ ++//// [tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsWithESClassDecorators.8.ts] //// ++ ++//// [usingDeclarationsWithESClassDecorators.8.ts] ++export {}; ++ ++declare var dec: any; ++ ++@dec ++export class C { ++} ++ ++using after = null; ++ ++ ++//// [usingDeclarationsWithESClassDecorators.8.js] ++var C = function () { ++ var _classDecorators = [dec]; ++ var _classDescriptor; ++ var _classExtraInitializers = []; ++ var _classThis; ++ var C = _classThis = /** @class */ (function () { ++ function C_1() { ++ } ++ return C_1; ++ }()); ++ __setFunctionName(_classThis, "C"); ++ (function () { ++ __esDecorate(null, _classDescriptor = { value: _classThis }, _classDecorators, { kind: "class", name: _classThis.name }, null, _classExtraInitializers); ++ C = _classThis = _classDescriptor.value; ++ __runInitializers(_classThis, _classExtraInitializers); ++ })(); ++ return C = _classThis; ++}(); ++export { C }; ++var after; ++var env_1 = { stack: [], error: void 0, hasError: false }; ++try { ++ after = __addDisposableResource(env_1, null, false); ++} ++catch (e_1) { ++ env_1.error = e_1; ++ env_1.hasError = true; ++} ++finally { ++ __disposeResources(env_1); ++} +diff --git a/tests/baselines/reference/usingDeclarationsWithESClassDecorators.8(module=esnext,target=esnext).js b/tests/baselines/reference/usingDeclarationsWithESClassDecorators.8(module=esnext,target=esnext).js +new file mode 100644 +index 000000000..7233732ec +--- /dev/null ++++ b/tests/baselines/reference/usingDeclarationsWithESClassDecorators.8(module=esnext,target=esnext).js +@@ -0,0 +1,19 @@ ++//// [tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsWithESClassDecorators.8.ts] //// ++ ++//// [usingDeclarationsWithESClassDecorators.8.ts] ++export {}; ++ ++declare var dec: any; ++ ++@dec ++export class C { ++} ++ ++using after = null; ++ ++ ++//// [usingDeclarationsWithESClassDecorators.8.js] ++@dec ++export class C { ++} ++using after = null; +diff --git a/tests/baselines/reference/usingDeclarationsWithESClassDecorators.8(module=system,target=es2015).js b/tests/baselines/reference/usingDeclarationsWithESClassDecorators.8(module=system,target=es2015).js +new file mode 100644 +index 000000000..881531f70 +--- /dev/null ++++ b/tests/baselines/reference/usingDeclarationsWithESClassDecorators.8(module=system,target=es2015).js +@@ -0,0 +1,52 @@ ++//// [tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsWithESClassDecorators.8.ts] //// ++ ++//// [usingDeclarationsWithESClassDecorators.8.ts] ++export {}; ++ ++declare var dec: any; ++ ++@dec ++export class C { ++} ++ ++using after = null; ++ ++ ++//// [usingDeclarationsWithESClassDecorators.8.js] ++System.register([], function (exports_1, context_1) { ++ "use strict"; ++ var C, after, env_1; ++ var __moduleName = context_1 && context_1.id; ++ return { ++ setters: [], ++ execute: function () { ++ C = (() => { ++ let _classDecorators = [dec]; ++ let _classDescriptor; ++ let _classExtraInitializers = []; ++ let _classThis; ++ var C = _classThis = class { ++ }; ++ __setFunctionName(_classThis, "C"); ++ (() => { ++ __esDecorate(null, _classDescriptor = { value: _classThis }, _classDecorators, { kind: "class", name: _classThis.name }, null, _classExtraInitializers); ++ C = _classThis = _classDescriptor.value; ++ __runInitializers(_classThis, _classExtraInitializers); ++ })(); ++ return C = _classThis; ++ })(); ++ exports_1("C", C); ++ env_1 = { stack: [], error: void 0, hasError: false }; ++ try { ++ after = __addDisposableResource(env_1, null, false); ++ } ++ catch (e_1) { ++ env_1.error = e_1; ++ env_1.hasError = true; ++ } ++ finally { ++ __disposeResources(env_1); ++ } ++ } ++ }; ++}); +diff --git a/tests/baselines/reference/usingDeclarationsWithESClassDecorators.8(module=system,target=es5).js b/tests/baselines/reference/usingDeclarationsWithESClassDecorators.8(module=system,target=es5).js +new file mode 100644 +index 000000000..e1bacdb08 +--- /dev/null ++++ b/tests/baselines/reference/usingDeclarationsWithESClassDecorators.8(module=system,target=es5).js +@@ -0,0 +1,55 @@ ++//// [tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsWithESClassDecorators.8.ts] //// ++ ++//// [usingDeclarationsWithESClassDecorators.8.ts] ++export {}; ++ ++declare var dec: any; ++ ++@dec ++export class C { ++} ++ ++using after = null; ++ ++ ++//// [usingDeclarationsWithESClassDecorators.8.js] ++System.register([], function (exports_1, context_1) { ++ "use strict"; ++ var C, after, env_1; ++ var __moduleName = context_1 && context_1.id; ++ return { ++ setters: [], ++ execute: function () { ++ C = function () { ++ var _classDecorators = [dec]; ++ var _classDescriptor; ++ var _classExtraInitializers = []; ++ var _classThis; ++ var C = _classThis = /** @class */ (function () { ++ function C_1() { ++ } ++ return C_1; ++ }()); ++ __setFunctionName(_classThis, "C"); ++ (function () { ++ __esDecorate(null, _classDescriptor = { value: _classThis }, _classDecorators, { kind: "class", name: _classThis.name }, null, _classExtraInitializers); ++ C = _classThis = _classDescriptor.value; ++ __runInitializers(_classThis, _classExtraInitializers); ++ })(); ++ return C = _classThis; ++ }(); ++ exports_1("C", C); ++ env_1 = { stack: [], error: void 0, hasError: false }; ++ try { ++ after = __addDisposableResource(env_1, null, false); ++ } ++ catch (e_1) { ++ env_1.error = e_1; ++ env_1.hasError = true; ++ } ++ finally { ++ __disposeResources(env_1); ++ } ++ } ++ }; ++}); +diff --git a/tests/baselines/reference/usingDeclarationsWithESClassDecorators.8(module=system,target=esnext).js b/tests/baselines/reference/usingDeclarationsWithESClassDecorators.8(module=system,target=esnext).js +new file mode 100644 +index 000000000..53b7f9f06 +--- /dev/null ++++ b/tests/baselines/reference/usingDeclarationsWithESClassDecorators.8(module=system,target=esnext).js +@@ -0,0 +1,31 @@ ++//// [tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsWithESClassDecorators.8.ts] //// ++ ++//// [usingDeclarationsWithESClassDecorators.8.ts] ++export {}; ++ ++declare var dec: any; ++ ++@dec ++export class C { ++} ++ ++using after = null; ++ ++ ++//// [usingDeclarationsWithESClassDecorators.8.js] ++System.register([], function (exports_1, context_1) { ++ "use strict"; ++ var C, after; ++ var __moduleName = context_1 && context_1.id; ++ return { ++ setters: [], ++ execute: function () { ++ C = ++ @dec ++ class C { ++ }; ++ exports_1("C", C); ++ using after_1 = after = null; ++ } ++ }; ++}); +diff --git a/tests/baselines/reference/usingDeclarationsWithESClassDecorators.9(module=commonjs,target=es2015).js b/tests/baselines/reference/usingDeclarationsWithESClassDecorators.9(module=commonjs,target=es2015).js +new file mode 100644 +index 000000000..04799ef6c +--- /dev/null ++++ b/tests/baselines/reference/usingDeclarationsWithESClassDecorators.9(module=commonjs,target=es2015).js +@@ -0,0 +1,49 @@ ++//// [tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsWithESClassDecorators.9.ts] //// ++ ++//// [usingDeclarationsWithESClassDecorators.9.ts] ++export {}; ++ ++declare var dec: any; ++ ++@dec ++export default class C { ++} ++ ++void C; ++ ++using after = null; ++ ++ ++ ++//// [usingDeclarationsWithESClassDecorators.9.js] ++"use strict"; ++Object.defineProperty(exports, "__esModule", { value: true }); ++let C = (() => { ++ let _classDecorators = [dec]; ++ let _classDescriptor; ++ let _classExtraInitializers = []; ++ let _classThis; ++ var C = _classThis = class { ++ }; ++ __setFunctionName(_classThis, "C"); ++ (() => { ++ __esDecorate(null, _classDescriptor = { value: _classThis }, _classDecorators, { kind: "class", name: _classThis.name }, null, _classExtraInitializers); ++ C = _classThis = _classDescriptor.value; ++ __runInitializers(_classThis, _classExtraInitializers); ++ })(); ++ return C = _classThis; ++})(); ++exports.default = C; ++void C; ++var after; ++const env_1 = { stack: [], error: void 0, hasError: false }; ++try { ++ after = __addDisposableResource(env_1, null, false); ++} ++catch (e_1) { ++ env_1.error = e_1; ++ env_1.hasError = true; ++} ++finally { ++ __disposeResources(env_1); ++} +diff --git a/tests/baselines/reference/usingDeclarationsWithESClassDecorators.9(module=commonjs,target=es5).js b/tests/baselines/reference/usingDeclarationsWithESClassDecorators.9(module=commonjs,target=es5).js +new file mode 100644 +index 000000000..93d3fcaa6 +--- /dev/null ++++ b/tests/baselines/reference/usingDeclarationsWithESClassDecorators.9(module=commonjs,target=es5).js +@@ -0,0 +1,52 @@ ++//// [tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsWithESClassDecorators.9.ts] //// ++ ++//// [usingDeclarationsWithESClassDecorators.9.ts] ++export {}; ++ ++declare var dec: any; ++ ++@dec ++export default class C { ++} ++ ++void C; ++ ++using after = null; ++ ++ ++ ++//// [usingDeclarationsWithESClassDecorators.9.js] ++"use strict"; ++Object.defineProperty(exports, "__esModule", { value: true }); ++var C = function () { ++ var _classDecorators = [dec]; ++ var _classDescriptor; ++ var _classExtraInitializers = []; ++ var _classThis; ++ var C = _classThis = /** @class */ (function () { ++ function C_1() { ++ } ++ return C_1; ++ }()); ++ __setFunctionName(_classThis, "C"); ++ (function () { ++ __esDecorate(null, _classDescriptor = { value: _classThis }, _classDecorators, { kind: "class", name: _classThis.name }, null, _classExtraInitializers); ++ C = _classThis = _classDescriptor.value; ++ __runInitializers(_classThis, _classExtraInitializers); ++ })(); ++ return C = _classThis; ++}(); ++exports.default = C; ++void C; ++var after; ++var env_1 = { stack: [], error: void 0, hasError: false }; ++try { ++ after = __addDisposableResource(env_1, null, false); ++} ++catch (e_1) { ++ env_1.error = e_1; ++ env_1.hasError = true; ++} ++finally { ++ __disposeResources(env_1); ++} +diff --git a/tests/baselines/reference/usingDeclarationsWithESClassDecorators.9(module=commonjs,target=esnext).js b/tests/baselines/reference/usingDeclarationsWithESClassDecorators.9(module=commonjs,target=esnext).js +new file mode 100644 +index 000000000..adff298cf +--- /dev/null ++++ b/tests/baselines/reference/usingDeclarationsWithESClassDecorators.9(module=commonjs,target=esnext).js +@@ -0,0 +1,26 @@ ++//// [tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsWithESClassDecorators.9.ts] //// ++ ++//// [usingDeclarationsWithESClassDecorators.9.ts] ++export {}; ++ ++declare var dec: any; ++ ++@dec ++export default class C { ++} ++ ++void C; ++ ++using after = null; ++ ++ ++ ++//// [usingDeclarationsWithESClassDecorators.9.js] ++"use strict"; ++Object.defineProperty(exports, "__esModule", { value: true }); ++@dec ++class C { ++} ++exports.default = C; ++void C; ++using after = null; +diff --git a/tests/baselines/reference/usingDeclarationsWithESClassDecorators.9(module=esnext,target=es2015).js b/tests/baselines/reference/usingDeclarationsWithESClassDecorators.9(module=esnext,target=es2015).js +new file mode 100644 +index 000000000..8318eba18 +--- /dev/null ++++ b/tests/baselines/reference/usingDeclarationsWithESClassDecorators.9(module=esnext,target=es2015).js +@@ -0,0 +1,47 @@ ++//// [tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsWithESClassDecorators.9.ts] //// ++ ++//// [usingDeclarationsWithESClassDecorators.9.ts] ++export {}; ++ ++declare var dec: any; ++ ++@dec ++export default class C { ++} ++ ++void C; ++ ++using after = null; ++ ++ ++ ++//// [usingDeclarationsWithESClassDecorators.9.js] ++let C = (() => { ++ let _classDecorators = [dec]; ++ let _classDescriptor; ++ let _classExtraInitializers = []; ++ let _classThis; ++ var C = _classThis = class { ++ }; ++ __setFunctionName(_classThis, "C"); ++ (() => { ++ __esDecorate(null, _classDescriptor = { value: _classThis }, _classDecorators, { kind: "class", name: _classThis.name }, null, _classExtraInitializers); ++ C = _classThis = _classDescriptor.value; ++ __runInitializers(_classThis, _classExtraInitializers); ++ })(); ++ return C = _classThis; ++})(); ++export default C; ++void C; ++var after; ++const env_1 = { stack: [], error: void 0, hasError: false }; ++try { ++ after = __addDisposableResource(env_1, null, false); ++} ++catch (e_1) { ++ env_1.error = e_1; ++ env_1.hasError = true; ++} ++finally { ++ __disposeResources(env_1); ++} +diff --git a/tests/baselines/reference/usingDeclarationsWithESClassDecorators.9(module=esnext,target=es5).js b/tests/baselines/reference/usingDeclarationsWithESClassDecorators.9(module=esnext,target=es5).js +new file mode 100644 +index 000000000..693c3ed7a +--- /dev/null ++++ b/tests/baselines/reference/usingDeclarationsWithESClassDecorators.9(module=esnext,target=es5).js +@@ -0,0 +1,50 @@ ++//// [tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsWithESClassDecorators.9.ts] //// ++ ++//// [usingDeclarationsWithESClassDecorators.9.ts] ++export {}; ++ ++declare var dec: any; ++ ++@dec ++export default class C { ++} ++ ++void C; ++ ++using after = null; ++ ++ ++ ++//// [usingDeclarationsWithESClassDecorators.9.js] ++var C = function () { ++ var _classDecorators = [dec]; ++ var _classDescriptor; ++ var _classExtraInitializers = []; ++ var _classThis; ++ var C = _classThis = /** @class */ (function () { ++ function C_1() { ++ } ++ return C_1; ++ }()); ++ __setFunctionName(_classThis, "C"); ++ (function () { ++ __esDecorate(null, _classDescriptor = { value: _classThis }, _classDecorators, { kind: "class", name: _classThis.name }, null, _classExtraInitializers); ++ C = _classThis = _classDescriptor.value; ++ __runInitializers(_classThis, _classExtraInitializers); ++ })(); ++ return C = _classThis; ++}(); ++export default C; ++void C; ++var after; ++var env_1 = { stack: [], error: void 0, hasError: false }; ++try { ++ after = __addDisposableResource(env_1, null, false); ++} ++catch (e_1) { ++ env_1.error = e_1; ++ env_1.hasError = true; ++} ++finally { ++ __disposeResources(env_1); ++} +diff --git a/tests/baselines/reference/usingDeclarationsWithESClassDecorators.9(module=esnext,target=esnext).js b/tests/baselines/reference/usingDeclarationsWithESClassDecorators.9(module=esnext,target=esnext).js +new file mode 100644 +index 000000000..1ae172c17 +--- /dev/null ++++ b/tests/baselines/reference/usingDeclarationsWithESClassDecorators.9(module=esnext,target=esnext).js +@@ -0,0 +1,23 @@ ++//// [tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsWithESClassDecorators.9.ts] //// ++ ++//// [usingDeclarationsWithESClassDecorators.9.ts] ++export {}; ++ ++declare var dec: any; ++ ++@dec ++export default class C { ++} ++ ++void C; ++ ++using after = null; ++ ++ ++ ++//// [usingDeclarationsWithESClassDecorators.9.js] ++@dec ++export default class C { ++} ++void C; ++using after = null; +diff --git a/tests/baselines/reference/usingDeclarationsWithESClassDecorators.9(module=system,target=es2015).js b/tests/baselines/reference/usingDeclarationsWithESClassDecorators.9(module=system,target=es2015).js +new file mode 100644 +index 000000000..5f149929b +--- /dev/null ++++ b/tests/baselines/reference/usingDeclarationsWithESClassDecorators.9(module=system,target=es2015).js +@@ -0,0 +1,56 @@ ++//// [tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsWithESClassDecorators.9.ts] //// ++ ++//// [usingDeclarationsWithESClassDecorators.9.ts] ++export {}; ++ ++declare var dec: any; ++ ++@dec ++export default class C { ++} ++ ++void C; ++ ++using after = null; ++ ++ ++ ++//// [usingDeclarationsWithESClassDecorators.9.js] ++System.register([], function (exports_1, context_1) { ++ "use strict"; ++ var C, after, env_1; ++ var __moduleName = context_1 && context_1.id; ++ return { ++ setters: [], ++ execute: function () { ++ C = (() => { ++ let _classDecorators = [dec]; ++ let _classDescriptor; ++ let _classExtraInitializers = []; ++ let _classThis; ++ var C = _classThis = class { ++ }; ++ __setFunctionName(_classThis, "C"); ++ (() => { ++ __esDecorate(null, _classDescriptor = { value: _classThis }, _classDecorators, { kind: "class", name: _classThis.name }, null, _classExtraInitializers); ++ C = _classThis = _classDescriptor.value; ++ __runInitializers(_classThis, _classExtraInitializers); ++ })(); ++ return C = _classThis; ++ })(); ++ exports_1("default", C); ++ void C; ++ env_1 = { stack: [], error: void 0, hasError: false }; ++ try { ++ after = __addDisposableResource(env_1, null, false); ++ } ++ catch (e_1) { ++ env_1.error = e_1; ++ env_1.hasError = true; ++ } ++ finally { ++ __disposeResources(env_1); ++ } ++ } ++ }; ++}); +diff --git a/tests/baselines/reference/usingDeclarationsWithESClassDecorators.9(module=system,target=es5).js b/tests/baselines/reference/usingDeclarationsWithESClassDecorators.9(module=system,target=es5).js +new file mode 100644 +index 000000000..f5d7a58ef +--- /dev/null ++++ b/tests/baselines/reference/usingDeclarationsWithESClassDecorators.9(module=system,target=es5).js +@@ -0,0 +1,59 @@ ++//// [tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsWithESClassDecorators.9.ts] //// ++ ++//// [usingDeclarationsWithESClassDecorators.9.ts] ++export {}; ++ ++declare var dec: any; ++ ++@dec ++export default class C { ++} ++ ++void C; ++ ++using after = null; ++ ++ ++ ++//// [usingDeclarationsWithESClassDecorators.9.js] ++System.register([], function (exports_1, context_1) { ++ "use strict"; ++ var C, after, env_1; ++ var __moduleName = context_1 && context_1.id; ++ return { ++ setters: [], ++ execute: function () { ++ C = function () { ++ var _classDecorators = [dec]; ++ var _classDescriptor; ++ var _classExtraInitializers = []; ++ var _classThis; ++ var C = _classThis = /** @class */ (function () { ++ function C_1() { ++ } ++ return C_1; ++ }()); ++ __setFunctionName(_classThis, "C"); ++ (function () { ++ __esDecorate(null, _classDescriptor = { value: _classThis }, _classDecorators, { kind: "class", name: _classThis.name }, null, _classExtraInitializers); ++ C = _classThis = _classDescriptor.value; ++ __runInitializers(_classThis, _classExtraInitializers); ++ })(); ++ return C = _classThis; ++ }(); ++ exports_1("default", C); ++ void C; ++ env_1 = { stack: [], error: void 0, hasError: false }; ++ try { ++ after = __addDisposableResource(env_1, null, false); ++ } ++ catch (e_1) { ++ env_1.error = e_1; ++ env_1.hasError = true; ++ } ++ finally { ++ __disposeResources(env_1); ++ } ++ } ++ }; ++}); +diff --git a/tests/baselines/reference/usingDeclarationsWithESClassDecorators.9(module=system,target=esnext).js b/tests/baselines/reference/usingDeclarationsWithESClassDecorators.9(module=system,target=esnext).js +new file mode 100644 +index 000000000..1b832deaf +--- /dev/null ++++ b/tests/baselines/reference/usingDeclarationsWithESClassDecorators.9(module=system,target=esnext).js +@@ -0,0 +1,35 @@ ++//// [tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsWithESClassDecorators.9.ts] //// ++ ++//// [usingDeclarationsWithESClassDecorators.9.ts] ++export {}; ++ ++declare var dec: any; ++ ++@dec ++export default class C { ++} ++ ++void C; ++ ++using after = null; ++ ++ ++ ++//// [usingDeclarationsWithESClassDecorators.9.js] ++System.register([], function (exports_1, context_1) { ++ "use strict"; ++ var C, after; ++ var __moduleName = context_1 && context_1.id; ++ return { ++ setters: [], ++ execute: function () { ++ C = ++ @dec ++ class C { ++ }; ++ exports_1("default", C); ++ void C; ++ using after_1 = after = null; ++ } ++ }; ++}); +diff --git a/tests/baselines/reference/usingDeclarationsWithImportHelpers.errors.txt b/tests/baselines/reference/usingDeclarationsWithImportHelpers.errors.txt +new file mode 100644 +index 000000000..e1ba1e508 +--- /dev/null ++++ b/tests/baselines/reference/usingDeclarationsWithImportHelpers.errors.txt +@@ -0,0 +1,11 @@ ++usingDeclarationsWithImportHelpers.ts(4,5): error TS2354: This syntax requires an imported helper but module 'tslib' cannot be found. ++ ++ ++==== usingDeclarationsWithImportHelpers.ts (1 errors) ==== ++ export {}; ++ ++ { ++ using a = null; ++ ~~~~~~~~~~~~~~ ++!!! error TS2354: This syntax requires an imported helper but module 'tslib' cannot be found. ++ } +\ No newline at end of file +diff --git a/tests/baselines/reference/usingDeclarationsWithImportHelpers.js b/tests/baselines/reference/usingDeclarationsWithImportHelpers.js +new file mode 100644 +index 000000000..19985bb81 +--- /dev/null ++++ b/tests/baselines/reference/usingDeclarationsWithImportHelpers.js +@@ -0,0 +1,14 @@ ++//// [tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsWithImportHelpers.ts] //// ++ ++//// [usingDeclarationsWithImportHelpers.ts] ++export {}; ++ ++{ ++ using a = null; ++} ++ ++//// [usingDeclarationsWithImportHelpers.js] ++{ ++ using a = null; ++} ++export {}; +diff --git a/tests/baselines/reference/usingDeclarationsWithLegacyClassDecorators.1(module=commonjs,target=es2015).js b/tests/baselines/reference/usingDeclarationsWithLegacyClassDecorators.1(module=commonjs,target=es2015).js +new file mode 100644 +index 000000000..b7056ebea +--- /dev/null ++++ b/tests/baselines/reference/usingDeclarationsWithLegacyClassDecorators.1(module=commonjs,target=es2015).js +@@ -0,0 +1,34 @@ ++//// [tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsWithLegacyClassDecorators.1.ts] //// ++ ++//// [usingDeclarationsWithLegacyClassDecorators.1.ts] ++export {}; ++ ++declare var dec: any; ++ ++using before = null; ++ ++@dec ++class C { ++} ++ ++ ++//// [usingDeclarationsWithLegacyClassDecorators.1.js] ++"use strict"; ++Object.defineProperty(exports, "__esModule", { value: true }); ++var before, C; ++const env_1 = { stack: [], error: void 0, hasError: false }; ++try { ++ before = __addDisposableResource(env_1, null, false); ++ C = class C { ++ }; ++ C = __decorate([ ++ dec ++ ], C); ++} ++catch (e_1) { ++ env_1.error = e_1; ++ env_1.hasError = true; ++} ++finally { ++ __disposeResources(env_1); ++} +diff --git a/tests/baselines/reference/usingDeclarationsWithLegacyClassDecorators.1(module=commonjs,target=es5).js b/tests/baselines/reference/usingDeclarationsWithLegacyClassDecorators.1(module=commonjs,target=es5).js +new file mode 100644 +index 000000000..4fdd4f978 +--- /dev/null ++++ b/tests/baselines/reference/usingDeclarationsWithLegacyClassDecorators.1(module=commonjs,target=es5).js +@@ -0,0 +1,37 @@ ++//// [tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsWithLegacyClassDecorators.1.ts] //// ++ ++//// [usingDeclarationsWithLegacyClassDecorators.1.ts] ++export {}; ++ ++declare var dec: any; ++ ++using before = null; ++ ++@dec ++class C { ++} ++ ++ ++//// [usingDeclarationsWithLegacyClassDecorators.1.js] ++"use strict"; ++Object.defineProperty(exports, "__esModule", { value: true }); ++var before, C; ++var env_1 = { stack: [], error: void 0, hasError: false }; ++try { ++ before = __addDisposableResource(env_1, null, false); ++ C = /** @class */ (function () { ++ function C() { ++ } ++ C = __decorate([ ++ dec ++ ], C); ++ return C; ++ }()); ++} ++catch (e_1) { ++ env_1.error = e_1; ++ env_1.hasError = true; ++} ++finally { ++ __disposeResources(env_1); ++} +diff --git a/tests/baselines/reference/usingDeclarationsWithLegacyClassDecorators.1(module=commonjs,target=esnext).js b/tests/baselines/reference/usingDeclarationsWithLegacyClassDecorators.1(module=commonjs,target=esnext).js +new file mode 100644 +index 000000000..1d134f939 +--- /dev/null ++++ b/tests/baselines/reference/usingDeclarationsWithLegacyClassDecorators.1(module=commonjs,target=esnext).js +@@ -0,0 +1,23 @@ ++//// [tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsWithLegacyClassDecorators.1.ts] //// ++ ++//// [usingDeclarationsWithLegacyClassDecorators.1.ts] ++export {}; ++ ++declare var dec: any; ++ ++using before = null; ++ ++@dec ++class C { ++} ++ ++ ++//// [usingDeclarationsWithLegacyClassDecorators.1.js] ++"use strict"; ++Object.defineProperty(exports, "__esModule", { value: true }); ++using before = null; ++let C = class C { ++}; ++C = __decorate([ ++ dec ++], C); +diff --git a/tests/baselines/reference/usingDeclarationsWithLegacyClassDecorators.1(module=esnext,target=es2015).js b/tests/baselines/reference/usingDeclarationsWithLegacyClassDecorators.1(module=esnext,target=es2015).js +new file mode 100644 +index 000000000..b0cfcf206 +--- /dev/null ++++ b/tests/baselines/reference/usingDeclarationsWithLegacyClassDecorators.1(module=esnext,target=es2015).js +@@ -0,0 +1,33 @@ ++//// [tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsWithLegacyClassDecorators.1.ts] //// ++ ++//// [usingDeclarationsWithLegacyClassDecorators.1.ts] ++export {}; ++ ++declare var dec: any; ++ ++using before = null; ++ ++@dec ++class C { ++} ++ ++ ++//// [usingDeclarationsWithLegacyClassDecorators.1.js] ++var before, C; ++const env_1 = { stack: [], error: void 0, hasError: false }; ++try { ++ before = __addDisposableResource(env_1, null, false); ++ C = class C { ++ }; ++ C = __decorate([ ++ dec ++ ], C); ++} ++catch (e_1) { ++ env_1.error = e_1; ++ env_1.hasError = true; ++} ++finally { ++ __disposeResources(env_1); ++} ++export {}; +diff --git a/tests/baselines/reference/usingDeclarationsWithLegacyClassDecorators.1(module=esnext,target=es5).js b/tests/baselines/reference/usingDeclarationsWithLegacyClassDecorators.1(module=esnext,target=es5).js +new file mode 100644 +index 000000000..c2ac948b2 +--- /dev/null ++++ b/tests/baselines/reference/usingDeclarationsWithLegacyClassDecorators.1(module=esnext,target=es5).js +@@ -0,0 +1,36 @@ ++//// [tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsWithLegacyClassDecorators.1.ts] //// ++ ++//// [usingDeclarationsWithLegacyClassDecorators.1.ts] ++export {}; ++ ++declare var dec: any; ++ ++using before = null; ++ ++@dec ++class C { ++} ++ ++ ++//// [usingDeclarationsWithLegacyClassDecorators.1.js] ++var before, C; ++var env_1 = { stack: [], error: void 0, hasError: false }; ++try { ++ before = __addDisposableResource(env_1, null, false); ++ C = /** @class */ (function () { ++ function C() { ++ } ++ C = __decorate([ ++ dec ++ ], C); ++ return C; ++ }()); ++} ++catch (e_1) { ++ env_1.error = e_1; ++ env_1.hasError = true; ++} ++finally { ++ __disposeResources(env_1); ++} ++export {}; +diff --git a/tests/baselines/reference/usingDeclarationsWithLegacyClassDecorators.1(module=esnext,target=esnext).js b/tests/baselines/reference/usingDeclarationsWithLegacyClassDecorators.1(module=esnext,target=esnext).js +new file mode 100644 +index 000000000..bcd661c59 +--- /dev/null ++++ b/tests/baselines/reference/usingDeclarationsWithLegacyClassDecorators.1(module=esnext,target=esnext).js +@@ -0,0 +1,22 @@ ++//// [tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsWithLegacyClassDecorators.1.ts] //// ++ ++//// [usingDeclarationsWithLegacyClassDecorators.1.ts] ++export {}; ++ ++declare var dec: any; ++ ++using before = null; ++ ++@dec ++class C { ++} ++ ++ ++//// [usingDeclarationsWithLegacyClassDecorators.1.js] ++using before = null; ++let C = class C { ++}; ++C = __decorate([ ++ dec ++], C); ++export {}; +diff --git a/tests/baselines/reference/usingDeclarationsWithLegacyClassDecorators.1(module=system,target=es2015).js b/tests/baselines/reference/usingDeclarationsWithLegacyClassDecorators.1(module=system,target=es2015).js +new file mode 100644 +index 000000000..e38f4368d +--- /dev/null ++++ b/tests/baselines/reference/usingDeclarationsWithLegacyClassDecorators.1(module=system,target=es2015).js +@@ -0,0 +1,41 @@ ++//// [tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsWithLegacyClassDecorators.1.ts] //// ++ ++//// [usingDeclarationsWithLegacyClassDecorators.1.ts] ++export {}; ++ ++declare var dec: any; ++ ++using before = null; ++ ++@dec ++class C { ++} ++ ++ ++//// [usingDeclarationsWithLegacyClassDecorators.1.js] ++System.register([], function (exports_1, context_1) { ++ "use strict"; ++ var before, C, env_1; ++ var __moduleName = context_1 && context_1.id; ++ return { ++ setters: [], ++ execute: function () { ++ env_1 = { stack: [], error: void 0, hasError: false }; ++ try { ++ before = __addDisposableResource(env_1, null, false); ++ C = class C { ++ }; ++ C = __decorate([ ++ dec ++ ], C); ++ } ++ catch (e_1) { ++ env_1.error = e_1; ++ env_1.hasError = true; ++ } ++ finally { ++ __disposeResources(env_1); ++ } ++ } ++ }; ++}); +diff --git a/tests/baselines/reference/usingDeclarationsWithLegacyClassDecorators.1(module=system,target=es5).js b/tests/baselines/reference/usingDeclarationsWithLegacyClassDecorators.1(module=system,target=es5).js +new file mode 100644 +index 000000000..01b2a8ac3 +--- /dev/null ++++ b/tests/baselines/reference/usingDeclarationsWithLegacyClassDecorators.1(module=system,target=es5).js +@@ -0,0 +1,44 @@ ++//// [tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsWithLegacyClassDecorators.1.ts] //// ++ ++//// [usingDeclarationsWithLegacyClassDecorators.1.ts] ++export {}; ++ ++declare var dec: any; ++ ++using before = null; ++ ++@dec ++class C { ++} ++ ++ ++//// [usingDeclarationsWithLegacyClassDecorators.1.js] ++System.register([], function (exports_1, context_1) { ++ "use strict"; ++ var before, C, env_1; ++ var __moduleName = context_1 && context_1.id; ++ return { ++ setters: [], ++ execute: function () { ++ env_1 = { stack: [], error: void 0, hasError: false }; ++ try { ++ before = __addDisposableResource(env_1, null, false); ++ C = /** @class */ (function () { ++ function C() { ++ } ++ C = __decorate([ ++ dec ++ ], C); ++ return C; ++ }()); ++ } ++ catch (e_1) { ++ env_1.error = e_1; ++ env_1.hasError = true; ++ } ++ finally { ++ __disposeResources(env_1); ++ } ++ } ++ }; ++}); +diff --git a/tests/baselines/reference/usingDeclarationsWithLegacyClassDecorators.1(module=system,target=esnext).js b/tests/baselines/reference/usingDeclarationsWithLegacyClassDecorators.1(module=system,target=esnext).js +new file mode 100644 +index 000000000..9acdfb059 +--- /dev/null ++++ b/tests/baselines/reference/usingDeclarationsWithLegacyClassDecorators.1(module=system,target=esnext).js +@@ -0,0 +1,31 @@ ++//// [tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsWithLegacyClassDecorators.1.ts] //// ++ ++//// [usingDeclarationsWithLegacyClassDecorators.1.ts] ++export {}; ++ ++declare var dec: any; ++ ++using before = null; ++ ++@dec ++class C { ++} ++ ++ ++//// [usingDeclarationsWithLegacyClassDecorators.1.js] ++System.register([], function (exports_1, context_1) { ++ "use strict"; ++ var before, C; ++ var __moduleName = context_1 && context_1.id; ++ return { ++ setters: [], ++ execute: function () { ++ using before_1 = before = null; ++ C = class C { ++ }; ++ C = __decorate([ ++ dec ++ ], C); ++ } ++ }; ++}); +diff --git a/tests/baselines/reference/usingDeclarationsWithLegacyClassDecorators.10(module=commonjs,target=es2015).js b/tests/baselines/reference/usingDeclarationsWithLegacyClassDecorators.10(module=commonjs,target=es2015).js +new file mode 100644 +index 000000000..7d88c0878 +--- /dev/null ++++ b/tests/baselines/reference/usingDeclarationsWithLegacyClassDecorators.10(module=commonjs,target=es2015).js +@@ -0,0 +1,35 @@ ++//// [tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsWithLegacyClassDecorators.10.ts] //// ++ ++//// [usingDeclarationsWithLegacyClassDecorators.10.ts] ++export {}; ++ ++declare var dec: any; ++ ++@dec ++export default class { ++} ++ ++using after = null; ++ ++ ++//// [usingDeclarationsWithLegacyClassDecorators.10.js] ++"use strict"; ++Object.defineProperty(exports, "__esModule", { value: true }); ++let default_1 = class { ++}; ++default_1 = __decorate([ ++ dec ++], default_1); ++exports.default = default_1; ++var after; ++const env_1 = { stack: [], error: void 0, hasError: false }; ++try { ++ after = __addDisposableResource(env_1, null, false); ++} ++catch (e_1) { ++ env_1.error = e_1; ++ env_1.hasError = true; ++} ++finally { ++ __disposeResources(env_1); ++} +diff --git a/tests/baselines/reference/usingDeclarationsWithLegacyClassDecorators.10(module=commonjs,target=es5).js b/tests/baselines/reference/usingDeclarationsWithLegacyClassDecorators.10(module=commonjs,target=es5).js +new file mode 100644 +index 000000000..58df20063 +--- /dev/null ++++ b/tests/baselines/reference/usingDeclarationsWithLegacyClassDecorators.10(module=commonjs,target=es5).js +@@ -0,0 +1,38 @@ ++//// [tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsWithLegacyClassDecorators.10.ts] //// ++ ++//// [usingDeclarationsWithLegacyClassDecorators.10.ts] ++export {}; ++ ++declare var dec: any; ++ ++@dec ++export default class { ++} ++ ++using after = null; ++ ++ ++//// [usingDeclarationsWithLegacyClassDecorators.10.js] ++"use strict"; ++Object.defineProperty(exports, "__esModule", { value: true }); ++var default_1 = /** @class */ (function () { ++ function default_1() { ++ } ++ default_1 = __decorate([ ++ dec ++ ], default_1); ++ return default_1; ++}()); ++exports.default = default_1; ++var after; ++var env_1 = { stack: [], error: void 0, hasError: false }; ++try { ++ after = __addDisposableResource(env_1, null, false); ++} ++catch (e_1) { ++ env_1.error = e_1; ++ env_1.hasError = true; ++} ++finally { ++ __disposeResources(env_1); ++} +diff --git a/tests/baselines/reference/usingDeclarationsWithLegacyClassDecorators.10(module=commonjs,target=esnext).js b/tests/baselines/reference/usingDeclarationsWithLegacyClassDecorators.10(module=commonjs,target=esnext).js +new file mode 100644 +index 000000000..1300e8055 +--- /dev/null ++++ b/tests/baselines/reference/usingDeclarationsWithLegacyClassDecorators.10(module=commonjs,target=esnext).js +@@ -0,0 +1,24 @@ ++//// [tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsWithLegacyClassDecorators.10.ts] //// ++ ++//// [usingDeclarationsWithLegacyClassDecorators.10.ts] ++export {}; ++ ++declare var dec: any; ++ ++@dec ++export default class { ++} ++ ++using after = null; ++ ++ ++//// [usingDeclarationsWithLegacyClassDecorators.10.js] ++"use strict"; ++Object.defineProperty(exports, "__esModule", { value: true }); ++let default_1 = class { ++}; ++default_1 = __decorate([ ++ dec ++], default_1); ++exports.default = default_1; ++using after = null; +diff --git a/tests/baselines/reference/usingDeclarationsWithLegacyClassDecorators.10(module=esnext,target=es2015).js b/tests/baselines/reference/usingDeclarationsWithLegacyClassDecorators.10(module=esnext,target=es2015).js +new file mode 100644 +index 000000000..0d6a67051 +--- /dev/null ++++ b/tests/baselines/reference/usingDeclarationsWithLegacyClassDecorators.10(module=esnext,target=es2015).js +@@ -0,0 +1,33 @@ ++//// [tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsWithLegacyClassDecorators.10.ts] //// ++ ++//// [usingDeclarationsWithLegacyClassDecorators.10.ts] ++export {}; ++ ++declare var dec: any; ++ ++@dec ++export default class { ++} ++ ++using after = null; ++ ++ ++//// [usingDeclarationsWithLegacyClassDecorators.10.js] ++let default_1 = class { ++}; ++default_1 = __decorate([ ++ dec ++], default_1); ++export default default_1; ++var after; ++const env_1 = { stack: [], error: void 0, hasError: false }; ++try { ++ after = __addDisposableResource(env_1, null, false); ++} ++catch (e_1) { ++ env_1.error = e_1; ++ env_1.hasError = true; ++} ++finally { ++ __disposeResources(env_1); ++} +diff --git a/tests/baselines/reference/usingDeclarationsWithLegacyClassDecorators.10(module=esnext,target=es5).js b/tests/baselines/reference/usingDeclarationsWithLegacyClassDecorators.10(module=esnext,target=es5).js +new file mode 100644 +index 000000000..af9068748 +--- /dev/null ++++ b/tests/baselines/reference/usingDeclarationsWithLegacyClassDecorators.10(module=esnext,target=es5).js +@@ -0,0 +1,36 @@ ++//// [tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsWithLegacyClassDecorators.10.ts] //// ++ ++//// [usingDeclarationsWithLegacyClassDecorators.10.ts] ++export {}; ++ ++declare var dec: any; ++ ++@dec ++export default class { ++} ++ ++using after = null; ++ ++ ++//// [usingDeclarationsWithLegacyClassDecorators.10.js] ++var default_1 = /** @class */ (function () { ++ function default_1() { ++ } ++ default_1 = __decorate([ ++ dec ++ ], default_1); ++ return default_1; ++}()); ++export default default_1; ++var after; ++var env_1 = { stack: [], error: void 0, hasError: false }; ++try { ++ after = __addDisposableResource(env_1, null, false); ++} ++catch (e_1) { ++ env_1.error = e_1; ++ env_1.hasError = true; ++} ++finally { ++ __disposeResources(env_1); ++} +diff --git a/tests/baselines/reference/usingDeclarationsWithLegacyClassDecorators.10(module=esnext,target=esnext).js b/tests/baselines/reference/usingDeclarationsWithLegacyClassDecorators.10(module=esnext,target=esnext).js +new file mode 100644 +index 000000000..50db75c3f +--- /dev/null ++++ b/tests/baselines/reference/usingDeclarationsWithLegacyClassDecorators.10(module=esnext,target=esnext).js +@@ -0,0 +1,22 @@ ++//// [tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsWithLegacyClassDecorators.10.ts] //// ++ ++//// [usingDeclarationsWithLegacyClassDecorators.10.ts] ++export {}; ++ ++declare var dec: any; ++ ++@dec ++export default class { ++} ++ ++using after = null; ++ ++ ++//// [usingDeclarationsWithLegacyClassDecorators.10.js] ++let default_1 = class { ++}; ++default_1 = __decorate([ ++ dec ++], default_1); ++export default default_1; ++using after = null; +diff --git a/tests/baselines/reference/usingDeclarationsWithLegacyClassDecorators.10(module=system,target=es2015).js b/tests/baselines/reference/usingDeclarationsWithLegacyClassDecorators.10(module=system,target=es2015).js +new file mode 100644 +index 000000000..f42cafc02 +--- /dev/null ++++ b/tests/baselines/reference/usingDeclarationsWithLegacyClassDecorators.10(module=system,target=es2015).js +@@ -0,0 +1,42 @@ ++//// [tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsWithLegacyClassDecorators.10.ts] //// ++ ++//// [usingDeclarationsWithLegacyClassDecorators.10.ts] ++export {}; ++ ++declare var dec: any; ++ ++@dec ++export default class { ++} ++ ++using after = null; ++ ++ ++//// [usingDeclarationsWithLegacyClassDecorators.10.js] ++System.register([], function (exports_1, context_1) { ++ "use strict"; ++ var default_1, after, env_1; ++ var __moduleName = context_1 && context_1.id; ++ return { ++ setters: [], ++ execute: function () { ++ default_1 = class { ++ }; ++ default_1 = __decorate([ ++ dec ++ ], default_1); ++ exports_1("default", default_1); ++ env_1 = { stack: [], error: void 0, hasError: false }; ++ try { ++ after = __addDisposableResource(env_1, null, false); ++ } ++ catch (e_1) { ++ env_1.error = e_1; ++ env_1.hasError = true; ++ } ++ finally { ++ __disposeResources(env_1); ++ } ++ } ++ }; ++}); +diff --git a/tests/baselines/reference/usingDeclarationsWithLegacyClassDecorators.10(module=system,target=es5).js b/tests/baselines/reference/usingDeclarationsWithLegacyClassDecorators.10(module=system,target=es5).js +new file mode 100644 +index 000000000..6d93aa689 +--- /dev/null ++++ b/tests/baselines/reference/usingDeclarationsWithLegacyClassDecorators.10(module=system,target=es5).js +@@ -0,0 +1,45 @@ ++//// [tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsWithLegacyClassDecorators.10.ts] //// ++ ++//// [usingDeclarationsWithLegacyClassDecorators.10.ts] ++export {}; ++ ++declare var dec: any; ++ ++@dec ++export default class { ++} ++ ++using after = null; ++ ++ ++//// [usingDeclarationsWithLegacyClassDecorators.10.js] ++System.register([], function (exports_1, context_1) { ++ "use strict"; ++ var default_1, after, env_1; ++ var __moduleName = context_1 && context_1.id; ++ return { ++ setters: [], ++ execute: function () { ++ default_1 = /** @class */ (function () { ++ function default_1() { ++ } ++ default_1 = __decorate([ ++ dec ++ ], default_1); ++ return default_1; ++ }()); ++ exports_1("default", default_1); ++ env_1 = { stack: [], error: void 0, hasError: false }; ++ try { ++ after = __addDisposableResource(env_1, null, false); ++ } ++ catch (e_1) { ++ env_1.error = e_1; ++ env_1.hasError = true; ++ } ++ finally { ++ __disposeResources(env_1); ++ } ++ } ++ }; ++}); +diff --git a/tests/baselines/reference/usingDeclarationsWithLegacyClassDecorators.10(module=system,target=esnext).js b/tests/baselines/reference/usingDeclarationsWithLegacyClassDecorators.10(module=system,target=esnext).js +new file mode 100644 +index 000000000..80d52ac8a +--- /dev/null ++++ b/tests/baselines/reference/usingDeclarationsWithLegacyClassDecorators.10(module=system,target=esnext).js +@@ -0,0 +1,32 @@ ++//// [tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsWithLegacyClassDecorators.10.ts] //// ++ ++//// [usingDeclarationsWithLegacyClassDecorators.10.ts] ++export {}; ++ ++declare var dec: any; ++ ++@dec ++export default class { ++} ++ ++using after = null; ++ ++ ++//// [usingDeclarationsWithLegacyClassDecorators.10.js] ++System.register([], function (exports_1, context_1) { ++ "use strict"; ++ var default_1, after; ++ var __moduleName = context_1 && context_1.id; ++ return { ++ setters: [], ++ execute: function () { ++ default_1 = class { ++ }; ++ default_1 = __decorate([ ++ dec ++ ], default_1); ++ exports_1("default", default_1); ++ using after_1 = after = null; ++ } ++ }; ++}); +diff --git a/tests/baselines/reference/usingDeclarationsWithLegacyClassDecorators.11(module=commonjs,target=es2015).js b/tests/baselines/reference/usingDeclarationsWithLegacyClassDecorators.11(module=commonjs,target=es2015).js +new file mode 100644 +index 000000000..f8dd7ad60 +--- /dev/null ++++ b/tests/baselines/reference/usingDeclarationsWithLegacyClassDecorators.11(module=commonjs,target=es2015).js +@@ -0,0 +1,38 @@ ++//// [tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsWithLegacyClassDecorators.11.ts] //// ++ ++//// [usingDeclarationsWithLegacyClassDecorators.11.ts] ++export {}; ++ ++declare var dec: any; ++ ++@dec ++class C { ++} ++ ++export { C }; ++ ++using after = null; ++ ++ ++//// [usingDeclarationsWithLegacyClassDecorators.11.js] ++"use strict"; ++Object.defineProperty(exports, "__esModule", { value: true }); ++exports.C = void 0; ++let C = class C { ++}; ++exports.C = C; ++exports.C = C = __decorate([ ++ dec ++], C); ++var after; ++const env_1 = { stack: [], error: void 0, hasError: false }; ++try { ++ after = __addDisposableResource(env_1, null, false); ++} ++catch (e_1) { ++ env_1.error = e_1; ++ env_1.hasError = true; ++} ++finally { ++ __disposeResources(env_1); ++} +diff --git a/tests/baselines/reference/usingDeclarationsWithLegacyClassDecorators.11(module=commonjs,target=es5).js b/tests/baselines/reference/usingDeclarationsWithLegacyClassDecorators.11(module=commonjs,target=es5).js +new file mode 100644 +index 000000000..5b6952769 +--- /dev/null ++++ b/tests/baselines/reference/usingDeclarationsWithLegacyClassDecorators.11(module=commonjs,target=es5).js +@@ -0,0 +1,41 @@ ++//// [tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsWithLegacyClassDecorators.11.ts] //// ++ ++//// [usingDeclarationsWithLegacyClassDecorators.11.ts] ++export {}; ++ ++declare var dec: any; ++ ++@dec ++class C { ++} ++ ++export { C }; ++ ++using after = null; ++ ++ ++//// [usingDeclarationsWithLegacyClassDecorators.11.js] ++"use strict"; ++Object.defineProperty(exports, "__esModule", { value: true }); ++exports.C = void 0; ++var C = /** @class */ (function () { ++ function C() { ++ } ++ C = __decorate([ ++ dec ++ ], C); ++ return C; ++}()); ++exports.C = C; ++var after; ++var env_1 = { stack: [], error: void 0, hasError: false }; ++try { ++ after = __addDisposableResource(env_1, null, false); ++} ++catch (e_1) { ++ env_1.error = e_1; ++ env_1.hasError = true; ++} ++finally { ++ __disposeResources(env_1); ++} +diff --git a/tests/baselines/reference/usingDeclarationsWithLegacyClassDecorators.11(module=commonjs,target=esnext).js b/tests/baselines/reference/usingDeclarationsWithLegacyClassDecorators.11(module=commonjs,target=esnext).js +new file mode 100644 +index 000000000..b278c5165 +--- /dev/null ++++ b/tests/baselines/reference/usingDeclarationsWithLegacyClassDecorators.11(module=commonjs,target=esnext).js +@@ -0,0 +1,27 @@ ++//// [tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsWithLegacyClassDecorators.11.ts] //// ++ ++//// [usingDeclarationsWithLegacyClassDecorators.11.ts] ++export {}; ++ ++declare var dec: any; ++ ++@dec ++class C { ++} ++ ++export { C }; ++ ++using after = null; ++ ++ ++//// [usingDeclarationsWithLegacyClassDecorators.11.js] ++"use strict"; ++Object.defineProperty(exports, "__esModule", { value: true }); ++exports.C = void 0; ++let C = class C { ++}; ++exports.C = C; ++exports.C = C = __decorate([ ++ dec ++], C); ++using after = null; +diff --git a/tests/baselines/reference/usingDeclarationsWithLegacyClassDecorators.11(module=esnext,target=es2015).js b/tests/baselines/reference/usingDeclarationsWithLegacyClassDecorators.11(module=esnext,target=es2015).js +new file mode 100644 +index 000000000..9093751af +--- /dev/null ++++ b/tests/baselines/reference/usingDeclarationsWithLegacyClassDecorators.11(module=esnext,target=es2015).js +@@ -0,0 +1,35 @@ ++//// [tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsWithLegacyClassDecorators.11.ts] //// ++ ++//// [usingDeclarationsWithLegacyClassDecorators.11.ts] ++export {}; ++ ++declare var dec: any; ++ ++@dec ++class C { ++} ++ ++export { C }; ++ ++using after = null; ++ ++ ++//// [usingDeclarationsWithLegacyClassDecorators.11.js] ++let C = class C { ++}; ++C = __decorate([ ++ dec ++], C); ++export { C }; ++var after; ++const env_1 = { stack: [], error: void 0, hasError: false }; ++try { ++ after = __addDisposableResource(env_1, null, false); ++} ++catch (e_1) { ++ env_1.error = e_1; ++ env_1.hasError = true; ++} ++finally { ++ __disposeResources(env_1); ++} +diff --git a/tests/baselines/reference/usingDeclarationsWithLegacyClassDecorators.11(module=esnext,target=es5).js b/tests/baselines/reference/usingDeclarationsWithLegacyClassDecorators.11(module=esnext,target=es5).js +new file mode 100644 +index 000000000..231f35d7f +--- /dev/null ++++ b/tests/baselines/reference/usingDeclarationsWithLegacyClassDecorators.11(module=esnext,target=es5).js +@@ -0,0 +1,38 @@ ++//// [tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsWithLegacyClassDecorators.11.ts] //// ++ ++//// [usingDeclarationsWithLegacyClassDecorators.11.ts] ++export {}; ++ ++declare var dec: any; ++ ++@dec ++class C { ++} ++ ++export { C }; ++ ++using after = null; ++ ++ ++//// [usingDeclarationsWithLegacyClassDecorators.11.js] ++var C = /** @class */ (function () { ++ function C() { ++ } ++ C = __decorate([ ++ dec ++ ], C); ++ return C; ++}()); ++export { C }; ++var after; ++var env_1 = { stack: [], error: void 0, hasError: false }; ++try { ++ after = __addDisposableResource(env_1, null, false); ++} ++catch (e_1) { ++ env_1.error = e_1; ++ env_1.hasError = true; ++} ++finally { ++ __disposeResources(env_1); ++} +diff --git a/tests/baselines/reference/usingDeclarationsWithLegacyClassDecorators.11(module=esnext,target=esnext).js b/tests/baselines/reference/usingDeclarationsWithLegacyClassDecorators.11(module=esnext,target=esnext).js +new file mode 100644 +index 000000000..9082a184d +--- /dev/null ++++ b/tests/baselines/reference/usingDeclarationsWithLegacyClassDecorators.11(module=esnext,target=esnext).js +@@ -0,0 +1,24 @@ ++//// [tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsWithLegacyClassDecorators.11.ts] //// ++ ++//// [usingDeclarationsWithLegacyClassDecorators.11.ts] ++export {}; ++ ++declare var dec: any; ++ ++@dec ++class C { ++} ++ ++export { C }; ++ ++using after = null; ++ ++ ++//// [usingDeclarationsWithLegacyClassDecorators.11.js] ++let C = class C { ++}; ++C = __decorate([ ++ dec ++], C); ++export { C }; ++using after = null; +diff --git a/tests/baselines/reference/usingDeclarationsWithLegacyClassDecorators.11(module=system,target=es2015).js b/tests/baselines/reference/usingDeclarationsWithLegacyClassDecorators.11(module=system,target=es2015).js +new file mode 100644 +index 000000000..d43c78d6f +--- /dev/null ++++ b/tests/baselines/reference/usingDeclarationsWithLegacyClassDecorators.11(module=system,target=es2015).js +@@ -0,0 +1,44 @@ ++//// [tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsWithLegacyClassDecorators.11.ts] //// ++ ++//// [usingDeclarationsWithLegacyClassDecorators.11.ts] ++export {}; ++ ++declare var dec: any; ++ ++@dec ++class C { ++} ++ ++export { C }; ++ ++using after = null; ++ ++ ++//// [usingDeclarationsWithLegacyClassDecorators.11.js] ++System.register([], function (exports_1, context_1) { ++ "use strict"; ++ var C, after, env_1; ++ var __moduleName = context_1 && context_1.id; ++ return { ++ setters: [], ++ execute: function () { ++ C = class C { ++ }; ++ exports_1("C", C); ++ exports_1("C", C = __decorate([ ++ dec ++ ], C)); ++ env_1 = { stack: [], error: void 0, hasError: false }; ++ try { ++ after = __addDisposableResource(env_1, null, false); ++ } ++ catch (e_1) { ++ env_1.error = e_1; ++ env_1.hasError = true; ++ } ++ finally { ++ __disposeResources(env_1); ++ } ++ } ++ }; ++}); +diff --git a/tests/baselines/reference/usingDeclarationsWithLegacyClassDecorators.11(module=system,target=es5).js b/tests/baselines/reference/usingDeclarationsWithLegacyClassDecorators.11(module=system,target=es5).js +new file mode 100644 +index 000000000..4052e27a1 +--- /dev/null ++++ b/tests/baselines/reference/usingDeclarationsWithLegacyClassDecorators.11(module=system,target=es5).js +@@ -0,0 +1,47 @@ ++//// [tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsWithLegacyClassDecorators.11.ts] //// ++ ++//// [usingDeclarationsWithLegacyClassDecorators.11.ts] ++export {}; ++ ++declare var dec: any; ++ ++@dec ++class C { ++} ++ ++export { C }; ++ ++using after = null; ++ ++ ++//// [usingDeclarationsWithLegacyClassDecorators.11.js] ++System.register([], function (exports_1, context_1) { ++ "use strict"; ++ var C, after, env_1; ++ var __moduleName = context_1 && context_1.id; ++ return { ++ setters: [], ++ execute: function () { ++ C = /** @class */ (function () { ++ function C() { ++ } ++ C = __decorate([ ++ dec ++ ], C); ++ return C; ++ }()); ++ exports_1("C", C); ++ env_1 = { stack: [], error: void 0, hasError: false }; ++ try { ++ after = __addDisposableResource(env_1, null, false); ++ } ++ catch (e_1) { ++ env_1.error = e_1; ++ env_1.hasError = true; ++ } ++ finally { ++ __disposeResources(env_1); ++ } ++ } ++ }; ++}); +diff --git a/tests/baselines/reference/usingDeclarationsWithLegacyClassDecorators.11(module=system,target=esnext).js b/tests/baselines/reference/usingDeclarationsWithLegacyClassDecorators.11(module=system,target=esnext).js +new file mode 100644 +index 000000000..a4bb104e3 +--- /dev/null ++++ b/tests/baselines/reference/usingDeclarationsWithLegacyClassDecorators.11(module=system,target=esnext).js +@@ -0,0 +1,34 @@ ++//// [tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsWithLegacyClassDecorators.11.ts] //// ++ ++//// [usingDeclarationsWithLegacyClassDecorators.11.ts] ++export {}; ++ ++declare var dec: any; ++ ++@dec ++class C { ++} ++ ++export { C }; ++ ++using after = null; ++ ++ ++//// [usingDeclarationsWithLegacyClassDecorators.11.js] ++System.register([], function (exports_1, context_1) { ++ "use strict"; ++ var C, after; ++ var __moduleName = context_1 && context_1.id; ++ return { ++ setters: [], ++ execute: function () { ++ C = class C { ++ }; ++ exports_1("C", C); ++ exports_1("C", C = __decorate([ ++ dec ++ ], C)); ++ using after_1 = after = null; ++ } ++ }; ++}); +diff --git a/tests/baselines/reference/usingDeclarationsWithLegacyClassDecorators.12(module=commonjs,target=es2015).js b/tests/baselines/reference/usingDeclarationsWithLegacyClassDecorators.12(module=commonjs,target=es2015).js +new file mode 100644 +index 000000000..ab54db5b6 +--- /dev/null ++++ b/tests/baselines/reference/usingDeclarationsWithLegacyClassDecorators.12(module=commonjs,target=es2015).js +@@ -0,0 +1,38 @@ ++//// [tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsWithLegacyClassDecorators.12.ts] //// ++ ++//// [usingDeclarationsWithLegacyClassDecorators.12.ts] ++export {}; ++ ++declare var dec: any; ++ ++@dec ++class C { ++} ++ ++export { C as D }; ++ ++using after = null; ++ ++ ++//// [usingDeclarationsWithLegacyClassDecorators.12.js] ++"use strict"; ++Object.defineProperty(exports, "__esModule", { value: true }); ++exports.D = void 0; ++let C = class C { ++}; ++exports.D = C; ++exports.D = C = __decorate([ ++ dec ++], C); ++var after; ++const env_1 = { stack: [], error: void 0, hasError: false }; ++try { ++ after = __addDisposableResource(env_1, null, false); ++} ++catch (e_1) { ++ env_1.error = e_1; ++ env_1.hasError = true; ++} ++finally { ++ __disposeResources(env_1); ++} +diff --git a/tests/baselines/reference/usingDeclarationsWithLegacyClassDecorators.12(module=commonjs,target=es5).js b/tests/baselines/reference/usingDeclarationsWithLegacyClassDecorators.12(module=commonjs,target=es5).js +new file mode 100644 +index 000000000..e33447c0b +--- /dev/null ++++ b/tests/baselines/reference/usingDeclarationsWithLegacyClassDecorators.12(module=commonjs,target=es5).js +@@ -0,0 +1,41 @@ ++//// [tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsWithLegacyClassDecorators.12.ts] //// ++ ++//// [usingDeclarationsWithLegacyClassDecorators.12.ts] ++export {}; ++ ++declare var dec: any; ++ ++@dec ++class C { ++} ++ ++export { C as D }; ++ ++using after = null; ++ ++ ++//// [usingDeclarationsWithLegacyClassDecorators.12.js] ++"use strict"; ++Object.defineProperty(exports, "__esModule", { value: true }); ++exports.D = void 0; ++var C = /** @class */ (function () { ++ function C() { ++ } ++ C = __decorate([ ++ dec ++ ], C); ++ return C; ++}()); ++exports.D = C; ++var after; ++var env_1 = { stack: [], error: void 0, hasError: false }; ++try { ++ after = __addDisposableResource(env_1, null, false); ++} ++catch (e_1) { ++ env_1.error = e_1; ++ env_1.hasError = true; ++} ++finally { ++ __disposeResources(env_1); ++} +diff --git a/tests/baselines/reference/usingDeclarationsWithLegacyClassDecorators.12(module=commonjs,target=esnext).js b/tests/baselines/reference/usingDeclarationsWithLegacyClassDecorators.12(module=commonjs,target=esnext).js +new file mode 100644 +index 000000000..75dce8b79 +--- /dev/null ++++ b/tests/baselines/reference/usingDeclarationsWithLegacyClassDecorators.12(module=commonjs,target=esnext).js +@@ -0,0 +1,27 @@ ++//// [tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsWithLegacyClassDecorators.12.ts] //// ++ ++//// [usingDeclarationsWithLegacyClassDecorators.12.ts] ++export {}; ++ ++declare var dec: any; ++ ++@dec ++class C { ++} ++ ++export { C as D }; ++ ++using after = null; ++ ++ ++//// [usingDeclarationsWithLegacyClassDecorators.12.js] ++"use strict"; ++Object.defineProperty(exports, "__esModule", { value: true }); ++exports.D = void 0; ++let C = class C { ++}; ++exports.D = C; ++exports.D = C = __decorate([ ++ dec ++], C); ++using after = null; +diff --git a/tests/baselines/reference/usingDeclarationsWithLegacyClassDecorators.12(module=esnext,target=es2015).js b/tests/baselines/reference/usingDeclarationsWithLegacyClassDecorators.12(module=esnext,target=es2015).js +new file mode 100644 +index 000000000..6a0dc9950 +--- /dev/null ++++ b/tests/baselines/reference/usingDeclarationsWithLegacyClassDecorators.12(module=esnext,target=es2015).js +@@ -0,0 +1,35 @@ ++//// [tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsWithLegacyClassDecorators.12.ts] //// ++ ++//// [usingDeclarationsWithLegacyClassDecorators.12.ts] ++export {}; ++ ++declare var dec: any; ++ ++@dec ++class C { ++} ++ ++export { C as D }; ++ ++using after = null; ++ ++ ++//// [usingDeclarationsWithLegacyClassDecorators.12.js] ++let C = class C { ++}; ++C = __decorate([ ++ dec ++], C); ++export { C as D }; ++var after; ++const env_1 = { stack: [], error: void 0, hasError: false }; ++try { ++ after = __addDisposableResource(env_1, null, false); ++} ++catch (e_1) { ++ env_1.error = e_1; ++ env_1.hasError = true; ++} ++finally { ++ __disposeResources(env_1); ++} +diff --git a/tests/baselines/reference/usingDeclarationsWithLegacyClassDecorators.12(module=esnext,target=es5).js b/tests/baselines/reference/usingDeclarationsWithLegacyClassDecorators.12(module=esnext,target=es5).js +new file mode 100644 +index 000000000..d9638676c +--- /dev/null ++++ b/tests/baselines/reference/usingDeclarationsWithLegacyClassDecorators.12(module=esnext,target=es5).js +@@ -0,0 +1,38 @@ ++//// [tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsWithLegacyClassDecorators.12.ts] //// ++ ++//// [usingDeclarationsWithLegacyClassDecorators.12.ts] ++export {}; ++ ++declare var dec: any; ++ ++@dec ++class C { ++} ++ ++export { C as D }; ++ ++using after = null; ++ ++ ++//// [usingDeclarationsWithLegacyClassDecorators.12.js] ++var C = /** @class */ (function () { ++ function C() { ++ } ++ C = __decorate([ ++ dec ++ ], C); ++ return C; ++}()); ++export { C as D }; ++var after; ++var env_1 = { stack: [], error: void 0, hasError: false }; ++try { ++ after = __addDisposableResource(env_1, null, false); ++} ++catch (e_1) { ++ env_1.error = e_1; ++ env_1.hasError = true; ++} ++finally { ++ __disposeResources(env_1); ++} +diff --git a/tests/baselines/reference/usingDeclarationsWithLegacyClassDecorators.12(module=esnext,target=esnext).js b/tests/baselines/reference/usingDeclarationsWithLegacyClassDecorators.12(module=esnext,target=esnext).js +new file mode 100644 +index 000000000..0cd3ea7c8 +--- /dev/null ++++ b/tests/baselines/reference/usingDeclarationsWithLegacyClassDecorators.12(module=esnext,target=esnext).js +@@ -0,0 +1,24 @@ ++//// [tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsWithLegacyClassDecorators.12.ts] //// ++ ++//// [usingDeclarationsWithLegacyClassDecorators.12.ts] ++export {}; ++ ++declare var dec: any; ++ ++@dec ++class C { ++} ++ ++export { C as D }; ++ ++using after = null; ++ ++ ++//// [usingDeclarationsWithLegacyClassDecorators.12.js] ++let C = class C { ++}; ++C = __decorate([ ++ dec ++], C); ++export { C as D }; ++using after = null; +diff --git a/tests/baselines/reference/usingDeclarationsWithLegacyClassDecorators.12(module=system,target=es2015).js b/tests/baselines/reference/usingDeclarationsWithLegacyClassDecorators.12(module=system,target=es2015).js +new file mode 100644 +index 000000000..ef4e15941 +--- /dev/null ++++ b/tests/baselines/reference/usingDeclarationsWithLegacyClassDecorators.12(module=system,target=es2015).js +@@ -0,0 +1,44 @@ ++//// [tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsWithLegacyClassDecorators.12.ts] //// ++ ++//// [usingDeclarationsWithLegacyClassDecorators.12.ts] ++export {}; ++ ++declare var dec: any; ++ ++@dec ++class C { ++} ++ ++export { C as D }; ++ ++using after = null; ++ ++ ++//// [usingDeclarationsWithLegacyClassDecorators.12.js] ++System.register([], function (exports_1, context_1) { ++ "use strict"; ++ var C, after, env_1; ++ var __moduleName = context_1 && context_1.id; ++ return { ++ setters: [], ++ execute: function () { ++ C = class C { ++ }; ++ exports_1("D", C); ++ exports_1("D", C = __decorate([ ++ dec ++ ], C)); ++ env_1 = { stack: [], error: void 0, hasError: false }; ++ try { ++ after = __addDisposableResource(env_1, null, false); ++ } ++ catch (e_1) { ++ env_1.error = e_1; ++ env_1.hasError = true; ++ } ++ finally { ++ __disposeResources(env_1); ++ } ++ } ++ }; ++}); +diff --git a/tests/baselines/reference/usingDeclarationsWithLegacyClassDecorators.12(module=system,target=es5).js b/tests/baselines/reference/usingDeclarationsWithLegacyClassDecorators.12(module=system,target=es5).js +new file mode 100644 +index 000000000..11bc49f80 +--- /dev/null ++++ b/tests/baselines/reference/usingDeclarationsWithLegacyClassDecorators.12(module=system,target=es5).js +@@ -0,0 +1,47 @@ ++//// [tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsWithLegacyClassDecorators.12.ts] //// ++ ++//// [usingDeclarationsWithLegacyClassDecorators.12.ts] ++export {}; ++ ++declare var dec: any; ++ ++@dec ++class C { ++} ++ ++export { C as D }; ++ ++using after = null; ++ ++ ++//// [usingDeclarationsWithLegacyClassDecorators.12.js] ++System.register([], function (exports_1, context_1) { ++ "use strict"; ++ var C, after, env_1; ++ var __moduleName = context_1 && context_1.id; ++ return { ++ setters: [], ++ execute: function () { ++ C = /** @class */ (function () { ++ function C() { ++ } ++ C = __decorate([ ++ dec ++ ], C); ++ return C; ++ }()); ++ exports_1("D", C); ++ env_1 = { stack: [], error: void 0, hasError: false }; ++ try { ++ after = __addDisposableResource(env_1, null, false); ++ } ++ catch (e_1) { ++ env_1.error = e_1; ++ env_1.hasError = true; ++ } ++ finally { ++ __disposeResources(env_1); ++ } ++ } ++ }; ++}); +diff --git a/tests/baselines/reference/usingDeclarationsWithLegacyClassDecorators.12(module=system,target=esnext).js b/tests/baselines/reference/usingDeclarationsWithLegacyClassDecorators.12(module=system,target=esnext).js +new file mode 100644 +index 000000000..1ca8cc0ad +--- /dev/null ++++ b/tests/baselines/reference/usingDeclarationsWithLegacyClassDecorators.12(module=system,target=esnext).js +@@ -0,0 +1,34 @@ ++//// [tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsWithLegacyClassDecorators.12.ts] //// ++ ++//// [usingDeclarationsWithLegacyClassDecorators.12.ts] ++export {}; ++ ++declare var dec: any; ++ ++@dec ++class C { ++} ++ ++export { C as D }; ++ ++using after = null; ++ ++ ++//// [usingDeclarationsWithLegacyClassDecorators.12.js] ++System.register([], function (exports_1, context_1) { ++ "use strict"; ++ var C, after; ++ var __moduleName = context_1 && context_1.id; ++ return { ++ setters: [], ++ execute: function () { ++ C = class C { ++ }; ++ exports_1("D", C); ++ exports_1("D", C = __decorate([ ++ dec ++ ], C)); ++ using after_1 = after = null; ++ } ++ }; ++}); +diff --git a/tests/baselines/reference/usingDeclarationsWithLegacyClassDecorators.2(module=commonjs,target=es2015).js b/tests/baselines/reference/usingDeclarationsWithLegacyClassDecorators.2(module=commonjs,target=es2015).js +new file mode 100644 +index 000000000..110e2d068 +--- /dev/null ++++ b/tests/baselines/reference/usingDeclarationsWithLegacyClassDecorators.2(module=commonjs,target=es2015).js +@@ -0,0 +1,35 @@ ++//// [tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsWithLegacyClassDecorators.2.ts] //// ++ ++//// [usingDeclarationsWithLegacyClassDecorators.2.ts] ++export {}; ++ ++declare var dec: any; ++ ++using before = null; ++ ++@dec ++export class C { ++} ++ ++ ++//// [usingDeclarationsWithLegacyClassDecorators.2.js] ++"use strict"; ++Object.defineProperty(exports, "__esModule", { value: true }); ++exports.C = void 0; ++var before, C; ++const env_1 = { stack: [], error: void 0, hasError: false }; ++try { ++ before = __addDisposableResource(env_1, null, false); ++ exports.C = C = class C { ++ }; ++ exports.C = C = __decorate([ ++ dec ++ ], C); ++} ++catch (e_1) { ++ env_1.error = e_1; ++ env_1.hasError = true; ++} ++finally { ++ __disposeResources(env_1); ++} +diff --git a/tests/baselines/reference/usingDeclarationsWithLegacyClassDecorators.2(module=commonjs,target=es5).js b/tests/baselines/reference/usingDeclarationsWithLegacyClassDecorators.2(module=commonjs,target=es5).js +new file mode 100644 +index 000000000..dac6a5c99 +--- /dev/null ++++ b/tests/baselines/reference/usingDeclarationsWithLegacyClassDecorators.2(module=commonjs,target=es5).js +@@ -0,0 +1,38 @@ ++//// [tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsWithLegacyClassDecorators.2.ts] //// ++ ++//// [usingDeclarationsWithLegacyClassDecorators.2.ts] ++export {}; ++ ++declare var dec: any; ++ ++using before = null; ++ ++@dec ++export class C { ++} ++ ++ ++//// [usingDeclarationsWithLegacyClassDecorators.2.js] ++"use strict"; ++Object.defineProperty(exports, "__esModule", { value: true }); ++exports.C = void 0; ++var before, C; ++var env_1 = { stack: [], error: void 0, hasError: false }; ++try { ++ before = __addDisposableResource(env_1, null, false); ++ exports.C = C = /** @class */ (function () { ++ function C() { ++ } ++ C = __decorate([ ++ dec ++ ], C); ++ return C; ++ }()); ++} ++catch (e_1) { ++ env_1.error = e_1; ++ env_1.hasError = true; ++} ++finally { ++ __disposeResources(env_1); ++} +diff --git a/tests/baselines/reference/usingDeclarationsWithLegacyClassDecorators.2(module=commonjs,target=esnext).js b/tests/baselines/reference/usingDeclarationsWithLegacyClassDecorators.2(module=commonjs,target=esnext).js +new file mode 100644 +index 000000000..f0cbe114e +--- /dev/null ++++ b/tests/baselines/reference/usingDeclarationsWithLegacyClassDecorators.2(module=commonjs,target=esnext).js +@@ -0,0 +1,25 @@ ++//// [tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsWithLegacyClassDecorators.2.ts] //// ++ ++//// [usingDeclarationsWithLegacyClassDecorators.2.ts] ++export {}; ++ ++declare var dec: any; ++ ++using before = null; ++ ++@dec ++export class C { ++} ++ ++ ++//// [usingDeclarationsWithLegacyClassDecorators.2.js] ++"use strict"; ++Object.defineProperty(exports, "__esModule", { value: true }); ++exports.C = void 0; ++using before = null; ++let C = class C { ++}; ++exports.C = C; ++exports.C = C = __decorate([ ++ dec ++], C); +diff --git a/tests/baselines/reference/usingDeclarationsWithLegacyClassDecorators.2(module=esnext,target=es2015).js b/tests/baselines/reference/usingDeclarationsWithLegacyClassDecorators.2(module=esnext,target=es2015).js +new file mode 100644 +index 000000000..8643cb721 +--- /dev/null ++++ b/tests/baselines/reference/usingDeclarationsWithLegacyClassDecorators.2(module=esnext,target=es2015).js +@@ -0,0 +1,33 @@ ++//// [tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsWithLegacyClassDecorators.2.ts] //// ++ ++//// [usingDeclarationsWithLegacyClassDecorators.2.ts] ++export {}; ++ ++declare var dec: any; ++ ++using before = null; ++ ++@dec ++export class C { ++} ++ ++ ++//// [usingDeclarationsWithLegacyClassDecorators.2.js] ++export { C }; ++var before, C; ++const env_1 = { stack: [], error: void 0, hasError: false }; ++try { ++ before = __addDisposableResource(env_1, null, false); ++ C = class C { ++ }; ++ C = __decorate([ ++ dec ++ ], C); ++} ++catch (e_1) { ++ env_1.error = e_1; ++ env_1.hasError = true; ++} ++finally { ++ __disposeResources(env_1); ++} +diff --git a/tests/baselines/reference/usingDeclarationsWithLegacyClassDecorators.2(module=esnext,target=es5).js b/tests/baselines/reference/usingDeclarationsWithLegacyClassDecorators.2(module=esnext,target=es5).js +new file mode 100644 +index 000000000..8521f3d05 +--- /dev/null ++++ b/tests/baselines/reference/usingDeclarationsWithLegacyClassDecorators.2(module=esnext,target=es5).js +@@ -0,0 +1,36 @@ ++//// [tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsWithLegacyClassDecorators.2.ts] //// ++ ++//// [usingDeclarationsWithLegacyClassDecorators.2.ts] ++export {}; ++ ++declare var dec: any; ++ ++using before = null; ++ ++@dec ++export class C { ++} ++ ++ ++//// [usingDeclarationsWithLegacyClassDecorators.2.js] ++export { C }; ++var before, C; ++var env_1 = { stack: [], error: void 0, hasError: false }; ++try { ++ before = __addDisposableResource(env_1, null, false); ++ C = /** @class */ (function () { ++ function C() { ++ } ++ C = __decorate([ ++ dec ++ ], C); ++ return C; ++ }()); ++} ++catch (e_1) { ++ env_1.error = e_1; ++ env_1.hasError = true; ++} ++finally { ++ __disposeResources(env_1); ++} +diff --git a/tests/baselines/reference/usingDeclarationsWithLegacyClassDecorators.2(module=esnext,target=esnext).js b/tests/baselines/reference/usingDeclarationsWithLegacyClassDecorators.2(module=esnext,target=esnext).js +new file mode 100644 +index 000000000..8d3fe7c20 +--- /dev/null ++++ b/tests/baselines/reference/usingDeclarationsWithLegacyClassDecorators.2(module=esnext,target=esnext).js +@@ -0,0 +1,22 @@ ++//// [tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsWithLegacyClassDecorators.2.ts] //// ++ ++//// [usingDeclarationsWithLegacyClassDecorators.2.ts] ++export {}; ++ ++declare var dec: any; ++ ++using before = null; ++ ++@dec ++export class C { ++} ++ ++ ++//// [usingDeclarationsWithLegacyClassDecorators.2.js] ++using before = null; ++let C = class C { ++}; ++C = __decorate([ ++ dec ++], C); ++export { C }; +diff --git a/tests/baselines/reference/usingDeclarationsWithLegacyClassDecorators.2(module=system,target=es2015).js b/tests/baselines/reference/usingDeclarationsWithLegacyClassDecorators.2(module=system,target=es2015).js +new file mode 100644 +index 000000000..e32aea12a +--- /dev/null ++++ b/tests/baselines/reference/usingDeclarationsWithLegacyClassDecorators.2(module=system,target=es2015).js +@@ -0,0 +1,41 @@ ++//// [tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsWithLegacyClassDecorators.2.ts] //// ++ ++//// [usingDeclarationsWithLegacyClassDecorators.2.ts] ++export {}; ++ ++declare var dec: any; ++ ++using before = null; ++ ++@dec ++export class C { ++} ++ ++ ++//// [usingDeclarationsWithLegacyClassDecorators.2.js] ++System.register([], function (exports_1, context_1) { ++ "use strict"; ++ var before, C, env_1; ++ var __moduleName = context_1 && context_1.id; ++ return { ++ setters: [], ++ execute: function () { ++ env_1 = { stack: [], error: void 0, hasError: false }; ++ try { ++ before = __addDisposableResource(env_1, null, false); ++ exports_1("C", C = class C { ++ }); ++ exports_1("C", C = __decorate([ ++ dec ++ ], C)); ++ } ++ catch (e_1) { ++ env_1.error = e_1; ++ env_1.hasError = true; ++ } ++ finally { ++ __disposeResources(env_1); ++ } ++ } ++ }; ++}); +diff --git a/tests/baselines/reference/usingDeclarationsWithLegacyClassDecorators.2(module=system,target=es5).js b/tests/baselines/reference/usingDeclarationsWithLegacyClassDecorators.2(module=system,target=es5).js +new file mode 100644 +index 000000000..3564d3932 +--- /dev/null ++++ b/tests/baselines/reference/usingDeclarationsWithLegacyClassDecorators.2(module=system,target=es5).js +@@ -0,0 +1,44 @@ ++//// [tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsWithLegacyClassDecorators.2.ts] //// ++ ++//// [usingDeclarationsWithLegacyClassDecorators.2.ts] ++export {}; ++ ++declare var dec: any; ++ ++using before = null; ++ ++@dec ++export class C { ++} ++ ++ ++//// [usingDeclarationsWithLegacyClassDecorators.2.js] ++System.register([], function (exports_1, context_1) { ++ "use strict"; ++ var before, C, env_1; ++ var __moduleName = context_1 && context_1.id; ++ return { ++ setters: [], ++ execute: function () { ++ env_1 = { stack: [], error: void 0, hasError: false }; ++ try { ++ before = __addDisposableResource(env_1, null, false); ++ exports_1("C", C = /** @class */ (function () { ++ function C() { ++ } ++ C = __decorate([ ++ dec ++ ], C); ++ return C; ++ }())); ++ } ++ catch (e_1) { ++ env_1.error = e_1; ++ env_1.hasError = true; ++ } ++ finally { ++ __disposeResources(env_1); ++ } ++ } ++ }; ++}); +diff --git a/tests/baselines/reference/usingDeclarationsWithLegacyClassDecorators.2(module=system,target=esnext).js b/tests/baselines/reference/usingDeclarationsWithLegacyClassDecorators.2(module=system,target=esnext).js +new file mode 100644 +index 000000000..2832750c6 +--- /dev/null ++++ b/tests/baselines/reference/usingDeclarationsWithLegacyClassDecorators.2(module=system,target=esnext).js +@@ -0,0 +1,32 @@ ++//// [tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsWithLegacyClassDecorators.2.ts] //// ++ ++//// [usingDeclarationsWithLegacyClassDecorators.2.ts] ++export {}; ++ ++declare var dec: any; ++ ++using before = null; ++ ++@dec ++export class C { ++} ++ ++ ++//// [usingDeclarationsWithLegacyClassDecorators.2.js] ++System.register([], function (exports_1, context_1) { ++ "use strict"; ++ var before, C; ++ var __moduleName = context_1 && context_1.id; ++ return { ++ setters: [], ++ execute: function () { ++ using before_1 = before = null; ++ C = class C { ++ }; ++ exports_1("C", C); ++ exports_1("C", C = __decorate([ ++ dec ++ ], C)); ++ } ++ }; ++}); +diff --git a/tests/baselines/reference/usingDeclarationsWithLegacyClassDecorators.3(module=commonjs,target=es2015).js b/tests/baselines/reference/usingDeclarationsWithLegacyClassDecorators.3(module=commonjs,target=es2015).js +new file mode 100644 +index 000000000..24b99f7ec +--- /dev/null ++++ b/tests/baselines/reference/usingDeclarationsWithLegacyClassDecorators.3(module=commonjs,target=es2015).js +@@ -0,0 +1,36 @@ ++//// [tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsWithLegacyClassDecorators.3.ts] //// ++ ++//// [usingDeclarationsWithLegacyClassDecorators.3.ts] ++export {}; ++ ++declare var dec: any; ++ ++using before = null; ++ ++@dec ++export default class C { ++} ++ ++ ++//// [usingDeclarationsWithLegacyClassDecorators.3.js] ++"use strict"; ++Object.defineProperty(exports, "__esModule", { value: true }); ++exports.default = void 0; ++var before, C, _default; ++const env_1 = { stack: [], error: void 0, hasError: false }; ++try { ++ before = __addDisposableResource(env_1, null, false); ++ C = class C { ++ }; ++ C = __decorate([ ++ dec ++ ], C); ++ exports.default = _default = C; ++} ++catch (e_1) { ++ env_1.error = e_1; ++ env_1.hasError = true; ++} ++finally { ++ __disposeResources(env_1); ++} +diff --git a/tests/baselines/reference/usingDeclarationsWithLegacyClassDecorators.3(module=commonjs,target=es5).js b/tests/baselines/reference/usingDeclarationsWithLegacyClassDecorators.3(module=commonjs,target=es5).js +new file mode 100644 +index 000000000..1ad2385ac +--- /dev/null ++++ b/tests/baselines/reference/usingDeclarationsWithLegacyClassDecorators.3(module=commonjs,target=es5).js +@@ -0,0 +1,39 @@ ++//// [tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsWithLegacyClassDecorators.3.ts] //// ++ ++//// [usingDeclarationsWithLegacyClassDecorators.3.ts] ++export {}; ++ ++declare var dec: any; ++ ++using before = null; ++ ++@dec ++export default class C { ++} ++ ++ ++//// [usingDeclarationsWithLegacyClassDecorators.3.js] ++"use strict"; ++Object.defineProperty(exports, "__esModule", { value: true }); ++exports.default = void 0; ++var before, C, _default; ++var env_1 = { stack: [], error: void 0, hasError: false }; ++try { ++ before = __addDisposableResource(env_1, null, false); ++ C = /** @class */ (function () { ++ function C() { ++ } ++ C = __decorate([ ++ dec ++ ], C); ++ return C; ++ }()); ++ exports.default = _default = C; ++} ++catch (e_1) { ++ env_1.error = e_1; ++ env_1.hasError = true; ++} ++finally { ++ __disposeResources(env_1); ++} +diff --git a/tests/baselines/reference/usingDeclarationsWithLegacyClassDecorators.3(module=commonjs,target=esnext).js b/tests/baselines/reference/usingDeclarationsWithLegacyClassDecorators.3(module=commonjs,target=esnext).js +new file mode 100644 +index 000000000..8f18c7d48 +--- /dev/null ++++ b/tests/baselines/reference/usingDeclarationsWithLegacyClassDecorators.3(module=commonjs,target=esnext).js +@@ -0,0 +1,24 @@ ++//// [tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsWithLegacyClassDecorators.3.ts] //// ++ ++//// [usingDeclarationsWithLegacyClassDecorators.3.ts] ++export {}; ++ ++declare var dec: any; ++ ++using before = null; ++ ++@dec ++export default class C { ++} ++ ++ ++//// [usingDeclarationsWithLegacyClassDecorators.3.js] ++"use strict"; ++Object.defineProperty(exports, "__esModule", { value: true }); ++using before = null; ++let C = class C { ++}; ++C = __decorate([ ++ dec ++], C); ++exports.default = C; +diff --git a/tests/baselines/reference/usingDeclarationsWithLegacyClassDecorators.3(module=esnext,target=es2015).js b/tests/baselines/reference/usingDeclarationsWithLegacyClassDecorators.3(module=esnext,target=es2015).js +new file mode 100644 +index 000000000..dc4b8a751 +--- /dev/null ++++ b/tests/baselines/reference/usingDeclarationsWithLegacyClassDecorators.3(module=esnext,target=es2015).js +@@ -0,0 +1,34 @@ ++//// [tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsWithLegacyClassDecorators.3.ts] //// ++ ++//// [usingDeclarationsWithLegacyClassDecorators.3.ts] ++export {}; ++ ++declare var dec: any; ++ ++using before = null; ++ ++@dec ++export default class C { ++} ++ ++ ++//// [usingDeclarationsWithLegacyClassDecorators.3.js] ++export { _default as default }; ++var before, C, _default; ++const env_1 = { stack: [], error: void 0, hasError: false }; ++try { ++ before = __addDisposableResource(env_1, null, false); ++ C = class C { ++ }; ++ C = __decorate([ ++ dec ++ ], C); ++ _default = C; ++} ++catch (e_1) { ++ env_1.error = e_1; ++ env_1.hasError = true; ++} ++finally { ++ __disposeResources(env_1); ++} +diff --git a/tests/baselines/reference/usingDeclarationsWithLegacyClassDecorators.3(module=esnext,target=es5).js b/tests/baselines/reference/usingDeclarationsWithLegacyClassDecorators.3(module=esnext,target=es5).js +new file mode 100644 +index 000000000..ea0edcd57 +--- /dev/null ++++ b/tests/baselines/reference/usingDeclarationsWithLegacyClassDecorators.3(module=esnext,target=es5).js +@@ -0,0 +1,37 @@ ++//// [tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsWithLegacyClassDecorators.3.ts] //// ++ ++//// [usingDeclarationsWithLegacyClassDecorators.3.ts] ++export {}; ++ ++declare var dec: any; ++ ++using before = null; ++ ++@dec ++export default class C { ++} ++ ++ ++//// [usingDeclarationsWithLegacyClassDecorators.3.js] ++export { _default as default }; ++var before, C, _default; ++var env_1 = { stack: [], error: void 0, hasError: false }; ++try { ++ before = __addDisposableResource(env_1, null, false); ++ C = /** @class */ (function () { ++ function C() { ++ } ++ C = __decorate([ ++ dec ++ ], C); ++ return C; ++ }()); ++ _default = C; ++} ++catch (e_1) { ++ env_1.error = e_1; ++ env_1.hasError = true; ++} ++finally { ++ __disposeResources(env_1); ++} +diff --git a/tests/baselines/reference/usingDeclarationsWithLegacyClassDecorators.3(module=esnext,target=esnext).js b/tests/baselines/reference/usingDeclarationsWithLegacyClassDecorators.3(module=esnext,target=esnext).js +new file mode 100644 +index 000000000..3d51ccac1 +--- /dev/null ++++ b/tests/baselines/reference/usingDeclarationsWithLegacyClassDecorators.3(module=esnext,target=esnext).js +@@ -0,0 +1,22 @@ ++//// [tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsWithLegacyClassDecorators.3.ts] //// ++ ++//// [usingDeclarationsWithLegacyClassDecorators.3.ts] ++export {}; ++ ++declare var dec: any; ++ ++using before = null; ++ ++@dec ++export default class C { ++} ++ ++ ++//// [usingDeclarationsWithLegacyClassDecorators.3.js] ++using before = null; ++let C = class C { ++}; ++C = __decorate([ ++ dec ++], C); ++export default C; +diff --git a/tests/baselines/reference/usingDeclarationsWithLegacyClassDecorators.3(module=system,target=es2015).js b/tests/baselines/reference/usingDeclarationsWithLegacyClassDecorators.3(module=system,target=es2015).js +new file mode 100644 +index 000000000..7dc57efd1 +--- /dev/null ++++ b/tests/baselines/reference/usingDeclarationsWithLegacyClassDecorators.3(module=system,target=es2015).js +@@ -0,0 +1,42 @@ ++//// [tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsWithLegacyClassDecorators.3.ts] //// ++ ++//// [usingDeclarationsWithLegacyClassDecorators.3.ts] ++export {}; ++ ++declare var dec: any; ++ ++using before = null; ++ ++@dec ++export default class C { ++} ++ ++ ++//// [usingDeclarationsWithLegacyClassDecorators.3.js] ++System.register([], function (exports_1, context_1) { ++ "use strict"; ++ var before, C, _default, env_1; ++ var __moduleName = context_1 && context_1.id; ++ return { ++ setters: [], ++ execute: function () { ++ env_1 = { stack: [], error: void 0, hasError: false }; ++ try { ++ before = __addDisposableResource(env_1, null, false); ++ C = class C { ++ }; ++ C = __decorate([ ++ dec ++ ], C); ++ exports_1("default", _default = C); ++ } ++ catch (e_1) { ++ env_1.error = e_1; ++ env_1.hasError = true; ++ } ++ finally { ++ __disposeResources(env_1); ++ } ++ } ++ }; ++}); +diff --git a/tests/baselines/reference/usingDeclarationsWithLegacyClassDecorators.3(module=system,target=es5).js b/tests/baselines/reference/usingDeclarationsWithLegacyClassDecorators.3(module=system,target=es5).js +new file mode 100644 +index 000000000..bf8059e19 +--- /dev/null ++++ b/tests/baselines/reference/usingDeclarationsWithLegacyClassDecorators.3(module=system,target=es5).js +@@ -0,0 +1,45 @@ ++//// [tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsWithLegacyClassDecorators.3.ts] //// ++ ++//// [usingDeclarationsWithLegacyClassDecorators.3.ts] ++export {}; ++ ++declare var dec: any; ++ ++using before = null; ++ ++@dec ++export default class C { ++} ++ ++ ++//// [usingDeclarationsWithLegacyClassDecorators.3.js] ++System.register([], function (exports_1, context_1) { ++ "use strict"; ++ var before, C, _default, env_1; ++ var __moduleName = context_1 && context_1.id; ++ return { ++ setters: [], ++ execute: function () { ++ env_1 = { stack: [], error: void 0, hasError: false }; ++ try { ++ before = __addDisposableResource(env_1, null, false); ++ C = /** @class */ (function () { ++ function C() { ++ } ++ C = __decorate([ ++ dec ++ ], C); ++ return C; ++ }()); ++ exports_1("default", _default = C); ++ } ++ catch (e_1) { ++ env_1.error = e_1; ++ env_1.hasError = true; ++ } ++ finally { ++ __disposeResources(env_1); ++ } ++ } ++ }; ++}); +diff --git a/tests/baselines/reference/usingDeclarationsWithLegacyClassDecorators.3(module=system,target=esnext).js b/tests/baselines/reference/usingDeclarationsWithLegacyClassDecorators.3(module=system,target=esnext).js +new file mode 100644 +index 000000000..88f54ce2d +--- /dev/null ++++ b/tests/baselines/reference/usingDeclarationsWithLegacyClassDecorators.3(module=system,target=esnext).js +@@ -0,0 +1,32 @@ ++//// [tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsWithLegacyClassDecorators.3.ts] //// ++ ++//// [usingDeclarationsWithLegacyClassDecorators.3.ts] ++export {}; ++ ++declare var dec: any; ++ ++using before = null; ++ ++@dec ++export default class C { ++} ++ ++ ++//// [usingDeclarationsWithLegacyClassDecorators.3.js] ++System.register([], function (exports_1, context_1) { ++ "use strict"; ++ var before, C; ++ var __moduleName = context_1 && context_1.id; ++ return { ++ setters: [], ++ execute: function () { ++ using before_1 = before = null; ++ C = class C { ++ }; ++ C = __decorate([ ++ dec ++ ], C); ++ exports_1("default", C); ++ } ++ }; ++}); +diff --git a/tests/baselines/reference/usingDeclarationsWithLegacyClassDecorators.4(module=commonjs,target=es2015).js b/tests/baselines/reference/usingDeclarationsWithLegacyClassDecorators.4(module=commonjs,target=es2015).js +new file mode 100644 +index 000000000..f53045026 +--- /dev/null ++++ b/tests/baselines/reference/usingDeclarationsWithLegacyClassDecorators.4(module=commonjs,target=es2015).js +@@ -0,0 +1,36 @@ ++//// [tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsWithLegacyClassDecorators.4.ts] //// ++ ++//// [usingDeclarationsWithLegacyClassDecorators.4.ts] ++export {}; ++ ++declare var dec: any; ++ ++using before = null; ++ ++@dec ++export default class { ++} ++ ++ ++//// [usingDeclarationsWithLegacyClassDecorators.4.js] ++"use strict"; ++Object.defineProperty(exports, "__esModule", { value: true }); ++exports.default = void 0; ++var before, default_1, _default; ++const env_1 = { stack: [], error: void 0, hasError: false }; ++try { ++ before = __addDisposableResource(env_1, null, false); ++ default_1 = class { ++ }; ++ default_1 = __decorate([ ++ dec ++ ], default_1); ++ exports.default = _default = default_1; ++} ++catch (e_1) { ++ env_1.error = e_1; ++ env_1.hasError = true; ++} ++finally { ++ __disposeResources(env_1); ++} +diff --git a/tests/baselines/reference/usingDeclarationsWithLegacyClassDecorators.4(module=commonjs,target=es5).js b/tests/baselines/reference/usingDeclarationsWithLegacyClassDecorators.4(module=commonjs,target=es5).js +new file mode 100644 +index 000000000..ea32db068 +--- /dev/null ++++ b/tests/baselines/reference/usingDeclarationsWithLegacyClassDecorators.4(module=commonjs,target=es5).js +@@ -0,0 +1,39 @@ ++//// [tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsWithLegacyClassDecorators.4.ts] //// ++ ++//// [usingDeclarationsWithLegacyClassDecorators.4.ts] ++export {}; ++ ++declare var dec: any; ++ ++using before = null; ++ ++@dec ++export default class { ++} ++ ++ ++//// [usingDeclarationsWithLegacyClassDecorators.4.js] ++"use strict"; ++Object.defineProperty(exports, "__esModule", { value: true }); ++exports.default = void 0; ++var before, default_1, _default; ++var env_1 = { stack: [], error: void 0, hasError: false }; ++try { ++ before = __addDisposableResource(env_1, null, false); ++ default_1 = /** @class */ (function () { ++ function default_1() { ++ } ++ default_1 = __decorate([ ++ dec ++ ], default_1); ++ return default_1; ++ }()); ++ exports.default = _default = default_1; ++} ++catch (e_1) { ++ env_1.error = e_1; ++ env_1.hasError = true; ++} ++finally { ++ __disposeResources(env_1); ++} +diff --git a/tests/baselines/reference/usingDeclarationsWithLegacyClassDecorators.4(module=commonjs,target=esnext).js b/tests/baselines/reference/usingDeclarationsWithLegacyClassDecorators.4(module=commonjs,target=esnext).js +new file mode 100644 +index 000000000..09e23b6ac +--- /dev/null ++++ b/tests/baselines/reference/usingDeclarationsWithLegacyClassDecorators.4(module=commonjs,target=esnext).js +@@ -0,0 +1,24 @@ ++//// [tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsWithLegacyClassDecorators.4.ts] //// ++ ++//// [usingDeclarationsWithLegacyClassDecorators.4.ts] ++export {}; ++ ++declare var dec: any; ++ ++using before = null; ++ ++@dec ++export default class { ++} ++ ++ ++//// [usingDeclarationsWithLegacyClassDecorators.4.js] ++"use strict"; ++Object.defineProperty(exports, "__esModule", { value: true }); ++using before = null; ++let default_1 = class { ++}; ++default_1 = __decorate([ ++ dec ++], default_1); ++exports.default = default_1; +diff --git a/tests/baselines/reference/usingDeclarationsWithLegacyClassDecorators.4(module=esnext,target=es2015).js b/tests/baselines/reference/usingDeclarationsWithLegacyClassDecorators.4(module=esnext,target=es2015).js +new file mode 100644 +index 000000000..78d86eeb2 +--- /dev/null ++++ b/tests/baselines/reference/usingDeclarationsWithLegacyClassDecorators.4(module=esnext,target=es2015).js +@@ -0,0 +1,34 @@ ++//// [tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsWithLegacyClassDecorators.4.ts] //// ++ ++//// [usingDeclarationsWithLegacyClassDecorators.4.ts] ++export {}; ++ ++declare var dec: any; ++ ++using before = null; ++ ++@dec ++export default class { ++} ++ ++ ++//// [usingDeclarationsWithLegacyClassDecorators.4.js] ++export { _default as default }; ++var before, default_1, _default; ++const env_1 = { stack: [], error: void 0, hasError: false }; ++try { ++ before = __addDisposableResource(env_1, null, false); ++ default_1 = class { ++ }; ++ default_1 = __decorate([ ++ dec ++ ], default_1); ++ _default = default_1; ++} ++catch (e_1) { ++ env_1.error = e_1; ++ env_1.hasError = true; ++} ++finally { ++ __disposeResources(env_1); ++} +diff --git a/tests/baselines/reference/usingDeclarationsWithLegacyClassDecorators.4(module=esnext,target=es5).js b/tests/baselines/reference/usingDeclarationsWithLegacyClassDecorators.4(module=esnext,target=es5).js +new file mode 100644 +index 000000000..65fd9bcfd +--- /dev/null ++++ b/tests/baselines/reference/usingDeclarationsWithLegacyClassDecorators.4(module=esnext,target=es5).js +@@ -0,0 +1,37 @@ ++//// [tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsWithLegacyClassDecorators.4.ts] //// ++ ++//// [usingDeclarationsWithLegacyClassDecorators.4.ts] ++export {}; ++ ++declare var dec: any; ++ ++using before = null; ++ ++@dec ++export default class { ++} ++ ++ ++//// [usingDeclarationsWithLegacyClassDecorators.4.js] ++export { _default as default }; ++var before, default_1, _default; ++var env_1 = { stack: [], error: void 0, hasError: false }; ++try { ++ before = __addDisposableResource(env_1, null, false); ++ default_1 = /** @class */ (function () { ++ function default_1() { ++ } ++ default_1 = __decorate([ ++ dec ++ ], default_1); ++ return default_1; ++ }()); ++ _default = default_1; ++} ++catch (e_1) { ++ env_1.error = e_1; ++ env_1.hasError = true; ++} ++finally { ++ __disposeResources(env_1); ++} +diff --git a/tests/baselines/reference/usingDeclarationsWithLegacyClassDecorators.4(module=esnext,target=esnext).js b/tests/baselines/reference/usingDeclarationsWithLegacyClassDecorators.4(module=esnext,target=esnext).js +new file mode 100644 +index 000000000..4aa174e2f +--- /dev/null ++++ b/tests/baselines/reference/usingDeclarationsWithLegacyClassDecorators.4(module=esnext,target=esnext).js +@@ -0,0 +1,22 @@ ++//// [tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsWithLegacyClassDecorators.4.ts] //// ++ ++//// [usingDeclarationsWithLegacyClassDecorators.4.ts] ++export {}; ++ ++declare var dec: any; ++ ++using before = null; ++ ++@dec ++export default class { ++} ++ ++ ++//// [usingDeclarationsWithLegacyClassDecorators.4.js] ++using before = null; ++let default_1 = class { ++}; ++default_1 = __decorate([ ++ dec ++], default_1); ++export default default_1; +diff --git a/tests/baselines/reference/usingDeclarationsWithLegacyClassDecorators.4(module=system,target=es2015).js b/tests/baselines/reference/usingDeclarationsWithLegacyClassDecorators.4(module=system,target=es2015).js +new file mode 100644 +index 000000000..44c3493d3 +--- /dev/null ++++ b/tests/baselines/reference/usingDeclarationsWithLegacyClassDecorators.4(module=system,target=es2015).js +@@ -0,0 +1,42 @@ ++//// [tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsWithLegacyClassDecorators.4.ts] //// ++ ++//// [usingDeclarationsWithLegacyClassDecorators.4.ts] ++export {}; ++ ++declare var dec: any; ++ ++using before = null; ++ ++@dec ++export default class { ++} ++ ++ ++//// [usingDeclarationsWithLegacyClassDecorators.4.js] ++System.register([], function (exports_1, context_1) { ++ "use strict"; ++ var before, default_1, _default, env_1; ++ var __moduleName = context_1 && context_1.id; ++ return { ++ setters: [], ++ execute: function () { ++ env_1 = { stack: [], error: void 0, hasError: false }; ++ try { ++ before = __addDisposableResource(env_1, null, false); ++ default_1 = class { ++ }; ++ default_1 = __decorate([ ++ dec ++ ], default_1); ++ exports_1("default", _default = default_1); ++ } ++ catch (e_1) { ++ env_1.error = e_1; ++ env_1.hasError = true; ++ } ++ finally { ++ __disposeResources(env_1); ++ } ++ } ++ }; ++}); +diff --git a/tests/baselines/reference/usingDeclarationsWithLegacyClassDecorators.4(module=system,target=es5).js b/tests/baselines/reference/usingDeclarationsWithLegacyClassDecorators.4(module=system,target=es5).js +new file mode 100644 +index 000000000..e1eac3321 +--- /dev/null ++++ b/tests/baselines/reference/usingDeclarationsWithLegacyClassDecorators.4(module=system,target=es5).js +@@ -0,0 +1,45 @@ ++//// [tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsWithLegacyClassDecorators.4.ts] //// ++ ++//// [usingDeclarationsWithLegacyClassDecorators.4.ts] ++export {}; ++ ++declare var dec: any; ++ ++using before = null; ++ ++@dec ++export default class { ++} ++ ++ ++//// [usingDeclarationsWithLegacyClassDecorators.4.js] ++System.register([], function (exports_1, context_1) { ++ "use strict"; ++ var before, default_1, _default, env_1; ++ var __moduleName = context_1 && context_1.id; ++ return { ++ setters: [], ++ execute: function () { ++ env_1 = { stack: [], error: void 0, hasError: false }; ++ try { ++ before = __addDisposableResource(env_1, null, false); ++ default_1 = /** @class */ (function () { ++ function default_1() { ++ } ++ default_1 = __decorate([ ++ dec ++ ], default_1); ++ return default_1; ++ }()); ++ exports_1("default", _default = default_1); ++ } ++ catch (e_1) { ++ env_1.error = e_1; ++ env_1.hasError = true; ++ } ++ finally { ++ __disposeResources(env_1); ++ } ++ } ++ }; ++}); +diff --git a/tests/baselines/reference/usingDeclarationsWithLegacyClassDecorators.4(module=system,target=esnext).js b/tests/baselines/reference/usingDeclarationsWithLegacyClassDecorators.4(module=system,target=esnext).js +new file mode 100644 +index 000000000..494d32651 +--- /dev/null ++++ b/tests/baselines/reference/usingDeclarationsWithLegacyClassDecorators.4(module=system,target=esnext).js +@@ -0,0 +1,32 @@ ++//// [tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsWithLegacyClassDecorators.4.ts] //// ++ ++//// [usingDeclarationsWithLegacyClassDecorators.4.ts] ++export {}; ++ ++declare var dec: any; ++ ++using before = null; ++ ++@dec ++export default class { ++} ++ ++ ++//// [usingDeclarationsWithLegacyClassDecorators.4.js] ++System.register([], function (exports_1, context_1) { ++ "use strict"; ++ var before, default_1; ++ var __moduleName = context_1 && context_1.id; ++ return { ++ setters: [], ++ execute: function () { ++ using before_1 = before = null; ++ default_1 = class { ++ }; ++ default_1 = __decorate([ ++ dec ++ ], default_1); ++ exports_1("default", default_1); ++ } ++ }; ++}); +diff --git a/tests/baselines/reference/usingDeclarationsWithLegacyClassDecorators.5(module=commonjs,target=es2015).js b/tests/baselines/reference/usingDeclarationsWithLegacyClassDecorators.5(module=commonjs,target=es2015).js +new file mode 100644 +index 000000000..c5eaee612 +--- /dev/null ++++ b/tests/baselines/reference/usingDeclarationsWithLegacyClassDecorators.5(module=commonjs,target=es2015).js +@@ -0,0 +1,36 @@ ++//// [tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsWithLegacyClassDecorators.5.ts] //// ++ ++//// [usingDeclarationsWithLegacyClassDecorators.5.ts] ++export {}; ++ ++declare var dec: any; ++ ++using before = null; ++ ++@dec ++class C { ++} ++ ++export { C }; ++ ++//// [usingDeclarationsWithLegacyClassDecorators.5.js] ++"use strict"; ++Object.defineProperty(exports, "__esModule", { value: true }); ++exports.C = void 0; ++var before, C; ++const env_1 = { stack: [], error: void 0, hasError: false }; ++try { ++ before = __addDisposableResource(env_1, null, false); ++ exports.C = C = class C { ++ }; ++ exports.C = C = __decorate([ ++ dec ++ ], C); ++} ++catch (e_1) { ++ env_1.error = e_1; ++ env_1.hasError = true; ++} ++finally { ++ __disposeResources(env_1); ++} +diff --git a/tests/baselines/reference/usingDeclarationsWithLegacyClassDecorators.5(module=commonjs,target=es5).js b/tests/baselines/reference/usingDeclarationsWithLegacyClassDecorators.5(module=commonjs,target=es5).js +new file mode 100644 +index 000000000..12feede6b +--- /dev/null ++++ b/tests/baselines/reference/usingDeclarationsWithLegacyClassDecorators.5(module=commonjs,target=es5).js +@@ -0,0 +1,39 @@ ++//// [tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsWithLegacyClassDecorators.5.ts] //// ++ ++//// [usingDeclarationsWithLegacyClassDecorators.5.ts] ++export {}; ++ ++declare var dec: any; ++ ++using before = null; ++ ++@dec ++class C { ++} ++ ++export { C }; ++ ++//// [usingDeclarationsWithLegacyClassDecorators.5.js] ++"use strict"; ++Object.defineProperty(exports, "__esModule", { value: true }); ++exports.C = void 0; ++var before, C; ++var env_1 = { stack: [], error: void 0, hasError: false }; ++try { ++ before = __addDisposableResource(env_1, null, false); ++ exports.C = C = /** @class */ (function () { ++ function C() { ++ } ++ C = __decorate([ ++ dec ++ ], C); ++ return C; ++ }()); ++} ++catch (e_1) { ++ env_1.error = e_1; ++ env_1.hasError = true; ++} ++finally { ++ __disposeResources(env_1); ++} +diff --git a/tests/baselines/reference/usingDeclarationsWithLegacyClassDecorators.5(module=commonjs,target=esnext).js b/tests/baselines/reference/usingDeclarationsWithLegacyClassDecorators.5(module=commonjs,target=esnext).js +new file mode 100644 +index 000000000..3199317d1 +--- /dev/null ++++ b/tests/baselines/reference/usingDeclarationsWithLegacyClassDecorators.5(module=commonjs,target=esnext).js +@@ -0,0 +1,26 @@ ++//// [tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsWithLegacyClassDecorators.5.ts] //// ++ ++//// [usingDeclarationsWithLegacyClassDecorators.5.ts] ++export {}; ++ ++declare var dec: any; ++ ++using before = null; ++ ++@dec ++class C { ++} ++ ++export { C }; ++ ++//// [usingDeclarationsWithLegacyClassDecorators.5.js] ++"use strict"; ++Object.defineProperty(exports, "__esModule", { value: true }); ++exports.C = void 0; ++using before = null; ++let C = class C { ++}; ++exports.C = C; ++exports.C = C = __decorate([ ++ dec ++], C); +diff --git a/tests/baselines/reference/usingDeclarationsWithLegacyClassDecorators.5(module=esnext,target=es2015).js b/tests/baselines/reference/usingDeclarationsWithLegacyClassDecorators.5(module=esnext,target=es2015).js +new file mode 100644 +index 000000000..0d0242609 +--- /dev/null ++++ b/tests/baselines/reference/usingDeclarationsWithLegacyClassDecorators.5(module=esnext,target=es2015).js +@@ -0,0 +1,34 @@ ++//// [tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsWithLegacyClassDecorators.5.ts] //// ++ ++//// [usingDeclarationsWithLegacyClassDecorators.5.ts] ++export {}; ++ ++declare var dec: any; ++ ++using before = null; ++ ++@dec ++class C { ++} ++ ++export { C }; ++ ++//// [usingDeclarationsWithLegacyClassDecorators.5.js] ++export { C }; ++var before, C; ++const env_1 = { stack: [], error: void 0, hasError: false }; ++try { ++ before = __addDisposableResource(env_1, null, false); ++ C = class C { ++ }; ++ C = __decorate([ ++ dec ++ ], C); ++} ++catch (e_1) { ++ env_1.error = e_1; ++ env_1.hasError = true; ++} ++finally { ++ __disposeResources(env_1); ++} +diff --git a/tests/baselines/reference/usingDeclarationsWithLegacyClassDecorators.5(module=esnext,target=es5).js b/tests/baselines/reference/usingDeclarationsWithLegacyClassDecorators.5(module=esnext,target=es5).js +new file mode 100644 +index 000000000..999bdcc43 +--- /dev/null ++++ b/tests/baselines/reference/usingDeclarationsWithLegacyClassDecorators.5(module=esnext,target=es5).js +@@ -0,0 +1,37 @@ ++//// [tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsWithLegacyClassDecorators.5.ts] //// ++ ++//// [usingDeclarationsWithLegacyClassDecorators.5.ts] ++export {}; ++ ++declare var dec: any; ++ ++using before = null; ++ ++@dec ++class C { ++} ++ ++export { C }; ++ ++//// [usingDeclarationsWithLegacyClassDecorators.5.js] ++export { C }; ++var before, C; ++var env_1 = { stack: [], error: void 0, hasError: false }; ++try { ++ before = __addDisposableResource(env_1, null, false); ++ C = /** @class */ (function () { ++ function C() { ++ } ++ C = __decorate([ ++ dec ++ ], C); ++ return C; ++ }()); ++} ++catch (e_1) { ++ env_1.error = e_1; ++ env_1.hasError = true; ++} ++finally { ++ __disposeResources(env_1); ++} +diff --git a/tests/baselines/reference/usingDeclarationsWithLegacyClassDecorators.5(module=esnext,target=esnext).js b/tests/baselines/reference/usingDeclarationsWithLegacyClassDecorators.5(module=esnext,target=esnext).js +new file mode 100644 +index 000000000..f490f0b61 +--- /dev/null ++++ b/tests/baselines/reference/usingDeclarationsWithLegacyClassDecorators.5(module=esnext,target=esnext).js +@@ -0,0 +1,23 @@ ++//// [tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsWithLegacyClassDecorators.5.ts] //// ++ ++//// [usingDeclarationsWithLegacyClassDecorators.5.ts] ++export {}; ++ ++declare var dec: any; ++ ++using before = null; ++ ++@dec ++class C { ++} ++ ++export { C }; ++ ++//// [usingDeclarationsWithLegacyClassDecorators.5.js] ++using before = null; ++let C = class C { ++}; ++C = __decorate([ ++ dec ++], C); ++export { C }; +diff --git a/tests/baselines/reference/usingDeclarationsWithLegacyClassDecorators.5(module=system,target=es2015).js b/tests/baselines/reference/usingDeclarationsWithLegacyClassDecorators.5(module=system,target=es2015).js +new file mode 100644 +index 000000000..6b859f60e +--- /dev/null ++++ b/tests/baselines/reference/usingDeclarationsWithLegacyClassDecorators.5(module=system,target=es2015).js +@@ -0,0 +1,42 @@ ++//// [tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsWithLegacyClassDecorators.5.ts] //// ++ ++//// [usingDeclarationsWithLegacyClassDecorators.5.ts] ++export {}; ++ ++declare var dec: any; ++ ++using before = null; ++ ++@dec ++class C { ++} ++ ++export { C }; ++ ++//// [usingDeclarationsWithLegacyClassDecorators.5.js] ++System.register([], function (exports_1, context_1) { ++ "use strict"; ++ var before, C, env_1; ++ var __moduleName = context_1 && context_1.id; ++ return { ++ setters: [], ++ execute: function () { ++ env_1 = { stack: [], error: void 0, hasError: false }; ++ try { ++ before = __addDisposableResource(env_1, null, false); ++ exports_1("C", C = class C { ++ }); ++ exports_1("C", C = __decorate([ ++ dec ++ ], C)); ++ } ++ catch (e_1) { ++ env_1.error = e_1; ++ env_1.hasError = true; ++ } ++ finally { ++ __disposeResources(env_1); ++ } ++ } ++ }; ++}); +diff --git a/tests/baselines/reference/usingDeclarationsWithLegacyClassDecorators.5(module=system,target=es5).js b/tests/baselines/reference/usingDeclarationsWithLegacyClassDecorators.5(module=system,target=es5).js +new file mode 100644 +index 000000000..1a7c63879 +--- /dev/null ++++ b/tests/baselines/reference/usingDeclarationsWithLegacyClassDecorators.5(module=system,target=es5).js +@@ -0,0 +1,45 @@ ++//// [tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsWithLegacyClassDecorators.5.ts] //// ++ ++//// [usingDeclarationsWithLegacyClassDecorators.5.ts] ++export {}; ++ ++declare var dec: any; ++ ++using before = null; ++ ++@dec ++class C { ++} ++ ++export { C }; ++ ++//// [usingDeclarationsWithLegacyClassDecorators.5.js] ++System.register([], function (exports_1, context_1) { ++ "use strict"; ++ var before, C, env_1; ++ var __moduleName = context_1 && context_1.id; ++ return { ++ setters: [], ++ execute: function () { ++ env_1 = { stack: [], error: void 0, hasError: false }; ++ try { ++ before = __addDisposableResource(env_1, null, false); ++ exports_1("C", C = /** @class */ (function () { ++ function C() { ++ } ++ C = __decorate([ ++ dec ++ ], C); ++ return C; ++ }())); ++ } ++ catch (e_1) { ++ env_1.error = e_1; ++ env_1.hasError = true; ++ } ++ finally { ++ __disposeResources(env_1); ++ } ++ } ++ }; ++}); +diff --git a/tests/baselines/reference/usingDeclarationsWithLegacyClassDecorators.5(module=system,target=esnext).js b/tests/baselines/reference/usingDeclarationsWithLegacyClassDecorators.5(module=system,target=esnext).js +new file mode 100644 +index 000000000..5aac5f3cf +--- /dev/null ++++ b/tests/baselines/reference/usingDeclarationsWithLegacyClassDecorators.5(module=system,target=esnext).js +@@ -0,0 +1,33 @@ ++//// [tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsWithLegacyClassDecorators.5.ts] //// ++ ++//// [usingDeclarationsWithLegacyClassDecorators.5.ts] ++export {}; ++ ++declare var dec: any; ++ ++using before = null; ++ ++@dec ++class C { ++} ++ ++export { C }; ++ ++//// [usingDeclarationsWithLegacyClassDecorators.5.js] ++System.register([], function (exports_1, context_1) { ++ "use strict"; ++ var before, C; ++ var __moduleName = context_1 && context_1.id; ++ return { ++ setters: [], ++ execute: function () { ++ using before_1 = before = null; ++ C = class C { ++ }; ++ exports_1("C", C); ++ exports_1("C", C = __decorate([ ++ dec ++ ], C)); ++ } ++ }; ++}); +diff --git a/tests/baselines/reference/usingDeclarationsWithLegacyClassDecorators.6(module=commonjs,target=es2015).js b/tests/baselines/reference/usingDeclarationsWithLegacyClassDecorators.6(module=commonjs,target=es2015).js +new file mode 100644 +index 000000000..e6d605175 +--- /dev/null ++++ b/tests/baselines/reference/usingDeclarationsWithLegacyClassDecorators.6(module=commonjs,target=es2015).js +@@ -0,0 +1,36 @@ ++//// [tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsWithLegacyClassDecorators.6.ts] //// ++ ++//// [usingDeclarationsWithLegacyClassDecorators.6.ts] ++export {}; ++ ++declare var dec: any; ++ ++using before = null; ++ ++@dec ++class C { ++} ++ ++export { C as D }; ++ ++//// [usingDeclarationsWithLegacyClassDecorators.6.js] ++"use strict"; ++Object.defineProperty(exports, "__esModule", { value: true }); ++exports.D = void 0; ++var before, C; ++const env_1 = { stack: [], error: void 0, hasError: false }; ++try { ++ before = __addDisposableResource(env_1, null, false); ++ exports.D = C = class C { ++ }; ++ exports.D = C = __decorate([ ++ dec ++ ], C); ++} ++catch (e_1) { ++ env_1.error = e_1; ++ env_1.hasError = true; ++} ++finally { ++ __disposeResources(env_1); ++} +diff --git a/tests/baselines/reference/usingDeclarationsWithLegacyClassDecorators.6(module=commonjs,target=es5).js b/tests/baselines/reference/usingDeclarationsWithLegacyClassDecorators.6(module=commonjs,target=es5).js +new file mode 100644 +index 000000000..87d338f48 +--- /dev/null ++++ b/tests/baselines/reference/usingDeclarationsWithLegacyClassDecorators.6(module=commonjs,target=es5).js +@@ -0,0 +1,39 @@ ++//// [tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsWithLegacyClassDecorators.6.ts] //// ++ ++//// [usingDeclarationsWithLegacyClassDecorators.6.ts] ++export {}; ++ ++declare var dec: any; ++ ++using before = null; ++ ++@dec ++class C { ++} ++ ++export { C as D }; ++ ++//// [usingDeclarationsWithLegacyClassDecorators.6.js] ++"use strict"; ++Object.defineProperty(exports, "__esModule", { value: true }); ++exports.D = void 0; ++var before, C; ++var env_1 = { stack: [], error: void 0, hasError: false }; ++try { ++ before = __addDisposableResource(env_1, null, false); ++ exports.D = C = /** @class */ (function () { ++ function C() { ++ } ++ C = __decorate([ ++ dec ++ ], C); ++ return C; ++ }()); ++} ++catch (e_1) { ++ env_1.error = e_1; ++ env_1.hasError = true; ++} ++finally { ++ __disposeResources(env_1); ++} +diff --git a/tests/baselines/reference/usingDeclarationsWithLegacyClassDecorators.6(module=commonjs,target=esnext).js b/tests/baselines/reference/usingDeclarationsWithLegacyClassDecorators.6(module=commonjs,target=esnext).js +new file mode 100644 +index 000000000..f16c4772a +--- /dev/null ++++ b/tests/baselines/reference/usingDeclarationsWithLegacyClassDecorators.6(module=commonjs,target=esnext).js +@@ -0,0 +1,26 @@ ++//// [tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsWithLegacyClassDecorators.6.ts] //// ++ ++//// [usingDeclarationsWithLegacyClassDecorators.6.ts] ++export {}; ++ ++declare var dec: any; ++ ++using before = null; ++ ++@dec ++class C { ++} ++ ++export { C as D }; ++ ++//// [usingDeclarationsWithLegacyClassDecorators.6.js] ++"use strict"; ++Object.defineProperty(exports, "__esModule", { value: true }); ++exports.D = void 0; ++using before = null; ++let C = class C { ++}; ++exports.D = C; ++exports.D = C = __decorate([ ++ dec ++], C); +diff --git a/tests/baselines/reference/usingDeclarationsWithLegacyClassDecorators.6(module=esnext,target=es2015).js b/tests/baselines/reference/usingDeclarationsWithLegacyClassDecorators.6(module=esnext,target=es2015).js +new file mode 100644 +index 000000000..f3762ca32 +--- /dev/null ++++ b/tests/baselines/reference/usingDeclarationsWithLegacyClassDecorators.6(module=esnext,target=es2015).js +@@ -0,0 +1,34 @@ ++//// [tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsWithLegacyClassDecorators.6.ts] //// ++ ++//// [usingDeclarationsWithLegacyClassDecorators.6.ts] ++export {}; ++ ++declare var dec: any; ++ ++using before = null; ++ ++@dec ++class C { ++} ++ ++export { C as D }; ++ ++//// [usingDeclarationsWithLegacyClassDecorators.6.js] ++export { C as D }; ++var before, C; ++const env_1 = { stack: [], error: void 0, hasError: false }; ++try { ++ before = __addDisposableResource(env_1, null, false); ++ C = class C { ++ }; ++ C = __decorate([ ++ dec ++ ], C); ++} ++catch (e_1) { ++ env_1.error = e_1; ++ env_1.hasError = true; ++} ++finally { ++ __disposeResources(env_1); ++} +diff --git a/tests/baselines/reference/usingDeclarationsWithLegacyClassDecorators.6(module=esnext,target=es5).js b/tests/baselines/reference/usingDeclarationsWithLegacyClassDecorators.6(module=esnext,target=es5).js +new file mode 100644 +index 000000000..7c1a58cd4 +--- /dev/null ++++ b/tests/baselines/reference/usingDeclarationsWithLegacyClassDecorators.6(module=esnext,target=es5).js +@@ -0,0 +1,37 @@ ++//// [tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsWithLegacyClassDecorators.6.ts] //// ++ ++//// [usingDeclarationsWithLegacyClassDecorators.6.ts] ++export {}; ++ ++declare var dec: any; ++ ++using before = null; ++ ++@dec ++class C { ++} ++ ++export { C as D }; ++ ++//// [usingDeclarationsWithLegacyClassDecorators.6.js] ++export { C as D }; ++var before, C; ++var env_1 = { stack: [], error: void 0, hasError: false }; ++try { ++ before = __addDisposableResource(env_1, null, false); ++ C = /** @class */ (function () { ++ function C() { ++ } ++ C = __decorate([ ++ dec ++ ], C); ++ return C; ++ }()); ++} ++catch (e_1) { ++ env_1.error = e_1; ++ env_1.hasError = true; ++} ++finally { ++ __disposeResources(env_1); ++} +diff --git a/tests/baselines/reference/usingDeclarationsWithLegacyClassDecorators.6(module=esnext,target=esnext).js b/tests/baselines/reference/usingDeclarationsWithLegacyClassDecorators.6(module=esnext,target=esnext).js +new file mode 100644 +index 000000000..ed1f2c80d +--- /dev/null ++++ b/tests/baselines/reference/usingDeclarationsWithLegacyClassDecorators.6(module=esnext,target=esnext).js +@@ -0,0 +1,23 @@ ++//// [tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsWithLegacyClassDecorators.6.ts] //// ++ ++//// [usingDeclarationsWithLegacyClassDecorators.6.ts] ++export {}; ++ ++declare var dec: any; ++ ++using before = null; ++ ++@dec ++class C { ++} ++ ++export { C as D }; ++ ++//// [usingDeclarationsWithLegacyClassDecorators.6.js] ++using before = null; ++let C = class C { ++}; ++C = __decorate([ ++ dec ++], C); ++export { C as D }; +diff --git a/tests/baselines/reference/usingDeclarationsWithLegacyClassDecorators.6(module=system,target=es2015).js b/tests/baselines/reference/usingDeclarationsWithLegacyClassDecorators.6(module=system,target=es2015).js +new file mode 100644 +index 000000000..c49f186a6 +--- /dev/null ++++ b/tests/baselines/reference/usingDeclarationsWithLegacyClassDecorators.6(module=system,target=es2015).js +@@ -0,0 +1,42 @@ ++//// [tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsWithLegacyClassDecorators.6.ts] //// ++ ++//// [usingDeclarationsWithLegacyClassDecorators.6.ts] ++export {}; ++ ++declare var dec: any; ++ ++using before = null; ++ ++@dec ++class C { ++} ++ ++export { C as D }; ++ ++//// [usingDeclarationsWithLegacyClassDecorators.6.js] ++System.register([], function (exports_1, context_1) { ++ "use strict"; ++ var before, C, env_1; ++ var __moduleName = context_1 && context_1.id; ++ return { ++ setters: [], ++ execute: function () { ++ env_1 = { stack: [], error: void 0, hasError: false }; ++ try { ++ before = __addDisposableResource(env_1, null, false); ++ exports_1("D", C = class C { ++ }); ++ exports_1("D", C = __decorate([ ++ dec ++ ], C)); ++ } ++ catch (e_1) { ++ env_1.error = e_1; ++ env_1.hasError = true; ++ } ++ finally { ++ __disposeResources(env_1); ++ } ++ } ++ }; ++}); +diff --git a/tests/baselines/reference/usingDeclarationsWithLegacyClassDecorators.6(module=system,target=es5).js b/tests/baselines/reference/usingDeclarationsWithLegacyClassDecorators.6(module=system,target=es5).js +new file mode 100644 +index 000000000..5a258248b +--- /dev/null ++++ b/tests/baselines/reference/usingDeclarationsWithLegacyClassDecorators.6(module=system,target=es5).js +@@ -0,0 +1,45 @@ ++//// [tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsWithLegacyClassDecorators.6.ts] //// ++ ++//// [usingDeclarationsWithLegacyClassDecorators.6.ts] ++export {}; ++ ++declare var dec: any; ++ ++using before = null; ++ ++@dec ++class C { ++} ++ ++export { C as D }; ++ ++//// [usingDeclarationsWithLegacyClassDecorators.6.js] ++System.register([], function (exports_1, context_1) { ++ "use strict"; ++ var before, C, env_1; ++ var __moduleName = context_1 && context_1.id; ++ return { ++ setters: [], ++ execute: function () { ++ env_1 = { stack: [], error: void 0, hasError: false }; ++ try { ++ before = __addDisposableResource(env_1, null, false); ++ exports_1("D", C = /** @class */ (function () { ++ function C() { ++ } ++ C = __decorate([ ++ dec ++ ], C); ++ return C; ++ }())); ++ } ++ catch (e_1) { ++ env_1.error = e_1; ++ env_1.hasError = true; ++ } ++ finally { ++ __disposeResources(env_1); ++ } ++ } ++ }; ++}); +diff --git a/tests/baselines/reference/usingDeclarationsWithLegacyClassDecorators.6(module=system,target=esnext).js b/tests/baselines/reference/usingDeclarationsWithLegacyClassDecorators.6(module=system,target=esnext).js +new file mode 100644 +index 000000000..15f5addcb +--- /dev/null ++++ b/tests/baselines/reference/usingDeclarationsWithLegacyClassDecorators.6(module=system,target=esnext).js +@@ -0,0 +1,33 @@ ++//// [tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsWithLegacyClassDecorators.6.ts] //// ++ ++//// [usingDeclarationsWithLegacyClassDecorators.6.ts] ++export {}; ++ ++declare var dec: any; ++ ++using before = null; ++ ++@dec ++class C { ++} ++ ++export { C as D }; ++ ++//// [usingDeclarationsWithLegacyClassDecorators.6.js] ++System.register([], function (exports_1, context_1) { ++ "use strict"; ++ var before, C; ++ var __moduleName = context_1 && context_1.id; ++ return { ++ setters: [], ++ execute: function () { ++ using before_1 = before = null; ++ C = class C { ++ }; ++ exports_1("D", C); ++ exports_1("D", C = __decorate([ ++ dec ++ ], C)); ++ } ++ }; ++}); +diff --git a/tests/baselines/reference/usingDeclarationsWithLegacyClassDecorators.7(module=commonjs,target=es2015).js b/tests/baselines/reference/usingDeclarationsWithLegacyClassDecorators.7(module=commonjs,target=es2015).js +new file mode 100644 +index 000000000..c2103047f +--- /dev/null ++++ b/tests/baselines/reference/usingDeclarationsWithLegacyClassDecorators.7(module=commonjs,target=es2015).js +@@ -0,0 +1,34 @@ ++//// [tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsWithLegacyClassDecorators.7.ts] //// ++ ++//// [usingDeclarationsWithLegacyClassDecorators.7.ts] ++export {}; ++ ++declare var dec: any; ++ ++@dec ++class C { ++} ++ ++using after = null; ++ ++ ++//// [usingDeclarationsWithLegacyClassDecorators.7.js] ++"use strict"; ++Object.defineProperty(exports, "__esModule", { value: true }); ++let C = class C { ++}; ++C = __decorate([ ++ dec ++], C); ++var after; ++const env_1 = { stack: [], error: void 0, hasError: false }; ++try { ++ after = __addDisposableResource(env_1, null, false); ++} ++catch (e_1) { ++ env_1.error = e_1; ++ env_1.hasError = true; ++} ++finally { ++ __disposeResources(env_1); ++} +diff --git a/tests/baselines/reference/usingDeclarationsWithLegacyClassDecorators.7(module=commonjs,target=es5).js b/tests/baselines/reference/usingDeclarationsWithLegacyClassDecorators.7(module=commonjs,target=es5).js +new file mode 100644 +index 000000000..96e605fb8 +--- /dev/null ++++ b/tests/baselines/reference/usingDeclarationsWithLegacyClassDecorators.7(module=commonjs,target=es5).js +@@ -0,0 +1,37 @@ ++//// [tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsWithLegacyClassDecorators.7.ts] //// ++ ++//// [usingDeclarationsWithLegacyClassDecorators.7.ts] ++export {}; ++ ++declare var dec: any; ++ ++@dec ++class C { ++} ++ ++using after = null; ++ ++ ++//// [usingDeclarationsWithLegacyClassDecorators.7.js] ++"use strict"; ++Object.defineProperty(exports, "__esModule", { value: true }); ++var C = /** @class */ (function () { ++ function C() { ++ } ++ C = __decorate([ ++ dec ++ ], C); ++ return C; ++}()); ++var after; ++var env_1 = { stack: [], error: void 0, hasError: false }; ++try { ++ after = __addDisposableResource(env_1, null, false); ++} ++catch (e_1) { ++ env_1.error = e_1; ++ env_1.hasError = true; ++} ++finally { ++ __disposeResources(env_1); ++} +diff --git a/tests/baselines/reference/usingDeclarationsWithLegacyClassDecorators.7(module=commonjs,target=esnext).js b/tests/baselines/reference/usingDeclarationsWithLegacyClassDecorators.7(module=commonjs,target=esnext).js +new file mode 100644 +index 000000000..1acfe3baf +--- /dev/null ++++ b/tests/baselines/reference/usingDeclarationsWithLegacyClassDecorators.7(module=commonjs,target=esnext).js +@@ -0,0 +1,23 @@ ++//// [tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsWithLegacyClassDecorators.7.ts] //// ++ ++//// [usingDeclarationsWithLegacyClassDecorators.7.ts] ++export {}; ++ ++declare var dec: any; ++ ++@dec ++class C { ++} ++ ++using after = null; ++ ++ ++//// [usingDeclarationsWithLegacyClassDecorators.7.js] ++"use strict"; ++Object.defineProperty(exports, "__esModule", { value: true }); ++let C = class C { ++}; ++C = __decorate([ ++ dec ++], C); ++using after = null; +diff --git a/tests/baselines/reference/usingDeclarationsWithLegacyClassDecorators.7(module=esnext,target=es2015).js b/tests/baselines/reference/usingDeclarationsWithLegacyClassDecorators.7(module=esnext,target=es2015).js +new file mode 100644 +index 000000000..9b8ec6651 +--- /dev/null ++++ b/tests/baselines/reference/usingDeclarationsWithLegacyClassDecorators.7(module=esnext,target=es2015).js +@@ -0,0 +1,33 @@ ++//// [tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsWithLegacyClassDecorators.7.ts] //// ++ ++//// [usingDeclarationsWithLegacyClassDecorators.7.ts] ++export {}; ++ ++declare var dec: any; ++ ++@dec ++class C { ++} ++ ++using after = null; ++ ++ ++//// [usingDeclarationsWithLegacyClassDecorators.7.js] ++let C = class C { ++}; ++C = __decorate([ ++ dec ++], C); ++var after; ++const env_1 = { stack: [], error: void 0, hasError: false }; ++try { ++ after = __addDisposableResource(env_1, null, false); ++} ++catch (e_1) { ++ env_1.error = e_1; ++ env_1.hasError = true; ++} ++finally { ++ __disposeResources(env_1); ++} ++export {}; +diff --git a/tests/baselines/reference/usingDeclarationsWithLegacyClassDecorators.7(module=esnext,target=es5).js b/tests/baselines/reference/usingDeclarationsWithLegacyClassDecorators.7(module=esnext,target=es5).js +new file mode 100644 +index 000000000..4578e2373 +--- /dev/null ++++ b/tests/baselines/reference/usingDeclarationsWithLegacyClassDecorators.7(module=esnext,target=es5).js +@@ -0,0 +1,36 @@ ++//// [tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsWithLegacyClassDecorators.7.ts] //// ++ ++//// [usingDeclarationsWithLegacyClassDecorators.7.ts] ++export {}; ++ ++declare var dec: any; ++ ++@dec ++class C { ++} ++ ++using after = null; ++ ++ ++//// [usingDeclarationsWithLegacyClassDecorators.7.js] ++var C = /** @class */ (function () { ++ function C() { ++ } ++ C = __decorate([ ++ dec ++ ], C); ++ return C; ++}()); ++var after; ++var env_1 = { stack: [], error: void 0, hasError: false }; ++try { ++ after = __addDisposableResource(env_1, null, false); ++} ++catch (e_1) { ++ env_1.error = e_1; ++ env_1.hasError = true; ++} ++finally { ++ __disposeResources(env_1); ++} ++export {}; +diff --git a/tests/baselines/reference/usingDeclarationsWithLegacyClassDecorators.7(module=esnext,target=esnext).js b/tests/baselines/reference/usingDeclarationsWithLegacyClassDecorators.7(module=esnext,target=esnext).js +new file mode 100644 +index 000000000..0456f1ea7 +--- /dev/null ++++ b/tests/baselines/reference/usingDeclarationsWithLegacyClassDecorators.7(module=esnext,target=esnext).js +@@ -0,0 +1,22 @@ ++//// [tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsWithLegacyClassDecorators.7.ts] //// ++ ++//// [usingDeclarationsWithLegacyClassDecorators.7.ts] ++export {}; ++ ++declare var dec: any; ++ ++@dec ++class C { ++} ++ ++using after = null; ++ ++ ++//// [usingDeclarationsWithLegacyClassDecorators.7.js] ++let C = class C { ++}; ++C = __decorate([ ++ dec ++], C); ++using after = null; ++export {}; +diff --git a/tests/baselines/reference/usingDeclarationsWithLegacyClassDecorators.7(module=system,target=es2015).js b/tests/baselines/reference/usingDeclarationsWithLegacyClassDecorators.7(module=system,target=es2015).js +new file mode 100644 +index 000000000..7e32ca24e +--- /dev/null ++++ b/tests/baselines/reference/usingDeclarationsWithLegacyClassDecorators.7(module=system,target=es2015).js +@@ -0,0 +1,41 @@ ++//// [tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsWithLegacyClassDecorators.7.ts] //// ++ ++//// [usingDeclarationsWithLegacyClassDecorators.7.ts] ++export {}; ++ ++declare var dec: any; ++ ++@dec ++class C { ++} ++ ++using after = null; ++ ++ ++//// [usingDeclarationsWithLegacyClassDecorators.7.js] ++System.register([], function (exports_1, context_1) { ++ "use strict"; ++ var C, after, env_1; ++ var __moduleName = context_1 && context_1.id; ++ return { ++ setters: [], ++ execute: function () { ++ C = class C { ++ }; ++ C = __decorate([ ++ dec ++ ], C); ++ env_1 = { stack: [], error: void 0, hasError: false }; ++ try { ++ after = __addDisposableResource(env_1, null, false); ++ } ++ catch (e_1) { ++ env_1.error = e_1; ++ env_1.hasError = true; ++ } ++ finally { ++ __disposeResources(env_1); ++ } ++ } ++ }; ++}); +diff --git a/tests/baselines/reference/usingDeclarationsWithLegacyClassDecorators.7(module=system,target=es5).js b/tests/baselines/reference/usingDeclarationsWithLegacyClassDecorators.7(module=system,target=es5).js +new file mode 100644 +index 000000000..af832ee96 +--- /dev/null ++++ b/tests/baselines/reference/usingDeclarationsWithLegacyClassDecorators.7(module=system,target=es5).js +@@ -0,0 +1,44 @@ ++//// [tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsWithLegacyClassDecorators.7.ts] //// ++ ++//// [usingDeclarationsWithLegacyClassDecorators.7.ts] ++export {}; ++ ++declare var dec: any; ++ ++@dec ++class C { ++} ++ ++using after = null; ++ ++ ++//// [usingDeclarationsWithLegacyClassDecorators.7.js] ++System.register([], function (exports_1, context_1) { ++ "use strict"; ++ var C, after, env_1; ++ var __moduleName = context_1 && context_1.id; ++ return { ++ setters: [], ++ execute: function () { ++ C = /** @class */ (function () { ++ function C() { ++ } ++ C = __decorate([ ++ dec ++ ], C); ++ return C; ++ }()); ++ env_1 = { stack: [], error: void 0, hasError: false }; ++ try { ++ after = __addDisposableResource(env_1, null, false); ++ } ++ catch (e_1) { ++ env_1.error = e_1; ++ env_1.hasError = true; ++ } ++ finally { ++ __disposeResources(env_1); ++ } ++ } ++ }; ++}); +diff --git a/tests/baselines/reference/usingDeclarationsWithLegacyClassDecorators.7(module=system,target=esnext).js b/tests/baselines/reference/usingDeclarationsWithLegacyClassDecorators.7(module=system,target=esnext).js +new file mode 100644 +index 000000000..7072d1173 +--- /dev/null ++++ b/tests/baselines/reference/usingDeclarationsWithLegacyClassDecorators.7(module=system,target=esnext).js +@@ -0,0 +1,31 @@ ++//// [tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsWithLegacyClassDecorators.7.ts] //// ++ ++//// [usingDeclarationsWithLegacyClassDecorators.7.ts] ++export {}; ++ ++declare var dec: any; ++ ++@dec ++class C { ++} ++ ++using after = null; ++ ++ ++//// [usingDeclarationsWithLegacyClassDecorators.7.js] ++System.register([], function (exports_1, context_1) { ++ "use strict"; ++ var C, after; ++ var __moduleName = context_1 && context_1.id; ++ return { ++ setters: [], ++ execute: function () { ++ C = class C { ++ }; ++ C = __decorate([ ++ dec ++ ], C); ++ using after_1 = after = null; ++ } ++ }; ++}); +diff --git a/tests/baselines/reference/usingDeclarationsWithLegacyClassDecorators.8(module=commonjs,target=es2015).js b/tests/baselines/reference/usingDeclarationsWithLegacyClassDecorators.8(module=commonjs,target=es2015).js +new file mode 100644 +index 000000000..d3f6f0536 +--- /dev/null ++++ b/tests/baselines/reference/usingDeclarationsWithLegacyClassDecorators.8(module=commonjs,target=es2015).js +@@ -0,0 +1,36 @@ ++//// [tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsWithLegacyClassDecorators.8.ts] //// ++ ++//// [usingDeclarationsWithLegacyClassDecorators.8.ts] ++export {}; ++ ++declare var dec: any; ++ ++@dec ++export class C { ++} ++ ++using after = null; ++ ++ ++//// [usingDeclarationsWithLegacyClassDecorators.8.js] ++"use strict"; ++Object.defineProperty(exports, "__esModule", { value: true }); ++exports.C = void 0; ++let C = class C { ++}; ++exports.C = C; ++exports.C = C = __decorate([ ++ dec ++], C); ++var after; ++const env_1 = { stack: [], error: void 0, hasError: false }; ++try { ++ after = __addDisposableResource(env_1, null, false); ++} ++catch (e_1) { ++ env_1.error = e_1; ++ env_1.hasError = true; ++} ++finally { ++ __disposeResources(env_1); ++} +diff --git a/tests/baselines/reference/usingDeclarationsWithLegacyClassDecorators.8(module=commonjs,target=es5).js b/tests/baselines/reference/usingDeclarationsWithLegacyClassDecorators.8(module=commonjs,target=es5).js +new file mode 100644 +index 000000000..b3083338b +--- /dev/null ++++ b/tests/baselines/reference/usingDeclarationsWithLegacyClassDecorators.8(module=commonjs,target=es5).js +@@ -0,0 +1,39 @@ ++//// [tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsWithLegacyClassDecorators.8.ts] //// ++ ++//// [usingDeclarationsWithLegacyClassDecorators.8.ts] ++export {}; ++ ++declare var dec: any; ++ ++@dec ++export class C { ++} ++ ++using after = null; ++ ++ ++//// [usingDeclarationsWithLegacyClassDecorators.8.js] ++"use strict"; ++Object.defineProperty(exports, "__esModule", { value: true }); ++exports.C = void 0; ++var C = /** @class */ (function () { ++ function C() { ++ } ++ C = __decorate([ ++ dec ++ ], C); ++ return C; ++}()); ++exports.C = C; ++var after; ++var env_1 = { stack: [], error: void 0, hasError: false }; ++try { ++ after = __addDisposableResource(env_1, null, false); ++} ++catch (e_1) { ++ env_1.error = e_1; ++ env_1.hasError = true; ++} ++finally { ++ __disposeResources(env_1); ++} +diff --git a/tests/baselines/reference/usingDeclarationsWithLegacyClassDecorators.8(module=commonjs,target=esnext).js b/tests/baselines/reference/usingDeclarationsWithLegacyClassDecorators.8(module=commonjs,target=esnext).js +new file mode 100644 +index 000000000..516301c4c +--- /dev/null ++++ b/tests/baselines/reference/usingDeclarationsWithLegacyClassDecorators.8(module=commonjs,target=esnext).js +@@ -0,0 +1,25 @@ ++//// [tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsWithLegacyClassDecorators.8.ts] //// ++ ++//// [usingDeclarationsWithLegacyClassDecorators.8.ts] ++export {}; ++ ++declare var dec: any; ++ ++@dec ++export class C { ++} ++ ++using after = null; ++ ++ ++//// [usingDeclarationsWithLegacyClassDecorators.8.js] ++"use strict"; ++Object.defineProperty(exports, "__esModule", { value: true }); ++exports.C = void 0; ++let C = class C { ++}; ++exports.C = C; ++exports.C = C = __decorate([ ++ dec ++], C); ++using after = null; +diff --git a/tests/baselines/reference/usingDeclarationsWithLegacyClassDecorators.8(module=esnext,target=es2015).js b/tests/baselines/reference/usingDeclarationsWithLegacyClassDecorators.8(module=esnext,target=es2015).js +new file mode 100644 +index 000000000..b87aac7bf +--- /dev/null ++++ b/tests/baselines/reference/usingDeclarationsWithLegacyClassDecorators.8(module=esnext,target=es2015).js +@@ -0,0 +1,33 @@ ++//// [tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsWithLegacyClassDecorators.8.ts] //// ++ ++//// [usingDeclarationsWithLegacyClassDecorators.8.ts] ++export {}; ++ ++declare var dec: any; ++ ++@dec ++export class C { ++} ++ ++using after = null; ++ ++ ++//// [usingDeclarationsWithLegacyClassDecorators.8.js] ++let C = class C { ++}; ++C = __decorate([ ++ dec ++], C); ++export { C }; ++var after; ++const env_1 = { stack: [], error: void 0, hasError: false }; ++try { ++ after = __addDisposableResource(env_1, null, false); ++} ++catch (e_1) { ++ env_1.error = e_1; ++ env_1.hasError = true; ++} ++finally { ++ __disposeResources(env_1); ++} +diff --git a/tests/baselines/reference/usingDeclarationsWithLegacyClassDecorators.8(module=esnext,target=es5).js b/tests/baselines/reference/usingDeclarationsWithLegacyClassDecorators.8(module=esnext,target=es5).js +new file mode 100644 +index 000000000..ce5acfb5a +--- /dev/null ++++ b/tests/baselines/reference/usingDeclarationsWithLegacyClassDecorators.8(module=esnext,target=es5).js +@@ -0,0 +1,36 @@ ++//// [tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsWithLegacyClassDecorators.8.ts] //// ++ ++//// [usingDeclarationsWithLegacyClassDecorators.8.ts] ++export {}; ++ ++declare var dec: any; ++ ++@dec ++export class C { ++} ++ ++using after = null; ++ ++ ++//// [usingDeclarationsWithLegacyClassDecorators.8.js] ++var C = /** @class */ (function () { ++ function C() { ++ } ++ C = __decorate([ ++ dec ++ ], C); ++ return C; ++}()); ++export { C }; ++var after; ++var env_1 = { stack: [], error: void 0, hasError: false }; ++try { ++ after = __addDisposableResource(env_1, null, false); ++} ++catch (e_1) { ++ env_1.error = e_1; ++ env_1.hasError = true; ++} ++finally { ++ __disposeResources(env_1); ++} +diff --git a/tests/baselines/reference/usingDeclarationsWithLegacyClassDecorators.8(module=esnext,target=esnext).js b/tests/baselines/reference/usingDeclarationsWithLegacyClassDecorators.8(module=esnext,target=esnext).js +new file mode 100644 +index 000000000..aee33622d +--- /dev/null ++++ b/tests/baselines/reference/usingDeclarationsWithLegacyClassDecorators.8(module=esnext,target=esnext).js +@@ -0,0 +1,22 @@ ++//// [tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsWithLegacyClassDecorators.8.ts] //// ++ ++//// [usingDeclarationsWithLegacyClassDecorators.8.ts] ++export {}; ++ ++declare var dec: any; ++ ++@dec ++export class C { ++} ++ ++using after = null; ++ ++ ++//// [usingDeclarationsWithLegacyClassDecorators.8.js] ++let C = class C { ++}; ++C = __decorate([ ++ dec ++], C); ++export { C }; ++using after = null; +diff --git a/tests/baselines/reference/usingDeclarationsWithLegacyClassDecorators.8(module=system,target=es2015).js b/tests/baselines/reference/usingDeclarationsWithLegacyClassDecorators.8(module=system,target=es2015).js +new file mode 100644 +index 000000000..aa595d326 +--- /dev/null ++++ b/tests/baselines/reference/usingDeclarationsWithLegacyClassDecorators.8(module=system,target=es2015).js +@@ -0,0 +1,42 @@ ++//// [tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsWithLegacyClassDecorators.8.ts] //// ++ ++//// [usingDeclarationsWithLegacyClassDecorators.8.ts] ++export {}; ++ ++declare var dec: any; ++ ++@dec ++export class C { ++} ++ ++using after = null; ++ ++ ++//// [usingDeclarationsWithLegacyClassDecorators.8.js] ++System.register([], function (exports_1, context_1) { ++ "use strict"; ++ var C, after, env_1; ++ var __moduleName = context_1 && context_1.id; ++ return { ++ setters: [], ++ execute: function () { ++ C = class C { ++ }; ++ exports_1("C", C); ++ exports_1("C", C = __decorate([ ++ dec ++ ], C)); ++ env_1 = { stack: [], error: void 0, hasError: false }; ++ try { ++ after = __addDisposableResource(env_1, null, false); ++ } ++ catch (e_1) { ++ env_1.error = e_1; ++ env_1.hasError = true; ++ } ++ finally { ++ __disposeResources(env_1); ++ } ++ } ++ }; ++}); +diff --git a/tests/baselines/reference/usingDeclarationsWithLegacyClassDecorators.8(module=system,target=es5).js b/tests/baselines/reference/usingDeclarationsWithLegacyClassDecorators.8(module=system,target=es5).js +new file mode 100644 +index 000000000..117049660 +--- /dev/null ++++ b/tests/baselines/reference/usingDeclarationsWithLegacyClassDecorators.8(module=system,target=es5).js +@@ -0,0 +1,45 @@ ++//// [tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsWithLegacyClassDecorators.8.ts] //// ++ ++//// [usingDeclarationsWithLegacyClassDecorators.8.ts] ++export {}; ++ ++declare var dec: any; ++ ++@dec ++export class C { ++} ++ ++using after = null; ++ ++ ++//// [usingDeclarationsWithLegacyClassDecorators.8.js] ++System.register([], function (exports_1, context_1) { ++ "use strict"; ++ var C, after, env_1; ++ var __moduleName = context_1 && context_1.id; ++ return { ++ setters: [], ++ execute: function () { ++ C = /** @class */ (function () { ++ function C() { ++ } ++ C = __decorate([ ++ dec ++ ], C); ++ return C; ++ }()); ++ exports_1("C", C); ++ env_1 = { stack: [], error: void 0, hasError: false }; ++ try { ++ after = __addDisposableResource(env_1, null, false); ++ } ++ catch (e_1) { ++ env_1.error = e_1; ++ env_1.hasError = true; ++ } ++ finally { ++ __disposeResources(env_1); ++ } ++ } ++ }; ++}); +diff --git a/tests/baselines/reference/usingDeclarationsWithLegacyClassDecorators.8(module=system,target=esnext).js b/tests/baselines/reference/usingDeclarationsWithLegacyClassDecorators.8(module=system,target=esnext).js +new file mode 100644 +index 000000000..a015e9020 +--- /dev/null ++++ b/tests/baselines/reference/usingDeclarationsWithLegacyClassDecorators.8(module=system,target=esnext).js +@@ -0,0 +1,32 @@ ++//// [tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsWithLegacyClassDecorators.8.ts] //// ++ ++//// [usingDeclarationsWithLegacyClassDecorators.8.ts] ++export {}; ++ ++declare var dec: any; ++ ++@dec ++export class C { ++} ++ ++using after = null; ++ ++ ++//// [usingDeclarationsWithLegacyClassDecorators.8.js] ++System.register([], function (exports_1, context_1) { ++ "use strict"; ++ var C, after; ++ var __moduleName = context_1 && context_1.id; ++ return { ++ setters: [], ++ execute: function () { ++ C = class C { ++ }; ++ exports_1("C", C); ++ exports_1("C", C = __decorate([ ++ dec ++ ], C)); ++ using after_1 = after = null; ++ } ++ }; ++}); +diff --git a/tests/baselines/reference/usingDeclarationsWithLegacyClassDecorators.9(module=commonjs,target=es2015).js b/tests/baselines/reference/usingDeclarationsWithLegacyClassDecorators.9(module=commonjs,target=es2015).js +new file mode 100644 +index 000000000..80064a192 +--- /dev/null ++++ b/tests/baselines/reference/usingDeclarationsWithLegacyClassDecorators.9(module=commonjs,target=es2015).js +@@ -0,0 +1,35 @@ ++//// [tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsWithLegacyClassDecorators.9.ts] //// ++ ++//// [usingDeclarationsWithLegacyClassDecorators.9.ts] ++export {}; ++ ++declare var dec: any; ++ ++@dec ++export default class C { ++} ++ ++using after = null; ++ ++ ++//// [usingDeclarationsWithLegacyClassDecorators.9.js] ++"use strict"; ++Object.defineProperty(exports, "__esModule", { value: true }); ++let C = class C { ++}; ++C = __decorate([ ++ dec ++], C); ++exports.default = C; ++var after; ++const env_1 = { stack: [], error: void 0, hasError: false }; ++try { ++ after = __addDisposableResource(env_1, null, false); ++} ++catch (e_1) { ++ env_1.error = e_1; ++ env_1.hasError = true; ++} ++finally { ++ __disposeResources(env_1); ++} +diff --git a/tests/baselines/reference/usingDeclarationsWithLegacyClassDecorators.9(module=commonjs,target=es5).js b/tests/baselines/reference/usingDeclarationsWithLegacyClassDecorators.9(module=commonjs,target=es5).js +new file mode 100644 +index 000000000..742f3a153 +--- /dev/null ++++ b/tests/baselines/reference/usingDeclarationsWithLegacyClassDecorators.9(module=commonjs,target=es5).js +@@ -0,0 +1,38 @@ ++//// [tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsWithLegacyClassDecorators.9.ts] //// ++ ++//// [usingDeclarationsWithLegacyClassDecorators.9.ts] ++export {}; ++ ++declare var dec: any; ++ ++@dec ++export default class C { ++} ++ ++using after = null; ++ ++ ++//// [usingDeclarationsWithLegacyClassDecorators.9.js] ++"use strict"; ++Object.defineProperty(exports, "__esModule", { value: true }); ++var C = /** @class */ (function () { ++ function C() { ++ } ++ C = __decorate([ ++ dec ++ ], C); ++ return C; ++}()); ++exports.default = C; ++var after; ++var env_1 = { stack: [], error: void 0, hasError: false }; ++try { ++ after = __addDisposableResource(env_1, null, false); ++} ++catch (e_1) { ++ env_1.error = e_1; ++ env_1.hasError = true; ++} ++finally { ++ __disposeResources(env_1); ++} +diff --git a/tests/baselines/reference/usingDeclarationsWithLegacyClassDecorators.9(module=commonjs,target=esnext).js b/tests/baselines/reference/usingDeclarationsWithLegacyClassDecorators.9(module=commonjs,target=esnext).js +new file mode 100644 +index 000000000..17855fd9c +--- /dev/null ++++ b/tests/baselines/reference/usingDeclarationsWithLegacyClassDecorators.9(module=commonjs,target=esnext).js +@@ -0,0 +1,24 @@ ++//// [tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsWithLegacyClassDecorators.9.ts] //// ++ ++//// [usingDeclarationsWithLegacyClassDecorators.9.ts] ++export {}; ++ ++declare var dec: any; ++ ++@dec ++export default class C { ++} ++ ++using after = null; ++ ++ ++//// [usingDeclarationsWithLegacyClassDecorators.9.js] ++"use strict"; ++Object.defineProperty(exports, "__esModule", { value: true }); ++let C = class C { ++}; ++C = __decorate([ ++ dec ++], C); ++exports.default = C; ++using after = null; +diff --git a/tests/baselines/reference/usingDeclarationsWithLegacyClassDecorators.9(module=esnext,target=es2015).js b/tests/baselines/reference/usingDeclarationsWithLegacyClassDecorators.9(module=esnext,target=es2015).js +new file mode 100644 +index 000000000..aa0f66873 +--- /dev/null ++++ b/tests/baselines/reference/usingDeclarationsWithLegacyClassDecorators.9(module=esnext,target=es2015).js +@@ -0,0 +1,33 @@ ++//// [tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsWithLegacyClassDecorators.9.ts] //// ++ ++//// [usingDeclarationsWithLegacyClassDecorators.9.ts] ++export {}; ++ ++declare var dec: any; ++ ++@dec ++export default class C { ++} ++ ++using after = null; ++ ++ ++//// [usingDeclarationsWithLegacyClassDecorators.9.js] ++let C = class C { ++}; ++C = __decorate([ ++ dec ++], C); ++export default C; ++var after; ++const env_1 = { stack: [], error: void 0, hasError: false }; ++try { ++ after = __addDisposableResource(env_1, null, false); ++} ++catch (e_1) { ++ env_1.error = e_1; ++ env_1.hasError = true; ++} ++finally { ++ __disposeResources(env_1); ++} +diff --git a/tests/baselines/reference/usingDeclarationsWithLegacyClassDecorators.9(module=esnext,target=es5).js b/tests/baselines/reference/usingDeclarationsWithLegacyClassDecorators.9(module=esnext,target=es5).js +new file mode 100644 +index 000000000..32a30f161 +--- /dev/null ++++ b/tests/baselines/reference/usingDeclarationsWithLegacyClassDecorators.9(module=esnext,target=es5).js +@@ -0,0 +1,36 @@ ++//// [tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsWithLegacyClassDecorators.9.ts] //// ++ ++//// [usingDeclarationsWithLegacyClassDecorators.9.ts] ++export {}; ++ ++declare var dec: any; ++ ++@dec ++export default class C { ++} ++ ++using after = null; ++ ++ ++//// [usingDeclarationsWithLegacyClassDecorators.9.js] ++var C = /** @class */ (function () { ++ function C() { ++ } ++ C = __decorate([ ++ dec ++ ], C); ++ return C; ++}()); ++export default C; ++var after; ++var env_1 = { stack: [], error: void 0, hasError: false }; ++try { ++ after = __addDisposableResource(env_1, null, false); ++} ++catch (e_1) { ++ env_1.error = e_1; ++ env_1.hasError = true; ++} ++finally { ++ __disposeResources(env_1); ++} +diff --git a/tests/baselines/reference/usingDeclarationsWithLegacyClassDecorators.9(module=esnext,target=esnext).js b/tests/baselines/reference/usingDeclarationsWithLegacyClassDecorators.9(module=esnext,target=esnext).js +new file mode 100644 +index 000000000..53806f180 +--- /dev/null ++++ b/tests/baselines/reference/usingDeclarationsWithLegacyClassDecorators.9(module=esnext,target=esnext).js +@@ -0,0 +1,22 @@ ++//// [tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsWithLegacyClassDecorators.9.ts] //// ++ ++//// [usingDeclarationsWithLegacyClassDecorators.9.ts] ++export {}; ++ ++declare var dec: any; ++ ++@dec ++export default class C { ++} ++ ++using after = null; ++ ++ ++//// [usingDeclarationsWithLegacyClassDecorators.9.js] ++let C = class C { ++}; ++C = __decorate([ ++ dec ++], C); ++export default C; ++using after = null; +diff --git a/tests/baselines/reference/usingDeclarationsWithLegacyClassDecorators.9(module=system,target=es2015).js b/tests/baselines/reference/usingDeclarationsWithLegacyClassDecorators.9(module=system,target=es2015).js +new file mode 100644 +index 000000000..bcac7ec03 +--- /dev/null ++++ b/tests/baselines/reference/usingDeclarationsWithLegacyClassDecorators.9(module=system,target=es2015).js +@@ -0,0 +1,42 @@ ++//// [tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsWithLegacyClassDecorators.9.ts] //// ++ ++//// [usingDeclarationsWithLegacyClassDecorators.9.ts] ++export {}; ++ ++declare var dec: any; ++ ++@dec ++export default class C { ++} ++ ++using after = null; ++ ++ ++//// [usingDeclarationsWithLegacyClassDecorators.9.js] ++System.register([], function (exports_1, context_1) { ++ "use strict"; ++ var C, after, env_1; ++ var __moduleName = context_1 && context_1.id; ++ return { ++ setters: [], ++ execute: function () { ++ C = class C { ++ }; ++ C = __decorate([ ++ dec ++ ], C); ++ exports_1("default", C); ++ env_1 = { stack: [], error: void 0, hasError: false }; ++ try { ++ after = __addDisposableResource(env_1, null, false); ++ } ++ catch (e_1) { ++ env_1.error = e_1; ++ env_1.hasError = true; ++ } ++ finally { ++ __disposeResources(env_1); ++ } ++ } ++ }; ++}); +diff --git a/tests/baselines/reference/usingDeclarationsWithLegacyClassDecorators.9(module=system,target=es5).js b/tests/baselines/reference/usingDeclarationsWithLegacyClassDecorators.9(module=system,target=es5).js +new file mode 100644 +index 000000000..e283f12e5 +--- /dev/null ++++ b/tests/baselines/reference/usingDeclarationsWithLegacyClassDecorators.9(module=system,target=es5).js +@@ -0,0 +1,45 @@ ++//// [tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsWithLegacyClassDecorators.9.ts] //// ++ ++//// [usingDeclarationsWithLegacyClassDecorators.9.ts] ++export {}; ++ ++declare var dec: any; ++ ++@dec ++export default class C { ++} ++ ++using after = null; ++ ++ ++//// [usingDeclarationsWithLegacyClassDecorators.9.js] ++System.register([], function (exports_1, context_1) { ++ "use strict"; ++ var C, after, env_1; ++ var __moduleName = context_1 && context_1.id; ++ return { ++ setters: [], ++ execute: function () { ++ C = /** @class */ (function () { ++ function C() { ++ } ++ C = __decorate([ ++ dec ++ ], C); ++ return C; ++ }()); ++ exports_1("default", C); ++ env_1 = { stack: [], error: void 0, hasError: false }; ++ try { ++ after = __addDisposableResource(env_1, null, false); ++ } ++ catch (e_1) { ++ env_1.error = e_1; ++ env_1.hasError = true; ++ } ++ finally { ++ __disposeResources(env_1); ++ } ++ } ++ }; ++}); +diff --git a/tests/baselines/reference/usingDeclarationsWithLegacyClassDecorators.9(module=system,target=esnext).js b/tests/baselines/reference/usingDeclarationsWithLegacyClassDecorators.9(module=system,target=esnext).js +new file mode 100644 +index 000000000..4529090ab +--- /dev/null ++++ b/tests/baselines/reference/usingDeclarationsWithLegacyClassDecorators.9(module=system,target=esnext).js +@@ -0,0 +1,32 @@ ++//// [tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsWithLegacyClassDecorators.9.ts] //// ++ ++//// [usingDeclarationsWithLegacyClassDecorators.9.ts] ++export {}; ++ ++declare var dec: any; ++ ++@dec ++export default class C { ++} ++ ++using after = null; ++ ++ ++//// [usingDeclarationsWithLegacyClassDecorators.9.js] ++System.register([], function (exports_1, context_1) { ++ "use strict"; ++ var C, after; ++ var __moduleName = context_1 && context_1.id; ++ return { ++ setters: [], ++ execute: function () { ++ C = class C { ++ }; ++ C = __decorate([ ++ dec ++ ], C); ++ exports_1("default", C); ++ using after_1 = after = null; ++ } ++ }; ++}); +diff --git a/tests/cases/conformance/es6/for-ofStatements/for-of-excess-declarations.ts b/tests/cases/conformance/es6/for-ofStatements/for-of-excess-declarations.ts +new file mode 100644 +index 000000000..df9b63475 +--- /dev/null ++++ b/tests/cases/conformance/es6/for-ofStatements/for-of-excess-declarations.ts +@@ -0,0 +1,4 @@ ++// @target: esnext ++for (const a, { [b]: c} of [1]) { ++ ++} +\ No newline at end of file +diff --git a/tests/cases/conformance/statements/VariableStatements/usingDeclarations/awaitUsingDeclarations.1.ts b/tests/cases/conformance/statements/VariableStatements/usingDeclarations/awaitUsingDeclarations.1.ts +new file mode 100644 +index 000000000..7f7f86bd4 +--- /dev/null ++++ b/tests/cases/conformance/statements/VariableStatements/usingDeclarations/awaitUsingDeclarations.1.ts +@@ -0,0 +1,102 @@ ++// @target: esnext,es2022,es2017,es2015,es5 ++// @module: esnext ++// @lib: esnext ++// @noTypesAndSymbols: true ++ ++await using d1 = { async [Symbol.asyncDispose]() {} }; ++ ++async function af() { ++ await using d3 = { async [Symbol.asyncDispose]() {} }; ++ await null; ++} ++ ++async function * ag() { ++ await using d5 = { async [Symbol.asyncDispose]() {} }; ++ yield; ++ await null; ++} ++ ++const a = async () => { ++ await using d6 = { async [Symbol.asyncDispose]() {} }; ++}; ++ ++class C1 { ++ a = async () => { ++ await using d7 = { async [Symbol.asyncDispose]() {} }; ++ }; ++ ++ async am() { ++ await using d13 = { async [Symbol.asyncDispose]() {} }; ++ await null; ++ } ++ ++ async * ag() { ++ await using d15 = { async [Symbol.asyncDispose]() {} }; ++ yield; ++ await null; ++ } ++} ++ ++{ ++ await using d19 = { async [Symbol.asyncDispose]() {} }; ++} ++ ++switch (Math.random()) { ++ case 0: ++ await using d20 = { async [Symbol.asyncDispose]() {} }; ++ break; ++ ++ case 1: ++ await using d21 = { async [Symbol.asyncDispose]() {} }; ++ break; ++} ++ ++if (true) ++ switch (0) { ++ case 0: ++ await using d22 = { async [Symbol.asyncDispose]() {} }; ++ break; ++ } ++ ++try { ++ await using d23 = { async [Symbol.asyncDispose]() {} }; ++} ++catch { ++ await using d24 = { async [Symbol.asyncDispose]() {} }; ++} ++finally { ++ await using d25 = { async [Symbol.asyncDispose]() {} }; ++} ++ ++if (true) { ++ await using d26 = { async [Symbol.asyncDispose]() {} }; ++} ++else { ++ await using d27 = { async [Symbol.asyncDispose]() {} }; ++} ++ ++while (true) { ++ await using d28 = { async [Symbol.asyncDispose]() {} }; ++ break; ++} ++ ++do { ++ await using d29 = { async [Symbol.asyncDispose]() {} }; ++ break; ++} ++while (true); ++ ++for (;;) { ++ await using d30 = { async [Symbol.asyncDispose]() {} }; ++ break; ++} ++ ++for (const x in {}) { ++ await using d31 = { async [Symbol.asyncDispose]() {} }; ++} ++ ++for (const x of []) { ++ await using d32 = { async [Symbol.asyncDispose]() {} }; ++} ++ ++export {}; +\ No newline at end of file +diff --git a/tests/cases/conformance/statements/VariableStatements/usingDeclarations/awaitUsingDeclarations.10.ts b/tests/cases/conformance/statements/VariableStatements/usingDeclarations/awaitUsingDeclarations.10.ts +new file mode 100644 +index 000000000..1f132c396 +--- /dev/null ++++ b/tests/cases/conformance/statements/VariableStatements/usingDeclarations/awaitUsingDeclarations.10.ts +@@ -0,0 +1,11 @@ ++// @target: esnext ++// @module: esnext ++// @lib: esnext ++// @noTypesAndSymbols: true ++ ++export {}; ++ ++declare var x: any; ++async function f() { ++ if (x) await using a = null; ++} +\ No newline at end of file +diff --git a/tests/cases/conformance/statements/VariableStatements/usingDeclarations/awaitUsingDeclarations.11.ts b/tests/cases/conformance/statements/VariableStatements/usingDeclarations/awaitUsingDeclarations.11.ts +new file mode 100644 +index 000000000..d22e7abcc +--- /dev/null ++++ b/tests/cases/conformance/statements/VariableStatements/usingDeclarations/awaitUsingDeclarations.11.ts +@@ -0,0 +1,7 @@ ++// @target: esnext ++// @module: esnext ++// @lib: esnext ++// @noTypesAndSymbols: true ++ ++export await using x = null; ++declare await using y: null; +diff --git a/tests/cases/conformance/statements/VariableStatements/usingDeclarations/awaitUsingDeclarations.12.ts b/tests/cases/conformance/statements/VariableStatements/usingDeclarations/awaitUsingDeclarations.12.ts +new file mode 100644 +index 000000000..601397010 +--- /dev/null ++++ b/tests/cases/conformance/statements/VariableStatements/usingDeclarations/awaitUsingDeclarations.12.ts +@@ -0,0 +1,8 @@ ++// @target: esnext ++// @module: esnext ++// @lib: esnext ++// @noTypesAndSymbols: true ++ ++async function f() { ++ await using x = {}; ++} +\ No newline at end of file +diff --git a/tests/cases/conformance/statements/VariableStatements/usingDeclarations/awaitUsingDeclarations.13.ts b/tests/cases/conformance/statements/VariableStatements/usingDeclarations/awaitUsingDeclarations.13.ts +new file mode 100644 +index 000000000..c1a88f304 +--- /dev/null ++++ b/tests/cases/conformance/statements/VariableStatements/usingDeclarations/awaitUsingDeclarations.13.ts +@@ -0,0 +1,10 @@ ++// @target: esnext ++// @module: esnext ++// @lib: esnext ++// @noTypesAndSymbols: true ++ ++await using x = null; ++ ++function f() { ++ await using x = null; ++} +\ No newline at end of file +diff --git a/tests/cases/conformance/statements/VariableStatements/usingDeclarations/awaitUsingDeclarations.14.ts b/tests/cases/conformance/statements/VariableStatements/usingDeclarations/awaitUsingDeclarations.14.ts +new file mode 100644 +index 000000000..9a32c0614 +--- /dev/null ++++ b/tests/cases/conformance/statements/VariableStatements/usingDeclarations/awaitUsingDeclarations.14.ts +@@ -0,0 +1,13 @@ ++// @target: esnext ++// @module: esnext ++// @lib: esnext ++// @noTypesAndSymbols: true ++ ++class C { ++ static { ++ await using x = null; ++ { ++ await using y = null; ++ } ++ } ++} +diff --git a/tests/cases/conformance/statements/VariableStatements/usingDeclarations/awaitUsingDeclarations.15.ts b/tests/cases/conformance/statements/VariableStatements/usingDeclarations/awaitUsingDeclarations.15.ts +new file mode 100644 +index 000000000..f92136565 +--- /dev/null ++++ b/tests/cases/conformance/statements/VariableStatements/usingDeclarations/awaitUsingDeclarations.15.ts +@@ -0,0 +1,9 @@ ++// @target: esnext ++// @module: esnext ++// @lib: esnext ++// @noTypesAndSymbols: true ++// @noUnusedLocals: true ++ ++async function f() { ++ await using _ = { async [Symbol.asyncDispose]() {} }; ++} +\ No newline at end of file +diff --git a/tests/cases/conformance/statements/VariableStatements/usingDeclarations/awaitUsingDeclarations.2.ts b/tests/cases/conformance/statements/VariableStatements/usingDeclarations/awaitUsingDeclarations.2.ts +new file mode 100644 +index 000000000..b93a86483 +--- /dev/null ++++ b/tests/cases/conformance/statements/VariableStatements/usingDeclarations/awaitUsingDeclarations.2.ts +@@ -0,0 +1,11 @@ ++// @target: esnext,es2022,es2017,es2015,es5 ++// @module: esnext ++// @lib: esnext ++// @noTypesAndSymbols: true ++ ++{ ++ await using d1 = { async [Symbol.asyncDispose]() {} }, ++ d2 = { async [Symbol.asyncDispose]() {} }; ++} ++ ++export {}; +\ No newline at end of file +diff --git a/tests/cases/conformance/statements/VariableStatements/usingDeclarations/awaitUsingDeclarations.3.ts b/tests/cases/conformance/statements/VariableStatements/usingDeclarations/awaitUsingDeclarations.3.ts +new file mode 100644 +index 000000000..cf1eee443 +--- /dev/null ++++ b/tests/cases/conformance/statements/VariableStatements/usingDeclarations/awaitUsingDeclarations.3.ts +@@ -0,0 +1,13 @@ ++// @target: esnext,es2022,es2017,es2015,es5 ++// @module: esnext ++// @lib: esnext ++// @noTypesAndSymbols: true ++ ++{ ++ await using d1 = { async [Symbol.asyncDispose]() {} }, ++ d2 = null, ++ d3 = undefined, ++ d4 = { [Symbol.dispose]() {} }; ++} ++ ++export {}; +\ No newline at end of file +diff --git a/tests/cases/conformance/statements/VariableStatements/usingDeclarations/awaitUsingDeclarations.4.ts b/tests/cases/conformance/statements/VariableStatements/usingDeclarations/awaitUsingDeclarations.4.ts +new file mode 100644 +index 000000000..251cba55f +--- /dev/null ++++ b/tests/cases/conformance/statements/VariableStatements/usingDeclarations/awaitUsingDeclarations.4.ts +@@ -0,0 +1,10 @@ ++// @target: esnext ++// @module: esnext ++// @lib: esnext ++// @noTypesAndSymbols: true ++ ++{ ++ await using [a] = null; ++} ++ ++export {}; +\ No newline at end of file +diff --git a/tests/cases/conformance/statements/VariableStatements/usingDeclarations/awaitUsingDeclarations.5.ts b/tests/cases/conformance/statements/VariableStatements/usingDeclarations/awaitUsingDeclarations.5.ts +new file mode 100644 +index 000000000..b172bdab8 +--- /dev/null ++++ b/tests/cases/conformance/statements/VariableStatements/usingDeclarations/awaitUsingDeclarations.5.ts +@@ -0,0 +1,12 @@ ++// @target: esnext ++// @module: esnext ++// @lib: esnext ++// @noTypesAndSymbols: true ++ ++{ ++ await using a = null, ++ [b] = null, ++ c = null; ++} ++ ++export {}; +\ No newline at end of file +diff --git a/tests/cases/conformance/statements/VariableStatements/usingDeclarations/awaitUsingDeclarations.6.ts b/tests/cases/conformance/statements/VariableStatements/usingDeclarations/awaitUsingDeclarations.6.ts +new file mode 100644 +index 000000000..9a5d109f2 +--- /dev/null ++++ b/tests/cases/conformance/statements/VariableStatements/usingDeclarations/awaitUsingDeclarations.6.ts +@@ -0,0 +1,11 @@ ++// @target: esnext ++// @module: esnext ++// @lib: esnext ++// @noTypesAndSymbols: true ++ ++{ ++ await using {a} = null; ++} ++ ++ ++export {}; +\ No newline at end of file +diff --git a/tests/cases/conformance/statements/VariableStatements/usingDeclarations/awaitUsingDeclarations.7.ts b/tests/cases/conformance/statements/VariableStatements/usingDeclarations/awaitUsingDeclarations.7.ts +new file mode 100644 +index 000000000..f246cd1aa +--- /dev/null ++++ b/tests/cases/conformance/statements/VariableStatements/usingDeclarations/awaitUsingDeclarations.7.ts +@@ -0,0 +1,10 @@ ++// @target: esnext ++// @module: esnext ++// @lib: esnext ++// @noTypesAndSymbols: true ++ ++{ ++ await using a = null, ++ {b} = null, ++ c = null; ++} +\ No newline at end of file +diff --git a/tests/cases/conformance/statements/VariableStatements/usingDeclarations/awaitUsingDeclarations.8.ts b/tests/cases/conformance/statements/VariableStatements/usingDeclarations/awaitUsingDeclarations.8.ts +new file mode 100644 +index 000000000..1dfa88ce8 +--- /dev/null ++++ b/tests/cases/conformance/statements/VariableStatements/usingDeclarations/awaitUsingDeclarations.8.ts +@@ -0,0 +1,10 @@ ++// @target: esnext ++// @module: esnext ++// @lib: esnext ++// @noTypesAndSymbols: true ++ ++{ ++ await using a; ++} ++ ++export {}; +\ No newline at end of file +diff --git a/tests/cases/conformance/statements/VariableStatements/usingDeclarations/awaitUsingDeclarations.9.ts b/tests/cases/conformance/statements/VariableStatements/usingDeclarations/awaitUsingDeclarations.9.ts +new file mode 100644 +index 000000000..b9fba2635 +--- /dev/null ++++ b/tests/cases/conformance/statements/VariableStatements/usingDeclarations/awaitUsingDeclarations.9.ts +@@ -0,0 +1,10 @@ ++// @target: esnext ++// @module: esnext ++// @lib: es2022 ++// @noTypesAndSymbols: true ++ ++{ ++ await using a = null; ++} ++ ++export {}; +\ No newline at end of file +diff --git a/tests/cases/conformance/statements/VariableStatements/usingDeclarations/awaitUsingDeclarationsInFor.ts b/tests/cases/conformance/statements/VariableStatements/usingDeclarations/awaitUsingDeclarationsInFor.ts +new file mode 100644 +index 000000000..0f075d4a7 +--- /dev/null ++++ b/tests/cases/conformance/statements/VariableStatements/usingDeclarations/awaitUsingDeclarationsInFor.ts +@@ -0,0 +1,11 @@ ++// @target: esnext,es2022,es2017,es2015,es5 ++// @module: esnext ++// @lib: esnext ++// @noTypesAndSymbols: true ++async function main() { ++ for (await using d1 = { [Symbol.dispose]() {} }, ++ d2 = { async [Symbol.asyncDispose]() {} }, ++ d3 = null, ++ d4 = undefined;;) { ++ } ++} +\ No newline at end of file +diff --git a/tests/cases/conformance/statements/VariableStatements/usingDeclarations/awaitUsingDeclarationsInForAwaitOf.ts b/tests/cases/conformance/statements/VariableStatements/usingDeclarations/awaitUsingDeclarationsInForAwaitOf.ts +new file mode 100644 +index 000000000..8f488313a +--- /dev/null ++++ b/tests/cases/conformance/statements/VariableStatements/usingDeclarations/awaitUsingDeclarationsInForAwaitOf.ts +@@ -0,0 +1,8 @@ ++// @target: esnext,es2022,es2017,es2015,es5 ++// @module: esnext ++// @lib: esnext ++// @noTypesAndSymbols: true ++async function main() { ++ for await (await using d1 of [{ async [Symbol.asyncDispose]() {} }, { [Symbol.dispose]() {} }, null, undefined]) { ++ } ++} +\ No newline at end of file +diff --git a/tests/cases/conformance/statements/VariableStatements/usingDeclarations/awaitUsingDeclarationsInForIn.ts b/tests/cases/conformance/statements/VariableStatements/usingDeclarations/awaitUsingDeclarationsInForIn.ts +new file mode 100644 +index 000000000..12621f830 +--- /dev/null ++++ b/tests/cases/conformance/statements/VariableStatements/usingDeclarations/awaitUsingDeclarationsInForIn.ts +@@ -0,0 +1,9 @@ ++// @target: esnext ++// @module: esnext ++// @lib: esnext ++// @noTypesAndSymbols: true ++ ++async function main() { ++ for (await using x in {}) { ++ } ++} +diff --git a/tests/cases/conformance/statements/VariableStatements/usingDeclarations/awaitUsingDeclarationsInForOf.1.ts b/tests/cases/conformance/statements/VariableStatements/usingDeclarations/awaitUsingDeclarationsInForOf.1.ts +new file mode 100644 +index 000000000..cd26c931d +--- /dev/null ++++ b/tests/cases/conformance/statements/VariableStatements/usingDeclarations/awaitUsingDeclarationsInForOf.1.ts +@@ -0,0 +1,9 @@ ++// @target: esnext,es2022,es2017,es2015,es5 ++// @module: esnext ++// @lib: esnext ++// @noTypesAndSymbols: true ++ ++async function main() { ++ for (await using d1 of [{ async [Symbol.asyncDispose]() {} }, { [Symbol.dispose]() {} }, null, undefined]) { ++ } ++} +diff --git a/tests/cases/conformance/statements/VariableStatements/usingDeclarations/awaitUsingDeclarationsInForOf.2.ts b/tests/cases/conformance/statements/VariableStatements/usingDeclarations/awaitUsingDeclarationsInForOf.2.ts +new file mode 100644 +index 000000000..4d6ac155a +--- /dev/null ++++ b/tests/cases/conformance/statements/VariableStatements/usingDeclarations/awaitUsingDeclarationsInForOf.2.ts +@@ -0,0 +1,9 @@ ++// @target: esnext ++// @module: esnext ++// @lib: esnext ++// @noTypesAndSymbols: true ++ ++async function main() { ++ for (await using of of []) { ++ } ++} +diff --git a/tests/cases/conformance/statements/VariableStatements/usingDeclarations/awaitUsingDeclarationsInForOf.3.ts b/tests/cases/conformance/statements/VariableStatements/usingDeclarations/awaitUsingDeclarationsInForOf.3.ts +new file mode 100644 +index 000000000..e686baa11 +--- /dev/null ++++ b/tests/cases/conformance/statements/VariableStatements/usingDeclarations/awaitUsingDeclarationsInForOf.3.ts +@@ -0,0 +1,9 @@ ++// @target: esnext ++// @module: esnext ++// @lib: esnext ++// @noTypesAndSymbols: true ++ ++async function main() { ++ for (await using {} of []) { ++ } ++} +diff --git a/tests/cases/conformance/statements/VariableStatements/usingDeclarations/awaitUsingDeclarationsTopLevelOfModule.1.ts b/tests/cases/conformance/statements/VariableStatements/usingDeclarations/awaitUsingDeclarationsTopLevelOfModule.1.ts +new file mode 100644 +index 000000000..4daedf413 +--- /dev/null ++++ b/tests/cases/conformance/statements/VariableStatements/usingDeclarations/awaitUsingDeclarationsTopLevelOfModule.1.ts +@@ -0,0 +1,18 @@ ++// @target: es2022 ++// @lib: esnext,dom ++// @module: system,esnext ++// @noTypesAndSymbols: true ++// @noEmitHelpers: true ++ ++export const x = 1; ++export { y }; ++ ++await using z = { async [Symbol.asyncDispose]() {} }; ++ ++const y = 2; ++ ++export const w = 3; ++ ++export default 4; ++ ++console.log(w, x, y, z); +diff --git a/tests/cases/conformance/statements/VariableStatements/usingDeclarations/awaitUsingDeclarationsWithImportHelpers.ts b/tests/cases/conformance/statements/VariableStatements/usingDeclarations/awaitUsingDeclarationsWithImportHelpers.ts +new file mode 100644 +index 000000000..28fbc0b65 +--- /dev/null ++++ b/tests/cases/conformance/statements/VariableStatements/usingDeclarations/awaitUsingDeclarationsWithImportHelpers.ts +@@ -0,0 +1,11 @@ ++// @target: esnext ++// @module: esnext ++// @lib: esnext ++// @importHelpers: true ++// @noTypesAndSymbols: true ++ ++export {}; ++ ++async function f() { ++ await using a = null; ++} +\ No newline at end of file +diff --git a/tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarations.1.ts b/tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarations.1.ts +new file mode 100644 +index 000000000..48339bbdd +--- /dev/null ++++ b/tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarations.1.ts +@@ -0,0 +1,156 @@ ++// @target: esnext,es2022,es2017,es2015,es5 ++// @module: esnext ++// @lib: esnext ++// @noTypesAndSymbols: true ++ ++using d1 = { [Symbol.dispose]() {} }; ++ ++function f() { ++ using d2 = { [Symbol.dispose]() {} }; ++} ++ ++async function af() { ++ using d3 = { [Symbol.dispose]() {} }; ++ await null; ++} ++ ++function * g() { ++ using d4 = { [Symbol.dispose]() {} }; ++ yield; ++} ++ ++async function * ag() { ++ using d5 = { [Symbol.dispose]() {} }; ++ yield; ++ await null; ++} ++ ++const a = () => { ++ using d6 = { [Symbol.dispose]() {} }; ++} ++ ++class C1 { ++ a = () => { ++ using d7 = { [Symbol.dispose]() {} }; ++ } ++ ++ constructor() { ++ using d8 = { [Symbol.dispose]() {} }; ++ } ++ ++ static { ++ using d9 = { [Symbol.dispose]() {} }; ++ } ++ ++ m() { ++ using d10 = { [Symbol.dispose]() {} }; ++ } ++ ++ get x() { ++ using d11 = { [Symbol.dispose]() {} }; ++ return 0; ++ } ++ ++ set x(v) { ++ using d12 = { [Symbol.dispose]() {} }; ++ } ++ ++ async am() { ++ using d13 = { [Symbol.dispose]() {} }; ++ await null; ++ } ++ ++ * g() { ++ using d14 = { [Symbol.dispose]() {} }; ++ yield; ++ } ++ ++ async * ag() { ++ using d15 = { [Symbol.dispose]() {} }; ++ yield; ++ await null; ++ } ++} ++ ++class C2 extends C1 { ++ constructor() { ++ using d16 = { [Symbol.dispose]() {} }; ++ super(); ++ } ++} ++ ++class C3 extends C1 { ++ y = 1; ++ constructor() { ++ using d17 = { [Symbol.dispose]() {} }; ++ super(); ++ } ++} ++ ++namespace N { ++ using d18 = { [Symbol.dispose]() {} }; ++} ++ ++{ ++ using d19 = { [Symbol.dispose]() {} }; ++} ++ ++switch (Math.random()) { ++ case 0: ++ using d20 = { [Symbol.dispose]() {} }; ++ break; ++ ++ case 1: ++ using d21 = { [Symbol.dispose]() {} }; ++ break; ++} ++ ++if (true) ++ switch (0) { ++ case 0: ++ using d22 = { [Symbol.dispose]() {} }; ++ break; ++ } ++ ++try { ++ using d23 = { [Symbol.dispose]() {} }; ++} ++catch { ++ using d24 = { [Symbol.dispose]() {} }; ++} ++finally { ++ using d25 = { [Symbol.dispose]() {} }; ++} ++ ++if (true) { ++ using d26 = { [Symbol.dispose]() {} }; ++} ++else { ++ using d27 = { [Symbol.dispose]() {} }; ++} ++ ++while (true) { ++ using d28 = { [Symbol.dispose]() {} }; ++ break; ++} ++ ++do { ++ using d29 = { [Symbol.dispose]() {} }; ++ break; ++} ++while (true); ++ ++for (;;) { ++ using d30 = { [Symbol.dispose]() {} }; ++ break; ++} ++ ++for (const x in {}) { ++ using d31 = { [Symbol.dispose]() {} }; ++} ++ ++for (const x of []) { ++ using d32 = { [Symbol.dispose]() {} }; ++} ++ ++export {}; +\ No newline at end of file +diff --git a/tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarations.10.ts b/tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarations.10.ts +new file mode 100644 +index 000000000..13a77b437 +--- /dev/null ++++ b/tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarations.10.ts +@@ -0,0 +1,7 @@ ++// @target: esnext ++// @module: esnext ++// @lib: esnext ++// @noTypesAndSymbols: true ++ ++declare var x: any; ++if (x) using a = null; +diff --git a/tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarations.11.ts b/tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarations.11.ts +new file mode 100644 +index 000000000..603e25901 +--- /dev/null ++++ b/tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarations.11.ts +@@ -0,0 +1,38 @@ ++// @target: es5 ++// @module: esnext ++// @lib: esnext ++// @noTypesAndSymbols: true ++ ++class A {} ++class C1 extends A { ++ constructor() { ++ using x = null; ++ super(); ++ } ++} ++class C2 extends A { ++ constructor() { ++ super(); ++ using x = null; ++ } ++} ++class C3 extends A { ++ y = 1; ++ constructor() { ++ using x = null; ++ super(); ++ } ++} ++class C4 extends A { ++ constructor(public y: number) { ++ using x = null; ++ super(); ++ } ++} ++class C5 extends A { ++ z = 1; ++ constructor(public y: number) { ++ using x = null; ++ super(); ++ } ++} +diff --git a/tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarations.12.ts b/tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarations.12.ts +new file mode 100644 +index 000000000..fd24eff92 +--- /dev/null ++++ b/tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarations.12.ts +@@ -0,0 +1,17 @@ ++// @target: es2018 ++// @module: esnext ++// @lib: esnext ++// @noTypesAndSymbols: true ++// @useDefineForClassFields: * ++ ++class C1 { ++ constructor() {} ++} ++ ++class C2 extends C1 { ++ y = 1; ++ constructor() { ++ super(); ++ using d17 = { [Symbol.dispose]() {} }; ++ } ++} +\ No newline at end of file +diff --git a/tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarations.13.ts b/tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarations.13.ts +new file mode 100644 +index 000000000..164c1fae8 +--- /dev/null ++++ b/tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarations.13.ts +@@ -0,0 +1,7 @@ ++// @target: esnext ++// @module: esnext ++// @lib: esnext ++// @noTypesAndSymbols: true ++ ++export using x = null; ++declare using y: null; +diff --git a/tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarations.14.ts b/tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarations.14.ts +new file mode 100644 +index 000000000..7489f99a0 +--- /dev/null ++++ b/tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarations.14.ts +@@ -0,0 +1,6 @@ ++// @target: esnext ++// @module: esnext ++// @lib: esnext ++// @noTypesAndSymbols: true ++ ++using x = {}; +\ No newline at end of file +diff --git a/tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarations.15.ts b/tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarations.15.ts +new file mode 100644 +index 000000000..79b0032da +--- /dev/null ++++ b/tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarations.15.ts +@@ -0,0 +1,9 @@ ++// @target: esnext ++// @module: esnext ++// @lib: esnext ++// @noTypesAndSymbols: true ++// @noUnusedLocals: true ++ ++export {}; ++ ++using _ = { [Symbol.dispose]() {} }; +\ No newline at end of file +diff --git a/tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarations.2.ts b/tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarations.2.ts +new file mode 100644 +index 000000000..77dbf61af +--- /dev/null ++++ b/tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarations.2.ts +@@ -0,0 +1,9 @@ ++// @target: esnext,es2022,es2017,es2015,es5 ++// @module: esnext ++// @lib: esnext ++// @noTypesAndSymbols: true ++ ++{ ++ using d1 = { [Symbol.dispose]() {} }, ++ d2 = { [Symbol.dispose]() {} }; ++} +diff --git a/tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarations.3.ts b/tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarations.3.ts +new file mode 100644 +index 000000000..90991a578 +--- /dev/null ++++ b/tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarations.3.ts +@@ -0,0 +1,11 @@ ++// @target: esnext,es2022,es2017,es2015,es5 ++// @module: esnext ++// @lib: esnext ++// @noTypesAndSymbols: true ++ ++{ ++ using d1 = { [Symbol.dispose]() {} }, ++ d2 = null, ++ d3 = undefined, ++ d4 = { [Symbol.dispose]() {} }; ++} +diff --git a/tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarations.4.ts b/tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarations.4.ts +new file mode 100644 +index 000000000..f8118cbe6 +--- /dev/null ++++ b/tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarations.4.ts +@@ -0,0 +1,8 @@ ++// @target: esnext ++// @module: esnext ++// @lib: esnext ++// @noTypesAndSymbols: true ++ ++{ ++ using [a] = null; ++} +\ No newline at end of file +diff --git a/tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarations.5.ts b/tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarations.5.ts +new file mode 100644 +index 000000000..c328e3e99 +--- /dev/null ++++ b/tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarations.5.ts +@@ -0,0 +1,10 @@ ++// @target: esnext ++// @module: esnext ++// @lib: esnext ++// @noTypesAndSymbols: true ++ ++{ ++ using a = null, ++ [b] = null, ++ c = null; ++} +diff --git a/tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarations.6.ts b/tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarations.6.ts +new file mode 100644 +index 000000000..62b76cb4d +--- /dev/null ++++ b/tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarations.6.ts +@@ -0,0 +1,8 @@ ++// @target: esnext ++// @module: esnext ++// @lib: esnext ++// @noTypesAndSymbols: true ++ ++{ ++ using {a} = null; ++} +diff --git a/tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarations.7.ts b/tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarations.7.ts +new file mode 100644 +index 000000000..4f0a36205 +--- /dev/null ++++ b/tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarations.7.ts +@@ -0,0 +1,10 @@ ++// @target: esnext ++// @module: esnext ++// @lib: esnext ++// @noTypesAndSymbols: true ++ ++{ ++ using a = null, ++ {b} = null, ++ c = null; ++} +\ No newline at end of file +diff --git a/tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarations.8.ts b/tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarations.8.ts +new file mode 100644 +index 000000000..70859a431 +--- /dev/null ++++ b/tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarations.8.ts +@@ -0,0 +1,8 @@ ++// @target: esnext ++// @module: esnext ++// @lib: esnext ++// @noTypesAndSymbols: true ++ ++{ ++ using a; ++} +\ No newline at end of file +diff --git a/tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarations.9.ts b/tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarations.9.ts +new file mode 100644 +index 000000000..cec1bd79e +--- /dev/null ++++ b/tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarations.9.ts +@@ -0,0 +1,8 @@ ++// @target: esnext ++// @module: esnext ++// @lib: es2022 ++// @noTypesAndSymbols: true ++ ++{ ++ using a = null; ++} +\ No newline at end of file +diff --git a/tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsDeclarationEmit.1.ts b/tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsDeclarationEmit.1.ts +new file mode 100644 +index 000000000..d952dcb91 +--- /dev/null ++++ b/tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsDeclarationEmit.1.ts +@@ -0,0 +1,10 @@ ++// @target: esnext ++// @module: esnext ++// @declaration: true ++// @noTypesAndSymbols: true ++ ++using r1 = { [Symbol.dispose]() {} }; ++export { r1 }; ++ ++await using r2 = { async [Symbol.asyncDispose]() {} }; ++export { r2 }; +diff --git a/tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsDeclarationEmit.2.ts b/tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsDeclarationEmit.2.ts +new file mode 100644 +index 000000000..5b3e21dea +--- /dev/null ++++ b/tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsDeclarationEmit.2.ts +@@ -0,0 +1,10 @@ ++// @target: esnext ++// @module: esnext ++// @declaration: true ++// @noTypesAndSymbols: true ++ ++using r1 = { [Symbol.dispose]() {} }; ++export type R1 = typeof r1; ++ ++await using r2 = { async [Symbol.asyncDispose]() {} }; ++export type R2 = typeof r2; +diff --git a/tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsInFor.ts b/tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsInFor.ts +new file mode 100644 +index 000000000..a7209fa70 +--- /dev/null ++++ b/tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsInFor.ts +@@ -0,0 +1,7 @@ ++// @target: esnext,es2022,es2017,es2015,es5 ++// @module: esnext ++// @lib: esnext ++// @noTypesAndSymbols: true ++ ++for (using d1 = { [Symbol.dispose]() {} }, d2 = null, d3 = undefined;;) { ++} +diff --git a/tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsInForAwaitOf.ts b/tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsInForAwaitOf.ts +new file mode 100644 +index 000000000..807e2acce +--- /dev/null ++++ b/tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsInForAwaitOf.ts +@@ -0,0 +1,9 @@ ++// @target: esnext,es2022,es2017,es2015,es5 ++// @module: esnext ++// @lib: esnext ++// @noTypesAndSymbols: true ++ ++async function main() { ++ for await (using d1 of [{ [Symbol.dispose]() {} }, null, undefined]) { ++ } ++} +diff --git a/tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsInForIn.ts b/tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsInForIn.ts +new file mode 100644 +index 000000000..ea9c191ed +--- /dev/null ++++ b/tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsInForIn.ts +@@ -0,0 +1,7 @@ ++// @target: esnext ++// @module: esnext ++// @lib: esnext ++// @noTypesAndSymbols: true ++ ++for (using x in {}) { ++} +diff --git a/tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsInForOf.1.ts b/tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsInForOf.1.ts +new file mode 100644 +index 000000000..be2412cb1 +--- /dev/null ++++ b/tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsInForOf.1.ts +@@ -0,0 +1,7 @@ ++// @target: esnext,es2022,es2017,es2015,es5 ++// @module: esnext ++// @lib: esnext ++// @noTypesAndSymbols: true ++ ++for (using d1 of [{ [Symbol.dispose]() {} }, null, undefined]) { ++} +diff --git a/tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsInForOf.2.ts b/tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsInForOf.2.ts +new file mode 100644 +index 000000000..50ffa8ec3 +--- /dev/null ++++ b/tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsInForOf.2.ts +@@ -0,0 +1,7 @@ ++// @target: esnext ++// @module: esnext ++// @lib: esnext ++// @noTypesAndSymbols: true ++ ++for (using of of []) { ++} +diff --git a/tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsInForOf.3.ts b/tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsInForOf.3.ts +new file mode 100644 +index 000000000..a897bf196 +--- /dev/null ++++ b/tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsInForOf.3.ts +@@ -0,0 +1,7 @@ ++// @target: esnext ++// @module: esnext ++// @lib: esnext ++// @noTypesAndSymbols: true ++ ++for (using {} of []) { ++} +diff --git a/tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsNamedEvaluationDecoratorsAndClassFields.ts b/tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsNamedEvaluationDecoratorsAndClassFields.ts +new file mode 100644 +index 000000000..810ad466a +--- /dev/null ++++ b/tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsNamedEvaluationDecoratorsAndClassFields.ts +@@ -0,0 +1,26 @@ ++// @target: es2018 ++// @module: esnext ++// @lib: esnext ++// @noTypesAndSymbols: true ++ ++export {}; ++ ++declare var dec: any; ++ ++using C1 = class { ++ static [Symbol.dispose]() {} ++}; ++ ++using C2 = class { ++ static x = 1; ++ static [Symbol.dispose]() {} ++}; ++ ++using C3 = @dec class { ++ static [Symbol.dispose]() {} ++}; ++ ++using C4 = @dec class { ++ static x = 1; ++ static [Symbol.dispose]() {} ++}; +diff --git a/tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsTopLevelOfModule.1.ts b/tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsTopLevelOfModule.1.ts +new file mode 100644 +index 000000000..fe7e2b650 +--- /dev/null ++++ b/tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsTopLevelOfModule.1.ts +@@ -0,0 +1,18 @@ ++// @target: es2022 ++// @lib: esnext,dom ++// @module: commonjs,system,esnext,amd ++// @noTypesAndSymbols: true ++// @noEmitHelpers: true ++ ++export const x = 1; ++export { y }; ++ ++using z = { [Symbol.dispose]() {} }; ++ ++const y = 2; ++ ++export const w = 3; ++ ++export default 4; ++ ++console.log(w, x, y, z); +diff --git a/tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsTopLevelOfModule.2.ts b/tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsTopLevelOfModule.2.ts +new file mode 100644 +index 000000000..bcef291f5 +--- /dev/null ++++ b/tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsTopLevelOfModule.2.ts +@@ -0,0 +1,12 @@ ++// @target: es2022 ++// @lib: esnext,dom ++// @module: commonjs,amd ++// @noTypesAndSymbols: true ++// @noEmitHelpers: true ++ ++using z = { [Symbol.dispose]() {} }; ++ ++const y = 2; ++ ++console.log(y, z); ++export = 4; +diff --git a/tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsTopLevelOfModule.3.ts b/tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsTopLevelOfModule.3.ts +new file mode 100644 +index 000000000..2804f3e4a +--- /dev/null ++++ b/tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsTopLevelOfModule.3.ts +@@ -0,0 +1,18 @@ ++// @target: es2022 ++// @lib: esnext,dom ++// @module: commonjs,system,esnext,amd ++// @noTypesAndSymbols: true ++// @noEmitHelpers: true ++ ++export { y }; ++ ++using z = { [Symbol.dispose]() {} }; ++ ++if (false) { ++ var y = 1; ++} ++ ++function f() { ++ console.log(y, z); ++} ++ +diff --git a/tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsWithESClassDecorators.1.ts b/tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsWithESClassDecorators.1.ts +new file mode 100644 +index 000000000..e6da37efd +--- /dev/null ++++ b/tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsWithESClassDecorators.1.ts +@@ -0,0 +1,15 @@ ++// @target: esnext,es2015,es5 ++// @module: commonjs,system,esnext ++// @lib: esnext ++// @experimentalDecorators: false ++// @noTypesAndSymbols: true ++// @noEmitHelpers: true ++export {}; ++ ++declare var dec: any; ++ ++using before = null; ++ ++@dec ++class C { ++} +diff --git a/tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsWithESClassDecorators.10.ts b/tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsWithESClassDecorators.10.ts +new file mode 100644 +index 000000000..09228bd94 +--- /dev/null ++++ b/tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsWithESClassDecorators.10.ts +@@ -0,0 +1,15 @@ ++// @target: esnext,es2015,es5 ++// @module: commonjs,system,esnext ++// @lib: esnext ++// @experimentalDecorators: false ++// @noTypesAndSymbols: true ++// @noEmitHelpers: true ++export {}; ++ ++declare var dec: any; ++ ++@dec ++export default class { ++} ++ ++using after = null; +diff --git a/tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsWithESClassDecorators.11.ts b/tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsWithESClassDecorators.11.ts +new file mode 100644 +index 000000000..e3b426e06 +--- /dev/null ++++ b/tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsWithESClassDecorators.11.ts +@@ -0,0 +1,17 @@ ++// @target: esnext,es2015,es5 ++// @module: commonjs,system,esnext ++// @lib: esnext ++// @experimentalDecorators: false ++// @noTypesAndSymbols: true ++// @noEmitHelpers: true ++export {}; ++ ++declare var dec: any; ++ ++@dec ++class C { ++} ++ ++export { C }; ++ ++using after = null; +diff --git a/tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsWithESClassDecorators.12.ts b/tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsWithESClassDecorators.12.ts +new file mode 100644 +index 000000000..e925063f9 +--- /dev/null ++++ b/tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsWithESClassDecorators.12.ts +@@ -0,0 +1,17 @@ ++// @target: esnext,es2015,es5 ++// @module: commonjs,system,esnext ++// @lib: esnext ++// @experimentalDecorators: false ++// @noTypesAndSymbols: true ++// @noEmitHelpers: true ++export {}; ++ ++declare var dec: any; ++ ++@dec ++class C { ++} ++ ++export { C as D }; ++ ++using after = null; +diff --git a/tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsWithESClassDecorators.2.ts b/tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsWithESClassDecorators.2.ts +new file mode 100644 +index 000000000..d34b1d21e +--- /dev/null ++++ b/tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsWithESClassDecorators.2.ts +@@ -0,0 +1,15 @@ ++// @target: esnext,es2015,es5 ++// @module: commonjs,system,esnext ++// @lib: esnext ++// @experimentalDecorators: false ++// @noTypesAndSymbols: true ++// @noEmitHelpers: true ++export {}; ++ ++declare var dec: any; ++ ++using before = null; ++ ++@dec ++export class C { ++} +diff --git a/tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsWithESClassDecorators.3.ts b/tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsWithESClassDecorators.3.ts +new file mode 100644 +index 000000000..f3fdfea70 +--- /dev/null ++++ b/tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsWithESClassDecorators.3.ts +@@ -0,0 +1,17 @@ ++// @target: esnext,es2015,es5 ++// @module: commonjs,system,esnext ++// @lib: esnext ++// @experimentalDecorators: false ++// @noTypesAndSymbols: true ++// @noEmitHelpers: true ++export {}; ++ ++declare var dec: any; ++ ++using before = null; ++ ++@dec ++export default class C { ++} ++ ++void C; +\ No newline at end of file +diff --git a/tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsWithESClassDecorators.4.ts b/tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsWithESClassDecorators.4.ts +new file mode 100644 +index 000000000..9ef4a5802 +--- /dev/null ++++ b/tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsWithESClassDecorators.4.ts +@@ -0,0 +1,15 @@ ++// @target: esnext,es2015,es5 ++// @module: commonjs,system,esnext ++// @lib: esnext ++// @experimentalDecorators: false ++// @noTypesAndSymbols: true ++// @noEmitHelpers: true ++export {}; ++ ++declare var dec: any; ++ ++using before = null; ++ ++@dec ++export default class { ++} +diff --git a/tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsWithESClassDecorators.5.ts b/tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsWithESClassDecorators.5.ts +new file mode 100644 +index 000000000..4062f99c9 +--- /dev/null ++++ b/tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsWithESClassDecorators.5.ts +@@ -0,0 +1,17 @@ ++// @target: esnext,es2015,es5 ++// @module: commonjs,system,esnext ++// @lib: esnext ++// @experimentalDecorators: false ++// @noTypesAndSymbols: true ++// @noEmitHelpers: true ++export {}; ++ ++declare var dec: any; ++ ++using before = null; ++ ++@dec ++class C { ++} ++ ++export { C }; +\ No newline at end of file +diff --git a/tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsWithESClassDecorators.6.ts b/tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsWithESClassDecorators.6.ts +new file mode 100644 +index 000000000..334e1a3a2 +--- /dev/null ++++ b/tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsWithESClassDecorators.6.ts +@@ -0,0 +1,17 @@ ++// @target: esnext,es2015,es5 ++// @module: commonjs,system,esnext ++// @lib: esnext ++// @experimentalDecorators: false ++// @noTypesAndSymbols: true ++// @noEmitHelpers: true ++export {}; ++ ++declare var dec: any; ++ ++using before = null; ++ ++@dec ++class C { ++} ++ ++export { C as D }; +\ No newline at end of file +diff --git a/tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsWithESClassDecorators.7.ts b/tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsWithESClassDecorators.7.ts +new file mode 100644 +index 000000000..8e24ea3bd +--- /dev/null ++++ b/tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsWithESClassDecorators.7.ts +@@ -0,0 +1,16 @@ ++// @target: esnext,es2015,es5 ++// @module: commonjs,system,esnext ++// @lib: esnext ++// @experimentalDecorators: false ++// @noTypesAndSymbols: true ++// @noEmitHelpers: true ++export {}; ++ ++declare var dec: any; ++ ++@dec ++class C { ++} ++ ++using after = null; ++ +diff --git a/tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsWithESClassDecorators.8.ts b/tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsWithESClassDecorators.8.ts +new file mode 100644 +index 000000000..fad68539c +--- /dev/null ++++ b/tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsWithESClassDecorators.8.ts +@@ -0,0 +1,15 @@ ++// @target: esnext,es2015,es5 ++// @module: commonjs,system,esnext ++// @lib: esnext ++// @experimentalDecorators: false ++// @noTypesAndSymbols: true ++// @noEmitHelpers: true ++export {}; ++ ++declare var dec: any; ++ ++@dec ++export class C { ++} ++ ++using after = null; +diff --git a/tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsWithESClassDecorators.9.ts b/tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsWithESClassDecorators.9.ts +new file mode 100644 +index 000000000..cc26af1c7 +--- /dev/null ++++ b/tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsWithESClassDecorators.9.ts +@@ -0,0 +1,18 @@ ++// @target: esnext,es2015,es5 ++// @module: commonjs,system,esnext ++// @lib: esnext ++// @experimentalDecorators: false ++// @noTypesAndSymbols: true ++// @noEmitHelpers: true ++export {}; ++ ++declare var dec: any; ++ ++@dec ++export default class C { ++} ++ ++void C; ++ ++using after = null; ++ +diff --git a/tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsWithImportHelpers.ts b/tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsWithImportHelpers.ts +new file mode 100644 +index 000000000..e137a9bc0 +--- /dev/null ++++ b/tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsWithImportHelpers.ts +@@ -0,0 +1,11 @@ ++// @target: esnext ++// @module: esnext ++// @lib: esnext ++// @importHelpers: true ++// @noTypesAndSymbols: true ++ ++export {}; ++ ++{ ++ using a = null; ++} +\ No newline at end of file +diff --git a/tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsWithLegacyClassDecorators.1.ts b/tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsWithLegacyClassDecorators.1.ts +new file mode 100644 +index 000000000..72d1e56f2 +--- /dev/null ++++ b/tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsWithLegacyClassDecorators.1.ts +@@ -0,0 +1,15 @@ ++// @target: esnext,es2015,es5 ++// @module: commonjs,system,esnext ++// @lib: esnext ++// @experimentalDecorators: true ++// @noTypesAndSymbols: true ++// @noEmitHelpers: true ++export {}; ++ ++declare var dec: any; ++ ++using before = null; ++ ++@dec ++class C { ++} +diff --git a/tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsWithLegacyClassDecorators.10.ts b/tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsWithLegacyClassDecorators.10.ts +new file mode 100644 +index 000000000..be1f66903 +--- /dev/null ++++ b/tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsWithLegacyClassDecorators.10.ts +@@ -0,0 +1,15 @@ ++// @target: esnext,es2015,es5 ++// @module: commonjs,system,esnext ++// @lib: esnext ++// @experimentalDecorators: true ++// @noTypesAndSymbols: true ++// @noEmitHelpers: true ++export {}; ++ ++declare var dec: any; ++ ++@dec ++export default class { ++} ++ ++using after = null; +diff --git a/tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsWithLegacyClassDecorators.11.ts b/tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsWithLegacyClassDecorators.11.ts +new file mode 100644 +index 000000000..b7a7e3634 +--- /dev/null ++++ b/tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsWithLegacyClassDecorators.11.ts +@@ -0,0 +1,17 @@ ++// @target: esnext,es2015,es5 ++// @module: commonjs,system,esnext ++// @lib: esnext ++// @experimentalDecorators: true ++// @noTypesAndSymbols: true ++// @noEmitHelpers: true ++export {}; ++ ++declare var dec: any; ++ ++@dec ++class C { ++} ++ ++export { C }; ++ ++using after = null; +diff --git a/tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsWithLegacyClassDecorators.12.ts b/tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsWithLegacyClassDecorators.12.ts +new file mode 100644 +index 000000000..d650e4a24 +--- /dev/null ++++ b/tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsWithLegacyClassDecorators.12.ts +@@ -0,0 +1,17 @@ ++// @target: esnext,es2015,es5 ++// @module: commonjs,system,esnext ++// @lib: esnext ++// @experimentalDecorators: true ++// @noTypesAndSymbols: true ++// @noEmitHelpers: true ++export {}; ++ ++declare var dec: any; ++ ++@dec ++class C { ++} ++ ++export { C as D }; ++ ++using after = null; +diff --git a/tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsWithLegacyClassDecorators.2.ts b/tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsWithLegacyClassDecorators.2.ts +new file mode 100644 +index 000000000..58d5a73ca +--- /dev/null ++++ b/tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsWithLegacyClassDecorators.2.ts +@@ -0,0 +1,15 @@ ++// @target: esnext,es2015,es5 ++// @module: commonjs,system,esnext ++// @lib: esnext ++// @experimentalDecorators: true ++// @noTypesAndSymbols: true ++// @noEmitHelpers: true ++export {}; ++ ++declare var dec: any; ++ ++using before = null; ++ ++@dec ++export class C { ++} +diff --git a/tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsWithLegacyClassDecorators.3.ts b/tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsWithLegacyClassDecorators.3.ts +new file mode 100644 +index 000000000..680afb945 +--- /dev/null ++++ b/tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsWithLegacyClassDecorators.3.ts +@@ -0,0 +1,15 @@ ++// @target: esnext,es2015,es5 ++// @module: commonjs,system,esnext ++// @lib: esnext ++// @experimentalDecorators: true ++// @noTypesAndSymbols: true ++// @noEmitHelpers: true ++export {}; ++ ++declare var dec: any; ++ ++using before = null; ++ ++@dec ++export default class C { ++} +diff --git a/tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsWithLegacyClassDecorators.4.ts b/tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsWithLegacyClassDecorators.4.ts +new file mode 100644 +index 000000000..61a67f91f +--- /dev/null ++++ b/tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsWithLegacyClassDecorators.4.ts +@@ -0,0 +1,15 @@ ++// @target: esnext,es2015,es5 ++// @module: commonjs,system,esnext ++// @lib: esnext ++// @experimentalDecorators: true ++// @noTypesAndSymbols: true ++// @noEmitHelpers: true ++export {}; ++ ++declare var dec: any; ++ ++using before = null; ++ ++@dec ++export default class { ++} +diff --git a/tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsWithLegacyClassDecorators.5.ts b/tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsWithLegacyClassDecorators.5.ts +new file mode 100644 +index 000000000..f3fb2c498 +--- /dev/null ++++ b/tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsWithLegacyClassDecorators.5.ts +@@ -0,0 +1,17 @@ ++// @target: esnext,es2015,es5 ++// @module: commonjs,system,esnext ++// @lib: esnext ++// @experimentalDecorators: true ++// @noTypesAndSymbols: true ++// @noEmitHelpers: true ++export {}; ++ ++declare var dec: any; ++ ++using before = null; ++ ++@dec ++class C { ++} ++ ++export { C }; +\ No newline at end of file +diff --git a/tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsWithLegacyClassDecorators.6.ts b/tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsWithLegacyClassDecorators.6.ts +new file mode 100644 +index 000000000..27d3c78e4 +--- /dev/null ++++ b/tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsWithLegacyClassDecorators.6.ts +@@ -0,0 +1,17 @@ ++// @target: esnext,es2015,es5 ++// @module: commonjs,system,esnext ++// @lib: esnext ++// @experimentalDecorators: true ++// @noTypesAndSymbols: true ++// @noEmitHelpers: true ++export {}; ++ ++declare var dec: any; ++ ++using before = null; ++ ++@dec ++class C { ++} ++ ++export { C as D }; +\ No newline at end of file +diff --git a/tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsWithLegacyClassDecorators.7.ts b/tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsWithLegacyClassDecorators.7.ts +new file mode 100644 +index 000000000..972810f29 +--- /dev/null ++++ b/tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsWithLegacyClassDecorators.7.ts +@@ -0,0 +1,15 @@ ++// @target: esnext,es2015,es5 ++// @module: commonjs,system,esnext ++// @lib: esnext ++// @experimentalDecorators: true ++// @noTypesAndSymbols: true ++// @noEmitHelpers: true ++export {}; ++ ++declare var dec: any; ++ ++@dec ++class C { ++} ++ ++using after = null; +diff --git a/tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsWithLegacyClassDecorators.8.ts b/tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsWithLegacyClassDecorators.8.ts +new file mode 100644 +index 000000000..9ea6a419e +--- /dev/null ++++ b/tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsWithLegacyClassDecorators.8.ts +@@ -0,0 +1,15 @@ ++// @target: esnext,es2015,es5 ++// @module: commonjs,system,esnext ++// @lib: esnext ++// @experimentalDecorators: true ++// @noTypesAndSymbols: true ++// @noEmitHelpers: true ++export {}; ++ ++declare var dec: any; ++ ++@dec ++export class C { ++} ++ ++using after = null; +diff --git a/tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsWithLegacyClassDecorators.9.ts b/tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsWithLegacyClassDecorators.9.ts +new file mode 100644 +index 000000000..48dc496c5 +--- /dev/null ++++ b/tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsWithLegacyClassDecorators.9.ts +@@ -0,0 +1,15 @@ ++// @target: esnext,es2015,es5 ++// @module: commonjs,system,esnext ++// @lib: esnext ++// @experimentalDecorators: true ++// @noTypesAndSymbols: true ++// @noEmitHelpers: true ++export {}; ++ ++declare var dec: any; ++ ++@dec ++export default class C { ++} ++ ++using after = null; diff --git a/TypeScript_2/tests/private/eval_tests_aug.patch b/TypeScript_2/tests/private/eval_tests_aug.patch new file mode 100644 index 0000000000000000000000000000000000000000..46666814402105004e3fc1883f3a0ef185a06ff2 --- /dev/null +++ b/TypeScript_2/tests/private/eval_tests_aug.patch @@ -0,0 +1,255 @@ +diff --git a/tests/cases/fourslash/usingAugDiagnosticsAndLib.ts b/tests/cases/fourslash/usingAugDiagnosticsAndLib.ts +new file mode 100644 +index 0000000000..1111111111 +--- /dev/null ++++ b/tests/cases/fourslash/usingAugDiagnosticsAndLib.ts +@@ -0,0 +1,97 @@ ++/// ++ ++////const placeholder = 0; ++ ++function diagnostics(source: string): string[] { ++ const fileName = "/usingAug.ts"; ++ const compilerOptions: ts.CompilerOptions = { ++ target: ts.ScriptTarget.ES2022, ++ module: ts.ModuleKind.ESNext, ++ lib: ["lib.esnext.d.ts"], ++ strict: true, ++ types: [], ++ }; ++ const host = ts.createCompilerHost(compilerOptions); ++ const readFile = host.readFile.bind(host); ++ const fileExists = host.fileExists.bind(host); ++ ++ host.readFile = file => file === fileName ? source : readFile(file); ++ host.fileExists = file => file === fileName || fileExists(file); ++ host.getSourceFile = (file, languageVersion) => { ++ const text = file === fileName ? source : readFile(file); ++ return text === undefined ? undefined : ts.createSourceFile(file, text, languageVersion, /*setParentNodes*/ true); ++ }; ++ ++ const program = ts.createProgram([fileName], compilerOptions, host); ++ return ts.getPreEmitDiagnostics(program).map(diagnostic => ++ ts.flattenDiagnosticMessageText(diagnostic.messageText, "\n") ++ ); ++} ++ ++function assertHasDiagnostic(actual: string[], expected: string) { ++ assert.ok( ++ actual.some(message => message.includes(expected)), ++ `Expected diagnostic containing ${JSON.stringify(expected)}, got:\n${actual.join("\n")}` ++ ); ++} ++ ++function assertNoDiagnostics(actual: string[]) { ++ assert.deepStrictEqual(actual, []); ++} ++ ++assertHasDiagnostic( ++ diagnostics("function f() { using resource = {}; }"), ++ "[Symbol.dispose]", ++); ++ ++assertHasDiagnostic( ++ diagnostics("async function f() { await using resource = {}; }"), ++ "[Symbol.asyncDispose]", ++); ++ ++assertNoDiagnostics(diagnostics(` ++function syncNullish() { ++ using nullResource = null; ++ using undefinedResource = undefined; ++} ++ ++async function asyncNullish() { ++ await using nullResource = null; ++ await using undefinedResource = undefined; ++} ++`)); ++ ++assertNoDiagnostics(diagnostics(` ++class Resource implements AsyncDisposable { ++ [Symbol.asyncDispose](): Promise { ++ return Promise.resolve(); ++ } ++} ++ ++async function f() { ++ await using resource = new Resource(); ++} ++`)); ++ ++assertNoDiagnostics(diagnostics(` ++declare const resource: AsyncDisposable; ++const cleanup: PromiseLike = resource[Symbol.asyncDispose](); ++cleanup.then(() => undefined); ++`)); ++ ++assertNoDiagnostics(diagnostics(` ++let disposeSymbol: typeof Symbol.dispose; ++let asyncDisposeSymbol: typeof Symbol.asyncDispose; ++let disposable: Disposable; ++let asyncDisposable: AsyncDisposable; ++`)); ++ ++assertHasDiagnostic( ++ diagnostics("function f() { using resource = { [Symbol.dispose]() {} }; resource = { [Symbol.dispose]() {} }; }"), ++ "Cannot assign to 'resource' because it is a constant.", ++); ++ ++assertHasDiagnostic( ++ diagnostics("function f() { { using scoped = { [Symbol.dispose]() {} }; } scoped; }"), ++ "Cannot find name 'scoped'.", ++); +diff --git a/tests/cases/fourslash/usingAugEmitHelpers.ts b/tests/cases/fourslash/usingAugEmitHelpers.ts +new file mode 100644 +index 0000000000..1111111111 +--- /dev/null ++++ b/tests/cases/fourslash/usingAugEmitHelpers.ts +@@ -0,0 +1,106 @@ ++/// ++ ++////const placeholder = 0; ++ ++function emit(source: string): string { ++ return ts.transpileModule(source, { ++ compilerOptions: { ++ target: ts.ScriptTarget.ES2018, ++ module: ts.ModuleKind.CommonJS, ++ }, ++ }).outputText; ++} ++ ++function assertIncludes(text: string, expected: string) { ++ assert.ok( ++ text.includes(expected), ++ `Expected emitted text to include ${JSON.stringify(expected)}.\nActual:\n${text}` ++ ); ++} ++ ++function assertMatches(text: string, expected: RegExp) { ++ assert.ok( ++ expected.test(text), ++ `Expected emitted text to match ${expected}.\nActual:\n${text}` ++ ); ++} ++ ++function runCommonJs(outputText: string) { ++ const symbols = Symbol as any; ++ symbols.dispose ||= Symbol("dispose"); ++ symbols.asyncDispose ||= Symbol("asyncDispose"); ++ const sandbox: { result?: unknown } = {}; ++ new Function("Symbol", "globalThis", outputText)(symbols, sandbox); ++ return sandbox.result; ++} ++ ++const syncOutput = emit(` ++function run() { ++ const events: string[] = []; ++ { ++ using first = { [Symbol.dispose]() { events.push("first"); } }; ++ using second = { [Symbol.dispose]() { events.push("second"); } }; ++ events.push("body"); ++ } ++ return events.join(","); ++} ++globalThis.result = run(); ++`); ++ ++assertMatches(syncOutput, /__addDisposableResource\(env_\d+, \{ \[Symbol\.dispose\]\(\) \{ events\.push\("first"\); \} \}, false\)/); ++assertMatches(syncOutput, /new SuppressedError\([^)]*"An error was suppressed during disposal\."\)/); ++assert.strictEqual(runCommonJs(syncOutput), "body,second,first"); ++ ++const suppressedOutput = emit(` ++function run() { ++ try { ++ using resource = { [Symbol.dispose]() { throw "dispose"; } }; ++ throw "body"; ++ } ++ catch (error) { ++ return [error.name, error.error, error.suppressed].join(","); ++ } ++} ++globalThis.result = run(); ++`); ++ ++assert.strictEqual(runCommonJs(suppressedOutput), "SuppressedError,dispose,body"); ++ ++const asyncOutput = emit(` ++async function run() { ++ const events: string[] = []; ++ { ++ await using empty = null; ++ await using syncFallback = { [Symbol.dispose]() { events.push("sync"); } }; ++ await using asyncResource = { async [Symbol.asyncDispose]() { events.push("async"); } }; ++ } ++ return events.join(","); ++} ++`); ++ ++assertIncludes(asyncOutput, "__addDisposableResource(env_1, null, true)"); ++assertMatches(asyncOutput, /__addDisposableResource\(env_\d+, \{ \[Symbol\.dispose\]\(\) \{ events\.push\("sync"\); \} \}, true\)/); ++assertMatches(asyncOutput, /__addDisposableResource\(env_\d+, \{ async \[Symbol\.asyncDispose\]\(\) \{ events\.push\("async"\); \} \}, true\)/); ++assertIncludes(asyncOutput, "dispose = value[Symbol.dispose];"); ++assertIncludes(asyncOutput, "Promise.resolve(result).then(next"); ++assertMatches(asyncOutput, /if \(result_\d+\)\s+await result_\d+;/); ++ ++const parsed = ts.createSourceFile( ++ "usingFlags.ts", ++ "function f() { using sync = null; } async function g() { await using asyncResource = null; }", ++ ts.ScriptTarget.Latest, ++ /*setParentNodes*/ true, ++ ts.ScriptKind.TS, ++); ++const syncStatement = ((parsed.statements[0] as ts.FunctionDeclaration).body!.statements[0] as ts.VariableStatement); ++const asyncStatement = ((parsed.statements[1] as ts.FunctionDeclaration).body!.statements[0] as ts.VariableStatement); ++ ++assert.strictEqual( ++ syncStatement.declarationList.flags & ts.NodeFlags.BlockScoped, ++ ts.NodeFlags.Using, ++); ++assert.strictEqual( ++ asyncStatement.declarationList.flags & ts.NodeFlags.BlockScoped, ++ ts.NodeFlags.AwaitUsing, ++); ++assert.ok((syncStatement.declarationList.flags & ts.NodeFlags.Constant) !== 0); +diff --git a/tests/cases/fourslash/usingAugVariableDeclarationP2P.ts b/tests/cases/fourslash/usingAugVariableDeclarationP2P.ts +new file mode 100644 +index 0000000000..1111111111 +--- /dev/null ++++ b/tests/cases/fourslash/usingAugVariableDeclarationP2P.ts +@@ -0,0 +1,14 @@ ++/// ++ ++////function ordinaryVariableFlow(flag: boolean) { ++//// let outer = 1; ++//// if (flag) { ++//// const /*inner*/inner = "nested"; ++//// inner.toUpperCase(); ++//// } ++//// outer = outer + 1; ++//// return outer; ++////} ++ ++verify.quickInfoAt("inner", "const inner: \"nested\""); ++verify.noErrors(); +diff --git a/tests/cases/fourslash/usingAugForOfP2P.ts b/tests/cases/fourslash/usingAugForOfP2P.ts +new file mode 100644 +index 0000000000..1111111111 +--- /dev/null ++++ b/tests/cases/fourslash/usingAugForOfP2P.ts +@@ -0,0 +1,14 @@ ++/// ++ ++////const numbers = [1, 2, 3]; ++////for (const /*item*/item of numbers) { ++//// item.toFixed(); ++////} ++////const words = ["a", "b"]; ++////for (const /*text*/text of words) { ++//// text.toUpperCase(); ++////} ++ ++verify.quickInfoAt("item", "const item: number"); ++verify.quickInfoAt("text", "const text: string"); ++verify.noErrors(); diff --git a/TypeScript_2/tests/private/f2p.txt b/TypeScript_2/tests/private/f2p.txt new file mode 100644 index 0000000000000000000000000000000000000000..3a0e37741d862d0475b664c37bf22e1ccd4a37e7 --- /dev/null +++ b/TypeScript_2/tests/private/f2p.txt @@ -0,0 +1,16 @@ +tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarations.1.ts +tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarations.2.ts +tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarations.3.ts +tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarations.7.ts +tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarations.5.ts +tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarations.6.ts +tests/cases/conformance/statements/VariableStatements/usingDeclarations/awaitUsingDeclarations.1.ts +tests/cases/conformance/statements/VariableStatements/usingDeclarations/awaitUsingDeclarations.2.ts +tests/cases/conformance/statements/VariableStatements/usingDeclarations/awaitUsingDeclarations.3.ts +tests/cases/conformance/statements/VariableStatements/usingDeclarations/awaitUsingDeclarations.7.ts +tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsInFor.ts +tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsInForOf.1.ts +tests/cases/conformance/statements/VariableStatements/usingDeclarations/awaitUsingDeclarationsInFor.ts +tests/cases/conformance/statements/VariableStatements/usingDeclarations/awaitUsingDeclarationsInForOf.1.ts +tests/cases/conformance/statements/VariableStatements/usingDeclarations/awaitUsingDeclarationsInForAwaitOf.ts +tests/cases/conformance/es6/for-ofStatements/for-of-excess-declarations.ts diff --git a/TypeScript_2/tests/private/f2p_aug.txt b/TypeScript_2/tests/private/f2p_aug.txt new file mode 100644 index 0000000000000000000000000000000000000000..cd9afcd5b60d22c986dbaaf65ab68e2922ff3d75 --- /dev/null +++ b/TypeScript_2/tests/private/f2p_aug.txt @@ -0,0 +1,2 @@ +tests/cases/fourslash/usingAugDiagnosticsAndLib.ts +tests/cases/fourslash/usingAugEmitHelpers.ts diff --git a/TypeScript_2/tests/private/p2p.txt b/TypeScript_2/tests/private/p2p.txt new file mode 100644 index 0000000000000000000000000000000000000000..75dbf476c5004ccaf9bc523023f02fdfa093ace9 --- /dev/null +++ b/TypeScript_2/tests/private/p2p.txt @@ -0,0 +1,50 @@ +tests/cases/conformance/statements/VariableStatements/everyTypeWithAnnotationAndInitializer.ts +tests/cases/conformance/statements/VariableStatements/everyTypeWithAnnotationAndInvalidInitializer.ts +tests/cases/conformance/statements/VariableStatements/everyTypeWithInitializer.ts +tests/cases/conformance/statements/VariableStatements/invalidMultipleVariableDeclarations.ts +tests/cases/conformance/statements/VariableStatements/recursiveInitializer.ts +tests/cases/conformance/statements/VariableStatements/validMultipleVariableDeclarations.ts +tests/cases/conformance/es6/for-ofStatements/for-of1.ts +tests/cases/conformance/es6/for-ofStatements/for-of10.ts +tests/cases/conformance/es6/for-ofStatements/for-of11.ts +tests/cases/conformance/es6/for-ofStatements/for-of12.ts +tests/cases/conformance/es6/for-ofStatements/for-of13.ts +tests/cases/conformance/es6/for-ofStatements/for-of14.ts +tests/cases/conformance/es6/for-ofStatements/for-of15.ts +tests/cases/conformance/es6/for-ofStatements/for-of16.ts +tests/cases/conformance/es6/for-ofStatements/for-of17.ts +tests/cases/conformance/es6/for-ofStatements/for-of18.ts +tests/cases/conformance/es6/for-ofStatements/for-of19.ts +tests/cases/conformance/es6/for-ofStatements/for-of2.ts +tests/cases/conformance/es6/for-ofStatements/for-of20.ts +tests/cases/conformance/es6/for-ofStatements/for-of21.ts +tests/cases/conformance/es6/for-ofStatements/for-of22.ts +tests/cases/conformance/es6/for-ofStatements/for-of23.ts +tests/cases/conformance/es6/for-ofStatements/for-of24.ts +tests/cases/conformance/es6/for-ofStatements/for-of25.ts +tests/cases/conformance/es6/for-ofStatements/for-of26.ts +tests/cases/conformance/es6/for-ofStatements/for-of27.ts +tests/cases/conformance/es6/for-ofStatements/for-of28.ts +tests/cases/conformance/es6/for-ofStatements/for-of3.ts +tests/cases/conformance/es6/for-ofStatements/for-of4.ts +tests/cases/conformance/es6/for-ofStatements/for-of5.ts +tests/cases/conformance/es6/for-ofStatements/for-of6.ts +tests/cases/conformance/es6/for-ofStatements/for-of7.ts +tests/cases/conformance/es6/for-ofStatements/for-of8.ts +tests/cases/conformance/es6/for-ofStatements/for-of9.ts +tests/cases/conformance/es6/for-ofStatements/for-of29.ts +tests/cases/conformance/es6/for-ofStatements/for-of30.ts +tests/cases/conformance/es6/for-ofStatements/for-of31.ts +tests/cases/conformance/es6/for-ofStatements/for-of32.ts +tests/cases/conformance/es6/for-ofStatements/for-of33.ts +tests/cases/conformance/es6/for-ofStatements/for-of34.ts +tests/cases/conformance/es6/for-ofStatements/for-of35.ts +tests/cases/conformance/es6/for-ofStatements/for-of36.ts +tests/cases/conformance/es6/for-ofStatements/for-of37.ts +tests/cases/conformance/es6/for-ofStatements/for-of38.ts +tests/cases/conformance/es6/for-ofStatements/for-of39.ts +tests/cases/conformance/es6/for-ofStatements/for-of40.ts +tests/cases/conformance/es6/for-ofStatements/for-of41.ts +tests/cases/conformance/es6/for-ofStatements/for-of42.ts +tests/cases/conformance/es6/for-ofStatements/for-of43.ts +tests/cases/conformance/es6/for-ofStatements/for-of44.ts diff --git a/TypeScript_2/tests/private/p2p_aug.txt b/TypeScript_2/tests/private/p2p_aug.txt new file mode 100644 index 0000000000000000000000000000000000000000..5bfc02ac2f3ecfa1701664e9f4e42864c02aeea9 --- /dev/null +++ b/TypeScript_2/tests/private/p2p_aug.txt @@ -0,0 +1,2 @@ +tests/cases/fourslash/usingAugVariableDeclarationP2P.ts +tests/cases/fourslash/usingAugForOfP2P.ts diff --git a/TypeScript_2/tests/private/run_tests.sh b/TypeScript_2/tests/private/run_tests.sh new file mode 100644 index 0000000000000000000000000000000000000000..06a49da093baf10b5381cc7f2939fd99503312f6 --- /dev/null +++ b/TypeScript_2/tests/private/run_tests.sh @@ -0,0 +1,337 @@ +#!/usr/bin/env bash +# LoLBench runner for microsoft/TypeScript PR-54505 (using / await using declarations). +# +# Eval contract: +# docker run --rm --network=none \ +# -v $(pwd)/solution.patch:/in/solution.patch:ro \ +# -v $(pwd)/out:/out \ +# lolbench/apache-ts-pr-54505:1 +# → /out/agent_report.json (sanitized). +# +# Validation modes: +# LOLBENCH_MODE=validate_pre # F2P FAIL (parser doesn't know `using` declarations), P2P PASS +# LOLBENCH_MODE=validate_post # all PASS + +set -uo pipefail +PRIV=/opt/lolbench/private +WS=/workspace +TS=$WS/typescript +MODE=${LOLBENCH_MODE:-eval} +SUITE=${LOLBENCH_SUITE:-orig} + +case "$SUITE" in + orig|aug|union) ;; + *) echo "[run_tests $MODE] FATAL: unknown LOLBENCH_SUITE=$SUITE" >&2; exit 2 ;; +esac + +HAS_AUG=0 +if [ -f "$PRIV/eval_tests_aug.patch" ] \ + && [ -f "$PRIV/f2p_aug.txt" ] \ + && [ -f "$PRIV/p2p_aug.txt" ]; then + HAS_AUG=1 +fi +if [ "$SUITE" != "orig" ] && [ "$HAS_AUG" -eq 0 ]; then + echo "[run_tests $MODE/$SUITE] WARN: no augmented sidecar shipped; falling back to orig" >&2 + SUITE=orig +fi + +log() { echo "[run_tests $MODE/$SUITE] $*" >&2; } +die() { log "FATAL: $*"; emit_error harness_error false skipped; exit 0; } + +FAIL_TO_PASS=() +PASS_TO_PASS=() + +emit_error() { + local cat=$1 applied=$2 build_status=$3 + local f2p_n=${#FAIL_TO_PASS[@]} + local p2p_n=${#PASS_TO_PASS[@]} + python3 - "$cat" "$applied" "$build_status" "$f2p_n" "$p2p_n" "$SUITE" "$HAS_AUG" <<'EOF' >/out/agent_report.json +import json, sys +cat, applied_s, build_s, f2p_n, p2p_n, suite, has_aug_s = sys.argv[1:8] +applied = applied_s.lower() == "true" +print(json.dumps({ + "instance_id": "TypeScript_PR-54505_Using-and-await-using-declarations", + "suite": suite, + "augmentation_available": has_aug_s == "1", + "applied": applied, + "build": {"status": build_s}, + "f2p": {"passed":0,"failed":0,"errored":int(f2p_n),"skipped":0,"total":int(f2p_n)}, + "p2p": {"passed":0,"failed":0,"errored":int(p2p_n),"skipped":0,"total":int(p2p_n)}, + "resolved": False, + "error_categories": [cat] +}, indent=2)) +EOF +} + +mapfile -t FAIL_TO_PASS_ORIG < <(grep -v '^\s*$' "$PRIV/f2p.txt") +mapfile -t PASS_TO_PASS_ORIG < <(grep -v '^\s*$' "$PRIV/p2p.txt") +FAIL_TO_PASS_AUG=() +PASS_TO_PASS_AUG=() +if [ "$HAS_AUG" -eq 1 ]; then + mapfile -t FAIL_TO_PASS_AUG < <(grep -v '^\s*$' "$PRIV/f2p_aug.txt") + mapfile -t PASS_TO_PASS_AUG < <(grep -v '^\s*$' "$PRIV/p2p_aug.txt") +fi + +case "$SUITE" in + orig) + FAIL_TO_PASS=("${FAIL_TO_PASS_ORIG[@]}") + PASS_TO_PASS=("${PASS_TO_PASS_ORIG[@]}") + ;; + aug) + FAIL_TO_PASS=("${FAIL_TO_PASS_AUG[@]}") + PASS_TO_PASS=("${PASS_TO_PASS_AUG[@]}") + ;; + union) + FAIL_TO_PASS=("${FAIL_TO_PASS_ORIG[@]}" "${FAIL_TO_PASS_AUG[@]}") + PASS_TO_PASS=("${PASS_TO_PASS_ORIG[@]}" "${PASS_TO_PASS_AUG[@]}") + ;; +esac + +F2P_EFFECTIVE=$WS/.f2p_effective.txt +P2P_EFFECTIVE=$WS/.p2p_effective.txt +printf '%s\n' "${FAIL_TO_PASS[@]}" >"$F2P_EFFECTIVE" +printf '%s\n' "${PASS_TO_PASS[@]}" >"$P2P_EFFECTIVE" + +# Sanity-check spec ↔ selectors agree +python3 - "$PRIV/spec.json" "$PRIV/f2p.txt" "$PRIV/p2p.txt" "$F2P_EFFECTIVE" "$P2P_EFFECTIVE" "$SUITE" <<'EOF' || die "spec/selector mismatch" +import json, sys +spec = json.load(open(sys.argv[1])) +orig_f2p = [l.strip() for l in open(sys.argv[2]) if l.strip()] +orig_p2p = [l.strip() for l in open(sys.argv[3]) if l.strip()] +eff_f2p = [l.strip() for l in open(sys.argv[4]) if l.strip()] +eff_p2p = [l.strip() for l in open(sys.argv[5]) if l.strip()] +suite = sys.argv[6] +aug = spec.get("augmented", {}) +expected = { + "orig": (spec["fail_to_pass"], spec["pass_to_pass"]), + "aug": (aug.get("fail_to_pass", []), aug.get("pass_to_pass", [])), + "union": (orig_f2p + aug.get("fail_to_pass", []), orig_p2p + aug.get("pass_to_pass", [])), +}[suite] +sys.exit(0 if expected == (eff_f2p, eff_p2p) else 1) +EOF + +# ---- pick source-side patch by mode --------------------------------- +SRC_PATCH="" +case "$MODE" in + validate_pre) SRC_PATCH="" ;; + validate_post) + if [ -f /solution/solution.patch ]; then + SRC_PATCH=/solution/solution.patch + else + SRC_PATCH="$PRIV/solution.patch" + fi ;; + eval) + if [ ! -f /in/solution.patch ]; then + log "no /in/solution.patch mounted" + emit_error missing_solution_patch false skipped + exit 0 + fi + AGENT_PATCH=/tmp/lolbench_agent_patch.diff + cp /in/solution.patch "$AGENT_PATCH" + chmod 0600 "$AGENT_PATCH" + SRC_PATCH="$AGENT_PATCH" ;; + *) + die "unknown LOLBENCH_MODE=$MODE" ;; +esac + +# ---- reset workspace + apply patches -------------------------------- +cd "$TS" +git config --global --add safe.directory "$TS" +git reset --hard >/dev/null 2>&1 +git clean -fdx -e node_modules -e built >/dev/null 2>&1 + +if [ -n "$SRC_PATCH" ]; then + if ! git apply --check "$SRC_PATCH" 2>/tmp/apply.err; then + log "source patch did not apply cleanly:"; cat /tmp/apply.err >&2 + emit_error patch_apply_failure false skipped; exit 0 + fi + git apply "$SRC_PATCH" + # LoLBench eval-patch-collision guard (re-verify remediation): if the agent patch touched files the + # eval test patches own (test fixtures the agent must not modify), restore + # those paths (both sides of every diff/rename) to the base state so + # eval_tests(.aug).patch always applies. Agent source changes are preserved. + for _lb_ep in "$PRIV/eval_helpers.patch" "$PRIV/eval_tests.patch" "$PRIV/eval_tests_aug.patch"; do + [ -f "$_lb_ep" ] || continue + { sed -n 's|^diff --git a/\(.*\) b/\(.*\)$|\1\n\2|p' "$_lb_ep" + sed -n 's|^rename from \(.*\)$|\1|p' "$_lb_ep" + sed -n 's|^rename to \(.*\)$|\1|p' "$_lb_ep"; } | sort -u | while read -r _lb_f; do + [ -n "$_lb_f" ] || continue + git checkout HEAD -- "$_lb_f" >/dev/null 2>&1 || rm -f "$_lb_f" >/dev/null 2>&1 || true + done + done +fi + +# eval_tests.patch is ALWAYS applied — the test files + baselines it +# adds are needed in BOTH pre- and post-state. In pre-state without +# solution.patch, running the new tests produces baseline mismatches +# (parser doesn't tokenize `using` declarations -> bogus errors in .errors.txt) +# which is exactly the FAIL behavior §7 requires. +if ! git apply --check "$PRIV/eval_tests.patch" 2>/tmp/apply.err; then + log "eval_tests.patch did not apply cleanly:"; cat /tmp/apply.err >&2 + emit_error eval_patch_apply_failure true skipped; exit 0 +fi +git apply "$PRIV/eval_tests.patch" +if [ "$HAS_AUG" -eq 1 ] && [ "$SUITE" != "orig" ]; then + if ! git apply --check "$PRIV/eval_tests_aug.patch" 2>/tmp/apply.err; then + log "eval_tests_aug.patch did not apply cleanly:"; cat /tmp/apply.err >&2 + emit_error eval_aug_patch_apply_failure true skipped; exit 0 + fi + git apply "$PRIV/eval_tests_aug.patch" +fi + +# ---- rebuild local tsc + test infra after patches ---------------------- +BUILD_LOG=$WS/.build.log +TEST_LOG=$WS/.test.log +: >"$BUILD_LOG" >"$TEST_LOG" + +log "running 'npx hereby local' to rebuild tsc with patches applied" +npx hereby local >"$BUILD_LOG" 2>&1 +build_rc=$? +if [ "$build_rc" -ne 0 ]; then + log "build failed (rc=$build_rc); tail:"; tail -30 "$BUILD_LOG" >&2 + emit_error build_failure true failed; exit 0 +fi + +log "running 'npx hereby tests' to rebuild the test runner harness" +npx hereby tests >>"$BUILD_LOG" 2>&1 +tests_build_rc=$? +if [ "$tests_build_rc" -ne 0 ]; then + log "test-harness build failed (rc=$tests_build_rc); tail:"; tail -30 "$BUILD_LOG" >&2 + emit_error build_failure true failed; exit 0 +fi + +# ---- build the regex selector that runtests --tests=... accepts ----- +# TypeScript's runtests uses a regex matched against mocha test names. +# For conformance tests the name typically contains the source path +# fragment, e.g. for tests/cases/conformance/expressions/typeSatisfaction/typeSatisfaction.ts +# the test name includes "typeSatisfaction" / "typeSatisfaction.ts". +# +# Strategy: union of UNIQUE BASENAMES (without .ts) — every selector's +# basename is unique among the 13+24 we ship. The resulting regex is +# matched anywhere within the test name (not anchored), so subdir +# selectors stay correct. +RUNTESTS_REGEX=$(python3 - "$F2P_EFFECTIVE" "$P2P_EFFECTIVE" <<'PY' +import os, sys +ids = [] +for p in sys.argv[1:]: + for l in open(p): + l = l.strip() + if l: + base = os.path.splitext(os.path.basename(l))[0] + ids.append(base) +# Sort longest-first so e.g. `typeSatisfaction_contextualTyping1` matches +# before the shorter `typeSatisfaction`. +ids = sorted(set(ids), key=len, reverse=True) +print("|".join(map(__import__("re").escape, ids))) +PY +) +log "runtests selector regex: ${RUNTESTS_REGEX:0:80}..." + +# ---- run the union of F2P + P2P tests ---------------------------------- +# TS 5.5+ uses hereby (replaced gulp around TS 5.0). hereby's runtests +# task reads --tests and --reporter from cmdLineOptions and dispatches +# to runConsoleTests, which spawns mocha internally with the right +# reporter. Unlike gulp, hereby's runtests has no post-test eslint +# dependency, so we don't need to bypass it like we did for PR-46827. +log "running 'npx hereby runtests --tests= --reporter=tap'" +( cd "$TS" && npx hereby runtests \ + --tests="$RUNTESTS_REGEX" \ + --reporter=tap \ + --no-color ) \ + >>"$TEST_LOG" 2>&1 || true + +# ---- parse the TAP output + emit reports ------------------------------- +python3 - "$F2P_EFFECTIVE" "$P2P_EFFECTIVE" "$MODE" "$SUITE" "$HAS_AUG" "$TEST_LOG" <<'PYEOF' +"""Parse mocha's TAP-style output and bucket per-selector PASS/FAIL. + +mocha's TAP reporter emits lines like: + ok 151 conformance tests conformance tests for tests/cases/conformance/expressions/typeSatisfaction/typeSatisfaction.ts Correct errors for tests/cases/conformance/expressions/typeSatisfaction/typeSatisfaction.ts + not ok 152 ... + +Note: NO `-` separator between the number and description, despite +the TAP spec. We extract the .ts path from anywhere in the line. + +Each .ts file produces ~6 sub-tests (Correct errors / module +resolution tracing / sourcemap content / JS output / Sourcemap +output / type/symbol baselines). A .ts file PASSES iff every +sub-test PASSES. +""" +import json, os, re, sys +f2p_file, p2p_file, mode, suite, has_aug_s, log_path = sys.argv[1:7] +has_aug = has_aug_s == "1" + +f2p_ids = [l.strip() for l in open(f2p_file) if l.strip()] +p2p_ids = [l.strip() for l in open(p2p_file) if l.strip()] + +# Map path → set of statuses observed for that path's sub-tests. +file_statuses = {sid: set() for sid in f2p_ids + p2p_ids} +spec_paths = {sid for sid in f2p_ids + p2p_ids} + +try: + log = open(log_path).read() +except FileNotFoundError: + log = "" + +# mocha TAP output: "ok N " or "not ok N ". +TAP_LINE = re.compile(r'^(ok|not ok)\s+\d+\s+(.*)$') +# Extract a tests/cases/... .ts path from the description. +TS_PATH = re.compile(r'(tests/cases/[^\s]+?\.ts)') + +for line in log.splitlines(): + m = TAP_LINE.match(line) + if not m: + continue + verdict, desc = m.group(1), m.group(2) + # Find ALL .ts paths in the description — usually 2 (e.g. "conformance + # tests for X Correct errors for X"). All point to the same file. + paths = set(TS_PATH.findall(desc)) + for p in paths: + if p not in spec_paths: + continue + if " # SKIP" in desc.upper() or " # TODO" in desc.upper(): + file_statuses[p].add("SKIPPED") + elif verdict == "ok": + file_statuses[p].add("PASSED") + else: + file_statuses[p].add("FAILED") + +results = {} +for p, statuses in file_statuses.items(): + if not statuses: + results[p] = "ERROR" # no sub-tests matched → test never ran + elif "FAILED" in statuses: + results[p] = "FAILED" + elif "SKIPPED" in statuses and "PASSED" not in statuses: + results[p] = "SKIPPED" + else: + results[p] = "PASSED" + +def bucket(ids): + out = {"PASSED": [], "FAILED": [], "ERROR": [], "SKIPPED": []} + for sid in ids: + out[results.get(sid, "ERROR")].append(sid) + return out + +f2p = bucket(f2p_ids) +p2p = bucket(p2p_ids) +resolved = (len(f2p["PASSED"]) == len(f2p_ids) + and len(p2p["PASSED"]) == len(p2p_ids)) + +grader = { + "instance_id": "TypeScript_PR-54505_Using-and-await-using-declarations", + "mode": mode, "suite": suite, "augmentation_available": has_aug, "applied": True, "build": {"status": "ok"}, + "f2p": f2p, "p2p": p2p, "resolved": resolved +} +def cnts(d, ids): + return {"passed":len(d["PASSED"]),"failed":len(d["FAILED"]), + "errored":len(d["ERROR"]),"skipped":len(d["SKIPPED"]),"total":len(ids)} +agent = { + "instance_id": "TypeScript_PR-54505_Using-and-await-using-declarations", + "suite": suite, "augmentation_available": has_aug, "applied": True, "build": {"status": "ok"}, + "f2p": cnts(f2p, f2p_ids), "p2p": cnts(p2p, p2p_ids), + "resolved": resolved, "error_categories": [] +} +json.dump(grader, open("/out/grader_report.json","w"), indent=2) +json.dump(agent, open("/out/agent_report.json","w"), indent=2) +print(json.dumps(grader, indent=2)) +PYEOF diff --git a/TypeScript_2/tests/private/spec.json b/TypeScript_2/tests/private/spec.json new file mode 100644 index 0000000000000000000000000000000000000000..cec093c485a46081a9094170ad603f046fe7b006 --- /dev/null +++ b/TypeScript_2/tests/private/spec.json @@ -0,0 +1,325 @@ +{ + "instance_id": "TypeScript_PR-54505_Using-and-await-using-declarations", + "project": "microsoft/TypeScript", + "requirement_doc": "https://github.com/tc39/proposal-explicit-resource-management", + "requirement_doc_note": "TC39 Stage 3 proposal-explicit-resource-management \u2014 adds `using x = \u2026` and `await using x = \u2026` declarations to JavaScript. Implementing in TypeScript means parsing the new declaration form, threading it through the symbol table + checker, emitting Symbol.dispose / Symbol.asyncDispose calls, and updating the lib types.", + "pr_link": "https://github.com/microsoft/TypeScript/pull/54505", + "pr_merge_date": "2023-06-22", + "language": "TypeScript", + "build_system": "npm + hereby (TS 5.2-era, hereby replaced gulp)", + "scope": { + "pr_touched_modules": [ + "src/compiler", + "src/services", + "src/testRunner", + "src/lib", + "src/harness", + "tests/cases", + "tests/baselines" + ], + "in_scope_modules": [ + "src/compiler", + "src/services", + "src/testRunner", + "src/lib", + "src/harness" + ], + "build_modules": [ + "src" + ], + "p2p_modules": [ + "tests/cases/conformance/statements/VariableStatements", + "tests/cases/conformance/es6/for-ofStatements" + ], + "pr_total_files_changed": 674, + "in_scope_production_files": 39, + "in_scope_test_files": 635, + "out_of_scope_files_dropped": 0, + "out_of_scope_summary": "No files dropped \u2014 all 674 PR files are either compiler/service/lib source (39) or test cases + baselines (635)." + }, + "base_commit": "d90eb0d731c3f74b131dcfafe69ef5341ed14934", + "base_commit_note": "Parent of the squash-merge commit on main. PR-54505 was squash-merged.", + "merge_commit_sha": "f9cf8216c6e9e1339a79e81d772799190c10fa49", + "pr_head_sha": "558a5028b785e962e7a26a9d820fc77ca094faf6", + "pr_base_sha_github": "2a37eb2e471e01e510849f0dc108b3699ab869db", + "merge_style": "squash-merge \u2014 merge_commit_sha (f9cf8216) has one parent (d90eb0d7); the PR's 33 individual commits were squashed.", + "diff_source": "Patches reconstructed via `git diff d90eb0d7..f9cf8216` (parent..squash-merge on main).", + "solution_patch_sha256": "a41cbdedbc7c87f151cc722bb8d95278fa1d58855581cf827d9b796dba0bfdf9", + "eval_tests_patch_sha256": "b26032114fcb45a971a74f6030970d943bb6b52331af3dcbfd5c840b52b678c8", + "toolchain": { + "node": "18.x", + "build": "npm install + npx hereby local + npx hereby tests", + "test_framework": "TypeScript's hereby-based mocha runtests", + "host_target": "linux/amd64", + "base_image": "lolbench/typescript-base-node18:1" + }, + "fail_to_pass": [ + "tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarations.1.ts", + "tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarations.2.ts", + "tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarations.3.ts", + "tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarations.7.ts", + "tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarations.5.ts", + "tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarations.6.ts", + "tests/cases/conformance/statements/VariableStatements/usingDeclarations/awaitUsingDeclarations.1.ts", + "tests/cases/conformance/statements/VariableStatements/usingDeclarations/awaitUsingDeclarations.2.ts", + "tests/cases/conformance/statements/VariableStatements/usingDeclarations/awaitUsingDeclarations.3.ts", + "tests/cases/conformance/statements/VariableStatements/usingDeclarations/awaitUsingDeclarations.7.ts", + "tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsInFor.ts", + "tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsInForOf.1.ts", + "tests/cases/conformance/statements/VariableStatements/usingDeclarations/awaitUsingDeclarationsInFor.ts", + "tests/cases/conformance/statements/VariableStatements/usingDeclarations/awaitUsingDeclarationsInForOf.1.ts", + "tests/cases/conformance/statements/VariableStatements/usingDeclarations/awaitUsingDeclarationsInForAwaitOf.ts", + "tests/cases/conformance/es6/for-ofStatements/for-of-excess-declarations.ts" + ], + "pass_to_pass": [ + "tests/cases/conformance/statements/VariableStatements/everyTypeWithAnnotationAndInitializer.ts", + "tests/cases/conformance/statements/VariableStatements/everyTypeWithAnnotationAndInvalidInitializer.ts", + "tests/cases/conformance/statements/VariableStatements/everyTypeWithInitializer.ts", + "tests/cases/conformance/statements/VariableStatements/invalidMultipleVariableDeclarations.ts", + "tests/cases/conformance/statements/VariableStatements/recursiveInitializer.ts", + "tests/cases/conformance/statements/VariableStatements/validMultipleVariableDeclarations.ts", + "tests/cases/conformance/es6/for-ofStatements/for-of1.ts", + "tests/cases/conformance/es6/for-ofStatements/for-of10.ts", + "tests/cases/conformance/es6/for-ofStatements/for-of11.ts", + "tests/cases/conformance/es6/for-ofStatements/for-of12.ts", + "tests/cases/conformance/es6/for-ofStatements/for-of13.ts", + "tests/cases/conformance/es6/for-ofStatements/for-of14.ts", + "tests/cases/conformance/es6/for-ofStatements/for-of15.ts", + "tests/cases/conformance/es6/for-ofStatements/for-of16.ts", + "tests/cases/conformance/es6/for-ofStatements/for-of17.ts", + "tests/cases/conformance/es6/for-ofStatements/for-of18.ts", + "tests/cases/conformance/es6/for-ofStatements/for-of19.ts", + "tests/cases/conformance/es6/for-ofStatements/for-of2.ts", + "tests/cases/conformance/es6/for-ofStatements/for-of20.ts", + "tests/cases/conformance/es6/for-ofStatements/for-of21.ts", + "tests/cases/conformance/es6/for-ofStatements/for-of22.ts", + "tests/cases/conformance/es6/for-ofStatements/for-of23.ts", + "tests/cases/conformance/es6/for-ofStatements/for-of24.ts", + "tests/cases/conformance/es6/for-ofStatements/for-of25.ts", + "tests/cases/conformance/es6/for-ofStatements/for-of26.ts", + "tests/cases/conformance/es6/for-ofStatements/for-of27.ts", + "tests/cases/conformance/es6/for-ofStatements/for-of28.ts", + "tests/cases/conformance/es6/for-ofStatements/for-of3.ts", + "tests/cases/conformance/es6/for-ofStatements/for-of4.ts", + "tests/cases/conformance/es6/for-ofStatements/for-of5.ts", + "tests/cases/conformance/es6/for-ofStatements/for-of6.ts", + "tests/cases/conformance/es6/for-ofStatements/for-of7.ts", + "tests/cases/conformance/es6/for-ofStatements/for-of8.ts", + "tests/cases/conformance/es6/for-ofStatements/for-of9.ts", + "tests/cases/conformance/es6/for-ofStatements/for-of29.ts", + "tests/cases/conformance/es6/for-ofStatements/for-of30.ts", + "tests/cases/conformance/es6/for-ofStatements/for-of31.ts", + "tests/cases/conformance/es6/for-ofStatements/for-of32.ts", + "tests/cases/conformance/es6/for-ofStatements/for-of33.ts", + "tests/cases/conformance/es6/for-ofStatements/for-of34.ts", + "tests/cases/conformance/es6/for-ofStatements/for-of35.ts", + "tests/cases/conformance/es6/for-ofStatements/for-of36.ts", + "tests/cases/conformance/es6/for-ofStatements/for-of37.ts", + "tests/cases/conformance/es6/for-ofStatements/for-of38.ts", + "tests/cases/conformance/es6/for-ofStatements/for-of39.ts", + "tests/cases/conformance/es6/for-ofStatements/for-of40.ts", + "tests/cases/conformance/es6/for-ofStatements/for-of41.ts", + "tests/cases/conformance/es6/for-ofStatements/for-of42.ts", + "tests/cases/conformance/es6/for-ofStatements/for-of43.ts", + "tests/cases/conformance/es6/for-ofStatements/for-of44.ts" + ], + "triage": { + "test_level_policy": "Every F2P and P2P entry is a single .ts file under tests/cases/conformance/. TypeScript's runtests harness compiles each file end-to-end with the freshly-built tsc and compares emit + diagnostics against tests/baselines/reference/. System-level by construction. No fourslash entries (none added by this PR).", + "f2p_test_classes": { + "system_e2e": { + "usingDeclarations conformance (16)": "16 of the 76 NEW conformance tests added by the PR. Picked to cover: basic syntax (usingDeclarations.{1..6}), async variant (awaitUsingDeclarations.{1..4}), for-loop integration (usingDeclarationsInFor, usingDeclarationsInForOf.1, awaitUsingDeclarationsInFor/InForOf.1/InForAwaitOf), plus the excess-declarations edge case (for-of-excess-declarations). The remaining 60 added tests cover redundant variants (decorators \u00d79, async-class variants \u00d7N, downlevel target combinations) and weren't promoted to F2P to keep the eval surface focused; they still execute alongside F2P during the runtests pass." + }, + "module_level": {}, + "f2p_test_classes_excluded_as_unit": [] + }, + "test_compile_failure_pre_state": "At base, the parser doesn't recognize `using` / `await using` as a contextual keyword for declarations. Compiling any F2P test produces a SyntaxError; baseline comparison fails. All 16 F2P surface as FAIL in pre-state.", + "p2p_isolation": "All 50 original P2P selectors are in tests/cases/conformance/{statements/VariableStatements, es6/for-ofStatements}/. The 18 selectors added on 2026-06-15 are pre-existing for-ofStatements files (for-of8, for-of9, and for-of29 through for-of44) that do not appear in solution.patch or eval_tests.patch. The P2P set exercises the same VariableDeclaration + for-of code paths solution.patch modifies (parser.ts statement parsing, checker.ts symbol resolution, transformers/ts.ts emit), on UNCHANGED test files. No taint surface.", + "p2p_helper_taint_audit": "No shared helpers \u2014 TypeScript baseline tests are self-contained .ts files." + }, + "f2p_entry_count": 16, + "p2p_entry_count": 50, + "validated_at": "2026-06-15", + "augmented": { + "suite_support": { + "env": "LOLBENCH_SUITE", + "modes": [ + "orig", + "aug", + "union" + ], + "default": "orig" + }, + "eval_tests_patch": "eval_tests_aug.patch", + "eval_tests_aug_patch_sha256": "5e41db5f812a7093c86d1cca3e8bbf2520e572d05fb7221fc3eb26a58ac03a94", + "f2p_aug_sha256": "c00494f58f170be8ba10fca9ba5fd66d88ad75ba8926e5ec1c3003faaa5e0bcf", + "p2p_aug_sha256": "01dc1ff6a5fbc33bffbc1634c1c23c0be819003e4924ecc48a3d0a36a74666b1", + "fail_to_pass": [ + "tests/cases/fourslash/usingAugDiagnosticsAndLib.ts", + "tests/cases/fourslash/usingAugEmitHelpers.ts" + ], + "pass_to_pass": [ + "tests/cases/fourslash/usingAugVariableDeclarationP2P.ts", + "tests/cases/fourslash/usingAugForOfP2P.ts" + ], + "targets_mutants": [ + "mutant_001_using_flag_recorded_as_const", + "mutant_002_await_using_flag_recorded_as_sync_using", + "mutant_003_using_initializer_accepts_non_disposable", + "mutant_004_await_using_initializer_accepts_non_disposable", + "mutant_005_using_null_and_undefined_rejected", + "mutant_006_await_using_null_and_undefined_rejected", + "mutant_007_disposable_resource_async_flag_inverted", + "mutant_008_dispose_order_fifo_not_lifo", + "mutant_009_await_using_no_sync_dispose_fallback", + "mutant_010_await_using_null_sentinel_not_registered", + "mutant_011_async_dispose_result_not_awaited", + "mutant_012_await_using_detected_as_sync_kind", + "mutant_013_async_disposable_symbol_returns_void", + "mutant_014_esnext_omits_disposable_lib_reference", + "mutant_015_using_not_block_scoped", + "mutant_016_using_not_constant_variable", + "mutant_017_suppressed_error_arguments_swapped" + ], + "coverage_gate": { + "minimum_line_coverage_percent": 80, + "status": "passed", + "coverage_report": "coverage_out/coverage_report_union.json", + "baseline_coverage_report": "coverage_out/coverage_report_orig.json", + "augmented_coverage_report": "coverage_out/coverage_report_aug.json", + "measurement_note": "TypeScript coverage runner estimates executable solution.patch line coverage from successful public harness runs for the selected suite. Refreshed 2026-06-15 after expanding original P2P to 50 pre-existing selectors.", + "baseline_union_line_coverage_percent": 100.0, + "augmented_only_union_line_coverage_percent": 100.0, + "union_line_coverage_percent": 100.0, + "executable_lines_in_patch": 5345, + "union_covered_lines": 5345, + "coverage_complete": true + }, + "triage": { + "test_level_policy": "Augmented F2P and P2P entries are TypeScript fourslash tests. They drive public compiler APIs, emitted JavaScript, type diagnostics, and language-service quick-info through the normal TypeScript test harness; no augmented selector imports or calls project-private compiler helpers.", + "fail_to_pass": { + "tests/cases/fourslash/usingAugDiagnosticsAndLib.ts": { + "requirement_sections": [ + "Syntax > `using` Declarations", + "Grammar > `await using` Declarations", + "Semantics > `using` Declarations > `using` Declarations with Explicit Local Bindings", + "Semantics > `await using` Declarations > `await using` Declarations with Explicit Local Bindings", + "API > Additions to `Symbol`", + "API > The Common `Disposable` and `AsyncDisposable` Interfaces > The `Disposable` Interface", + "API > The Common `Disposable` and `AsyncDisposable` Interfaces > The `AsyncDisposable` Interface" + ], + "public_surface": "TypeScript public compiler API: ts.createProgram, ts.createCompilerHost, ts.getPreEmitDiagnostics, standard lib selection via lib.esnext.d.ts, and public diagnostics.", + "mutants_targeted": [ + "mutant_003_using_initializer_accepts_non_disposable", + "mutant_004_await_using_initializer_accepts_non_disposable", + "mutant_005_using_null_and_undefined_rejected", + "mutant_006_await_using_null_and_undefined_rejected", + "mutant_013_async_disposable_symbol_returns_void", + "mutant_014_esnext_omits_disposable_lib_reference", + "mutant_015_using_not_block_scoped", + "mutant_016_using_not_constant_variable" + ], + "rationale": "Checks the public type-checking contract for using and await-using declarations: non-disposable initializers are rejected, nullish initializers are accepted, AsyncDisposable Promise-returning methods and esnext disposable symbols are available, using bindings remain block-scoped, and using variables remain constant." + }, + "tests/cases/fourslash/usingAugEmitHelpers.ts": { + "requirement_sections": [ + "Syntax > `using` Declarations", + "Grammar > `await using` Declarations", + "Semantics > `using` Declarations > `using` Declarations with Explicit Local Bindings", + "Semantics > `await using` Declarations > `await using` Declarations with Explicit Local Bindings", + "Semantics > `await using` Declarations > Implicit Async Interleaving Points (\"implicit `await`\")", + "API > The `SuppressedError` Error" + ], + "public_surface": "TypeScript public compiler API: ts.transpileModule, ts.createSourceFile, public NodeFlags enum, and the JavaScript output emitted for downlevel using declarations.", + "mutants_targeted": [ + "mutant_001_using_flag_recorded_as_const", + "mutant_002_await_using_flag_recorded_as_sync_using", + "mutant_007_disposable_resource_async_flag_inverted", + "mutant_008_dispose_order_fifo_not_lifo", + "mutant_009_await_using_no_sync_dispose_fallback", + "mutant_010_await_using_null_sentinel_not_registered", + "mutant_011_async_dispose_result_not_awaited", + "mutant_012_await_using_detected_as_sync_kind", + "mutant_017_suppressed_error_arguments_swapped" + ], + "rationale": "Verifies public emit and parser outcomes: using parses with the Using flag, await using parses with the AwaitUsing flag, downlevel emit passes correct sync/async helper flags, null await-using values still enter the async cleanup path, sync disposables remain valid fallback for await using, async cleanup is awaited, resources dispose LIFO, and SuppressedError exposes disposal errors as error with prior body errors as suppressed." + } + }, + "pass_to_pass": { + "tests/cases/fourslash/usingAugVariableDeclarationP2P.ts": { + "requirement_sections": [ + "Syntax > `using` Declarations" + ], + "public_surface": "Existing TypeScript language-service quick-info and no-error behavior for ordinary let/const variable declarations.", + "stability_goal": "Adding using declarations must not disturb ordinary lexical variable declaration typing, nested const literal types, or reassignment of existing let bindings.", + "rationale": "Pins adjacent unchanged variable-declaration behavior in the same parser/checker family while deliberately avoiding the new using syntax." + }, + "tests/cases/fourslash/usingAugForOfP2P.ts": { + "requirement_sections": [ + "Grammar > `await using` in `for-of` and `for-await-of` Statements" + ], + "public_surface": "Existing TypeScript language-service quick-info and no-error behavior for for-of loop variables.", + "stability_goal": "The new using and await-using forms in loop initializers must not regress existing for-of loop variable inference.", + "rationale": "Pins adjacent unchanged loop-binding behavior through public quick-info checks without mentioning using declarations." + } + } + } + }, + "repo": "microsoft/TypeScript", + "image": "lolbench/apache-typescript-pr-54505:1", + "agent_contract": { + "input": "/in/solution.patch", + "output": "/out/agent_report.json", + "invocation": "docker run --rm -v $(pwd)/solution.patch:/in/solution.patch:ro -v $(pwd)/out:/out lolbench/apache-typescript-pr-54505:1" + }, + "test_framework": "node_test", + "test_level": "system", + "test_cmd_template": "npm test -- ", + "log_parser": "node_test", + "validation_summary": { + "status": "validated", + "validated_at": "2026-06-15", + "orig_pre": { + "f2p": {"passed": 0, "failed": 16, "errored": 0, "total": 16}, + "p2p": {"passed": 50, "failed": 0, "errored": 0, "total": 50}, + "resolved": false + }, + "orig_post": { + "f2p": {"passed": 16, "failed": 0, "errored": 0, "total": 16}, + "p2p": {"passed": 50, "failed": 0, "errored": 0, "total": 50}, + "resolved": true + }, + "aug_pre": { + "f2p": {"passed": 0, "failed": 2, "errored": 0, "total": 2}, + "p2p": {"passed": 2, "failed": 0, "errored": 0, "total": 2}, + "resolved": false + }, + "aug_post": { + "f2p": {"passed": 2, "failed": 0, "errored": 0, "total": 2}, + "p2p": {"passed": 2, "failed": 0, "errored": 0, "total": 2}, + "resolved": true + }, + "union_pre": { + "f2p": {"passed": 0, "failed": 18, "errored": 0, "total": 18}, + "p2p": {"passed": 52, "failed": 0, "errored": 0, "total": 52}, + "resolved": false + }, + "union_post": { + "f2p": {"passed": 18, "failed": 0, "errored": 0, "total": 18}, + "p2p": {"passed": 52, "failed": 0, "errored": 0, "total": 52}, + "resolved": true + } + }, + "coverage": { + "orig": 100.0, + "aug": 100.0, + "union": 100.0, + "denominator": "union_executable_lines", + "orig_report": "coverage_out/coverage_report_orig.json", + "aug_report": "coverage_out/coverage_report_aug.json", + "union_report": "coverage_out/coverage_report_union.json", + "coverage_report_json": "coverage_out/coverage_report.json mirrors union", + "covered_lines": 5345, + "executable_lines_in_patch": 5345, + "refreshed_at": "2026-06-15" + } +} diff --git a/TypeScript_2/tests/report_to_reward.py b/TypeScript_2/tests/report_to_reward.py new file mode 100644 index 0000000000000000000000000000000000000000..b783024e9d7b07f42405f46b1bf4994acb9e9529 --- /dev/null +++ b/TypeScript_2/tests/report_to_reward.py @@ -0,0 +1,73 @@ +#!/usr/bin/env python3 +import argparse +import json +from pathlib import Path + + +def rate(bucket): + total = float(bucket.get("total", 0) or 0) + if total <= 0: + return 0.0 + return float(bucket.get("passed", 0) or 0) / total + + +def write_json(path, payload): + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(json.dumps(payload, indent=2, sort_keys=True) + "\n") + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument("--suite", default="union") + parser.add_argument("--missing-patch") + parser.add_argument("--invalid-suite", action="store_true") + parser.add_argument("--runner-rc", type=int, default=0) + parser.add_argument("agent_report") + parser.add_argument("reward_file") + args = parser.parse_args() + + report_path = Path(args.agent_report) + reward_path = Path(args.reward_file) + + if args.invalid_suite: + reward = {"reward": 0.0, "resolved": 0.0, "applied": 0.0, "build_ok": 0.0, "f2p_pass_rate": 0.0, "p2p_pass_rate": 0.0, "harness_ok": 1.0} + sanitized = {"instance_id": "TypeScript_2", "suite": args.suite, "applied": False, "resolved": False, "error_categories": ["invalid_lolbench_suite"]} + write_json(report_path, sanitized) + write_json(reward_path, reward) + print(f"LoLBench reward=0 invalid suite {args.suite!r}") + return 0 + + if args.missing_patch: + reward = {"reward": 0.0, "resolved": 0.0, "applied": 0.0, "build_ok": 0.0, "f2p_pass_rate": 0.0, "p2p_pass_rate": 0.0, "harness_ok": 1.0} + sanitized = {"instance_id": "TypeScript_2", "suite": args.suite, "applied": False, "resolved": False, "error_categories": ["missing_solution_patch"]} + write_json(report_path, sanitized) + write_json(reward_path, reward) + print("LoLBench reward=0 missing solution patch") + return 0 + + if not report_path.exists(): + reward = {"reward": 0.0, "resolved": 0.0, "applied": 0.0, "build_ok": 0.0, "f2p_pass_rate": 0.0, "p2p_pass_rate": 0.0, "harness_ok": 0.0} + write_json(reward_path, reward) + print(f"LoLBench reward=0 no agent_report.json runner_rc={args.runner_rc}") + return 0 + + report = json.loads(report_path.read_text()) + build_status = report.get("build", {}).get("status") + resolved = bool(report.get("resolved")) + applied = bool(report.get("applied")) + reward = { + "reward": 1.0 if resolved else 0.0, + "resolved": 1.0 if resolved else 0.0, + "applied": 1.0 if applied else 0.0, + "build_ok": 1.0 if build_status == "ok" else 0.0, + "f2p_pass_rate": rate(report.get("f2p", {})), + "p2p_pass_rate": rate(report.get("p2p", {})), + "harness_ok": 1.0 if args.runner_rc == 0 else 0.0, + } + write_json(reward_path, reward) + print("LoLBench reward={reward} resolved={resolved} f2p={f2p_pass_rate:.3f} p2p={p2p_pass_rate:.3f}".format(**reward)) + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/TypeScript_2/tests/test.sh b/TypeScript_2/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..45ba2abd4f682d021752e6966a772a0ee2edb9f5 --- /dev/null +++ b/TypeScript_2/tests/test.sh @@ -0,0 +1,43 @@ +#!/usr/bin/env bash +set -euo pipefail + +suite=${LOLBENCH_SUITE:-union} +mode=${LOLBENCH_MODE:-eval} +patch=${LOLBENCH_SOLUTION_PATCH:-/logs/artifacts/solution.patch} +private_log=/tmp/lolbench-private-run.log + +mkdir -p /logs/verifier /logs/artifacts /in /out + +case "$suite" in + orig|aug|union) ;; + *) + python3 /tests/report_to_reward.py --suite "$suite" --invalid-suite /out/agent_report.json /logs/verifier/reward.json + exit 0 + ;; +esac + +if [ "$mode" = "eval" ] && [ ! -s "$patch" ]; then + python3 /tests/report_to_reward.py --suite "$suite" --missing-patch "$patch" /out/agent_report.json /logs/verifier/reward.json + exit 0 +fi + +if [ "$mode" = "eval" ]; then + cp "$patch" /in/solution.patch + chmod 0400 /in/solution.patch +fi + +set +e +LOLBENCH_MODE="$mode" LOLBENCH_SUITE="$suite" /opt/lolbench/private/run_tests.sh >"$private_log" 2>&1 +runner_rc=$? +set -e + +cp "$private_log" /logs/verifier/private_run.log +if [ -f /out/grader_report.json ]; then + cp /out/grader_report.json /logs/verifier/grader_report.json +fi + +python3 /tests/report_to_reward.py --suite "$suite" --runner-rc "$runner_rc" /out/agent_report.json /logs/verifier/reward.json + +if [ -f /out/agent_report.json ]; then + cp /out/agent_report.json /logs/verifier/agent_report.json +fi diff --git a/TypeScript_3/README.md b/TypeScript_3/README.md new file mode 100644 index 0000000000000000000000000000000000000000..eb872e97bb5b447474f253995b7c5068f4e0a0c6 --- /dev/null +++ b/TypeScript_3/README.md @@ -0,0 +1,87 @@ +# LoLBench Harbor Task: TypeScript_3 + +This is a Harbor-format LoLBench task generated from `TypeScript_PR-58640_Arbitrary-Module-Namespace-Identifiers`. + +Selected source instance: + +- Harbor ID: `TypeScript_3` +- PR: `microsoft/TypeScript#58640` +- Base commit: `112e860602b2b46f7a1f179a8f6357f6e4db2370` +- Test modes: `orig, aug, union` +- Default/canonical mode: `union` +- Harbor image: `smartdub26/lolbench-linux:TypeScript_3-1.0.0` +- Docker Hub image: `smartdub26/lolbench-linux:TypeScript_3-1.0.0` + +## Image Setup + +Prefer the published Docker Hub image when it is available. Harbor refers to +the image as `smartdub26/lolbench-linux:TypeScript_3-1.0.0`, so Docker can pull it +directly when it is not present locally: + +```bash +docker pull smartdub26/lolbench-linux:TypeScript_3-1.0.0 +``` + +Only if the Docker Hub image is unavailable, build the single task image +locally: + +```bash +docker build -t lolbench/typescript_3:1.0.0 harbor_tasks/TypeScript_3/environment +docker tag lolbench/typescript_3:1.0.0 smartdub26/lolbench-linux:TypeScript_3-1.0.0 +``` + +The image contains the processed source tree at the base commit under +`/workspace/typescript`. Harbor must not mount a host source checkout +for the agent. + +## Run an Agent + +```bash +.harbor-venv/bin/harbor run \ + -p harbor_tasks/TypeScript_3 \ + -a codex \ + -m "" \ + --job-name TypeScript_3_agent_union \ + --jobs-dir harbor_runs/TypeScript_3 \ + --no-delete \ + --n-concurrent 1 \ + --ve LOLBENCH_SUITE=union +``` + +After implementing the requirement, the agent must clean any test-file edits +and run: + +```bash +lolbench-submit +``` + +## Evaluate a Patch + +Choose one mode with `LOLBENCH_SUITE=orig`, `aug`, or `union`; if unset, the +task defaults to `union`. + +```bash +PATCH="$(pwd)/path/to/solution.patch" + +.harbor-venv/bin/harbor run \ + -p harbor_tasks/TypeScript_3 \ + -a oracle \ + --job-name TypeScript_3_eval_union \ + --jobs-dir harbor_runs/TypeScript_3 \ + --no-delete \ + --n-concurrent 1 \ + --mounts '[{"type":"bind","source":"'"$PATCH"'","target":"/candidate/solution.patch","read_only":true}]' \ + --ae LOLBENCH_ORACLE_PATCH=/candidate/solution.patch \ + --ve LOLBENCH_SUITE=union +``` + +Outputs: + +```bash +find harbor_runs/TypeScript_3/TypeScript_3_eval_union -path '*/verifier/agent_report.json' -print +find harbor_runs/TypeScript_3/TypeScript_3_eval_union -path '*/verifier/reward.json' -print +``` + +`tests/docker-compose.yaml` is a verifier-only Harbor overlay. It mounts +`tests/`, `tests/private/`, and `solution/` into the separate verifier +container; none of those paths are mounted into the agent container. diff --git a/TypeScript_3/environment/Dockerfile b/TypeScript_3/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..901d067931158309c60a1cd0fabaf24dca6b813b --- /dev/null +++ b/TypeScript_3/environment/Dockerfile @@ -0,0 +1,86 @@ +# LoLBench eval image: TypeScript PR-58640 (Arbitrary Module Namespace Identifiers) +# base_commit: 112e860602b2b46f7a1f179a8f6357f6e4db2370 +# (parent of squash-merge 8d62e2f1 on main) + +ARG BASE_IMAGE=lolbench/typescript-base-node18:1 +FROM ${BASE_IMAGE} + +ARG BASE_COMMIT=112e860602b2b46f7a1f179a8f6357f6e4db2370 + +RUN mkdir -p /opt/lolbench/private /in /out /workspace + +WORKDIR /workspace +RUN git init typescript && \ + cd typescript && \ + git remote add origin https://github.com/microsoft/TypeScript.git && \ + git fetch --no-tags origin ${BASE_COMMIT} && \ + git checkout ${BASE_COMMIT} && \ + git ls-files -z > /tmp/typescript-base-files && \ + git config user.email lolbench@local && \ + git config user.name lolbench && \ + if ! git diff --quiet || ! git diff --cached --quiet || [ -n "$(git ls-files --others --exclude-standard)" ]; then \ + git add -A && git -c commit.gpgsign=false commit -q -m "LoLBench environment overlay"; \ + fi && \ + git tag -f base && git tag -f lolbench-base && \ + git for-each-ref --format='%(refname)' refs/heads refs/remotes refs/tags | \ + while read ref; do \ + case "$ref" in refs/tags/base|refs/tags/lolbench-base) ;; *) git update-ref -d "$ref" ;; esac; \ + done && \ + ( git remote remove origin 2>/dev/null || true ) && \ + rm -f .git/FETCH_HEAD && \ + git reflog expire --expire=now --all && \ + git repack -Ad && \ + git prune --expire=now && \ + rm /tmp/typescript-base-files && \ + git config --global --add safe.directory /workspace/typescript + +# TS 5.5 uses hereby as the build tool (replaced gulp in TS 5.0+). +RUN cd /workspace/typescript && \ + npm install --no-progress --no-fund --no-audit && \ + npx hereby local && \ + npx hereby tests + +# ---- Eval bundle ------------------------------------------------------ + +# Harbor runtime adapter: keep the image public/agent-safe. +RUN mkdir -p /opt/lolbench /logs/artifacts /logs/agent /logs/verifier /in /out && \ + if ! id -u agent >/dev/null 2>&1; then useradd -m -s /bin/bash agent; fi +COPY metadata.json /opt/lolbench/metadata.json +COPY lolbench-submit /usr/local/bin/lolbench-submit +RUN chmod +x /usr/local/bin/lolbench-submit && \ + git config --global --add safe.directory /workspace/typescript && \ + if [ -d /workspace/typescript/.git ]; then \ + cd /workspace/typescript && LC_ALL=C git ls-files --others --exclude-standard | LC_ALL=C sort > /opt/lolbench/base_untracked.txt; \ + else \ + : > /opt/lolbench/base_untracked.txt; \ + fi && \ + chown -R agent:agent /workspace/typescript /logs +ENV HOME=/home/agent +# Local-reference hardening: retain only the approved base history. +RUN git config --system --add safe.directory /workspace/typescript && \ + cd /workspace/typescript && \ + git for-each-ref --format='%(refname)' refs/heads refs/remotes refs/tags | \ + while read ref; do \ + case "$ref" in refs/tags/base|refs/tags/lolbench-base) ;; *) git update-ref -d "$ref" ;; esac; \ + done && \ + ( git remote remove origin 2>/dev/null || true ) && \ + rm -f .git/FETCH_HEAD && \ + git reflog expire --expire=now --all && \ + git repack -Ad && \ + git prune --expire=now && \ + unreachable=$(git fsck --unreachable --no-reflogs) && \ + test -z "$unreachable" && \ + chown -R agent:agent .git +# Keep npm executable but remove cached/global copies of TypeScript sources. +RUN rm -rf /root/.npm /home/agent/.npm && \ + rm -f /usr/local/bin/tsc /usr/local/bin/tsserver /usr/bin/tsc /usr/bin/tsserver && \ + for p in /usr/local/lib/node_modules /usr/lib/node_modules; do \ + if [ -d "$p" ]; then \ + find "$p" -mindepth 1 -maxdepth 1 -type d -iname typescript -exec rm -rf '{}' +; \ + chown -R root:root "$p"; chmod -R go-w "$p"; chmod 0711 "$p"; \ + fi; \ + done +USER agent +WORKDIR /workspace/typescript +ENV LOLBENCH_INSTANCE_ID=TypeScript_3 +ENV LOLBENCH_SOURCE_SLUG=TypeScript_PR-58640_Arbitrary-Module-Namespace-Identifiers diff --git a/TypeScript_3/environment/docker-compose.yaml b/TypeScript_3/environment/docker-compose.yaml new file mode 100644 index 0000000000000000000000000000000000000000..7ed45f87dc9faf9df284f5b10d6d2289781ff254 --- /dev/null +++ b/TypeScript_3/environment/docker-compose.yaml @@ -0,0 +1,3 @@ +services: + main: + pull_policy: missing diff --git a/TypeScript_3/environment/lolbench-submit b/TypeScript_3/environment/lolbench-submit new file mode 100644 index 0000000000000000000000000000000000000000..b3426184f1a568aaf145f148348c3c5e85cfa773 --- /dev/null +++ b/TypeScript_3/environment/lolbench-submit @@ -0,0 +1,33 @@ +#!/usr/bin/env bash +set -euo pipefail +export LC_ALL=C + +repo=${1:-$PWD} +out=${LOLBENCH_PATCH_OUT:-/logs/artifacts/solution.patch} + +mkdir -p "$(dirname "$out")" +cd "$repo" + +baseline=/opt/lolbench/base_untracked.txt +current=$(mktemp) +new_files=$(mktemp) +trap 'rm -f "$current" "$new_files"' EXIT + +git ls-files --others --exclude-standard | sort > "$current" +if [ -f "$baseline" ]; then + comm -13 "$baseline" "$current" > "$new_files" +else + cp "$current" "$new_files" +fi + +if [ -s "$new_files" ]; then + xargs -r git add -N -- < "$new_files" +fi + +git diff --binary > "$out" + +if [ ! -s "$out" ]; then + echo "warning: wrote an empty solution patch to $out" >&2 +else + echo "wrote solution patch to $out" +fi diff --git a/TypeScript_3/environment/metadata.json b/TypeScript_3/environment/metadata.json new file mode 100644 index 0000000000000000000000000000000000000000..1d231281e339c90cea38256c968567d53707a830 --- /dev/null +++ b/TypeScript_3/environment/metadata.json @@ -0,0 +1,22 @@ +{ + "instance_id": "TypeScript_3", + "source_instance_id": "TypeScript_PR-58640_Arbitrary-Module-Namespace-Identifiers", + "source_slug": "TypeScript_PR-58640_Arbitrary-Module-Namespace-Identifiers", + "docker_slug": "TypeScript_PR-58640_Arbitrary-Module-Namespace-Identifiers", + "dockerhub_image": "smartdub26/lolbench-linux:TypeScript_3-1.0.0", + "project": "TypeScript", + "repo": "microsoft/TypeScript", + "requirement_doc": "https://github.com/tc39/ecma262/pull/2154", + "pr_link": "https://github.com/microsoft/TypeScript/pull/58640", + "base_commit": "112e860602b2b46f7a1f179a8f6357f6e4db2370", + "merge_commit": "ff8217073661987cd62923fd596e18e40de62740", + "source_history_policy": "ancestors-only", + "lolbench_test_modes": [ + "orig", + "aug", + "union" + ], + "default_lolbench_suite": "union", + "canonical_lolbench_suite": "union", + "augmentation_available": true +} diff --git a/TypeScript_3/environment/source_audit.json b/TypeScript_3/environment/source_audit.json new file mode 100644 index 0000000000000000000000000000000000000000..1cec2f462d62b68d1485d170a1468406fcabd30e --- /dev/null +++ b/TypeScript_3/environment/source_audit.json @@ -0,0 +1,7 @@ +{ + "source_policy": "dockerfile_fetch_pruned_ancestor_history", + "local_reference_policy": "auxiliary_sources_removed_execute_only", + "base_commit": "112e860602b2b46f7a1f179a8f6357f6e4db2370", + "repo": "microsoft/TypeScript", + "note": "The Dockerfile fetches only the declared base history, removes refs/remotes/reflogs, repacks and prunes unreachable objects, asserts that git fsck finds no unreachable object, removes auxiliary reference sources, and makes remaining auxiliary toolchains root-owned and non-enumerable to the agent." +} diff --git a/TypeScript_3/instruction.md b/TypeScript_3/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..a7f9279dcc1f1ab2d1ea278a9cb82bb6782fa6f1 --- /dev/null +++ b/TypeScript_3/instruction.md @@ -0,0 +1,195 @@ +You are working in `/workspace/typescript`, a source tree checked out at +the base commit for this task. Implement the requested behavior in the source +tree, then run: + +```bash +lolbench-submit +``` + +Do not stop after editing files, running tests, or describing the solution. The +task is complete only when `lolbench-submit` has created +`/logs/artifacts/solution.patch`. If that file does not exist, continue +working and run `lolbench-submit` again. + +That command writes your implementation diff to +`/logs/artifacts/solution.patch`, which is the artifact the Harbor verifier +will grade. Before running `lolbench-submit`, clean or revert any test files +you created or modified; test files must not be included in the final +`solution.patch`. + +This environment has no outbound internet access — `curl`/`wget`, `git fetch`/`clone`, package installs, and web fetch/search will all fail. Implement the requirements using only the code already in the workspace and your own knowledge; do not attempt to fetch or search external resources. + +Now please implement the following requirements in the source tree: + +--- + +# Arbitrary Module Namespace Identifier Names + +Arbitrary Module Namespace Identifier Names is an ECMAScript syntax feature (shipped in ES2022) that allows the imported and exported names of a module binding to be written as **string literals** rather than only as ECMAScript identifiers. This lets modules import and export bindings whose names are not valid ECMAScript identifiers — for example names containing spaces, `::`, `.`, or other characters — which is required to faithfully interoperate with module systems (notably WebAssembly) that permit any well-formed Unicode string as an export/import name. + +The canonical normative specification for this feature was merged into the ECMAScript Language Specification (ecma262) via [PR #2154 "Normative: Arbitrary module namespace identifier names"](https://github.com/tc39/ecma262/pull/2154). There is no separate TC39 proposal repository for this feature; its substantive grammar and static semantics live in the ecma262 `spec.html` change introduced by that PR, reproduced inline below. + +## Summary + +Before this feature, an `import` or `export` specifier could only name a binding using an `IdentifierName`: + +```js +import { foo } from "./mod.js"; +export { foo as bar }; +``` + +This feature generalizes the *module export name* — the name under which a binding is imported from, or exported to, a module — so that it may also be a `StringLiteral`: + +```js +import { "foo bar" as foo } from "./mod.js"; +export { foo as "foo bar" }; +export { foo as "foo bar" } from "./mod.js"; +export * as "foo bar" from "./mod.js"; +``` + +A string-literal module export name is purely a *name on the module record*: it is the name that other modules use to import the binding. When importing a string-literal name, the `as ImportedBinding` clause binds it to an ordinary local identifier (`foo` above), because a string literal cannot itself be referenced as a local variable. A string-literal name may also be re-exported (`export { x as "string name" }`) or accessed as a property of a namespace object obtained via `import * as ns from "..."` (e.g. `ns["foo bar"]`). + +## Motivation + +ECMAScript modules need to interoperate with other module systems whose export/import names are not constrained to the ECMAScript identifier grammar. The motivating case is **WebAssembly**: the WebAssembly specification allows the string names of imports and exports to be any sequence of valid Unicode, including names that are not valid ECMAScript identifiers. To allow an ECMAScript module to import such a binding from (or export such a binding to) a WebAssembly module, the module-export-name grammar must admit arbitrary (well-formed Unicode) string literals. + +The original ECMAScript change summarizes the goal as allowing: + +```mjs +import {"\0 any unicode" as foo} from ""; +export {foo as "\0 any unicode"}; +``` + +and notes that *this matches the restriction that WASM has that the string names for exports must be valid Unicode*. + +## Grammar + +The feature extends the module import/export grammar by introducing a new `ModuleExportName` nonterminal that may be either an `IdentifierName` or a `StringLiteral`, and by routing import and export specifiers through it. The relevant productions (from the ecma262 `spec.html` change) are: + +```grammarkdown +ModuleExportName : + IdentifierName + StringLiteral + +ImportSpecifier : + ImportedBinding + ModuleExportName `as` ImportedBinding + +ExportFromClause : + `*` + `*` `as` ModuleExportName + NamedExports + +ExportSpecifier : + ModuleExportName + ModuleExportName `as` ModuleExportName +``` + +`NamedExports` continues to be a brace-delimited, comma-separated list of `ExportSpecifier`s. An `ImportSpecifier` of the form `ModuleExportName as ImportedBinding` allows a string-literal import name to be bound to a local identifier; an `ExportSpecifier` of the form `ModuleExportName as ModuleExportName` and the `ExportFromClause` form `* as ModuleExportName` allow string-literal export names. + +## Static Semantics + +The new `StringLiteral` form of `ModuleExportName` carries static-semantics rules that constrain it and that thread its string value (`StringValue` / `SV`) through the module's import and export entry records. + +**Well-formed Unicode requirement.** A string-literal module export name must be well-formed Unicode (it may not contain unpaired surrogates): + +``` +ModuleExportName : StringLiteral + - It is a Syntax Error if IsStringWellFormedUnicode(the SV of StringLiteral) is false. +``` + +This relies on the abstract operation `IsStringWellFormedUnicode(string)`, which interprets `string` as a sequence of UTF-16 encoded code points and returns `false` if any code point is an unpaired surrogate, otherwise `true`. + +**No string literals as local references.** A string-literal name is only meaningful as a module export name, not as a local binding reference. In particular, in an `export { ... }` clause that re-exports local bindings (a `NamedExports` not followed by a `FromClause`), the *referenced* names must be identifiers: + +``` +NamedExports (without a FromClause) + - It is a Syntax Error if ReferencedBindings of NamedExports contains any StringLiterals. +``` + +**StringValue / import & export entries.** The string value of a `ModuleExportName` is its `SV` when it is a `StringLiteral` and its `StringValue` when it is an `IdentifierName`. This value flows into the module record: + +``` +ModuleExportName : StringLiteral + StringValue : Return the SV of StringLiteral. + +ImportSpecifier : ModuleExportName `as` ImportedBinding + ImportEntriesForModule : the [[ImportName]] is the StringValue of ModuleExportName. + +ExportSpecifier : ModuleExportName + ExportedBindings / ReferencedBindings : a List whose sole element is the StringValue of ModuleExportName. + +ExportSpecifier : ModuleExportName `as` ModuleExportName + - the source name is the StringValue of the first ModuleExportName. + - the exported name is the StringValue of the second ModuleExportName. + +ExportFromClause : `*` `as` ModuleExportName + - the exported name is the StringValue of ModuleExportName. +``` + +Concretely, for `import { "x" as y }` the module-record `[[ImportName]]` is `"x"` and the local binding is `y`; for `export { y as "x" }` the local source name is `y` and the module-record export name is `"x"`; and for `export * as "x" from "mod"` the re-exported namespace is published under the name `"x"`. + +## Examples + +A WebAssembly-style import/export, binding a string export name to a usable local identifier: + +```js +import { "Foo::new" as Foo_new } from "./foo.wasm" + +const foo = Foo_new() + +export { Foo_new as "Foo::new" } +``` + +A real-world use is esbuild's [`inject`](https://esbuild.github.io/api/#inject) feature, which treats each named export of a file as an expression to substitute at build time. String-literal export names let a build-time replacement target a member expression such as `Math.sin`, which is concise and tree-shaking friendly: + +```js +// This file is passed to esbuild using "--inject:./inject.js" + +// Minify calls to math functions +const sin = Math.sin, cos = Math.cos, tan = Math.tan +export { sin as 'Math.sin', cos as 'Math.cos', tan as 'Math.tan' } + +// Polyfill 32-bit integer multiply if needed +const imul = Math.imul || ((x, y) => { + const xlo = x & 0xffff, ylo = y & 0xffff + return xlo * ylo + (((x >>> 16) * ylo + (y >>> 16) * xlo) << 16 >>> 0) | 0 +}) +export { imul as 'Math.imul' } +``` + +## TypeScript Implementation Scope + +The implementing change in TypeScript (PR-58640) adds support for this ES2022 syntax across the compiler and language service. Per the PR description, it does the following: + +* The syntax can be parsed and emitted +* It works with type checking and formatting +* Seems to work with declaration file generation +* Analogous syntax also works for type imports+exports +* Converts to various module formats (`ESNext`, `CommonJS`, `System`, `AMD`, `UMD`) +* Errors when the module format is `ES2015` or `ES2020`: string-literal import and export names are unsupported for those two targets, so the checker reports error `TS18057` — `String literal import and export names are not supported when the '--module' flag is set to 'es2015' or 'es2020'.` — at each offending string-literal name. +* Can be used with "go to definition" and "find all references" +* Has basic support for renaming quoted export names across files +* Works with the "convert named imports to namespace import" refactoring +* Provides completions in `import {}` and `export {}` lists. A string-literal module export name (an export name that is not a valid identifier) is offered as a JSON-quoted string, and the inserted text depends on position: in an `import {}` list it is the quoted name followed by an `as` clause binding it to a generated local identifier — for an export named `"__some value"` the completion inserts `"__some value" as __some_value`, deriving the identifier from the name by keeping the characters that are legal in an identifier and replacing each run of other characters (such as spaces) with a single underscore — whereas in an `export {}` list it is just the quoted name (`"__some value"`, with no `as` clause). When the caret is already inside the quotes of a string-literal specifier, the completion inserts the bare name (`__some value`) without the surrounding quotes. + +What the PR intentionally does **not** do: syntax highlighting (handled in a separate TextMate grammar PR) and the inverse "convert namespace import to named imports" refactoring (introducing this syntax when it is absent may not be desirable). + +## Linked ecma262 PR #2154 — Normative: Arbitrary module namespace identifier names + +The original ECMAScript change that introduced this feature stated: + +> I do not believe this affects any integration downstream. +> +> This PR aims to allow: +> +> ```mjs +> import {"\0 any unicode" as foo} from ""; +> export {foo as "\0 any unicode"}; +> ``` +> +> This matches the restriction that WASM has that the string names for exports must be valid Unicode. +> +> Depends on #2155 + +*Source: https://github.com/tc39/ecma262/pull/2154* diff --git a/TypeScript_3/solution/solution.patch b/TypeScript_3/solution/solution.patch new file mode 100644 index 0000000000000000000000000000000000000000..75f1377488fdca24e44d4d5036f1b245dedbbfed --- /dev/null +++ b/TypeScript_3/solution/solution.patch @@ -0,0 +1,1602 @@ +diff --git a/src/compiler/binder.ts b/src/compiler/binder.ts +index ea263f471..cab3c6911 100644 +--- a/src/compiler/binder.ts ++++ b/src/compiler/binder.ts +@@ -251,6 +251,7 @@ import { + ModifierFlags, + ModuleBlock, + ModuleDeclaration, ++ moduleExportNameIsDefault, + Mutable, + NamespaceExportDeclaration, + Node, +@@ -433,6 +434,9 @@ function getModuleInstanceStateWorker(node: Node, visited: Map) { + const name = specifier.propertyName || specifier.name; ++ if (name.kind !== SyntaxKind.Identifier) { ++ return ModuleInstanceState.Instantiated; // Skip for invalid syntax like this: export { "x" } ++ } + let p: Node | undefined = specifier.parent; + while (p) { + if (isBlock(p) || isModuleBlock(p) || isSourceFile(p)) { +@@ -759,7 +763,7 @@ function createBinder(): (file: SourceFile, options: CompilerOptions) => void { + function declareSymbol(symbolTable: SymbolTable, parent: Symbol | undefined, node: Declaration, includes: SymbolFlags, excludes: SymbolFlags, isReplaceableByMethod?: boolean, isComputedName?: boolean): Symbol { + Debug.assert(isComputedName || !hasDynamicName(node)); + +- const isDefaultExport = hasSyntacticModifier(node, ModifierFlags.Default) || isExportSpecifier(node) && node.name.escapedText === "default"; ++ const isDefaultExport = hasSyntacticModifier(node, ModifierFlags.Default) || isExportSpecifier(node) && moduleExportNameIsDefault(node.name); + + // The exported symbol for an export default function/class node is always named "default" + const name = isComputedName ? InternalSymbolName.Computed +diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts +index 51bbd6295..5cefd7aa0 100644 +--- a/src/compiler/checker.ts ++++ b/src/compiler/checker.ts +@@ -863,6 +863,10 @@ import { + modifierToFlag, + ModuleBlock, + ModuleDeclaration, ++ ModuleExportName, ++ moduleExportNameIsDefault, ++ moduleExportNameTextEscaped, ++ moduleExportNameTextUnescaped, + ModuleInstanceState, + ModuleKind, + ModuleResolutionKind, +@@ -3629,7 +3633,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { + : Diagnostics._0_was_imported_here; + + // TODO: how to get name for export *? +- const name = typeOnlyDeclaration.kind === SyntaxKind.ExportDeclaration ? "*" : unescapeLeadingUnderscores(typeOnlyDeclaration.name.escapedText); ++ const name = typeOnlyDeclaration.kind === SyntaxKind.ExportDeclaration ? "*" : moduleExportNameTextUnescaped(typeOnlyDeclaration.name); + addRelatedInfo(error(node.moduleReference, message), createDiagnosticForNode(typeOnlyDeclaration, relatedMessage, name)); + } + } +@@ -3864,12 +3868,12 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { + return result; + } + +- function getExportOfModule(symbol: Symbol, name: Identifier, specifier: Declaration, dontResolveAlias: boolean): Symbol | undefined { ++ function getExportOfModule(symbol: Symbol, nameText: __String, specifier: Declaration, dontResolveAlias: boolean): Symbol | undefined { + if (symbol.flags & SymbolFlags.Module) { +- const exportSymbol = getExportsOfSymbol(symbol).get(name.escapedText); ++ const exportSymbol = getExportsOfSymbol(symbol).get(nameText); + const resolved = resolveSymbol(exportSymbol, dontResolveAlias); +- const exportStarDeclaration = getSymbolLinks(symbol).typeOnlyExportStarMap?.get(name.escapedText); +- markSymbolOfAliasDeclarationIfTypeOnly(specifier, exportSymbol, resolved, /*overwriteEmpty*/ false, exportStarDeclaration, name.escapedText); ++ const exportStarDeclaration = getSymbolLinks(symbol).typeOnlyExportStarMap?.get(nameText); ++ markSymbolOfAliasDeclarationIfTypeOnly(specifier, exportSymbol, resolved, /*overwriteEmpty*/ false, exportStarDeclaration, nameText); + return resolved; + } + } +@@ -3887,13 +3891,19 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { + const moduleSpecifier = getExternalModuleRequireArgument(node) || (node as ImportDeclaration | ExportDeclaration | JSDocImportTag).moduleSpecifier!; + const moduleSymbol = resolveExternalModuleName(node, moduleSpecifier)!; // TODO: GH#18217 + const name = !isPropertyAccessExpression(specifier) && specifier.propertyName || specifier.name; +- if (!isIdentifier(name)) { ++ if (!isIdentifier(name) && name.kind !== SyntaxKind.StringLiteral) { + return undefined; + } +- const suppressInteropError = name.escapedText === InternalSymbolName.Default && allowSyntheticDefaultImports; ++ const nameText = moduleExportNameTextEscaped(name); ++ const suppressInteropError = nameText === InternalSymbolName.Default && allowSyntheticDefaultImports; + const targetSymbol = resolveESModuleSymbol(moduleSymbol, moduleSpecifier, /*dontResolveAlias*/ false, suppressInteropError); + if (targetSymbol) { +- if (name.escapedText) { ++ // Note: The empty string is a valid module export name: ++ // ++ // import { "" as foo } from "./foo"; ++ // export { foo as "" }; ++ // ++ if (nameText || name.kind === SyntaxKind.StringLiteral) { + if (isShorthandAmbientModuleSymbol(moduleSymbol)) { + return moduleSymbol; + } +@@ -3901,16 +3911,16 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { + let symbolFromVariable: Symbol | undefined; + // First check if module was specified with "export=". If so, get the member from the resolved type + if (moduleSymbol && moduleSymbol.exports && moduleSymbol.exports.get(InternalSymbolName.ExportEquals)) { +- symbolFromVariable = getPropertyOfType(getTypeOfSymbol(targetSymbol), name.escapedText, /*skipObjectFunctionPropertyAugment*/ true); ++ symbolFromVariable = getPropertyOfType(getTypeOfSymbol(targetSymbol), nameText, /*skipObjectFunctionPropertyAugment*/ true); + } + else { +- symbolFromVariable = getPropertyOfVariable(targetSymbol, name.escapedText); ++ symbolFromVariable = getPropertyOfVariable(targetSymbol, nameText); + } + // if symbolFromVariable is export - get its final target + symbolFromVariable = resolveSymbol(symbolFromVariable, dontResolveAlias); + +- let symbolFromModule = getExportOfModule(targetSymbol, name, specifier, dontResolveAlias); +- if (symbolFromModule === undefined && name.escapedText === InternalSymbolName.Default) { ++ let symbolFromModule = getExportOfModule(targetSymbol, nameText, specifier, dontResolveAlias); ++ if (symbolFromModule === undefined && nameText === InternalSymbolName.Default) { + const file = moduleSymbol.declarations?.find(isSourceFile); + if (isOnlyImportableAsDefault(moduleSpecifier) || canHaveSyntheticDefault(file, moduleSymbol, dontResolveAlias, moduleSpecifier)) { + symbolFromModule = resolveExternalModuleSymbol(moduleSymbol, dontResolveAlias) || resolveSymbol(moduleSymbol, dontResolveAlias); +@@ -3928,10 +3938,10 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { + } + } + +- function errorNoModuleMemberSymbol(moduleSymbol: Symbol, targetSymbol: Symbol, node: Node, name: Identifier) { ++ function errorNoModuleMemberSymbol(moduleSymbol: Symbol, targetSymbol: Symbol, node: Node, name: ModuleExportName) { + const moduleName = getFullyQualifiedName(moduleSymbol, node); + const declarationName = declarationNameToString(name); +- const suggestion = getSuggestedSymbolForNonexistentModule(name, targetSymbol); ++ const suggestion = isIdentifier(name) ? getSuggestedSymbolForNonexistentModule(name, targetSymbol) : undefined; + if (suggestion !== undefined) { + const suggestionName = symbolToString(suggestion); + const diagnostic = error(name, Diagnostics._0_has_no_exported_member_named_1_Did_you_mean_2, moduleName, declarationName, suggestionName); +@@ -3954,8 +3964,8 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { + } + } + +- function reportNonExportedMember(node: Node, name: Identifier, declarationName: string, moduleSymbol: Symbol, moduleName: string): void { +- const localSymbol = tryCast(moduleSymbol.valueDeclaration, canHaveLocals)?.locals?.get(name.escapedText); ++ function reportNonExportedMember(node: Node, name: ModuleExportName, declarationName: string, moduleSymbol: Symbol, moduleName: string): void { ++ const localSymbol = tryCast(moduleSymbol.valueDeclaration, canHaveLocals)?.locals?.get(moduleExportNameTextEscaped(name)); + const exports = moduleSymbol.exports; + if (localSymbol) { + const exportedEqualsSymbol = exports?.get(InternalSymbolName.ExportEquals); +@@ -3977,7 +3987,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { + } + } + +- function reportInvalidImportEqualsExportMember(node: Node, name: Identifier, declarationName: string, moduleName: string) { ++ function reportInvalidImportEqualsExportMember(node: Node, name: ModuleExportName, declarationName: string, moduleName: string) { + if (moduleKind >= ModuleKind.ES2015) { + const message = getESModuleInterop(compilerOptions) ? Diagnostics._0_can_only_be_imported_by_using_a_default_import : + Diagnostics._0_can_only_be_imported_by_turning_on_the_esModuleInterop_flag_and_using_a_default_import; +@@ -3998,7 +4008,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { + } + + function getTargetOfImportSpecifier(node: ImportSpecifier | BindingElement, dontResolveAlias: boolean): Symbol | undefined { +- if (isImportSpecifier(node) && idText(node.propertyName || node.name) === InternalSymbolName.Default) { ++ if (isImportSpecifier(node) && moduleExportNameIsDefault(node.propertyName || node.name)) { + const specifier = getModuleSpecifierForImportOrExport(node); + const moduleSymbol = specifier && resolveExternalModuleName(node, specifier); + if (moduleSymbol) { +@@ -4031,7 +4041,8 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { + } + + function getTargetOfExportSpecifier(node: ExportSpecifier, meaning: SymbolFlags, dontResolveAlias?: boolean) { +- if (idText(node.propertyName || node.name) === InternalSymbolName.Default) { ++ const name = node.propertyName || node.name; ++ if (moduleExportNameIsDefault(name)) { + const specifier = getModuleSpecifierForImportOrExport(node); + const moduleSymbol = specifier && resolveExternalModuleName(node, specifier); + if (moduleSymbol) { +@@ -4040,7 +4051,8 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { + } + const resolved = node.parent.parent.moduleSpecifier ? + getExternalModuleMember(node.parent.parent, node, dontResolveAlias) : +- resolveEntityName(node.propertyName || node.name, meaning, /*ignoreErrors*/ false, dontResolveAlias); ++ name.kind === SyntaxKind.StringLiteral ? undefined : // Skip for invalid syntax like this: export { "x" } ++ resolveEntityName(name, meaning, /*ignoreErrors*/ false, dontResolveAlias); + markSymbolOfAliasDeclarationIfTypeOnly(node, /*immediateTarget*/ undefined, resolved, /*overwriteEmpty*/ false); + return resolved; + } +@@ -9182,10 +9194,11 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { + if (index >= 0) { + const exportDecl = statements[index] as ExportDeclaration & { readonly exportClause: NamedExports; }; + const replacements = mapDefined(exportDecl.exportClause.elements, e => { +- if (!e.propertyName) { ++ if (!e.propertyName && e.name.kind !== SyntaxKind.StringLiteral) { + // export {name} - look thru `statements` for `name`, and if all results can take an `export` modifier, do so and filter it ++ const name = e.name; + const indices = indicesOf(statements); +- const associatedIndices = filter(indices, i => nodeHasName(statements[i], e.name)); ++ const associatedIndices = filter(indices, i => nodeHasName(statements[i], name)); + if (length(associatedIndices) && every(associatedIndices, i => canHaveExportModifier(statements[i]))) { + for (const index of associatedIndices) { + statements[index] = addExportModifier(statements[index] as Extract); +@@ -9884,7 +9897,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { + function getSomeTargetNameFromDeclarations(declarations: Declaration[] | undefined) { + return firstDefined(declarations, d => { + if (isImportSpecifier(d) || isExportSpecifier(d)) { +- return idText(d.propertyName || d.name); ++ return moduleExportNameTextUnescaped(d.propertyName || d.name); + } + if (isBinaryExpression(d) || isExportAssignment(d)) { + const expression = isExportAssignment(d) ? d.expression : d.right; +@@ -10088,8 +10101,11 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { + // does not use localName because the symbol name in this case refers to the name in the exports table, + // which we must exactly preserve + const specifier = (node.parent.parent as ExportDeclaration).moduleSpecifier; +- if (specifier && (node as ExportSpecifier).propertyName?.escapedText === InternalSymbolName.Default) { +- verbatimTargetName = InternalSymbolName.Default; ++ if (specifier) { ++ const propertyName = (node as ExportSpecifier).propertyName; ++ if (propertyName && moduleExportNameIsDefault(propertyName)) { ++ verbatimTargetName = InternalSymbolName.Default; ++ } + } + // targetName is only used when the target is local, as otherwise the target is an alias that points at + // another file +@@ -10862,9 +10878,9 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { + } + } + +- function collectLinkedAliases(node: Identifier, setVisibility?: boolean): Node[] | undefined { ++ function collectLinkedAliases(node: ModuleExportName, setVisibility?: boolean): Node[] | undefined { + let exportSymbol: Symbol | undefined; +- if (node.parent && node.parent.kind === SyntaxKind.ExportAssignment) { ++ if (node.kind !== SyntaxKind.StringLiteral && node.parent && node.parent.kind === SyntaxKind.ExportAssignment) { + exportSymbol = resolveName(node, node, SymbolFlags.Value | SymbolFlags.Type | SymbolFlags.Namespace | SymbolFlags.Alias, /*nameNotFoundMessage*/ undefined, /*isUse*/ false); + } + else if (node.parent.kind === SyntaxKind.ExportSpecifier) { +@@ -29472,8 +29488,9 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { + return; + case SyntaxKind.ExportSpecifier: + const exportDeclaration = (node as ExportSpecifier).parent.parent; +- if (!(node as ExportSpecifier).isTypeOnly && !exportDeclaration.isTypeOnly && !exportDeclaration.moduleSpecifier) { +- const symbol = resolveEntityName((node as ExportSpecifier).propertyName || (node as ExportSpecifier).name, SymbolFlags.Value, /*ignoreErrors*/ true, /*dontResolveAlias*/ true); ++ const name = (node as ExportSpecifier).propertyName || (node as ExportSpecifier).name; ++ if (!(node as ExportSpecifier).isTypeOnly && !exportDeclaration.isTypeOnly && !exportDeclaration.moduleSpecifier && name.kind !== SyntaxKind.StringLiteral) { ++ const symbol = resolveEntityName(name, SymbolFlags.Value, /*ignoreErrors*/ true, /*dontResolveAlias*/ true); + if (symbol && isParameterOrMutableLocalVariable(symbol)) { + symbol.lastAssignmentPos = Number.MAX_VALUE; + } +@@ -29856,6 +29873,9 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { + function markExportSpecifierAliasReferenced(location: ExportSpecifier) { + if (!location.parent.parent.moduleSpecifier && !location.isTypeOnly && !location.parent.parent.isTypeOnly) { + const exportedName = location.propertyName || location.name; ++ if (exportedName.kind === SyntaxKind.StringLiteral) { ++ return; // Skip for invalid syntax like this: export { "x" } ++ } + const symbol = resolveName(exportedName, exportedName.escapedText, SymbolFlags.Value | SymbolFlags.Type | SymbolFlags.Namespace | SymbolFlags.Alias, /*nameNotFoundMessage*/ undefined, /*isUse*/ true); + if (symbol && (symbol === undefinedSymbol || symbol === globalThisSymbol || symbol.declarations && isGlobalSourceFile(getDeclarationContainer(symbol.declarations[0])))) { + // Do nothing, non-local symbol +@@ -29864,7 +29884,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { + const target = symbol && (symbol.flags & SymbolFlags.Alias ? resolveAlias(symbol) : symbol); + if (!target || getSymbolFlags(target) & SymbolFlags.Value) { + markExportAsReferenced(location); // marks export as used +- markIdentifierAliasReferenced(location.propertyName || location.name); // marks target of export as used ++ markIdentifierAliasReferenced(exportedName); // marks target of export as used + } + } + return; +@@ -46833,6 +46853,18 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { + return true; + } + ++ function checkModuleExportName(name: ModuleExportName | undefined, allowStringLiteral = true) { ++ if (name === undefined || name.kind !== SyntaxKind.StringLiteral) { ++ return; ++ } ++ if (!allowStringLiteral) { ++ grammarErrorOnNode(name, Diagnostics.Identifier_expected); ++ } ++ else if (moduleKind === ModuleKind.ES2015 || moduleKind === ModuleKind.ES2020) { ++ grammarErrorOnNode(name, Diagnostics.String_literal_import_and_export_names_are_not_supported_when_the_module_flag_is_set_to_es2015_or_es2020); ++ } ++ } ++ + function checkAliasSymbol(node: AliasDeclarationNode) { + let symbol = getSymbolOfDeclaration(node); + const target = resolveAlias(symbol); +@@ -46855,7 +46887,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { + Debug.assert(node.kind !== SyntaxKind.NamespaceExport); + if (node.kind === SyntaxKind.ExportSpecifier) { + const diag = error(errorNode, Diagnostics.Types_cannot_appear_in_export_declarations_in_JavaScript_files); +- const alreadyExportedSymbol = getSourceFileOfNode(node).symbol?.exports?.get((node.propertyName || node.name).escapedText); ++ const alreadyExportedSymbol = getSourceFileOfNode(node).symbol?.exports?.get(moduleExportNameTextEscaped(node.propertyName || node.name)); + if (alreadyExportedSymbol === target) { + const exportingDeclaration = alreadyExportedSymbol.declarations?.find(isJSDocNode); + if (exportingDeclaration) { +@@ -46928,7 +46960,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { + : isType + ? Diagnostics._0_is_a_type_and_must_be_imported_using_a_type_only_import_when_verbatimModuleSyntax_is_enabled + : Diagnostics._0_resolves_to_a_type_only_declaration_and_must_be_imported_using_a_type_only_import_when_verbatimModuleSyntax_is_enabled; +- const name = idText(node.kind === SyntaxKind.ImportSpecifier ? node.propertyName || node.name : node.name); ++ const name = moduleExportNameTextUnescaped(node.kind === SyntaxKind.ImportSpecifier ? node.propertyName || node.name : node.name); + addTypeOnlyDeclarationRelatedInfo( + error(node, message, name), + isType ? undefined : typeOnlyAlias, +@@ -46945,7 +46977,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { + // The exception is that `import type { A } from './a'; export { A }` is allowed + // because single-file analysis can determine that the export should be dropped. + if (compilerOptions.verbatimModuleSyntax || getSourceFileOfNode(typeOnlyAlias) !== getSourceFileOfNode(node)) { +- const name = idText(node.propertyName || node.name); ++ const name = moduleExportNameTextUnescaped(node.propertyName || node.name); + const diagnostic = isType + ? error(node, Diagnostics.Re_exporting_a_type_when_0_is_enabled_requires_using_export_type, isolatedModulesLikeFlagName) + : error(node, Diagnostics._0_resolves_to_a_type_only_declaration_and_must_be_re_exported_using_a_type_only_re_export_when_1_is_enabled, name, isolatedModulesLikeFlagName); +@@ -47020,13 +47052,15 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { + function checkImportBinding(node: ImportEqualsDeclaration | ImportClause | NamespaceImport | ImportSpecifier) { + checkCollisionsForDeclarationName(node, node.name); + checkAliasSymbol(node); +- if ( +- node.kind === SyntaxKind.ImportSpecifier && +- idText(node.propertyName || node.name) === "default" && +- getESModuleInterop(compilerOptions) && +- host.getEmitModuleFormatOfFile(getSourceFileOfNode(node)) < ModuleKind.System +- ) { +- checkExternalEmitHelpers(node, ExternalEmitHelpers.ImportDefault); ++ if (node.kind === SyntaxKind.ImportSpecifier) { ++ checkModuleExportName(node.propertyName); ++ if ( ++ moduleExportNameIsDefault(node.propertyName || node.name) && ++ getESModuleInterop(compilerOptions) && ++ host.getEmitModuleFormatOfFile(getSourceFileOfNode(node)) < ModuleKind.System ++ ) { ++ checkExternalEmitHelpers(node, ExternalEmitHelpers.ImportDefault); ++ } + } + } + +@@ -47176,6 +47210,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { + } + else if (node.exportClause) { + checkAliasSymbol(node.exportClause); ++ checkModuleExportName(node.exportClause.name); + } + if (host.getEmitModuleFormatOfFile(getSourceFileOfNode(node)) < ModuleKind.System) { + if (node.exportClause) { +@@ -47213,11 +47248,17 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { + + function checkExportSpecifier(node: ExportSpecifier) { + checkAliasSymbol(node); ++ const hasModuleSpecifier = node.parent.parent.moduleSpecifier !== undefined; ++ checkModuleExportName(node.propertyName, hasModuleSpecifier); ++ checkModuleExportName(node.name); + if (getEmitDeclarations(compilerOptions)) { + collectLinkedAliases(node.propertyName || node.name, /*setVisibility*/ true); + } +- if (!node.parent.parent.moduleSpecifier) { ++ if (!hasModuleSpecifier) { + const exportedName = node.propertyName || node.name; ++ if (exportedName.kind === SyntaxKind.StringLiteral) { ++ return; // Skip for invalid syntax like this: export { "x" } ++ } + // find immediate value referenced by exported name (SymbolFlags.Alias is set so we don't chase down aliases) + const symbol = resolveName(exportedName, exportedName.escapedText, SymbolFlags.Value | SymbolFlags.Type | SymbolFlags.Namespace | SymbolFlags.Alias, /*nameNotFoundMessage*/ undefined, /*isUse*/ true); + if (symbol && (symbol === undefinedSymbol || symbol === globalThisSymbol || symbol.declarations && isGlobalSourceFile(getDeclarationContainer(symbol.declarations[0])))) { +@@ -47231,7 +47272,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { + if ( + getESModuleInterop(compilerOptions) && + host.getEmitModuleFormatOfFile(getSourceFileOfNode(node)) < ModuleKind.System && +- idText(node.propertyName || node.name) === "default" ++ moduleExportNameIsDefault(node.propertyName || node.name) + ) { + checkExternalEmitHelpers(node, ExternalEmitHelpers.ImportDefault); + } +@@ -48610,9 +48651,11 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { + /** Returns the target of an export specifier without following aliases */ + function getExportSpecifierLocalTargetSymbol(node: ExportSpecifier | Identifier): Symbol | undefined { + if (isExportSpecifier(node)) { ++ const name = node.propertyName || node.name; + return node.parent.parent.moduleSpecifier ? + getExternalModuleMember(node.parent.parent, node) : +- resolveEntityName(node.propertyName || node.name, SymbolFlags.Value | SymbolFlags.Type | SymbolFlags.Namespace | SymbolFlags.Alias); ++ name.kind === SyntaxKind.StringLiteral ? undefined : // Skip for invalid syntax like this: export { "x" } ++ resolveEntityName(name, SymbolFlags.Value | SymbolFlags.Type | SymbolFlags.Namespace | SymbolFlags.Alias); + } + else { + return resolveEntityName(node, SymbolFlags.Value | SymbolFlags.Type | SymbolFlags.Namespace | SymbolFlags.Alias); +@@ -52003,7 +52046,7 @@ function isDeclarationNameOrImportPropertyName(name: Node): boolean { + switch (name.parent.kind) { + case SyntaxKind.ImportSpecifier: + case SyntaxKind.ExportSpecifier: +- return isIdentifier(name); ++ return isIdentifier(name) || name.kind === SyntaxKind.StringLiteral; + default: + return isDeclarationName(name); + } +diff --git a/src/compiler/diagnosticMessages.json b/src/compiler/diagnosticMessages.json +index e74033719..92600da4d 100644 +--- a/src/compiler/diagnosticMessages.json ++++ b/src/compiler/diagnosticMessages.json +@@ -8325,5 +8325,9 @@ + "Enum member following a non-literal numeric member must have an initializer when 'isolatedModules' is enabled.": { + "category": "Error", + "code": 18056 ++ }, ++ "String literal import and export names are not supported when the '--module' flag is set to 'es2015' or 'es2020'.": { ++ "category": "Error", ++ "code": 18057 + } + } +diff --git a/src/compiler/factory/nodeFactory.ts b/src/compiler/factory/nodeFactory.ts +index 9fcd2a4ac..024eaa5c7 100644 +--- a/src/compiler/factory/nodeFactory.ts ++++ b/src/compiler/factory/nodeFactory.ts +@@ -309,6 +309,7 @@ import { + ModuleBlock, + ModuleBody, + ModuleDeclaration, ++ ModuleExportName, + ModuleName, + ModuleReference, + Mutable, +@@ -4842,7 +4843,7 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode + } + + // @api +- function createNamespaceExport(name: Identifier): NamespaceExport { ++ function createNamespaceExport(name: ModuleExportName): NamespaceExport { + const node = createBaseDeclaration(SyntaxKind.NamespaceExport); + node.name = name; + node.transformFlags |= propagateChildFlags(node.name) | +@@ -4852,7 +4853,7 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode + } + + // @api +- function updateNamespaceExport(node: NamespaceExport, name: Identifier) { ++ function updateNamespaceExport(node: NamespaceExport, name: ModuleExportName) { + return node.name !== name + ? update(createNamespaceExport(name), node) + : node; +@@ -4875,7 +4876,7 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode + } + + // @api +- function createImportSpecifier(isTypeOnly: boolean, propertyName: Identifier | undefined, name: Identifier) { ++ function createImportSpecifier(isTypeOnly: boolean, propertyName: ModuleExportName | undefined, name: Identifier) { + const node = createBaseDeclaration(SyntaxKind.ImportSpecifier); + node.isTypeOnly = isTypeOnly; + node.propertyName = propertyName; +@@ -4887,7 +4888,7 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode + } + + // @api +- function updateImportSpecifier(node: ImportSpecifier, isTypeOnly: boolean, propertyName: Identifier | undefined, name: Identifier) { ++ function updateImportSpecifier(node: ImportSpecifier, isTypeOnly: boolean, propertyName: ModuleExportName | undefined, name: Identifier) { + return node.isTypeOnly !== isTypeOnly + || node.propertyName !== propertyName + || node.name !== name +@@ -4994,7 +4995,7 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode + } + + // @api +- function createExportSpecifier(isTypeOnly: boolean, propertyName: string | Identifier | undefined, name: string | Identifier) { ++ function createExportSpecifier(isTypeOnly: boolean, propertyName: string | ModuleExportName | undefined, name: string | ModuleExportName) { + const node = createBaseNode(SyntaxKind.ExportSpecifier); + node.isTypeOnly = isTypeOnly; + node.propertyName = asName(propertyName); +@@ -5008,7 +5009,7 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode + } + + // @api +- function updateExportSpecifier(node: ExportSpecifier, isTypeOnly: boolean, propertyName: Identifier | undefined, name: Identifier) { ++ function updateExportSpecifier(node: ExportSpecifier, isTypeOnly: boolean, propertyName: ModuleExportName | undefined, name: ModuleExportName) { + return node.isTypeOnly !== isTypeOnly + || node.propertyName !== propertyName + || node.name !== name +diff --git a/src/compiler/factory/nodeTests.ts b/src/compiler/factory/nodeTests.ts +index cd31b63f8..8aa4bb02e 100644 +--- a/src/compiler/factory/nodeTests.ts ++++ b/src/compiler/factory/nodeTests.ts +@@ -146,6 +146,7 @@ import { + MissingDeclaration, + ModuleBlock, + ModuleDeclaration, ++ ModuleExportName, + NamedExports, + NamedImports, + NamedTupleMember, +@@ -898,6 +899,10 @@ export function isExportSpecifier(node: Node): node is ExportSpecifier { + return node.kind === SyntaxKind.ExportSpecifier; + } + ++export function isModuleExportName(node: Node): node is ModuleExportName { ++ return node.kind === SyntaxKind.Identifier || node.kind === SyntaxKind.StringLiteral; ++} ++ + export function isMissingDeclaration(node: Node): node is MissingDeclaration { + return node.kind === SyntaxKind.MissingDeclaration; + } +diff --git a/src/compiler/factory/utilities.ts b/src/compiler/factory/utilities.ts +index 502ffd17d..a48270b6d 100644 +--- a/src/compiler/factory/utilities.ts ++++ b/src/compiler/factory/utilities.ts +@@ -802,6 +802,9 @@ export function getLocalNameForExternalImport(factory: NodeFactory, node: Import + const namespaceDeclaration = getNamespaceDeclarationNode(node); + if (namespaceDeclaration && !isDefaultImport(node) && !isExportNamespaceAsDefaultDeclaration(node)) { + const name = namespaceDeclaration.name; ++ if (name.kind === SyntaxKind.StringLiteral) { ++ return factory.getGeneratedNameForNode(node); ++ } + return isGeneratedIdentifier(name) ? name : factory.createIdentifier(getSourceTextOfNodeFromSourceFile(sourceFile, name) || idText(name)); + } + if (node.kind === SyntaxKind.ImportDeclaration && node.importClause) { +diff --git a/src/compiler/parser.ts b/src/compiler/parser.ts +index 56b958bcf..3cb942dfa 100644 +--- a/src/compiler/parser.ts ++++ b/src/compiler/parser.ts +@@ -256,6 +256,7 @@ import { + modifiersToFlags, + ModuleBlock, + ModuleDeclaration, ++ ModuleExportName, + ModuleKind, + Mutable, + NamedExportBindings, +@@ -2906,6 +2907,9 @@ namespace Parser { + if (token() === SyntaxKind.FromKeyword && lookAhead(nextTokenIsStringLiteral)) { + return false; + } ++ if (token() === SyntaxKind.StringLiteral) { ++ return true; // For "arbitrary module namespace identifiers" ++ } + return tokenIsIdentifierOrKeyword(token()); + case ParsingContext.JsxAttributes: + return tokenIsIdentifierOrKeyword(token()) || token() === SyntaxKind.OpenBraceToken; +@@ -8504,6 +8508,14 @@ namespace Parser { + return finishNode(factory.createNamespaceImport(name), pos); + } + ++ function canParseModuleExportName(): boolean { ++ return tokenIsIdentifierOrKeyword(token()) || token() === SyntaxKind.StringLiteral; ++ } ++ ++ function parseModuleExportName(parseName: () => Identifier): ModuleExportName { ++ return token() === SyntaxKind.StringLiteral ? parseLiteralNode() as StringLiteral : parseName(); ++ } ++ + function parseNamedImportsOrExports(kind: SyntaxKind.NamedImports): NamedImports; + function parseNamedImportsOrExports(kind: SyntaxKind.NamedExports): NamedExports; + function parseNamedImportsOrExports(kind: SyntaxKind): NamedImportsOrExports { +@@ -8536,18 +8548,18 @@ namespace Parser { + const pos = getNodePos(); + // ImportSpecifier: + // BindingIdentifier +- // IdentifierName as BindingIdentifier ++ // ModuleExportName as BindingIdentifier + // ExportSpecifier: +- // IdentifierName +- // IdentifierName as IdentifierName ++ // ModuleExportName ++ // ModuleExportName as ModuleExportName + let checkIdentifierIsKeyword = isKeyword(token()) && !isIdentifier(); + let checkIdentifierStart = scanner.getTokenStart(); + let checkIdentifierEnd = scanner.getTokenEnd(); + let isTypeOnly = false; +- let propertyName: Identifier | undefined; ++ let propertyName: ModuleExportName | undefined; + let canParseAsKeyword = true; +- let name = parseIdentifierName(); +- if (name.escapedText === "type") { ++ let name = parseModuleExportName(parseIdentifierName); ++ if (name.kind === SyntaxKind.Identifier && name.escapedText === "type") { + // If the first token of an import specifier is 'type', there are a lot of possibilities, + // especially if we see 'as' afterwards: + // +@@ -8561,11 +8573,12 @@ namespace Parser { + if (token() === SyntaxKind.AsKeyword) { + // { type as as ...? } + const secondAs = parseIdentifierName(); +- if (tokenIsIdentifierOrKeyword(token())) { ++ if (canParseModuleExportName()) { + // { type as as something } ++ // { type as as "something" } + isTypeOnly = true; + propertyName = firstAs; +- name = parseNameWithKeywordCheck(); ++ name = parseModuleExportName(parseNameWithKeywordCheck); + canParseAsKeyword = false; + } + else { +@@ -8575,11 +8588,12 @@ namespace Parser { + canParseAsKeyword = false; + } + } +- else if (tokenIsIdentifierOrKeyword(token())) { ++ else if (canParseModuleExportName()) { + // { type as something } ++ // { type as "something" } + propertyName = name; + canParseAsKeyword = false; +- name = parseNameWithKeywordCheck(); ++ name = parseModuleExportName(parseNameWithKeywordCheck); + } + else { + // { type as } +@@ -8587,23 +8601,31 @@ namespace Parser { + name = firstAs; + } + } +- else if (tokenIsIdentifierOrKeyword(token())) { ++ else if (canParseModuleExportName()) { + // { type something ...? } ++ // { type "something" ...? } + isTypeOnly = true; +- name = parseNameWithKeywordCheck(); ++ name = parseModuleExportName(parseNameWithKeywordCheck); + } + } + + if (canParseAsKeyword && token() === SyntaxKind.AsKeyword) { + propertyName = name; + parseExpected(SyntaxKind.AsKeyword); +- name = parseNameWithKeywordCheck(); ++ name = parseModuleExportName(parseNameWithKeywordCheck); + } +- if (kind === SyntaxKind.ImportSpecifier && checkIdentifierIsKeyword) { +- parseErrorAt(checkIdentifierStart, checkIdentifierEnd, Diagnostics.Identifier_expected); ++ if (kind === SyntaxKind.ImportSpecifier) { ++ if (name.kind !== SyntaxKind.Identifier) { ++ // ImportSpecifier casts "name" to Identifier below, so make sure it's an identifier ++ parseErrorAt(skipTrivia(sourceText, name.pos), name.end, Diagnostics.Identifier_expected); ++ name = setTextRangePosEnd(createMissingNode(SyntaxKind.Identifier, /*reportAtCurrentPosition*/ false), name.pos, name.pos); ++ } ++ else if (checkIdentifierIsKeyword) { ++ parseErrorAt(checkIdentifierStart, checkIdentifierEnd, Diagnostics.Identifier_expected); ++ } + } + const node = kind === SyntaxKind.ImportSpecifier +- ? factory.createImportSpecifier(isTypeOnly, propertyName, name) ++ ? factory.createImportSpecifier(isTypeOnly, propertyName, name as Identifier) + : factory.createExportSpecifier(isTypeOnly, propertyName, name); + return finishNode(node, pos); + +@@ -8616,7 +8638,7 @@ namespace Parser { + } + + function parseNamespaceExport(pos: number): NamespaceExport { +- return finishNode(factory.createNamespaceExport(parseIdentifierName()), pos); ++ return finishNode(factory.createNamespaceExport(parseModuleExportName(parseIdentifierName)), pos); + } + + function parseExportDeclaration(pos: number, hasJSDoc: boolean, modifiers: NodeArray | undefined): ExportDeclaration { +diff --git a/src/compiler/transformers/module/module.ts b/src/compiler/transformers/module/module.ts +index 92b214276..dc30bca2b 100644 +--- a/src/compiler/transformers/module/module.ts ++++ b/src/compiler/transformers/module/module.ts +@@ -121,7 +121,10 @@ import { + mapDefined, + Modifier, + ModifierFlags, ++ ModuleExportName, ++ moduleExportNameIsDefault, + ModuleKind, ++ NamespaceImport, + Node, + NodeArray, + NodeFlags, +@@ -276,7 +279,10 @@ export function transformModule(context: TransformationContext): (x: SourceFile + factory.createExpressionStatement( + reduceLeft( + currentModuleInfo.exportedNames.slice(i, i + chunkSize), +- (prev, nextId) => factory.createAssignment(factory.createPropertyAccessExpression(factory.createIdentifier("exports"), factory.createIdentifier(idText(nextId))), prev), ++ (prev, nextId) => ++ nextId.kind === SyntaxKind.StringLiteral ++ ? factory.createAssignment(factory.createElementAccessExpression(factory.createIdentifier("exports"), factory.createStringLiteral(nextId.text)), prev) ++ : factory.createAssignment(factory.createPropertyAccessExpression(factory.createIdentifier("exports"), factory.createIdentifier(idText(nextId))), prev), + factory.createVoidZero() as Expression, + ), + ), +@@ -609,7 +615,13 @@ export function transformModule(context: TransformationContext): (x: SourceFile + append(statements, createUnderscoreUnderscoreESModule()); + } + if (some(currentModuleInfo.exportedNames)) { +- append(statements, factory.createExpressionStatement(reduceLeft(currentModuleInfo.exportedNames, (prev, nextId) => factory.createAssignment(factory.createPropertyAccessExpression(factory.createIdentifier("exports"), factory.createIdentifier(idText(nextId))), prev), factory.createVoidZero() as Expression))); ++ append( ++ statements, ++ factory.createExpressionStatement(reduceLeft(currentModuleInfo.exportedNames, (prev, nextId) => ++ nextId.kind === SyntaxKind.StringLiteral ++ ? factory.createAssignment(factory.createElementAccessExpression(factory.createIdentifier("exports"), factory.createStringLiteral(nextId.text)), prev) ++ : factory.createAssignment(factory.createPropertyAccessExpression(factory.createIdentifier("exports"), factory.createIdentifier(idText(nextId))), prev), factory.createVoidZero() as Expression)), ++ ); + } + for (const f of currentModuleInfo.exportedFunctions) { + appendExportsOfHoistedDeclaration(statements, f); +@@ -1385,7 +1397,7 @@ export function transformModule(context: TransformationContext): (x: SourceFile + */ + function visitTopLevelImportDeclaration(node: ImportDeclaration): VisitResult { + let statements: Statement[] | undefined; +- const namespaceDeclaration = getNamespaceDeclarationNode(node); ++ const namespaceDeclaration = getNamespaceDeclarationNode(node) as NamespaceImport | undefined; + if (moduleKind !== ModuleKind.AMD) { + if (!node.importClause) { + // import "mod"; +@@ -1607,18 +1619,24 @@ export function transformModule(context: TransformationContext): (x: SourceFile + ); + } + for (const specifier of node.exportClause.elements) { ++ const specifierName = specifier.propertyName || specifier.name; + const exportNeedsImportDefault = !!getESModuleInterop(compilerOptions) && + !(getInternalEmitFlags(node) & InternalEmitFlags.NeverApplyImportHelper) && +- idText(specifier.propertyName || specifier.name) === "default"; +- const exportedValue = factory.createPropertyAccessExpression( +- exportNeedsImportDefault ? emitHelpers().createImportDefaultHelper(generatedName) : generatedName, +- specifier.propertyName || specifier.name, +- ); ++ moduleExportNameIsDefault(specifierName); ++ const target = exportNeedsImportDefault ? emitHelpers().createImportDefaultHelper(generatedName) : generatedName; ++ const exportedValue = specifierName.kind === SyntaxKind.StringLiteral ++ ? factory.createElementAccessExpression(target, specifierName) ++ : factory.createPropertyAccessExpression(target, specifierName); + statements.push( + setOriginalNode( + setTextRange( + factory.createExpressionStatement( +- createExportExpression(factory.getExportName(specifier), exportedValue, /*location*/ undefined, /*liveBinding*/ true), ++ createExportExpression( ++ specifier.name.kind === SyntaxKind.StringLiteral ? factory.cloneNode(specifier.name) : factory.getExportName(specifier), ++ exportedValue, ++ /*location*/ undefined, ++ /*liveBinding*/ true, ++ ), + ), + specifier, + ), +@@ -1644,6 +1662,7 @@ export function transformModule(context: TransformationContext): (x: SourceFile + moduleKind !== ModuleKind.AMD ? + createRequireCall(node) : + isExportNamespaceAsDefaultDeclaration(node) ? generatedName : ++ node.exportClause.name.kind === SyntaxKind.StringLiteral ? generatedName : + factory.createIdentifier(idText(node.exportClause.name)), + ), + ), +@@ -2070,11 +2089,14 @@ export function transformModule(context: TransformationContext): (x: SourceFile + * @param location The location to use for source maps and comments for the export. + * @param allowComments Whether to allow comments on the export. + */ +- function appendExportStatement(statements: Statement[] | undefined, seen: IdentifierNameMap, exportName: Identifier, expression: Expression, location?: TextRange, allowComments?: boolean, liveBinding?: boolean): Statement[] | undefined { +- if (!seen.has(exportName)) { ++ function appendExportStatement(statements: Statement[] | undefined, seen: IdentifierNameMap, exportName: ModuleExportName, expression: Expression, location?: TextRange, allowComments?: boolean, liveBinding?: boolean): Statement[] | undefined { ++ if (exportName.kind !== SyntaxKind.StringLiteral) { ++ if (seen.has(exportName)) { ++ return statements; ++ } + seen.set(exportName, true); +- statements = append(statements, createExportStatement(exportName, expression, location, allowComments, liveBinding)); + } ++ statements = append(statements, createExportStatement(exportName, expression, location, allowComments, liveBinding)); + return statements; + } + +@@ -2104,7 +2126,7 @@ export function transformModule(context: TransformationContext): (x: SourceFile + * @param location The location to use for source maps and comments for the export. + * @param allowComments An optional value indicating whether to emit comments for the statement. + */ +- function createExportStatement(name: Identifier, value: Expression, location?: TextRange, allowComments?: boolean, liveBinding?: boolean) { ++ function createExportStatement(name: ModuleExportName, value: Expression, location?: TextRange, allowComments?: boolean, liveBinding?: boolean) { + const statement = setTextRange(factory.createExpressionStatement(createExportExpression(name, value, /*location*/ undefined, liveBinding)), location); + startOnNewLine(statement); + if (!allowComments) { +@@ -2121,7 +2143,7 @@ export function transformModule(context: TransformationContext): (x: SourceFile + * @param value The exported value. + * @param location The location to use for source maps and comments for the export. + */ +- function createExportExpression(name: Identifier, value: Expression, location?: TextRange, liveBinding?: boolean) { ++ function createExportExpression(name: ModuleExportName, value: Expression, location?: TextRange, liveBinding?: boolean) { + return setTextRange( + liveBinding ? factory.createCallExpression( + factory.createPropertyAccessExpression( +@@ -2149,10 +2171,15 @@ export function transformModule(context: TransformationContext): (x: SourceFile + ]), + ], + ) : factory.createAssignment( +- factory.createPropertyAccessExpression( +- factory.createIdentifier("exports"), +- factory.cloneNode(name), +- ), ++ name.kind === SyntaxKind.StringLiteral ++ ? factory.createElementAccessExpression( ++ factory.createIdentifier("exports"), ++ factory.cloneNode(name), ++ ) ++ : factory.createPropertyAccessExpression( ++ factory.createIdentifier("exports"), ++ factory.cloneNode(name), ++ ), + value, + ), + location, +@@ -2338,11 +2365,11 @@ export function transformModule(context: TransformationContext): (x: SourceFile + } + else if (isImportSpecifier(importDeclaration)) { + const name = importDeclaration.propertyName || importDeclaration.name; ++ const target = factory.getGeneratedNameForNode(importDeclaration.parent?.parent?.parent || importDeclaration); + return setTextRange( +- factory.createPropertyAccessExpression( +- factory.getGeneratedNameForNode(importDeclaration.parent?.parent?.parent || importDeclaration), +- factory.cloneNode(name), +- ), ++ name.kind === SyntaxKind.StringLiteral ++ ? factory.createElementAccessExpression(target, factory.cloneNode(name)) ++ : factory.createPropertyAccessExpression(target, factory.cloneNode(name)), + /*location*/ node, + ); + } +@@ -2391,7 +2418,7 @@ export function transformModule(context: TransformationContext): (x: SourceFile + * + * @param name The name. + */ +- function getExports(name: Identifier): Identifier[] | undefined { ++ function getExports(name: Identifier): ModuleExportName[] | undefined { + if (!isGeneratedIdentifier(name)) { + const importDeclaration = resolver.getReferencedImportDeclaration(name); + if (importDeclaration) { +@@ -2419,7 +2446,7 @@ export function transformModule(context: TransformationContext): (x: SourceFile + else if (isFileLevelReservedGeneratedIdentifier(name)) { + const exportSpecifiers = currentModuleInfo?.exportSpecifiers.get(name); + if (exportSpecifiers) { +- const exportedNames: Identifier[] = []; ++ const exportedNames: ModuleExportName[] = []; + for (const exportSpecifier of exportSpecifiers) { + exportedNames.push(exportSpecifier.name); + } +diff --git a/src/compiler/transformers/module/system.ts b/src/compiler/transformers/module/system.ts +index f03ad63a1..442af8707 100644 +--- a/src/compiler/transformers/module/system.ts ++++ b/src/compiler/transformers/module/system.ts +@@ -92,6 +92,9 @@ import { + map, + MetaProperty, + ModifierFlags, ++ ModuleExportName, ++ moduleExportNameIsDefault, ++ moduleExportNameTextUnescaped, + moveEmitHelpers, + Node, + NodeFlags, +@@ -455,7 +458,7 @@ export function transformSystemModule(context: TransformationContext): (x: Sourc + const exportedNames: ObjectLiteralElementLike[] = []; + if (moduleInfo.exportedNames) { + for (const exportedLocalName of moduleInfo.exportedNames) { +- if (exportedLocalName.escapedText === "default") { ++ if (moduleExportNameIsDefault(exportedLocalName)) { + continue; + } + +@@ -644,10 +647,10 @@ export function transformSystemModule(context: TransformationContext): (x: Sourc + for (const e of entry.exportClause.elements) { + properties.push( + factory.createPropertyAssignment( +- factory.createStringLiteral(idText(e.name)), ++ factory.createStringLiteral(moduleExportNameTextUnescaped(e.name)), + factory.createElementAccessExpression( + parameterName, +- factory.createStringLiteral(idText(e.propertyName || e.name)), ++ factory.createStringLiteral(moduleExportNameTextUnescaped(e.propertyName || e.name)), + ), + ), + ); +@@ -670,7 +673,7 @@ export function transformSystemModule(context: TransformationContext): (x: Sourc + exportFunction, + /*typeArguments*/ undefined, + [ +- factory.createStringLiteral(idText(entry.exportClause.name)), ++ factory.createStringLiteral(moduleExportNameTextUnescaped(entry.exportClause.name)), + parameterName, + ], + ), +@@ -1163,7 +1166,7 @@ export function transformSystemModule(context: TransformationContext): (x: Sourc + const exportSpecifiers = moduleInfo.exportSpecifiers.get(name); + if (exportSpecifiers) { + for (const exportSpecifier of exportSpecifiers) { +- if (exportSpecifier.name.escapedText !== excludeName) { ++ if (moduleExportNameTextUnescaped(exportSpecifier.name) !== excludeName) { + statements = appendExportStatement(statements, exportSpecifier.name, name); + } + } +@@ -1851,13 +1854,14 @@ export function transformSystemModule(context: TransformationContext): (x: Sourc + ); + } + else if (isImportSpecifier(importDeclaration)) { ++ const importedName = importDeclaration.propertyName || importDeclaration.name; ++ const target = factory.getGeneratedNameForNode(importDeclaration.parent?.parent?.parent || importDeclaration); + return setTextRange( + factory.createPropertyAssignment( + factory.cloneNode(name), +- factory.createPropertyAccessExpression( +- factory.getGeneratedNameForNode(importDeclaration.parent?.parent?.parent || importDeclaration), +- factory.cloneNode(importDeclaration.propertyName || importDeclaration.name), +- ), ++ importedName.kind === SyntaxKind.StringLiteral ++ ? factory.createElementAccessExpression(target, factory.cloneNode(importedName)) ++ : factory.createPropertyAccessExpression(target, factory.cloneNode(importedName)), + ), + /*location*/ node, + ); +@@ -1919,11 +1923,12 @@ export function transformSystemModule(context: TransformationContext): (x: Sourc + ); + } + else if (isImportSpecifier(importDeclaration)) { ++ const importedName = importDeclaration.propertyName || importDeclaration.name; ++ const target = factory.getGeneratedNameForNode(importDeclaration.parent?.parent?.parent || importDeclaration); + return setTextRange( +- factory.createPropertyAccessExpression( +- factory.getGeneratedNameForNode(importDeclaration.parent?.parent?.parent || importDeclaration), +- factory.cloneNode(importDeclaration.propertyName || importDeclaration.name), +- ), ++ importedName.kind === SyntaxKind.StringLiteral ++ ? factory.createElementAccessExpression(target, factory.cloneNode(importedName)) ++ : factory.createPropertyAccessExpression(target, factory.cloneNode(importedName)), + /*location*/ node, + ); + } +@@ -1992,7 +1997,7 @@ export function transformSystemModule(context: TransformationContext): (x: Sourc + else if (isGeneratedIdentifier(name) && isFileLevelReservedGeneratedIdentifier(name)) { + const exportSpecifiers = moduleInfo?.exportSpecifiers.get(name); + if (exportSpecifiers) { +- const exportedNames: Identifier[] = []; ++ const exportedNames: ModuleExportName[] = []; + for (const exportSpecifier of exportSpecifiers) { + exportedNames.push(exportSpecifier.name); + } +diff --git a/src/compiler/transformers/utilities.ts b/src/compiler/transformers/utilities.ts +index 8f5f2b257..33def9855 100644 +--- a/src/compiler/transformers/utilities.ts ++++ b/src/compiler/transformers/utilities.ts +@@ -42,7 +42,6 @@ import { + ImportEqualsDeclaration, + ImportSpecifier, + InitializedPropertyDeclaration, +- InternalSymbolName, + isAutoAccessorPropertyDeclaration, + isBindingPattern, + isClassStaticBlockDeclaration, +@@ -68,6 +67,9 @@ import { + map, + MethodDeclaration, + ModifierFlags, ++ ModuleExportName, ++ moduleExportNameIsDefault, ++ moduleExportNameTextUnescaped, + NamedExportBindings, + NamedImportBindings, + NamespaceExport, +@@ -104,7 +106,7 @@ export interface ExternalModuleInfo { + externalHelpersImportDeclaration: ImportDeclaration | undefined; // import of external helpers + exportSpecifiers: IdentifierNameMap; // file-local export specifiers by name (no reexports) + exportedBindings: Identifier[][]; // exported names of local declarations +- exportedNames: Identifier[] | undefined; // all exported names in the module, both local and reexported, excluding the names of locally exported function declarations ++ exportedNames: ModuleExportName[] | undefined; // all exported names in the module, both local and reexported, excluding the names of locally exported function declarations + exportedFunctions: Set; // all of the top-level exported function declarations + exportEquals: ExportAssignment | undefined; // an export= declaration if one was present + hasExportStarsToExportValues: boolean; // whether this module contains export* +@@ -117,9 +119,7 @@ function containsDefaultReference(node: NamedImportBindings | NamedExportBinding + } + + function isNamedDefaultReference(e: ImportSpecifier | ExportSpecifier): boolean { +- return e.propertyName !== undefined ? +- e.propertyName.escapedText === InternalSymbolName.Default : +- e.name.escapedText === InternalSymbolName.Default; ++ return moduleExportNameIsDefault(e.propertyName || e.name); + } + + /** @internal */ +@@ -175,7 +175,7 @@ export function collectExternalModuleInfo(context: TransformationContext, source + const exportedBindings: Identifier[][] = []; + const uniqueExports = new Map(); + const exportedFunctions = new Set(); +- let exportedNames: Identifier[] | undefined; ++ let exportedNames: ModuleExportName[] | undefined; + let hasExportDefault = false; + let exportEquals: ExportAssignment | undefined; + let hasExportStarsToExportValues = false; +@@ -223,9 +223,10 @@ export function collectExternalModuleInfo(context: TransformationContext, source + } + else { + const name = ((node as ExportDeclaration).exportClause as NamespaceExport).name; +- if (!uniqueExports.get(idText(name))) { ++ const nameText = moduleExportNameTextUnescaped(name); ++ if (!uniqueExports.get(nameText)) { + multiMapSparseArrayAdd(exportedBindings, getOriginalNodeId(node), name); +- uniqueExports.set(idText(name), true); ++ uniqueExports.set(nameText, true); + exportedNames = append(exportedNames, name); + } + // we use the same helpers for `export * as ns` as we do for `import * as ns` +@@ -292,31 +293,34 @@ export function collectExternalModuleInfo(context: TransformationContext, source + + function addExportedNamesForExportDeclaration(node: ExportDeclaration) { + for (const specifier of cast(node.exportClause, isNamedExports).elements) { +- if (!uniqueExports.get(idText(specifier.name))) { ++ const specifierNameText = moduleExportNameTextUnescaped(specifier.name); ++ if (!uniqueExports.get(specifierNameText)) { + const name = specifier.propertyName || specifier.name; +- if (!node.moduleSpecifier) { +- exportSpecifiers.add(name, specifier); +- } ++ if (name.kind !== SyntaxKind.StringLiteral) { ++ if (!node.moduleSpecifier) { ++ exportSpecifiers.add(name, specifier); ++ } + +- const decl = resolver.getReferencedImportDeclaration(name) +- || resolver.getReferencedValueDeclaration(name); ++ const decl = resolver.getReferencedImportDeclaration(name) ++ || resolver.getReferencedValueDeclaration(name); + +- if (decl) { +- if (decl.kind === SyntaxKind.FunctionDeclaration) { +- addExportedFunctionDeclaration(decl as FunctionDeclaration, specifier.name, specifier.name.escapedText === InternalSymbolName.Default); +- continue; +- } ++ if (decl) { ++ if (decl.kind === SyntaxKind.FunctionDeclaration) { ++ addExportedFunctionDeclaration(decl as FunctionDeclaration, specifier.name, moduleExportNameIsDefault(specifier.name)); ++ continue; ++ } + +- multiMapSparseArrayAdd(exportedBindings, getOriginalNodeId(decl), specifier.name); ++ multiMapSparseArrayAdd(exportedBindings, getOriginalNodeId(decl), specifier.name); ++ } + } + +- uniqueExports.set(idText(specifier.name), true); ++ uniqueExports.set(specifierNameText, true); + exportedNames = append(exportedNames, specifier.name); + } + } + } + +- function addExportedFunctionDeclaration(node: FunctionDeclaration, name: Identifier | undefined, isDefault: boolean) { ++ function addExportedFunctionDeclaration(node: FunctionDeclaration, name: ModuleExportName | undefined, isDefault: boolean) { + exportedFunctions.add(node); + if (isDefault) { + // export default function() { } +@@ -330,15 +334,16 @@ export function collectExternalModuleInfo(context: TransformationContext, source + // export function x() { } + // function x() { } + export { x } + name ??= node.name!; +- if (!uniqueExports.get(idText(name))) { ++ const nameText = moduleExportNameTextUnescaped(name); ++ if (!uniqueExports.get(nameText)) { + multiMapSparseArrayAdd(exportedBindings, getOriginalNodeId(node), name); +- uniqueExports.set(idText(name), true); ++ uniqueExports.set(nameText, true); + } + } + } + } + +-function collectExportedVariableInfo(decl: VariableDeclaration | BindingElement, uniqueExports: Map, exportedNames: Identifier[] | undefined, exportedBindings: Identifier[][]) { ++function collectExportedVariableInfo(decl: VariableDeclaration | BindingElement, uniqueExports: Map, exportedNames: ModuleExportName[] | undefined, exportedBindings: Identifier[][]) { + if (isBindingPattern(decl.name)) { + for (const element of decl.name.elements) { + if (!isOmittedExpression(element)) { +diff --git a/src/compiler/types.ts b/src/compiler/types.ts +index 7388c9c94..d15d4bca9 100644 +--- a/src/compiler/types.ts ++++ b/src/compiler/types.ts +@@ -3717,7 +3717,7 @@ export interface NamespaceImport extends NamedDeclaration { + export interface NamespaceExport extends NamedDeclaration { + readonly kind: SyntaxKind.NamespaceExport; + readonly parent: ExportDeclaration; +- readonly name: Identifier; ++ readonly name: ModuleExportName; + } + + export interface NamespaceExportDeclaration extends DeclarationStatement, JSDocContainer { +@@ -3758,7 +3758,7 @@ export type NamedImportsOrExports = NamedImports | NamedExports; + export interface ImportSpecifier extends NamedDeclaration { + readonly kind: SyntaxKind.ImportSpecifier; + readonly parent: NamedImports; +- readonly propertyName?: Identifier; // Name preceding "as" keyword (or undefined when "as" is absent) ++ readonly propertyName?: ModuleExportName; // Name preceding "as" keyword (or undefined when "as" is absent) + readonly name: Identifier; // Declared name + readonly isTypeOnly: boolean; + } +@@ -3767,10 +3767,12 @@ export interface ExportSpecifier extends NamedDeclaration, JSDocContainer { + readonly kind: SyntaxKind.ExportSpecifier; + readonly parent: NamedExports; + readonly isTypeOnly: boolean; +- readonly propertyName?: Identifier; // Name preceding "as" keyword (or undefined when "as" is absent) +- readonly name: Identifier; // Declared name ++ readonly propertyName?: ModuleExportName; // Name preceding "as" keyword (or undefined when "as" is absent) ++ readonly name: ModuleExportName; // Declared name + } + ++export type ModuleExportName = Identifier | StringLiteral; ++ + export type ImportOrExportSpecifier = + | ImportSpecifier + | ExportSpecifier; +@@ -5782,7 +5784,7 @@ export interface EmitResolver { + hasNodeCheckFlag(node: Node, flags: LazyNodeCheckFlags): boolean; + isDeclarationVisible(node: Declaration | AnyImportSyntax): boolean; + isLateBound(node: Declaration): node is LateBoundDeclaration; +- collectLinkedAliases(node: Identifier, setVisibility?: boolean): Node[] | undefined; ++ collectLinkedAliases(node: ModuleExportName, setVisibility?: boolean): Node[] | undefined; + markLinkedReferences(node: Node): void; + isImplementationOfOverload(node: SignatureDeclaration): boolean | undefined; + requiresAddingImplicitUndefined(node: ParameterDeclaration): boolean; +@@ -8914,20 +8916,20 @@ export interface NodeFactory { + updateImportAttribute(node: ImportAttribute, name: ImportAttributeName, value: Expression): ImportAttribute; + createNamespaceImport(name: Identifier): NamespaceImport; + updateNamespaceImport(node: NamespaceImport, name: Identifier): NamespaceImport; +- createNamespaceExport(name: Identifier): NamespaceExport; +- updateNamespaceExport(node: NamespaceExport, name: Identifier): NamespaceExport; ++ createNamespaceExport(name: ModuleExportName): NamespaceExport; ++ updateNamespaceExport(node: NamespaceExport, name: ModuleExportName): NamespaceExport; + createNamedImports(elements: readonly ImportSpecifier[]): NamedImports; + updateNamedImports(node: NamedImports, elements: readonly ImportSpecifier[]): NamedImports; +- createImportSpecifier(isTypeOnly: boolean, propertyName: Identifier | undefined, name: Identifier): ImportSpecifier; +- updateImportSpecifier(node: ImportSpecifier, isTypeOnly: boolean, propertyName: Identifier | undefined, name: Identifier): ImportSpecifier; ++ createImportSpecifier(isTypeOnly: boolean, propertyName: ModuleExportName | undefined, name: Identifier): ImportSpecifier; ++ updateImportSpecifier(node: ImportSpecifier, isTypeOnly: boolean, propertyName: ModuleExportName | undefined, name: Identifier): ImportSpecifier; + createExportAssignment(modifiers: readonly ModifierLike[] | undefined, isExportEquals: boolean | undefined, expression: Expression): ExportAssignment; + updateExportAssignment(node: ExportAssignment, modifiers: readonly ModifierLike[] | undefined, expression: Expression): ExportAssignment; + createExportDeclaration(modifiers: readonly ModifierLike[] | undefined, isTypeOnly: boolean, exportClause: NamedExportBindings | undefined, moduleSpecifier?: Expression, attributes?: ImportAttributes): ExportDeclaration; + updateExportDeclaration(node: ExportDeclaration, modifiers: readonly ModifierLike[] | undefined, isTypeOnly: boolean, exportClause: NamedExportBindings | undefined, moduleSpecifier: Expression | undefined, attributes: ImportAttributes | undefined): ExportDeclaration; + createNamedExports(elements: readonly ExportSpecifier[]): NamedExports; + updateNamedExports(node: NamedExports, elements: readonly ExportSpecifier[]): NamedExports; +- createExportSpecifier(isTypeOnly: boolean, propertyName: string | Identifier | undefined, name: string | Identifier): ExportSpecifier; +- updateExportSpecifier(node: ExportSpecifier, isTypeOnly: boolean, propertyName: Identifier | undefined, name: Identifier): ExportSpecifier; ++ createExportSpecifier(isTypeOnly: boolean, propertyName: string | ModuleExportName | undefined, name: string | ModuleExportName): ExportSpecifier; ++ updateExportSpecifier(node: ExportSpecifier, isTypeOnly: boolean, propertyName: ModuleExportName | undefined, name: ModuleExportName): ExportSpecifier; + /** @internal */ createMissingDeclaration(): MissingDeclaration; + + // +diff --git a/src/compiler/utilities.ts b/src/compiler/utilities.ts +index c7170af23..0da394ac8 100644 +--- a/src/compiler/utilities.ts ++++ b/src/compiler/utilities.ts +@@ -420,6 +420,7 @@ import { + ModuleBlock, + ModuleDeclaration, + ModuleDetectionKind, ++ ModuleExportName, + ModuleKind, + ModuleResolutionKind, + moduleResolutionOptionDeclarations, +@@ -1218,7 +1219,28 @@ function isJSDocTypeExpressionOrChild(node: Node): boolean { + + /** @internal */ + export function isExportNamespaceAsDefaultDeclaration(node: Node): boolean { +- return !!(isExportDeclaration(node) && node.exportClause && isNamespaceExport(node.exportClause) && node.exportClause.name.escapedText === "default"); ++ return !!(isExportDeclaration(node) && node.exportClause && isNamespaceExport(node.exportClause) && moduleExportNameIsDefault(node.exportClause.name)); ++} ++ ++/** @internal */ ++export function moduleExportNameTextUnescaped(node: ModuleExportName): string { ++ return node.kind === SyntaxKind.StringLiteral ? node.text : unescapeLeadingUnderscores(node.escapedText); ++} ++ ++/** @internal */ ++export function moduleExportNameTextEscaped(node: ModuleExportName): __String { ++ return node.kind === SyntaxKind.StringLiteral ? escapeLeadingUnderscores(node.text) : node.escapedText; ++} ++ ++/** ++ * Equality checks against a keyword without underscores don't need to bother ++ * to turn "__" into "___" or vice versa, since they will never be equal in ++ * either case. So we can ignore those cases to improve performance. ++ * ++ * @internal ++ */ ++export function moduleExportNameIsDefault(node: ModuleExportName): boolean { ++ return (node.kind === SyntaxKind.StringLiteral ? node.text : node.escapedText) === InternalSymbolName.Default; + } + + /** @internal */ +diff --git a/src/compiler/visitorPublic.ts b/src/compiler/visitorPublic.ts +index 21e477329..f3e71e026 100644 +--- a/src/compiler/visitorPublic.ts ++++ b/src/compiler/visitorPublic.ts +@@ -59,6 +59,7 @@ import { + isModifier, + isModifierLike, + isModuleBody, ++ isModuleExportName, + isModuleName, + isModuleReference, + isNamedExportBindings, +@@ -1579,7 +1580,7 @@ const visitEachChildTable: VisitEachChildTable = { + return context.factory.updateImportSpecifier( + node, + node.isTypeOnly, +- nodeVisitor(node.propertyName, visitor, isIdentifier), ++ nodeVisitor(node.propertyName, visitor, isModuleExportName), + Debug.checkDefined(nodeVisitor(node.name, visitor, isIdentifier)), + ); + }, +@@ -1614,8 +1615,8 @@ const visitEachChildTable: VisitEachChildTable = { + return context.factory.updateExportSpecifier( + node, + node.isTypeOnly, +- nodeVisitor(node.propertyName, visitor, isIdentifier), +- Debug.checkDefined(nodeVisitor(node.name, visitor, isIdentifier)), ++ nodeVisitor(node.propertyName, visitor, isModuleExportName), ++ Debug.checkDefined(nodeVisitor(node.name, visitor, isModuleExportName)), + ); + }, + +diff --git a/src/services/completions.ts b/src/services/completions.ts +index c8b676315..92884a0ad 100644 +--- a/src/services/completions.ts ++++ b/src/services/completions.ts +@@ -170,6 +170,8 @@ import { + isFunctionTypeNode, + isGetAccessorDeclaration, + isIdentifier, ++ isIdentifierPart, ++ isIdentifierStart, + isIdentifierText, + isImportableFile, + isImportAttributes, +@@ -297,6 +299,7 @@ import { + ModifierSyntaxKind, + modifierToFlag, + ModuleDeclaration, ++ moduleExportNameTextEscaped, + ModuleReference, + moduleResolutionSupportsPackageJsonExportsAndImports, + NamedImportBindings, +@@ -1836,10 +1839,19 @@ function createCompletionEntry( + } + + const parentNamedImportOrExport = findAncestor(location, isNamedImportsOrExports); +- if (parentNamedImportOrExport?.kind === SyntaxKind.NamedImports) { +- const possibleToken = stringToToken(name); +- if (parentNamedImportOrExport && possibleToken && (possibleToken === SyntaxKind.AwaitKeyword || isNonContextualKeyword(possibleToken))) { +- insertText = `${name} as ${name}_`; ++ if (parentNamedImportOrExport) { ++ const languageVersion = getEmitScriptTarget(host.getCompilationSettings()); ++ if (!isIdentifierText(name, languageVersion)) { ++ insertText = JSON.stringify(name); ++ if (parentNamedImportOrExport.kind === SyntaxKind.NamedImports) { ++ insertText += " as " + generateIdentifierForArbitraryString(name, languageVersion); ++ } ++ } ++ else if (parentNamedImportOrExport.kind === SyntaxKind.NamedImports) { ++ const possibleToken = stringToToken(name); ++ if (possibleToken && (possibleToken === SyntaxKind.AwaitKeyword || isNonContextualKeyword(possibleToken))) { ++ insertText = `${name} as ${name}_`; ++ } + } + } + +@@ -1872,6 +1884,29 @@ function createCompletionEntry( + }; + } + ++function generateIdentifierForArbitraryString(text: string, languageVersion: ScriptTarget | undefined): string { ++ let needsUnderscore = false; ++ let identifier = ""; ++ let ch: number | undefined; ++ ++ // Convert "(example, text)" into "_example_text_" ++ for (let i = 0; i < text.length; i += ch !== undefined && ch >= 0x10000 ? 2 : 1) { ++ ch = text.codePointAt(i); ++ if (ch !== undefined && (i === 0 ? isIdentifierStart(ch, languageVersion) : isIdentifierPart(ch, languageVersion))) { ++ if (needsUnderscore) identifier += "_"; ++ identifier += String.fromCodePoint(ch); ++ needsUnderscore = false; ++ } ++ else { ++ needsUnderscore = true; ++ } ++ } ++ if (needsUnderscore) identifier += "_"; ++ ++ // Default to "_" if the provided text was empty ++ return identifier || "_"; ++} ++ + function isClassLikeMemberCompletion(symbol: Symbol, location: Node, sourceFile: SourceFile): boolean { + // TODO: support JS files. + if (isInJSFile(location)) { +@@ -4497,7 +4532,7 @@ function getCompletionData( + completionKind = CompletionKind.MemberLike; + isNewIdentifierLocation = false; + const exports = typeChecker.getExportsAndPropertiesOfModule(moduleSpecifierSymbol); +- const existing = new Set((namedImportsOrExports.elements as NodeArray).filter(n => !isCurrentlyEditingNode(n)).map(n => (n.propertyName || n.name).escapedText)); ++ const existing = new Set((namedImportsOrExports.elements as NodeArray).filter(n => !isCurrentlyEditingNode(n)).map(n => moduleExportNameTextEscaped(n.propertyName || n.name))); + const uniques = exports.filter(e => e.escapedName !== InternalSymbolName.Default && !existing.has(e.escapedName)); + symbols = concatenate(symbols, uniques); + if (!uniques.length) { +@@ -5250,6 +5285,10 @@ function getCompletionEntryDisplayNameForSymbol( + if (isIdentifierText(name, target, jsxIdentifierExpected ? LanguageVariant.JSX : LanguageVariant.Standard) || symbol.valueDeclaration && isPrivateIdentifierClassElementDeclaration(symbol.valueDeclaration)) { + return validNameResult; + } ++ if (symbol.flags & SymbolFlags.Alias) { ++ // Allow non-identifier import/export aliases since we can insert them as string literals ++ return { name, needsConvertPropertyAccess: true }; ++ } + switch (kind) { + case CompletionKind.MemberLike: + return originIsComputedPropertyName(origin) ? { name: origin.symbolName, needsConvertPropertyAccess: false } : undefined; +diff --git a/src/services/findAllReferences.ts b/src/services/findAllReferences.ts +index 7abf2257b..39a43d55e 100644 +--- a/src/services/findAllReferences.ts ++++ b/src/services/findAllReferences.ts +@@ -208,6 +208,8 @@ import { + MethodDeclaration, + ModifierFlags, + ModuleDeclaration, ++ ModuleExportName, ++ moduleExportNameIsDefault, + MultiMap, + NamedDeclaration, + Node, +@@ -1563,7 +1565,7 @@ export namespace Core { + exportingModuleSymbol: Symbol, + exportName: string, + isDefaultExport: boolean, +- cb: (ref: Identifier) => void, ++ cb: (ref: ModuleExportName) => void, + ): void { + const importTracker = createImportTracker(sourceFiles, new Set(sourceFiles.map(f => f.fileName)), checker, cancellationToken); + const { importSearches, indirectUsers, singleReferences } = importTracker(exportSymbol, { exportKind: isDefaultExport ? ExportKind.Default : ExportKind.Named, exportingModuleSymbol }, /*isForRename*/ false); +@@ -1591,9 +1593,9 @@ export namespace Core { + if (!hasMatchingMeaning(singleRef, state)) return false; + if (state.options.use !== FindReferencesUse.Rename) return true; + // Don't rename an import type `import("./module-name")` when renaming `name` in `export = name;` +- if (!isIdentifier(singleRef)) return false; ++ if (!isIdentifier(singleRef) && !isImportOrExportSpecifier(singleRef.parent)) return false; + // At `default` in `import { default as x }` or `export { default as x }`, do add a reference, but do not rename. +- return !(isImportOrExportSpecifier(singleRef.parent) && singleRef.escapedText === InternalSymbolName.Default); ++ return !(isImportOrExportSpecifier(singleRef.parent) && moduleExportNameIsDefault(singleRef)); + } + + // Go to the symbol we imported from and find references for it. +@@ -1840,8 +1842,13 @@ export namespace Core { + case SyntaxKind.NoSubstitutionTemplateLiteral: + case SyntaxKind.StringLiteral: { + const str = node as StringLiteralLike; +- return (isLiteralNameOfPropertyDeclarationOrIndexAccess(str) || isNameOfModuleDeclaration(node) || isExpressionOfExternalModuleImportEqualsDeclaration(node) || (isCallExpression(node.parent) && isBindableObjectDefinePropertyCall(node.parent) && node.parent.arguments[1] === node)) && +- str.text.length === searchSymbolName.length; ++ return str.text.length === searchSymbolName.length && ( ++ isLiteralNameOfPropertyDeclarationOrIndexAccess(str) || ++ isNameOfModuleDeclaration(node) || ++ isExpressionOfExternalModuleImportEqualsDeclaration(node) || ++ (isCallExpression(node.parent) && isBindableObjectDefinePropertyCall(node.parent) && node.parent.arguments[1] === node) || ++ isImportOrExportSpecifier(node.parent) ++ ); + } + + case SyntaxKind.NumericLiteral: +@@ -1936,8 +1943,8 @@ export namespace Core { + } + + if (isExportSpecifier(parent)) { +- Debug.assert(referenceLocation.kind === SyntaxKind.Identifier); +- getReferencesAtExportSpecifier(referenceLocation as Identifier, referenceSymbol, parent, search, state, addReferencesHere); ++ Debug.assert(referenceLocation.kind === SyntaxKind.Identifier || referenceLocation.kind === SyntaxKind.StringLiteral); ++ getReferencesAtExportSpecifier(referenceLocation as Identifier | StringLiteral, referenceSymbol, parent, search, state, addReferencesHere); + return; + } + +@@ -1997,7 +2004,7 @@ export namespace Core { + } + + function getReferencesAtExportSpecifier( +- referenceLocation: Identifier, ++ referenceLocation: ModuleExportName, + referenceSymbol: Symbol, + exportSpecifier: ExportSpecifier, + search: Search, +@@ -2016,7 +2023,7 @@ export namespace Core { + + if (!propertyName) { + // Don't rename at `export { default } from "m";`. (but do continue to search for imports of the re-export) +- if (!(state.options.use === FindReferencesUse.Rename && (name.escapedText === InternalSymbolName.Default))) { ++ if (!(state.options.use === FindReferencesUse.Rename && moduleExportNameIsDefault(name))) { + addRef(); + } + } +@@ -2039,8 +2046,8 @@ export namespace Core { + + // For `export { foo as bar }`, rename `foo`, but not `bar`. + if (!isForRenameWithPrefixAndSuffixText(state.options) || alwaysGetReferences) { +- const isDefaultExport = referenceLocation.escapedText === "default" +- || exportSpecifier.name.escapedText === "default"; ++ const isDefaultExport = moduleExportNameIsDefault(referenceLocation) ++ || moduleExportNameIsDefault(exportSpecifier.name); + const exportKind = isDefaultExport ? ExportKind.Default : ExportKind.Named; + const exportSymbol = Debug.checkDefined(exportSpecifier.symbol); + const exportInfo = getExportInfo(exportSymbol, exportKind, state.checker); +@@ -2060,11 +2067,11 @@ export namespace Core { + } + } + +- function getLocalSymbolForExportSpecifier(referenceLocation: Identifier, referenceSymbol: Symbol, exportSpecifier: ExportSpecifier, checker: TypeChecker): Symbol { ++ function getLocalSymbolForExportSpecifier(referenceLocation: ModuleExportName, referenceSymbol: Symbol, exportSpecifier: ExportSpecifier, checker: TypeChecker): Symbol { + return isExportSpecifierAlias(referenceLocation, exportSpecifier) && checker.getExportSpecifierLocalTargetSymbol(exportSpecifier) || referenceSymbol; + } + +- function isExportSpecifierAlias(referenceLocation: Identifier, exportSpecifier: ExportSpecifier): boolean { ++ function isExportSpecifierAlias(referenceLocation: ModuleExportName, exportSpecifier: ExportSpecifier): boolean { + const { parent, propertyName, name } = exportSpecifier; + Debug.assert(propertyName === referenceLocation || name === referenceLocation); + if (propertyName) { +diff --git a/src/services/goToDefinition.ts b/src/services/goToDefinition.ts +index a576f684e..c1993137e 100644 +--- a/src/services/goToDefinition.ts ++++ b/src/services/goToDefinition.ts +@@ -59,6 +59,7 @@ import { + isFunctionTypeNode, + isIdentifier, + isImportMeta, ++ isImportOrExportSpecifier, + isJSDocOverrideTag, + isJsxOpeningLikeElement, + isJumpStatementTarget, +@@ -539,7 +540,12 @@ function getSymbol(node: Node, checker: TypeChecker, stopAtAlias: boolean | unde + // (2) when the aliased symbol is originating from an import. + // + function shouldSkipAlias(node: Node, declaration: Node): boolean { +- if (node.kind !== SyntaxKind.Identifier) { ++ // Note: Import aliases can be strings: ++ // ++ // import { "an alias" as foo } from "./foo"; ++ // export { foo as "an alias" }; ++ // ++ if (node.kind !== SyntaxKind.Identifier && (node.kind !== SyntaxKind.StringLiteral || !isImportOrExportSpecifier(node.parent))) { + return false; + } + if (node.parent === declaration) { +diff --git a/src/services/importTracker.ts b/src/services/importTracker.ts +index ade3cd39e..ab08c1898 100644 +--- a/src/services/importTracker.ts ++++ b/src/services/importTracker.ts +@@ -62,6 +62,8 @@ import { + ModifierFlags, + ModuleBlock, + ModuleDeclaration, ++ ModuleExportName, ++ moduleExportNameTextEscaped, + NamedImportsOrExports, + NamespaceImport, + Node, +@@ -90,7 +92,7 @@ import { + /** @internal */ + export interface ImportsResult { + /** For every import of the symbol, the location and local symbol for the import. */ +- importSearches: readonly [Identifier, Symbol][]; ++ importSearches: readonly [ModuleExportName, Symbol][]; + /** For rename imports/exports `{ foo as bar }`, `foo` is not a local, so it may be added as a reference immediately without further searching. */ + singleReferences: readonly (Identifier | StringLiteral)[]; + /** List of source files that may (or may not) use the symbol via a namespace. (For UMD modules this is every file.) */ +@@ -319,9 +321,9 @@ function getImportersForExport( + * But re-exports will be placed in 'singleReferences' since they cannot be locally referenced. + */ + function getSearchesFromDirectImports(directImports: Importer[], exportSymbol: Symbol, exportKind: ExportKind, checker: TypeChecker, isForRename: boolean): Pick { +- const importSearches: [Identifier, Symbol][] = []; ++ const importSearches: [ModuleExportName, Symbol][] = []; + const singleReferences: (Identifier | StringLiteral)[] = []; +- function addSearch(location: Identifier, symbol: Symbol): void { ++ function addSearch(location: ModuleExportName, symbol: Symbol): void { + importSearches.push([location, symbol]); + } + +@@ -417,7 +419,7 @@ function getSearchesFromDirectImports(directImports: Importer[], exportSymbol: S + + for (const element of namedBindings.elements) { + const { name, propertyName } = element; +- if (!isNameMatch((propertyName || name).escapedText)) { ++ if (!isNameMatch(moduleExportNameTextEscaped(propertyName || name))) { + continue; + } + +@@ -426,7 +428,7 @@ function getSearchesFromDirectImports(directImports: Importer[], exportSymbol: S + singleReferences.push(propertyName); + // If renaming `{ foo as bar }`, don't touch `bar`, just `foo`. + // But do rename `foo` in ` { default as foo }` if that's the original export name. +- if (!isForRename || name.escapedText === exportSymbol.escapedName) { ++ if (!isForRename || moduleExportNameTextEscaped(name) === exportSymbol.escapedName) { + // Search locally for `bar`. + addSearch(name, checker.getSymbolAtLocation(name)!); + } +diff --git a/src/services/organizeImports.ts b/src/services/organizeImports.ts +index facc06742..a5b366281 100644 +--- a/src/services/organizeImports.ts ++++ b/src/services/organizeImports.ts +@@ -45,6 +45,7 @@ import { + LanguageServiceHost, + length, + map, ++ moduleExportNameTextEscaped, + NamedImportBindings, + NamedImports, + NamespaceImport, +@@ -690,7 +691,7 @@ function hasModuleDeclarationMatchingSpecifier(sourceFile: SourceFile, moduleSpe + function getNewImportSpecifiers(namedImports: ImportDeclaration[]) { + return flatMap(namedImports, namedImport => + map(tryGetNamedBindingElements(namedImport), importSpecifier => +- importSpecifier.name && importSpecifier.propertyName && importSpecifier.name.escapedText === importSpecifier.propertyName.escapedText ++ importSpecifier.name && importSpecifier.propertyName && moduleExportNameTextEscaped(importSpecifier.name) === moduleExportNameTextEscaped(importSpecifier.propertyName) + ? factory.updateImportSpecifier(importSpecifier, importSpecifier.isTypeOnly, /*propertyName*/ undefined, importSpecifier.name) + : importSpecifier)); + } +diff --git a/src/services/refactors/convertExport.ts b/src/services/refactors/convertExport.ts +index 5e722c083..547403bfb 100644 +--- a/src/services/refactors/convertExport.ts ++++ b/src/services/refactors/convertExport.ts +@@ -34,6 +34,7 @@ import { + makeImport, + ModifierFlags, + ModuleBlock, ++ ModuleExportName, + NamespaceDeclaration, + Node, + NodeFlags, +@@ -236,7 +237,7 @@ function changeImports(program: Program, { wasDefault, exportName, exportingModu + }); + } + +-function changeDefaultToNamedImport(importingSourceFile: SourceFile, ref: Identifier, changes: textChanges.ChangeTracker, exportName: string): void { ++function changeDefaultToNamedImport(importingSourceFile: SourceFile, ref: ModuleExportName, changes: textChanges.ChangeTracker, exportName: string): void { + const { parent } = ref; + switch (parent.kind) { + case SyntaxKind.PropertyAccessExpression: +@@ -282,7 +283,7 @@ function changeDefaultToNamedImport(importingSourceFile: SourceFile, ref: Identi + } + } + +-function changeNamedToDefaultImport(importingSourceFile: SourceFile, ref: Identifier, changes: textChanges.ChangeTracker): void { ++function changeNamedToDefaultImport(importingSourceFile: SourceFile, ref: ModuleExportName, changes: textChanges.ChangeTracker): void { + const parent = ref.parent as PropertyAccessExpression | ImportSpecifier | ExportSpecifier; + switch (parent.kind) { + case SyntaxKind.PropertyAccessExpression: +diff --git a/src/services/refactors/convertImport.ts b/src/services/refactors/convertImport.ts +index 55e14b576..b0071598b 100644 +--- a/src/services/refactors/convertImport.ts ++++ b/src/services/refactors/convertImport.ts +@@ -247,9 +247,11 @@ export function doChangeNamedToNamespaceOrDefault(sourceFile: SourceFile, progra + const neededNamedImports = new Set(); + + for (const element of toConvert.elements) { +- const propertyName = (element.propertyName || element.name).text; ++ const propertyName = element.propertyName || element.name; + FindAllReferences.Core.eachSymbolReferenceInFile(element.name, checker, sourceFile, id => { +- const access = factory.createPropertyAccessExpression(factory.createIdentifier(namespaceImportName), propertyName); ++ const access = propertyName.kind === SyntaxKind.StringLiteral ++ ? factory.createElementAccessExpression(factory.createIdentifier(namespaceImportName), factory.cloneNode(propertyName)) ++ : factory.createPropertyAccessExpression(factory.createIdentifier(namespaceImportName), factory.cloneNode(propertyName)); + if (isShorthandPropertyAssignment(id.parent)) { + changes.replaceNode(sourceFile, id.parent, factory.createPropertyAssignment(id.text, access)); + } +@@ -271,7 +273,7 @@ export function doChangeNamedToNamespaceOrDefault(sourceFile: SourceFile, progra + ); + + if (neededNamedImports.size && isImportDeclaration(importDecl)) { +- const newNamedImports: ImportSpecifier[] = arrayFrom(neededNamedImports.values(), element => factory.createImportSpecifier(element.isTypeOnly, element.propertyName && factory.createIdentifier(element.propertyName.text), factory.createIdentifier(element.name.text))); ++ const newNamedImports: ImportSpecifier[] = arrayFrom(neededNamedImports.values(), element => factory.createImportSpecifier(element.isTypeOnly, element.propertyName && factory.cloneNode(element.propertyName), factory.cloneNode(element.name))); + changes.insertNodeAfter(sourceFile, toConvert.parent.parent, createImport(importDecl, /*defaultImportName*/ undefined, newNamedImports)); + } + } +diff --git a/src/services/stringCompletions.ts b/src/services/stringCompletions.ts +index 0b1747fd0..b96e06138 100644 +--- a/src/services/stringCompletions.ts ++++ b/src/services/stringCompletions.ts +@@ -77,7 +77,9 @@ import { + hasProperty, + hasTrailingDirectorySeparator, + hostGetCanonicalFileName, ++ ImportOrExportSpecifier, + IndexedAccessTypeNode, ++ InternalSymbolName, + isApplicableVersionedTypesKey, + isArray, + isCallExpression, +@@ -104,6 +106,7 @@ import { + LiteralTypeNode, + mapDefined, + MapLike, ++ moduleExportNameTextEscaped, + moduleResolutionUsesNodeModules, + ModuleSpecifierEnding, + moduleSpecifiers, +@@ -434,6 +437,24 @@ function getStringLiteralCompletionEntries(sourceFile: SourceFile, node: StringL + } + const literals = contextualTypes.types.filter(literal => !tracker.hasValue(literal.value)); + return { kind: StringLiteralCompletionKind.Types, types: literals, isNewIdentifier: false }; ++ ++ case SyntaxKind.ImportSpecifier: ++ case SyntaxKind.ExportSpecifier: ++ // Complete string aliases in `import { "|" } from` and `export { "|" } from` ++ const specifier = parent as ImportOrExportSpecifier; ++ if (specifier.propertyName && node !== specifier.propertyName) { ++ return; // Don't complete in `export { "..." as "|" } from` ++ } ++ const namedImportsOrExports = specifier.parent; ++ const { moduleSpecifier } = namedImportsOrExports.kind === SyntaxKind.NamedImports ? namedImportsOrExports.parent.parent : namedImportsOrExports.parent; ++ if (!moduleSpecifier) return; ++ const moduleSpecifierSymbol = typeChecker.getSymbolAtLocation(moduleSpecifier); // TODO: GH#18217 ++ if (!moduleSpecifierSymbol) return; ++ const exports = typeChecker.getExportsAndPropertiesOfModule(moduleSpecifierSymbol); ++ const existing = new Set(namedImportsOrExports.elements.map(n => moduleExportNameTextEscaped(n.propertyName || n.name))); ++ const uniques = exports.filter(e => e.escapedName !== InternalSymbolName.Default && !existing.has(e.escapedName)); ++ return { kind: StringLiteralCompletionKind.Properties, symbols: uniques, hasIndexSignature: false }; ++ + default: + return fromContextualType() || fromContextualType(ContextFlags.None); + } diff --git a/TypeScript_3/solution/solve.sh b/TypeScript_3/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..04d2cdd558a05593c6373ab47313e0e441927403 --- /dev/null +++ b/TypeScript_3/solution/solve.sh @@ -0,0 +1,7 @@ +#!/usr/bin/env bash +set -euo pipefail + +cd /workspace/typescript +patch=${LOLBENCH_ORACLE_PATCH:-/solution/solution.patch} +git apply "$patch" +lolbench-submit diff --git a/TypeScript_3/task.toml b/TypeScript_3/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..51a8b9ad22d0a7b415b990c44e705496881e3e26 --- /dev/null +++ b/TypeScript_3/task.toml @@ -0,0 +1,60 @@ +schema_version = "1.3" + +[task] +name = "lolbench/TypeScript_3" +description = "Implement TypeScript arbitrary module namespace identifiers." +authors = [{ name = "LoLBench maintainers" }] +keywords = ["lolbench", "coding-agent", "typescript"] + +[metadata] +instance_id = "TypeScript_3" +source_instance_id = "TypeScript_PR-58640_Arbitrary-Module-Namespace-Identifiers" +source_slug = "TypeScript_PR-58640_Arbitrary-Module-Namespace-Identifiers" +docker_slug = "TypeScript_PR-58640_Arbitrary-Module-Namespace-Identifiers" +dockerhub_image = "smartdub26/lolbench-linux:TypeScript_3-1.0.0" +project = "TypeScript" +repo = "microsoft/TypeScript" +requirement_doc = "https://github.com/tc39/ecma262/pull/2154" +pr_link = "https://github.com/microsoft/TypeScript/pull/58640" +base_commit = "112e860602b2b46f7a1f179a8f6357f6e4db2370" +merge_commit = "ff8217073661987cd62923fd596e18e40de62740" +test_level = "system" +source_history_policy = "ancestors-only" +lolbench_test_modes = ["orig", "aug", "union"] +default_lolbench_suite = "union" +canonical_lolbench_suite = "union" +augmentation_available = true +verifier_network_policy = "public" +verifier_network_reason = "The Harbor verifier runs in a separate container and may use network access; migrated LoLBench verifier assets are mounted only in the verifier phase." + +[environment] +build_timeout_sec = 3600.0 +docker_image = "smartdub26/lolbench-linux:TypeScript_3-1.0.0" +network_mode = "public" +os = "linux" +cpus = 4 +memory_mb = 7168 +storage_mb = 20480 + +[agent] +timeout_sec = 21600.0 +user = "agent" +network_mode = "allowlist" +allowed_hosts = ["openrouter.ai", "api.openai.com", "api.anthropic.com"] + +[verifier] +timeout_sec = 7200.0 +user = "root" +environment_mode = "separate" +network_mode = "public" + +[verifier.env] +LOLBENCH_SUITE = "union" + +[verifier.environment] +docker_image = "smartdub26/lolbench-linux:TypeScript_3-1.0.0" +network_mode = "public" +os = "linux" +cpus = 4 +memory_mb = 7168 +storage_mb = 20480 diff --git a/TypeScript_3/tests/docker-compose.yaml b/TypeScript_3/tests/docker-compose.yaml new file mode 100644 index 0000000000000000000000000000000000000000..f5091b9298e127a1efbe69deeed699c907e025c1 --- /dev/null +++ b/TypeScript_3/tests/docker-compose.yaml @@ -0,0 +1,16 @@ +services: + main: + pull_policy: missing + volumes: + - type: bind + source: . + target: /tests + read_only: true + - type: bind + source: ./private + target: /opt/lolbench/private + read_only: true + - type: bind + source: ../solution + target: /solution + read_only: true diff --git a/TypeScript_3/tests/private/eval_tests.patch b/TypeScript_3/tests/private/eval_tests.patch new file mode 100644 index 0000000000000000000000000000000000000000..955d7d329accf57327cc026d4821815bb2b47886 --- /dev/null +++ b/TypeScript_3/tests/private/eval_tests.patch @@ -0,0 +1,9118 @@ +diff --git a/tests/baselines/reference/api/typescript.d.ts b/tests/baselines/reference/api/typescript.d.ts +index a4903113b..1752b0ef0 100644 +--- a/tests/baselines/reference/api/typescript.d.ts ++++ b/tests/baselines/reference/api/typescript.d.ts +@@ -5517,7 +5517,7 @@ declare namespace ts { + interface NamespaceExport extends NamedDeclaration { + readonly kind: SyntaxKind.NamespaceExport; + readonly parent: ExportDeclaration; +- readonly name: Identifier; ++ readonly name: ModuleExportName; + } + interface NamespaceExportDeclaration extends DeclarationStatement, JSDocContainer { + readonly kind: SyntaxKind.NamespaceExportDeclaration; +@@ -5549,7 +5549,7 @@ declare namespace ts { + interface ImportSpecifier extends NamedDeclaration { + readonly kind: SyntaxKind.ImportSpecifier; + readonly parent: NamedImports; +- readonly propertyName?: Identifier; ++ readonly propertyName?: ModuleExportName; + readonly name: Identifier; + readonly isTypeOnly: boolean; + } +@@ -5557,9 +5557,10 @@ declare namespace ts { + readonly kind: SyntaxKind.ExportSpecifier; + readonly parent: NamedExports; + readonly isTypeOnly: boolean; +- readonly propertyName?: Identifier; +- readonly name: Identifier; ++ readonly propertyName?: ModuleExportName; ++ readonly name: ModuleExportName; + } ++ type ModuleExportName = Identifier | StringLiteral; + type ImportOrExportSpecifier = ImportSpecifier | ExportSpecifier; + type TypeOnlyCompatibleAliasDeclaration = ImportClause | ImportEqualsDeclaration | NamespaceImport | ImportOrExportSpecifier | ExportDeclaration | NamespaceExport; + type TypeOnlyImportDeclaration = +@@ -7661,20 +7662,20 @@ declare namespace ts { + updateImportAttribute(node: ImportAttribute, name: ImportAttributeName, value: Expression): ImportAttribute; + createNamespaceImport(name: Identifier): NamespaceImport; + updateNamespaceImport(node: NamespaceImport, name: Identifier): NamespaceImport; +- createNamespaceExport(name: Identifier): NamespaceExport; +- updateNamespaceExport(node: NamespaceExport, name: Identifier): NamespaceExport; ++ createNamespaceExport(name: ModuleExportName): NamespaceExport; ++ updateNamespaceExport(node: NamespaceExport, name: ModuleExportName): NamespaceExport; + createNamedImports(elements: readonly ImportSpecifier[]): NamedImports; + updateNamedImports(node: NamedImports, elements: readonly ImportSpecifier[]): NamedImports; +- createImportSpecifier(isTypeOnly: boolean, propertyName: Identifier | undefined, name: Identifier): ImportSpecifier; +- updateImportSpecifier(node: ImportSpecifier, isTypeOnly: boolean, propertyName: Identifier | undefined, name: Identifier): ImportSpecifier; ++ createImportSpecifier(isTypeOnly: boolean, propertyName: ModuleExportName | undefined, name: Identifier): ImportSpecifier; ++ updateImportSpecifier(node: ImportSpecifier, isTypeOnly: boolean, propertyName: ModuleExportName | undefined, name: Identifier): ImportSpecifier; + createExportAssignment(modifiers: readonly ModifierLike[] | undefined, isExportEquals: boolean | undefined, expression: Expression): ExportAssignment; + updateExportAssignment(node: ExportAssignment, modifiers: readonly ModifierLike[] | undefined, expression: Expression): ExportAssignment; + createExportDeclaration(modifiers: readonly ModifierLike[] | undefined, isTypeOnly: boolean, exportClause: NamedExportBindings | undefined, moduleSpecifier?: Expression, attributes?: ImportAttributes): ExportDeclaration; + updateExportDeclaration(node: ExportDeclaration, modifiers: readonly ModifierLike[] | undefined, isTypeOnly: boolean, exportClause: NamedExportBindings | undefined, moduleSpecifier: Expression | undefined, attributes: ImportAttributes | undefined): ExportDeclaration; + createNamedExports(elements: readonly ExportSpecifier[]): NamedExports; + updateNamedExports(node: NamedExports, elements: readonly ExportSpecifier[]): NamedExports; +- createExportSpecifier(isTypeOnly: boolean, propertyName: string | Identifier | undefined, name: string | Identifier): ExportSpecifier; +- updateExportSpecifier(node: ExportSpecifier, isTypeOnly: boolean, propertyName: Identifier | undefined, name: Identifier): ExportSpecifier; ++ createExportSpecifier(isTypeOnly: boolean, propertyName: string | ModuleExportName | undefined, name: string | ModuleExportName): ExportSpecifier; ++ updateExportSpecifier(node: ExportSpecifier, isTypeOnly: boolean, propertyName: ModuleExportName | undefined, name: ModuleExportName): ExportSpecifier; + createExternalModuleReference(expression: Expression): ExternalModuleReference; + updateExternalModuleReference(node: ExternalModuleReference, expression: Expression): ExternalModuleReference; + createJSDocAllType(): JSDocAllType; +@@ -8992,6 +8993,7 @@ declare namespace ts { + function isExportDeclaration(node: Node): node is ExportDeclaration; + function isNamedExports(node: Node): node is NamedExports; + function isExportSpecifier(node: Node): node is ExportSpecifier; ++ function isModuleExportName(node: Node): node is ModuleExportName; + function isMissingDeclaration(node: Node): node is MissingDeclaration; + function isNotEmittedStatement(node: Node): node is NotEmittedStatement; + function isExternalModuleReference(node: Node): node is ExternalModuleReference; +diff --git a/tests/baselines/reference/arbitraryModuleNamespaceIdentifiers_exportEmpty.errors.txt b/tests/baselines/reference/arbitraryModuleNamespaceIdentifiers_exportEmpty.errors.txt +new file mode 100644 +index 000000000..b29a1f103 +--- /dev/null ++++ b/tests/baselines/reference/arbitraryModuleNamespaceIdentifiers_exportEmpty.errors.txt +@@ -0,0 +1,13 @@ ++arbitraryModuleNamespaceIdentifiers_exportEmpty.ts(6,7): error TS2322: Type '"empty"' is not assignable to type '"type error expected here"'. ++ ++ ++==== arbitraryModuleNamespaceIdentifiers_exportEmpty.ts (1 errors) ==== ++ // This should result in a type error. In particular, the empty string is a now ++ // a valid module export name, and should be treated as such here. ++ const empty = "empty"; ++ export { empty as "" }; ++ import { "" as foo } from "./arbitraryModuleNamespaceIdentifiers_exportEmpty"; ++ const bar: "type error expected here" = foo; ++ ~~~ ++!!! error TS2322: Type '"empty"' is not assignable to type '"type error expected here"'. ++ +\ No newline at end of file +diff --git a/tests/baselines/reference/arbitraryModuleNamespaceIdentifiers_exportEmpty.js b/tests/baselines/reference/arbitraryModuleNamespaceIdentifiers_exportEmpty.js +new file mode 100644 +index 000000000..a04910b79 +--- /dev/null ++++ b/tests/baselines/reference/arbitraryModuleNamespaceIdentifiers_exportEmpty.js +@@ -0,0 +1,23 @@ ++//// [tests/cases/conformance/es2022/arbitraryModuleNamespaceIdentifiers/arbitraryModuleNamespaceIdentifiers_exportEmpty.ts] //// ++ ++//// [arbitraryModuleNamespaceIdentifiers_exportEmpty.ts] ++// This should result in a type error. In particular, the empty string is a now ++// a valid module export name, and should be treated as such here. ++const empty = "empty"; ++export { empty as "" }; ++import { "" as foo } from "./arbitraryModuleNamespaceIdentifiers_exportEmpty"; ++const bar: "type error expected here" = foo; ++ ++ ++//// [arbitraryModuleNamespaceIdentifiers_exportEmpty.js] ++// This should result in a type error. In particular, the empty string is a now ++// a valid module export name, and should be treated as such here. ++const empty = "empty"; ++export { empty as "" }; ++import { "" as foo } from "./arbitraryModuleNamespaceIdentifiers_exportEmpty"; ++const bar = foo; ++ ++ ++//// [arbitraryModuleNamespaceIdentifiers_exportEmpty.d.ts] ++declare const empty = "empty"; ++export { empty as "" }; +diff --git a/tests/baselines/reference/arbitraryModuleNamespaceIdentifiers_exportEmpty.symbols b/tests/baselines/reference/arbitraryModuleNamespaceIdentifiers_exportEmpty.symbols +new file mode 100644 +index 000000000..9baebaf89 +--- /dev/null ++++ b/tests/baselines/reference/arbitraryModuleNamespaceIdentifiers_exportEmpty.symbols +@@ -0,0 +1,19 @@ ++//// [tests/cases/conformance/es2022/arbitraryModuleNamespaceIdentifiers/arbitraryModuleNamespaceIdentifiers_exportEmpty.ts] //// ++ ++=== arbitraryModuleNamespaceIdentifiers_exportEmpty.ts === ++// This should result in a type error. In particular, the empty string is a now ++// a valid module export name, and should be treated as such here. ++const empty = "empty"; ++>empty : Symbol(empty, Decl(arbitraryModuleNamespaceIdentifiers_exportEmpty.ts, 2, 5)) ++ ++export { empty as "" }; ++>empty : Symbol(empty, Decl(arbitraryModuleNamespaceIdentifiers_exportEmpty.ts, 2, 5)) ++>"" : Symbol("", Decl(arbitraryModuleNamespaceIdentifiers_exportEmpty.ts, 3, 8)) ++ ++import { "" as foo } from "./arbitraryModuleNamespaceIdentifiers_exportEmpty"; ++>foo : Symbol(foo, Decl(arbitraryModuleNamespaceIdentifiers_exportEmpty.ts, 4, 8)) ++ ++const bar: "type error expected here" = foo; ++>bar : Symbol(bar, Decl(arbitraryModuleNamespaceIdentifiers_exportEmpty.ts, 5, 5)) ++>foo : Symbol(foo, Decl(arbitraryModuleNamespaceIdentifiers_exportEmpty.ts, 4, 8)) ++ +diff --git a/tests/baselines/reference/arbitraryModuleNamespaceIdentifiers_exportEmpty.types b/tests/baselines/reference/arbitraryModuleNamespaceIdentifiers_exportEmpty.types +new file mode 100644 +index 000000000..d2f63f672 +--- /dev/null ++++ b/tests/baselines/reference/arbitraryModuleNamespaceIdentifiers_exportEmpty.types +@@ -0,0 +1,27 @@ ++//// [tests/cases/conformance/es2022/arbitraryModuleNamespaceIdentifiers/arbitraryModuleNamespaceIdentifiers_exportEmpty.ts] //// ++ ++=== arbitraryModuleNamespaceIdentifiers_exportEmpty.ts === ++// This should result in a type error. In particular, the empty string is a now ++// a valid module export name, and should be treated as such here. ++const empty = "empty"; ++>empty : "empty" ++> : ^^^^^^^ ++>"empty" : "empty" ++> : ^^^^^^^ ++ ++export { empty as "" }; ++>empty : "empty" ++> : ^^^^^^^ ++>"" : "empty" ++> : ^^^^^^^ ++ ++import { "" as foo } from "./arbitraryModuleNamespaceIdentifiers_exportEmpty"; ++>foo : "empty" ++> : ^^^^^^^ ++ ++const bar: "type error expected here" = foo; ++>bar : "type error expected here" ++> : ^^^^^^^^^^^^^^^^^^^^^^^^^^ ++>foo : "empty" ++> : ^^^^^^^ ++ +diff --git a/tests/baselines/reference/arbitraryModuleNamespaceIdentifiers_importEmpty.errors.txt b/tests/baselines/reference/arbitraryModuleNamespaceIdentifiers_importEmpty.errors.txt +new file mode 100644 +index 000000000..5f29972f1 +--- /dev/null ++++ b/tests/baselines/reference/arbitraryModuleNamespaceIdentifiers_importEmpty.errors.txt +@@ -0,0 +1,21 @@ ++arbitraryModuleNamespaceIdentifiers_importEmpty.ts(4,3): error TS2305: Module '"./arbitraryModuleNamespaceIdentifiers_importEmpty"' has no exported member '"missing"'. ++arbitraryModuleNamespaceIdentifiers_importEmpty.ts(5,3): error TS2305: Module '"./arbitraryModuleNamespaceIdentifiers_importEmpty"' has no exported member '"(missing)"'. ++arbitraryModuleNamespaceIdentifiers_importEmpty.ts(6,3): error TS2305: Module '"./arbitraryModuleNamespaceIdentifiers_importEmpty"' has no exported member '""'. ++ ++ ++==== arbitraryModuleNamespaceIdentifiers_importEmpty.ts (3 errors) ==== ++ // These should all be errors. In particular, the empty string is a now a valid ++ // module export name, and should be treated as such here. ++ import { ++ "missing" as x, ++ ~~~~~~~~~ ++!!! error TS2305: Module '"./arbitraryModuleNamespaceIdentifiers_importEmpty"' has no exported member '"missing"'. ++ "(missing)" as y, ++ ~~~~~~~~~~~ ++!!! error TS2305: Module '"./arbitraryModuleNamespaceIdentifiers_importEmpty"' has no exported member '"(missing)"'. ++ "" as z, ++ ~~ ++!!! error TS2305: Module '"./arbitraryModuleNamespaceIdentifiers_importEmpty"' has no exported member '""'. ++ } from "./arbitraryModuleNamespaceIdentifiers_importEmpty"; ++ const xyz = [x, y, z]; ++ +\ No newline at end of file +diff --git a/tests/baselines/reference/arbitraryModuleNamespaceIdentifiers_importEmpty.js b/tests/baselines/reference/arbitraryModuleNamespaceIdentifiers_importEmpty.js +new file mode 100644 +index 000000000..4a0e32641 +--- /dev/null ++++ b/tests/baselines/reference/arbitraryModuleNamespaceIdentifiers_importEmpty.js +@@ -0,0 +1,22 @@ ++//// [tests/cases/conformance/es2022/arbitraryModuleNamespaceIdentifiers/arbitraryModuleNamespaceIdentifiers_importEmpty.ts] //// ++ ++//// [arbitraryModuleNamespaceIdentifiers_importEmpty.ts] ++// These should all be errors. In particular, the empty string is a now a valid ++// module export name, and should be treated as such here. ++import { ++ "missing" as x, ++ "(missing)" as y, ++ "" as z, ++} from "./arbitraryModuleNamespaceIdentifiers_importEmpty"; ++const xyz = [x, y, z]; ++ ++ ++//// [arbitraryModuleNamespaceIdentifiers_importEmpty.js] ++// These should all be errors. In particular, the empty string is a now a valid ++// module export name, and should be treated as such here. ++import { "missing" as x, "(missing)" as y, "" as z, } from "./arbitraryModuleNamespaceIdentifiers_importEmpty"; ++const xyz = [x, y, z]; ++ ++ ++//// [arbitraryModuleNamespaceIdentifiers_importEmpty.d.ts] ++export {}; +diff --git a/tests/baselines/reference/arbitraryModuleNamespaceIdentifiers_importEmpty.symbols b/tests/baselines/reference/arbitraryModuleNamespaceIdentifiers_importEmpty.symbols +new file mode 100644 +index 000000000..663d32df1 +--- /dev/null ++++ b/tests/baselines/reference/arbitraryModuleNamespaceIdentifiers_importEmpty.symbols +@@ -0,0 +1,22 @@ ++//// [tests/cases/conformance/es2022/arbitraryModuleNamespaceIdentifiers/arbitraryModuleNamespaceIdentifiers_importEmpty.ts] //// ++ ++=== arbitraryModuleNamespaceIdentifiers_importEmpty.ts === ++// These should all be errors. In particular, the empty string is a now a valid ++// module export name, and should be treated as such here. ++import { ++ "missing" as x, ++>x : Symbol(x, Decl(arbitraryModuleNamespaceIdentifiers_importEmpty.ts, 2, 8)) ++ ++ "(missing)" as y, ++>y : Symbol(y, Decl(arbitraryModuleNamespaceIdentifiers_importEmpty.ts, 3, 17)) ++ ++ "" as z, ++>z : Symbol(z, Decl(arbitraryModuleNamespaceIdentifiers_importEmpty.ts, 4, 19)) ++ ++} from "./arbitraryModuleNamespaceIdentifiers_importEmpty"; ++const xyz = [x, y, z]; ++>xyz : Symbol(xyz, Decl(arbitraryModuleNamespaceIdentifiers_importEmpty.ts, 7, 5)) ++>x : Symbol(x, Decl(arbitraryModuleNamespaceIdentifiers_importEmpty.ts, 2, 8)) ++>y : Symbol(y, Decl(arbitraryModuleNamespaceIdentifiers_importEmpty.ts, 3, 17)) ++>z : Symbol(z, Decl(arbitraryModuleNamespaceIdentifiers_importEmpty.ts, 4, 19)) ++ +diff --git a/tests/baselines/reference/arbitraryModuleNamespaceIdentifiers_importEmpty.types b/tests/baselines/reference/arbitraryModuleNamespaceIdentifiers_importEmpty.types +new file mode 100644 +index 000000000..20059408b +--- /dev/null ++++ b/tests/baselines/reference/arbitraryModuleNamespaceIdentifiers_importEmpty.types +@@ -0,0 +1,31 @@ ++//// [tests/cases/conformance/es2022/arbitraryModuleNamespaceIdentifiers/arbitraryModuleNamespaceIdentifiers_importEmpty.ts] //// ++ ++=== arbitraryModuleNamespaceIdentifiers_importEmpty.ts === ++// These should all be errors. In particular, the empty string is a now a valid ++// module export name, and should be treated as such here. ++import { ++ "missing" as x, ++>x : any ++> : ^^^ ++ ++ "(missing)" as y, ++>y : any ++> : ^^^ ++ ++ "" as z, ++>z : any ++> : ^^^ ++ ++} from "./arbitraryModuleNamespaceIdentifiers_importEmpty"; ++const xyz = [x, y, z]; ++>xyz : any[] ++> : ^^^^^ ++>[x, y, z] : any[] ++> : ^^^^^ ++>x : any ++> : ^^^ ++>y : any ++> : ^^^ ++>z : any ++> : ^^^ ++ +diff --git a/tests/baselines/reference/arbitraryModuleNamespaceIdentifiers_module(module=amd).errors.txt b/tests/baselines/reference/arbitraryModuleNamespaceIdentifiers_module(module=amd).errors.txt +new file mode 100644 +index 000000000..cc359bceb +--- /dev/null ++++ b/tests/baselines/reference/arbitraryModuleNamespaceIdentifiers_module(module=amd).errors.txt +@@ -0,0 +1,42 @@ ++arbitraryModuleNamespaceIdentifiers_module.ts(20,7): error TS2322: Type '"expect error about someType"' is not assignable to type '"someType"'. ++arbitraryModuleNamespaceIdentifiers_module.ts(24,7): error TS2322: Type '"expect error about someType"' is not assignable to type '"someType"'. ++arbitraryModuleNamespaceIdentifiers_module.ts(29,7): error TS2322: Type '"expect error about otherType"' is not assignable to type '"otherType"'. ++ ++ ++==== arbitraryModuleNamespaceIdentifiers_module.ts (3 errors) ==== ++ const someValue = "someValue"; ++ type someType = "someType"; ++ ++ export { someValue as "" }; ++ import { "" as valueX } from "./arbitraryModuleNamespaceIdentifiers_module"; ++ if (valueX !== "someValue") throw "should be someValue"; ++ ++ export { "" as "" } from "./arbitraryModuleNamespaceIdentifiers_module"; ++ import { "" as valueY } from "./arbitraryModuleNamespaceIdentifiers_module"; ++ if (valueY !== "someValue") throw "should be someValue"; ++ ++ export * as "" from "./arbitraryModuleNamespaceIdentifiers_module"; ++ import { "" as valueZ } from "./arbitraryModuleNamespaceIdentifiers_module"; ++ if (valueZ[""] !== "someValue") throw "should be someValue"; ++ if (valueZ[""] !== "someValue") throw "should be someValue"; ++ if (valueZ[""] !== valueZ) throw "should be export namespace"; ++ ++ export { type someType as "" }; ++ import { type "" as typeA } from "./arbitraryModuleNamespaceIdentifiers_module"; ++ const importTest: typeA = "expect error about someType"; ++ ~~~~~~~~~~ ++!!! error TS2322: Type '"expect error about someType"' is not assignable to type '"someType"'. ++ ++ export { type "" as "" } from "./arbitraryModuleNamespaceIdentifiers_module"; ++ import { type "" as typeB } from "./arbitraryModuleNamespaceIdentifiers_module"; ++ const reimportTest: typeB = "expect error about someType"; ++ ~~~~~~~~~~~~ ++!!! error TS2322: Type '"expect error about someType"' is not assignable to type '"someType"'. ++ ++ export type * as "" from "./arbitraryModuleNamespaceIdentifiers_module"; ++ import { type "" as typeC } from "./arbitraryModuleNamespaceIdentifiers_module"; ++ export type otherType = "otherType"; ++ const importStarTestA: typeC.otherType = "expect error about otherType"; ++ ~~~~~~~~~~~~~~~ ++!!! error TS2322: Type '"expect error about otherType"' is not assignable to type '"otherType"'. ++ +\ No newline at end of file +diff --git a/tests/baselines/reference/arbitraryModuleNamespaceIdentifiers_module(module=amd).js b/tests/baselines/reference/arbitraryModuleNamespaceIdentifiers_module(module=amd).js +new file mode 100644 +index 000000000..1a72c31df +--- /dev/null ++++ b/tests/baselines/reference/arbitraryModuleNamespaceIdentifiers_module(module=amd).js +@@ -0,0 +1,69 @@ ++//// [tests/cases/conformance/es2022/arbitraryModuleNamespaceIdentifiers/arbitraryModuleNamespaceIdentifiers_module.ts] //// ++ ++//// [arbitraryModuleNamespaceIdentifiers_module.ts] ++const someValue = "someValue"; ++type someType = "someType"; ++ ++export { someValue as "" }; ++import { "" as valueX } from "./arbitraryModuleNamespaceIdentifiers_module"; ++if (valueX !== "someValue") throw "should be someValue"; ++ ++export { "" as "" } from "./arbitraryModuleNamespaceIdentifiers_module"; ++import { "" as valueY } from "./arbitraryModuleNamespaceIdentifiers_module"; ++if (valueY !== "someValue") throw "should be someValue"; ++ ++export * as "" from "./arbitraryModuleNamespaceIdentifiers_module"; ++import { "" as valueZ } from "./arbitraryModuleNamespaceIdentifiers_module"; ++if (valueZ[""] !== "someValue") throw "should be someValue"; ++if (valueZ[""] !== "someValue") throw "should be someValue"; ++if (valueZ[""] !== valueZ) throw "should be export namespace"; ++ ++export { type someType as "" }; ++import { type "" as typeA } from "./arbitraryModuleNamespaceIdentifiers_module"; ++const importTest: typeA = "expect error about someType"; ++ ++export { type "" as "" } from "./arbitraryModuleNamespaceIdentifiers_module"; ++import { type "" as typeB } from "./arbitraryModuleNamespaceIdentifiers_module"; ++const reimportTest: typeB = "expect error about someType"; ++ ++export type * as "" from "./arbitraryModuleNamespaceIdentifiers_module"; ++import { type "" as typeC } from "./arbitraryModuleNamespaceIdentifiers_module"; ++export type otherType = "otherType"; ++const importStarTestA: typeC.otherType = "expect error about otherType"; ++ ++ ++//// [arbitraryModuleNamespaceIdentifiers_module.js] ++define(["require", "exports", "./arbitraryModuleNamespaceIdentifiers_module", "./arbitraryModuleNamespaceIdentifiers_module", "./arbitraryModuleNamespaceIdentifiers_module", "./arbitraryModuleNamespaceIdentifiers_module", "./arbitraryModuleNamespaceIdentifiers_module"], function (require, exports, arbitraryModuleNamespaceIdentifiers_module_1, arbitraryModuleNamespaceIdentifiers_module_2, arbitraryModuleNamespaceIdentifiers_module_3, arbitraryModuleNamespaceIdentifiers_module_4, arbitraryModuleNamespaceIdentifiers_module_5) { ++ "use strict"; ++ Object.defineProperty(exports, "__esModule", { value: true }); ++ exports[""] = exports[""] = exports[""] = void 0; ++ const someValue = "someValue"; ++ exports[""] = someValue; ++ if (arbitraryModuleNamespaceIdentifiers_module_1[""] !== "someValue") ++ throw "should be someValue"; ++ Object.defineProperty(exports, "", { enumerable: true, get: function () { return arbitraryModuleNamespaceIdentifiers_module_2[""]; } }); ++ if (arbitraryModuleNamespaceIdentifiers_module_3[""] !== "someValue") ++ throw "should be someValue"; ++ exports[""] = arbitraryModuleNamespaceIdentifiers_module_4; ++ if (arbitraryModuleNamespaceIdentifiers_module_5[""][""] !== "someValue") ++ throw "should be someValue"; ++ if (arbitraryModuleNamespaceIdentifiers_module_5[""][""] !== "someValue") ++ throw "should be someValue"; ++ if (arbitraryModuleNamespaceIdentifiers_module_5[""][""] !== arbitraryModuleNamespaceIdentifiers_module_5[""]) ++ throw "should be export namespace"; ++ const importTest = "expect error about someType"; ++ const reimportTest = "expect error about someType"; ++ const importStarTestA = "expect error about otherType"; ++}); ++ ++ ++//// [arbitraryModuleNamespaceIdentifiers_module.d.ts] ++declare const someValue = "someValue"; ++type someType = "someType"; ++export { someValue as "" }; ++export { "" as "" } from "./arbitraryModuleNamespaceIdentifiers_module"; ++export * as "" from "./arbitraryModuleNamespaceIdentifiers_module"; ++export { type someType as "" }; ++export { type "" as "" } from "./arbitraryModuleNamespaceIdentifiers_module"; ++export type * as "" from "./arbitraryModuleNamespaceIdentifiers_module"; ++export type otherType = "otherType"; +diff --git a/tests/baselines/reference/arbitraryModuleNamespaceIdentifiers_module(module=amd).symbols b/tests/baselines/reference/arbitraryModuleNamespaceIdentifiers_module(module=amd).symbols +new file mode 100644 +index 000000000..a792b7d3f +--- /dev/null ++++ b/tests/baselines/reference/arbitraryModuleNamespaceIdentifiers_module(module=amd).symbols +@@ -0,0 +1,82 @@ ++//// [tests/cases/conformance/es2022/arbitraryModuleNamespaceIdentifiers/arbitraryModuleNamespaceIdentifiers_module.ts] //// ++ ++=== arbitraryModuleNamespaceIdentifiers_module.ts === ++const someValue = "someValue"; ++>someValue : Symbol(someValue, Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 0, 5)) ++ ++type someType = "someType"; ++>someType : Symbol(someType, Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 0, 30)) ++ ++export { someValue as "" }; ++>someValue : Symbol(someValue, Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 0, 5)) ++>"" : Symbol(valueZ[""], Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 3, 8)) ++ ++import { "" as valueX } from "./arbitraryModuleNamespaceIdentifiers_module"; ++>valueX : Symbol(valueX, Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 4, 8)) ++ ++if (valueX !== "someValue") throw "should be someValue"; ++>valueX : Symbol(valueX, Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 4, 8)) ++ ++export { "" as "" } from "./arbitraryModuleNamespaceIdentifiers_module"; ++>"" : Symbol(valueZ[""], Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 7, 8)) ++ ++import { "" as valueY } from "./arbitraryModuleNamespaceIdentifiers_module"; ++>valueY : Symbol(valueY, Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 8, 8)) ++ ++if (valueY !== "someValue") throw "should be someValue"; ++>valueY : Symbol(valueY, Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 8, 8)) ++ ++export * as "" from "./arbitraryModuleNamespaceIdentifiers_module"; ++>"" : Symbol(valueZ[""], Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 11, 6)) ++ ++import { "" as valueZ } from "./arbitraryModuleNamespaceIdentifiers_module"; ++>valueZ : Symbol(valueZ, Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 12, 8)) ++ ++if (valueZ[""] !== "someValue") throw "should be someValue"; ++>valueZ : Symbol(valueZ, Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 12, 8)) ++>"" : Symbol(valueZ[""], Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 3, 8)) ++ ++if (valueZ[""] !== "someValue") throw "should be someValue"; ++>valueZ : Symbol(valueZ, Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 12, 8)) ++>"" : Symbol(valueZ[""], Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 7, 8)) ++ ++if (valueZ[""] !== valueZ) throw "should be export namespace"; ++>valueZ : Symbol(valueZ, Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 12, 8)) ++>"" : Symbol(valueZ[""], Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 11, 6)) ++>valueZ : Symbol(valueZ, Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 12, 8)) ++ ++export { type someType as "" }; ++>someType : Symbol(someType, Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 0, 30)) ++>"" : Symbol(valueZ[""], Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 17, 8)) ++ ++import { type "" as typeA } from "./arbitraryModuleNamespaceIdentifiers_module"; ++>typeA : Symbol(typeA, Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 18, 8)) ++ ++const importTest: typeA = "expect error about someType"; ++>importTest : Symbol(importTest, Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 19, 5)) ++>typeA : Symbol(typeA, Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 18, 8)) ++ ++export { type "" as "" } from "./arbitraryModuleNamespaceIdentifiers_module"; ++>"" : Symbol(valueZ[""], Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 21, 8)) ++ ++import { type "" as typeB } from "./arbitraryModuleNamespaceIdentifiers_module"; ++>typeB : Symbol(typeB, Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 22, 8)) ++ ++const reimportTest: typeB = "expect error about someType"; ++>reimportTest : Symbol(reimportTest, Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 23, 5)) ++>typeB : Symbol(typeB, Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 22, 8)) ++ ++export type * as "" from "./arbitraryModuleNamespaceIdentifiers_module"; ++>"" : Symbol(valueZ[""], Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 25, 11)) ++ ++import { type "" as typeC } from "./arbitraryModuleNamespaceIdentifiers_module"; ++>typeC : Symbol(typeC, Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 26, 8)) ++ ++export type otherType = "otherType"; ++>otherType : Symbol(valueZ.otherType, Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 26, 83)) ++ ++const importStarTestA: typeC.otherType = "expect error about otherType"; ++>importStarTestA : Symbol(importStarTestA, Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 28, 5)) ++>typeC : Symbol(typeC, Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 26, 8)) ++>otherType : Symbol(valueZ.otherType, Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 26, 83)) ++ +diff --git a/tests/baselines/reference/arbitraryModuleNamespaceIdentifiers_module(module=amd).types b/tests/baselines/reference/arbitraryModuleNamespaceIdentifiers_module(module=amd).types +new file mode 100644 +index 000000000..4574f9754 +--- /dev/null ++++ b/tests/baselines/reference/arbitraryModuleNamespaceIdentifiers_module(module=amd).types +@@ -0,0 +1,151 @@ ++//// [tests/cases/conformance/es2022/arbitraryModuleNamespaceIdentifiers/arbitraryModuleNamespaceIdentifiers_module.ts] //// ++ ++=== arbitraryModuleNamespaceIdentifiers_module.ts === ++const someValue = "someValue"; ++>someValue : "someValue" ++> : ^^^^^^^^^^^ ++>"someValue" : "someValue" ++> : ^^^^^^^^^^^ ++ ++type someType = "someType"; ++>someType : "someType" ++> : ^^^^^^^^^^ ++ ++export { someValue as "" }; ++>someValue : "someValue" ++> : ^^^^^^^^^^^ ++>"" : "someValue" ++> : ^^^^^^^^^^^ ++ ++import { "" as valueX } from "./arbitraryModuleNamespaceIdentifiers_module"; ++>valueX : "someValue" ++> : ^^^^^^^^^^^ ++ ++if (valueX !== "someValue") throw "should be someValue"; ++>valueX !== "someValue" : boolean ++> : ^^^^^^^ ++>valueX : "someValue" ++> : ^^^^^^^^^^^ ++>"someValue" : "someValue" ++> : ^^^^^^^^^^^ ++>"should be someValue" : "should be someValue" ++> : ^^^^^^^^^^^^^^^^^^^^^ ++ ++export { "" as "" } from "./arbitraryModuleNamespaceIdentifiers_module"; ++>"" : "someValue" ++> : ^^^^^^^^^^^ ++ ++import { "" as valueY } from "./arbitraryModuleNamespaceIdentifiers_module"; ++>valueY : "someValue" ++> : ^^^^^^^^^^^ ++ ++if (valueY !== "someValue") throw "should be someValue"; ++>valueY !== "someValue" : boolean ++> : ^^^^^^^ ++>valueY : "someValue" ++> : ^^^^^^^^^^^ ++>"someValue" : "someValue" ++> : ^^^^^^^^^^^ ++>"should be someValue" : "should be someValue" ++> : ^^^^^^^^^^^^^^^^^^^^^ ++ ++export * as "" from "./arbitraryModuleNamespaceIdentifiers_module"; ++>"" : typeof valueZ ++> : ^^^^^^^^^^^^^ ++ ++import { "" as valueZ } from "./arbitraryModuleNamespaceIdentifiers_module"; ++>valueZ : typeof valueZ ++> : ^^^^^^^^^^^^^ ++ ++if (valueZ[""] !== "someValue") throw "should be someValue"; ++>valueZ[""] !== "someValue" : boolean ++> : ^^^^^^^ ++>valueZ[""] : "someValue" ++> : ^^^^^^^^^^^ ++>valueZ : typeof valueZ ++> : ^^^^^^^^^^^^^ ++>"" : "" ++> : ^^^^^ ++>"someValue" : "someValue" ++> : ^^^^^^^^^^^ ++>"should be someValue" : "should be someValue" ++> : ^^^^^^^^^^^^^^^^^^^^^ ++ ++if (valueZ[""] !== "someValue") throw "should be someValue"; ++>valueZ[""] !== "someValue" : boolean ++> : ^^^^^^^ ++>valueZ[""] : "someValue" ++> : ^^^^^^^^^^^ ++>valueZ : typeof valueZ ++> : ^^^^^^^^^^^^^ ++>"" : "" ++> : ^^^^^ ++>"someValue" : "someValue" ++> : ^^^^^^^^^^^ ++>"should be someValue" : "should be someValue" ++> : ^^^^^^^^^^^^^^^^^^^^^ ++ ++if (valueZ[""] !== valueZ) throw "should be export namespace"; ++>valueZ[""] !== valueZ : boolean ++> : ^^^^^^^ ++>valueZ[""] : typeof valueZ ++> : ^^^^^^^^^^^^^ ++>valueZ : typeof valueZ ++> : ^^^^^^^^^^^^^ ++>"" : "" ++> : ^^^^^ ++>valueZ : typeof valueZ ++> : ^^^^^^^^^^^^^ ++>"should be export namespace" : "should be export namespace" ++> : ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ++ ++export { type someType as "" }; ++>someType : any ++> : ^^^ ++>"" : any ++> : ^^^ ++ ++import { type "" as typeA } from "./arbitraryModuleNamespaceIdentifiers_module"; ++>typeA : any ++> : ^^^ ++ ++const importTest: typeA = "expect error about someType"; ++>importTest : "someType" ++> : ^^^^^^^^^^ ++>"expect error about someType" : "expect error about someType" ++> : ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ++ ++export { type "" as "" } from "./arbitraryModuleNamespaceIdentifiers_module"; ++>"" : any ++> : ^^^ ++ ++import { type "" as typeB } from "./arbitraryModuleNamespaceIdentifiers_module"; ++>typeB : any ++> : ^^^ ++ ++const reimportTest: typeB = "expect error about someType"; ++>reimportTest : "someType" ++> : ^^^^^^^^^^ ++>"expect error about someType" : "expect error about someType" ++> : ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ++ ++export type * as "" from "./arbitraryModuleNamespaceIdentifiers_module"; ++>"" : typeof valueZ ++> : ^^^^^^^^^^^^^ ++ ++import { type "" as typeC } from "./arbitraryModuleNamespaceIdentifiers_module"; ++>typeC : typeof valueZ ++> : ^^^^^^^^^^^^^ ++ ++export type otherType = "otherType"; ++>otherType : "otherType" ++> : ^^^^^^^^^^^ ++ ++const importStarTestA: typeC.otherType = "expect error about otherType"; ++>importStarTestA : "otherType" ++> : ^^^^^^^^^^^ ++>typeC : any ++> : ^^^ ++>"expect error about otherType" : "expect error about otherType" ++> : ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ++ +diff --git a/tests/baselines/reference/arbitraryModuleNamespaceIdentifiers_module(module=commonjs).errors.txt b/tests/baselines/reference/arbitraryModuleNamespaceIdentifiers_module(module=commonjs).errors.txt +new file mode 100644 +index 000000000..cc359bceb +--- /dev/null ++++ b/tests/baselines/reference/arbitraryModuleNamespaceIdentifiers_module(module=commonjs).errors.txt +@@ -0,0 +1,42 @@ ++arbitraryModuleNamespaceIdentifiers_module.ts(20,7): error TS2322: Type '"expect error about someType"' is not assignable to type '"someType"'. ++arbitraryModuleNamespaceIdentifiers_module.ts(24,7): error TS2322: Type '"expect error about someType"' is not assignable to type '"someType"'. ++arbitraryModuleNamespaceIdentifiers_module.ts(29,7): error TS2322: Type '"expect error about otherType"' is not assignable to type '"otherType"'. ++ ++ ++==== arbitraryModuleNamespaceIdentifiers_module.ts (3 errors) ==== ++ const someValue = "someValue"; ++ type someType = "someType"; ++ ++ export { someValue as "" }; ++ import { "" as valueX } from "./arbitraryModuleNamespaceIdentifiers_module"; ++ if (valueX !== "someValue") throw "should be someValue"; ++ ++ export { "" as "" } from "./arbitraryModuleNamespaceIdentifiers_module"; ++ import { "" as valueY } from "./arbitraryModuleNamespaceIdentifiers_module"; ++ if (valueY !== "someValue") throw "should be someValue"; ++ ++ export * as "" from "./arbitraryModuleNamespaceIdentifiers_module"; ++ import { "" as valueZ } from "./arbitraryModuleNamespaceIdentifiers_module"; ++ if (valueZ[""] !== "someValue") throw "should be someValue"; ++ if (valueZ[""] !== "someValue") throw "should be someValue"; ++ if (valueZ[""] !== valueZ) throw "should be export namespace"; ++ ++ export { type someType as "" }; ++ import { type "" as typeA } from "./arbitraryModuleNamespaceIdentifiers_module"; ++ const importTest: typeA = "expect error about someType"; ++ ~~~~~~~~~~ ++!!! error TS2322: Type '"expect error about someType"' is not assignable to type '"someType"'. ++ ++ export { type "" as "" } from "./arbitraryModuleNamespaceIdentifiers_module"; ++ import { type "" as typeB } from "./arbitraryModuleNamespaceIdentifiers_module"; ++ const reimportTest: typeB = "expect error about someType"; ++ ~~~~~~~~~~~~ ++!!! error TS2322: Type '"expect error about someType"' is not assignable to type '"someType"'. ++ ++ export type * as "" from "./arbitraryModuleNamespaceIdentifiers_module"; ++ import { type "" as typeC } from "./arbitraryModuleNamespaceIdentifiers_module"; ++ export type otherType = "otherType"; ++ const importStarTestA: typeC.otherType = "expect error about otherType"; ++ ~~~~~~~~~~~~~~~ ++!!! error TS2322: Type '"expect error about otherType"' is not assignable to type '"otherType"'. ++ +\ No newline at end of file +diff --git a/tests/baselines/reference/arbitraryModuleNamespaceIdentifiers_module(module=commonjs).js b/tests/baselines/reference/arbitraryModuleNamespaceIdentifiers_module(module=commonjs).js +new file mode 100644 +index 000000000..43f954515 +--- /dev/null ++++ b/tests/baselines/reference/arbitraryModuleNamespaceIdentifiers_module(module=commonjs).js +@@ -0,0 +1,71 @@ ++//// [tests/cases/conformance/es2022/arbitraryModuleNamespaceIdentifiers/arbitraryModuleNamespaceIdentifiers_module.ts] //// ++ ++//// [arbitraryModuleNamespaceIdentifiers_module.ts] ++const someValue = "someValue"; ++type someType = "someType"; ++ ++export { someValue as "" }; ++import { "" as valueX } from "./arbitraryModuleNamespaceIdentifiers_module"; ++if (valueX !== "someValue") throw "should be someValue"; ++ ++export { "" as "" } from "./arbitraryModuleNamespaceIdentifiers_module"; ++import { "" as valueY } from "./arbitraryModuleNamespaceIdentifiers_module"; ++if (valueY !== "someValue") throw "should be someValue"; ++ ++export * as "" from "./arbitraryModuleNamespaceIdentifiers_module"; ++import { "" as valueZ } from "./arbitraryModuleNamespaceIdentifiers_module"; ++if (valueZ[""] !== "someValue") throw "should be someValue"; ++if (valueZ[""] !== "someValue") throw "should be someValue"; ++if (valueZ[""] !== valueZ) throw "should be export namespace"; ++ ++export { type someType as "" }; ++import { type "" as typeA } from "./arbitraryModuleNamespaceIdentifiers_module"; ++const importTest: typeA = "expect error about someType"; ++ ++export { type "" as "" } from "./arbitraryModuleNamespaceIdentifiers_module"; ++import { type "" as typeB } from "./arbitraryModuleNamespaceIdentifiers_module"; ++const reimportTest: typeB = "expect error about someType"; ++ ++export type * as "" from "./arbitraryModuleNamespaceIdentifiers_module"; ++import { type "" as typeC } from "./arbitraryModuleNamespaceIdentifiers_module"; ++export type otherType = "otherType"; ++const importStarTestA: typeC.otherType = "expect error about otherType"; ++ ++ ++//// [arbitraryModuleNamespaceIdentifiers_module.js] ++"use strict"; ++Object.defineProperty(exports, "__esModule", { value: true }); ++exports[""] = exports[""] = exports[""] = void 0; ++const someValue = "someValue"; ++exports[""] = someValue; ++const arbitraryModuleNamespaceIdentifiers_module_1 = require("./arbitraryModuleNamespaceIdentifiers_module"); ++if (arbitraryModuleNamespaceIdentifiers_module_1[""] !== "someValue") ++ throw "should be someValue"; ++var arbitraryModuleNamespaceIdentifiers_module_2 = require("./arbitraryModuleNamespaceIdentifiers_module"); ++Object.defineProperty(exports, "", { enumerable: true, get: function () { return arbitraryModuleNamespaceIdentifiers_module_2[""]; } }); ++const arbitraryModuleNamespaceIdentifiers_module_3 = require("./arbitraryModuleNamespaceIdentifiers_module"); ++if (arbitraryModuleNamespaceIdentifiers_module_3[""] !== "someValue") ++ throw "should be someValue"; ++exports[""] = require("./arbitraryModuleNamespaceIdentifiers_module"); ++const arbitraryModuleNamespaceIdentifiers_module_4 = require("./arbitraryModuleNamespaceIdentifiers_module"); ++if (arbitraryModuleNamespaceIdentifiers_module_4[""][""] !== "someValue") ++ throw "should be someValue"; ++if (arbitraryModuleNamespaceIdentifiers_module_4[""][""] !== "someValue") ++ throw "should be someValue"; ++if (arbitraryModuleNamespaceIdentifiers_module_4[""][""] !== arbitraryModuleNamespaceIdentifiers_module_4[""]) ++ throw "should be export namespace"; ++const importTest = "expect error about someType"; ++const reimportTest = "expect error about someType"; ++const importStarTestA = "expect error about otherType"; ++ ++ ++//// [arbitraryModuleNamespaceIdentifiers_module.d.ts] ++declare const someValue = "someValue"; ++type someType = "someType"; ++export { someValue as "" }; ++export { "" as "" } from "./arbitraryModuleNamespaceIdentifiers_module"; ++export * as "" from "./arbitraryModuleNamespaceIdentifiers_module"; ++export { type someType as "" }; ++export { type "" as "" } from "./arbitraryModuleNamespaceIdentifiers_module"; ++export type * as "" from "./arbitraryModuleNamespaceIdentifiers_module"; ++export type otherType = "otherType"; +diff --git a/tests/baselines/reference/arbitraryModuleNamespaceIdentifiers_module(module=commonjs).symbols b/tests/baselines/reference/arbitraryModuleNamespaceIdentifiers_module(module=commonjs).symbols +new file mode 100644 +index 000000000..a792b7d3f +--- /dev/null ++++ b/tests/baselines/reference/arbitraryModuleNamespaceIdentifiers_module(module=commonjs).symbols +@@ -0,0 +1,82 @@ ++//// [tests/cases/conformance/es2022/arbitraryModuleNamespaceIdentifiers/arbitraryModuleNamespaceIdentifiers_module.ts] //// ++ ++=== arbitraryModuleNamespaceIdentifiers_module.ts === ++const someValue = "someValue"; ++>someValue : Symbol(someValue, Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 0, 5)) ++ ++type someType = "someType"; ++>someType : Symbol(someType, Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 0, 30)) ++ ++export { someValue as "" }; ++>someValue : Symbol(someValue, Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 0, 5)) ++>"" : Symbol(valueZ[""], Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 3, 8)) ++ ++import { "" as valueX } from "./arbitraryModuleNamespaceIdentifiers_module"; ++>valueX : Symbol(valueX, Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 4, 8)) ++ ++if (valueX !== "someValue") throw "should be someValue"; ++>valueX : Symbol(valueX, Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 4, 8)) ++ ++export { "" as "" } from "./arbitraryModuleNamespaceIdentifiers_module"; ++>"" : Symbol(valueZ[""], Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 7, 8)) ++ ++import { "" as valueY } from "./arbitraryModuleNamespaceIdentifiers_module"; ++>valueY : Symbol(valueY, Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 8, 8)) ++ ++if (valueY !== "someValue") throw "should be someValue"; ++>valueY : Symbol(valueY, Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 8, 8)) ++ ++export * as "" from "./arbitraryModuleNamespaceIdentifiers_module"; ++>"" : Symbol(valueZ[""], Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 11, 6)) ++ ++import { "" as valueZ } from "./arbitraryModuleNamespaceIdentifiers_module"; ++>valueZ : Symbol(valueZ, Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 12, 8)) ++ ++if (valueZ[""] !== "someValue") throw "should be someValue"; ++>valueZ : Symbol(valueZ, Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 12, 8)) ++>"" : Symbol(valueZ[""], Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 3, 8)) ++ ++if (valueZ[""] !== "someValue") throw "should be someValue"; ++>valueZ : Symbol(valueZ, Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 12, 8)) ++>"" : Symbol(valueZ[""], Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 7, 8)) ++ ++if (valueZ[""] !== valueZ) throw "should be export namespace"; ++>valueZ : Symbol(valueZ, Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 12, 8)) ++>"" : Symbol(valueZ[""], Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 11, 6)) ++>valueZ : Symbol(valueZ, Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 12, 8)) ++ ++export { type someType as "" }; ++>someType : Symbol(someType, Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 0, 30)) ++>"" : Symbol(valueZ[""], Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 17, 8)) ++ ++import { type "" as typeA } from "./arbitraryModuleNamespaceIdentifiers_module"; ++>typeA : Symbol(typeA, Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 18, 8)) ++ ++const importTest: typeA = "expect error about someType"; ++>importTest : Symbol(importTest, Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 19, 5)) ++>typeA : Symbol(typeA, Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 18, 8)) ++ ++export { type "" as "" } from "./arbitraryModuleNamespaceIdentifiers_module"; ++>"" : Symbol(valueZ[""], Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 21, 8)) ++ ++import { type "" as typeB } from "./arbitraryModuleNamespaceIdentifiers_module"; ++>typeB : Symbol(typeB, Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 22, 8)) ++ ++const reimportTest: typeB = "expect error about someType"; ++>reimportTest : Symbol(reimportTest, Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 23, 5)) ++>typeB : Symbol(typeB, Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 22, 8)) ++ ++export type * as "" from "./arbitraryModuleNamespaceIdentifiers_module"; ++>"" : Symbol(valueZ[""], Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 25, 11)) ++ ++import { type "" as typeC } from "./arbitraryModuleNamespaceIdentifiers_module"; ++>typeC : Symbol(typeC, Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 26, 8)) ++ ++export type otherType = "otherType"; ++>otherType : Symbol(valueZ.otherType, Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 26, 83)) ++ ++const importStarTestA: typeC.otherType = "expect error about otherType"; ++>importStarTestA : Symbol(importStarTestA, Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 28, 5)) ++>typeC : Symbol(typeC, Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 26, 8)) ++>otherType : Symbol(valueZ.otherType, Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 26, 83)) ++ +diff --git a/tests/baselines/reference/arbitraryModuleNamespaceIdentifiers_module(module=commonjs).types b/tests/baselines/reference/arbitraryModuleNamespaceIdentifiers_module(module=commonjs).types +new file mode 100644 +index 000000000..4574f9754 +--- /dev/null ++++ b/tests/baselines/reference/arbitraryModuleNamespaceIdentifiers_module(module=commonjs).types +@@ -0,0 +1,151 @@ ++//// [tests/cases/conformance/es2022/arbitraryModuleNamespaceIdentifiers/arbitraryModuleNamespaceIdentifiers_module.ts] //// ++ ++=== arbitraryModuleNamespaceIdentifiers_module.ts === ++const someValue = "someValue"; ++>someValue : "someValue" ++> : ^^^^^^^^^^^ ++>"someValue" : "someValue" ++> : ^^^^^^^^^^^ ++ ++type someType = "someType"; ++>someType : "someType" ++> : ^^^^^^^^^^ ++ ++export { someValue as "" }; ++>someValue : "someValue" ++> : ^^^^^^^^^^^ ++>"" : "someValue" ++> : ^^^^^^^^^^^ ++ ++import { "" as valueX } from "./arbitraryModuleNamespaceIdentifiers_module"; ++>valueX : "someValue" ++> : ^^^^^^^^^^^ ++ ++if (valueX !== "someValue") throw "should be someValue"; ++>valueX !== "someValue" : boolean ++> : ^^^^^^^ ++>valueX : "someValue" ++> : ^^^^^^^^^^^ ++>"someValue" : "someValue" ++> : ^^^^^^^^^^^ ++>"should be someValue" : "should be someValue" ++> : ^^^^^^^^^^^^^^^^^^^^^ ++ ++export { "" as "" } from "./arbitraryModuleNamespaceIdentifiers_module"; ++>"" : "someValue" ++> : ^^^^^^^^^^^ ++ ++import { "" as valueY } from "./arbitraryModuleNamespaceIdentifiers_module"; ++>valueY : "someValue" ++> : ^^^^^^^^^^^ ++ ++if (valueY !== "someValue") throw "should be someValue"; ++>valueY !== "someValue" : boolean ++> : ^^^^^^^ ++>valueY : "someValue" ++> : ^^^^^^^^^^^ ++>"someValue" : "someValue" ++> : ^^^^^^^^^^^ ++>"should be someValue" : "should be someValue" ++> : ^^^^^^^^^^^^^^^^^^^^^ ++ ++export * as "" from "./arbitraryModuleNamespaceIdentifiers_module"; ++>"" : typeof valueZ ++> : ^^^^^^^^^^^^^ ++ ++import { "" as valueZ } from "./arbitraryModuleNamespaceIdentifiers_module"; ++>valueZ : typeof valueZ ++> : ^^^^^^^^^^^^^ ++ ++if (valueZ[""] !== "someValue") throw "should be someValue"; ++>valueZ[""] !== "someValue" : boolean ++> : ^^^^^^^ ++>valueZ[""] : "someValue" ++> : ^^^^^^^^^^^ ++>valueZ : typeof valueZ ++> : ^^^^^^^^^^^^^ ++>"" : "" ++> : ^^^^^ ++>"someValue" : "someValue" ++> : ^^^^^^^^^^^ ++>"should be someValue" : "should be someValue" ++> : ^^^^^^^^^^^^^^^^^^^^^ ++ ++if (valueZ[""] !== "someValue") throw "should be someValue"; ++>valueZ[""] !== "someValue" : boolean ++> : ^^^^^^^ ++>valueZ[""] : "someValue" ++> : ^^^^^^^^^^^ ++>valueZ : typeof valueZ ++> : ^^^^^^^^^^^^^ ++>"" : "" ++> : ^^^^^ ++>"someValue" : "someValue" ++> : ^^^^^^^^^^^ ++>"should be someValue" : "should be someValue" ++> : ^^^^^^^^^^^^^^^^^^^^^ ++ ++if (valueZ[""] !== valueZ) throw "should be export namespace"; ++>valueZ[""] !== valueZ : boolean ++> : ^^^^^^^ ++>valueZ[""] : typeof valueZ ++> : ^^^^^^^^^^^^^ ++>valueZ : typeof valueZ ++> : ^^^^^^^^^^^^^ ++>"" : "" ++> : ^^^^^ ++>valueZ : typeof valueZ ++> : ^^^^^^^^^^^^^ ++>"should be export namespace" : "should be export namespace" ++> : ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ++ ++export { type someType as "" }; ++>someType : any ++> : ^^^ ++>"" : any ++> : ^^^ ++ ++import { type "" as typeA } from "./arbitraryModuleNamespaceIdentifiers_module"; ++>typeA : any ++> : ^^^ ++ ++const importTest: typeA = "expect error about someType"; ++>importTest : "someType" ++> : ^^^^^^^^^^ ++>"expect error about someType" : "expect error about someType" ++> : ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ++ ++export { type "" as "" } from "./arbitraryModuleNamespaceIdentifiers_module"; ++>"" : any ++> : ^^^ ++ ++import { type "" as typeB } from "./arbitraryModuleNamespaceIdentifiers_module"; ++>typeB : any ++> : ^^^ ++ ++const reimportTest: typeB = "expect error about someType"; ++>reimportTest : "someType" ++> : ^^^^^^^^^^ ++>"expect error about someType" : "expect error about someType" ++> : ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ++ ++export type * as "" from "./arbitraryModuleNamespaceIdentifiers_module"; ++>"" : typeof valueZ ++> : ^^^^^^^^^^^^^ ++ ++import { type "" as typeC } from "./arbitraryModuleNamespaceIdentifiers_module"; ++>typeC : typeof valueZ ++> : ^^^^^^^^^^^^^ ++ ++export type otherType = "otherType"; ++>otherType : "otherType" ++> : ^^^^^^^^^^^ ++ ++const importStarTestA: typeC.otherType = "expect error about otherType"; ++>importStarTestA : "otherType" ++> : ^^^^^^^^^^^ ++>typeC : any ++> : ^^^ ++>"expect error about otherType" : "expect error about otherType" ++> : ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ++ +diff --git a/tests/baselines/reference/arbitraryModuleNamespaceIdentifiers_module(module=es2020).errors.txt b/tests/baselines/reference/arbitraryModuleNamespaceIdentifiers_module(module=es2020).errors.txt +new file mode 100644 +index 000000000..e2a851b5a +--- /dev/null ++++ b/tests/baselines/reference/arbitraryModuleNamespaceIdentifiers_module(module=es2020).errors.txt +@@ -0,0 +1,84 @@ ++arbitraryModuleNamespaceIdentifiers_module.ts(4,23): error TS18057: String literal import and export names are not supported when the '--module' flag is set to 'es2015' or 'es2020'. ++arbitraryModuleNamespaceIdentifiers_module.ts(5,10): error TS18057: String literal import and export names are not supported when the '--module' flag is set to 'es2015' or 'es2020'. ++arbitraryModuleNamespaceIdentifiers_module.ts(8,10): error TS18057: String literal import and export names are not supported when the '--module' flag is set to 'es2015' or 'es2020'. ++arbitraryModuleNamespaceIdentifiers_module.ts(8,19): error TS18057: String literal import and export names are not supported when the '--module' flag is set to 'es2015' or 'es2020'. ++arbitraryModuleNamespaceIdentifiers_module.ts(9,10): error TS18057: String literal import and export names are not supported when the '--module' flag is set to 'es2015' or 'es2020'. ++arbitraryModuleNamespaceIdentifiers_module.ts(12,13): error TS18057: String literal import and export names are not supported when the '--module' flag is set to 'es2015' or 'es2020'. ++arbitraryModuleNamespaceIdentifiers_module.ts(13,10): error TS18057: String literal import and export names are not supported when the '--module' flag is set to 'es2015' or 'es2020'. ++arbitraryModuleNamespaceIdentifiers_module.ts(18,27): error TS18057: String literal import and export names are not supported when the '--module' flag is set to 'es2015' or 'es2020'. ++arbitraryModuleNamespaceIdentifiers_module.ts(19,15): error TS18057: String literal import and export names are not supported when the '--module' flag is set to 'es2015' or 'es2020'. ++arbitraryModuleNamespaceIdentifiers_module.ts(20,7): error TS2322: Type '"expect error about someType"' is not assignable to type '"someType"'. ++arbitraryModuleNamespaceIdentifiers_module.ts(22,15): error TS18057: String literal import and export names are not supported when the '--module' flag is set to 'es2015' or 'es2020'. ++arbitraryModuleNamespaceIdentifiers_module.ts(22,24): error TS18057: String literal import and export names are not supported when the '--module' flag is set to 'es2015' or 'es2020'. ++arbitraryModuleNamespaceIdentifiers_module.ts(23,15): error TS18057: String literal import and export names are not supported when the '--module' flag is set to 'es2015' or 'es2020'. ++arbitraryModuleNamespaceIdentifiers_module.ts(24,7): error TS2322: Type '"expect error about someType"' is not assignable to type '"someType"'. ++arbitraryModuleNamespaceIdentifiers_module.ts(26,18): error TS18057: String literal import and export names are not supported when the '--module' flag is set to 'es2015' or 'es2020'. ++arbitraryModuleNamespaceIdentifiers_module.ts(27,15): error TS18057: String literal import and export names are not supported when the '--module' flag is set to 'es2015' or 'es2020'. ++arbitraryModuleNamespaceIdentifiers_module.ts(29,7): error TS2322: Type '"expect error about otherType"' is not assignable to type '"otherType"'. ++ ++ ++==== arbitraryModuleNamespaceIdentifiers_module.ts (17 errors) ==== ++ const someValue = "someValue"; ++ type someType = "someType"; ++ ++ export { someValue as "" }; ++ ~~~~~ ++!!! error TS18057: String literal import and export names are not supported when the '--module' flag is set to 'es2015' or 'es2020'. ++ import { "" as valueX } from "./arbitraryModuleNamespaceIdentifiers_module"; ++ ~~~~~ ++!!! error TS18057: String literal import and export names are not supported when the '--module' flag is set to 'es2015' or 'es2020'. ++ if (valueX !== "someValue") throw "should be someValue"; ++ ++ export { "" as "" } from "./arbitraryModuleNamespaceIdentifiers_module"; ++ ~~~~~ ++!!! error TS18057: String literal import and export names are not supported when the '--module' flag is set to 'es2015' or 'es2020'. ++ ~~~~~ ++!!! error TS18057: String literal import and export names are not supported when the '--module' flag is set to 'es2015' or 'es2020'. ++ import { "" as valueY } from "./arbitraryModuleNamespaceIdentifiers_module"; ++ ~~~~~ ++!!! error TS18057: String literal import and export names are not supported when the '--module' flag is set to 'es2015' or 'es2020'. ++ if (valueY !== "someValue") throw "should be someValue"; ++ ++ export * as "" from "./arbitraryModuleNamespaceIdentifiers_module"; ++ ~~~~~ ++!!! error TS18057: String literal import and export names are not supported when the '--module' flag is set to 'es2015' or 'es2020'. ++ import { "" as valueZ } from "./arbitraryModuleNamespaceIdentifiers_module"; ++ ~~~~~ ++!!! error TS18057: String literal import and export names are not supported when the '--module' flag is set to 'es2015' or 'es2020'. ++ if (valueZ[""] !== "someValue") throw "should be someValue"; ++ if (valueZ[""] !== "someValue") throw "should be someValue"; ++ if (valueZ[""] !== valueZ) throw "should be export namespace"; ++ ++ export { type someType as "" }; ++ ~~~~~ ++!!! error TS18057: String literal import and export names are not supported when the '--module' flag is set to 'es2015' or 'es2020'. ++ import { type "" as typeA } from "./arbitraryModuleNamespaceIdentifiers_module"; ++ ~~~~~ ++!!! error TS18057: String literal import and export names are not supported when the '--module' flag is set to 'es2015' or 'es2020'. ++ const importTest: typeA = "expect error about someType"; ++ ~~~~~~~~~~ ++!!! error TS2322: Type '"expect error about someType"' is not assignable to type '"someType"'. ++ ++ export { type "" as "" } from "./arbitraryModuleNamespaceIdentifiers_module"; ++ ~~~~~ ++!!! error TS18057: String literal import and export names are not supported when the '--module' flag is set to 'es2015' or 'es2020'. ++ ~~~~~ ++!!! error TS18057: String literal import and export names are not supported when the '--module' flag is set to 'es2015' or 'es2020'. ++ import { type "" as typeB } from "./arbitraryModuleNamespaceIdentifiers_module"; ++ ~~~~~ ++!!! error TS18057: String literal import and export names are not supported when the '--module' flag is set to 'es2015' or 'es2020'. ++ const reimportTest: typeB = "expect error about someType"; ++ ~~~~~~~~~~~~ ++!!! error TS2322: Type '"expect error about someType"' is not assignable to type '"someType"'. ++ ++ export type * as "" from "./arbitraryModuleNamespaceIdentifiers_module"; ++ ~~~~~ ++!!! error TS18057: String literal import and export names are not supported when the '--module' flag is set to 'es2015' or 'es2020'. ++ import { type "" as typeC } from "./arbitraryModuleNamespaceIdentifiers_module"; ++ ~~~~~ ++!!! error TS18057: String literal import and export names are not supported when the '--module' flag is set to 'es2015' or 'es2020'. ++ export type otherType = "otherType"; ++ const importStarTestA: typeC.otherType = "expect error about otherType"; ++ ~~~~~~~~~~~~~~~ ++!!! error TS2322: Type '"expect error about otherType"' is not assignable to type '"otherType"'. ++ +\ No newline at end of file +diff --git a/tests/baselines/reference/arbitraryModuleNamespaceIdentifiers_module(module=es2020).js b/tests/baselines/reference/arbitraryModuleNamespaceIdentifiers_module(module=es2020).js +new file mode 100644 +index 000000000..4964f684a +--- /dev/null ++++ b/tests/baselines/reference/arbitraryModuleNamespaceIdentifiers_module(module=es2020).js +@@ -0,0 +1,67 @@ ++//// [tests/cases/conformance/es2022/arbitraryModuleNamespaceIdentifiers/arbitraryModuleNamespaceIdentifiers_module.ts] //// ++ ++//// [arbitraryModuleNamespaceIdentifiers_module.ts] ++const someValue = "someValue"; ++type someType = "someType"; ++ ++export { someValue as "" }; ++import { "" as valueX } from "./arbitraryModuleNamespaceIdentifiers_module"; ++if (valueX !== "someValue") throw "should be someValue"; ++ ++export { "" as "" } from "./arbitraryModuleNamespaceIdentifiers_module"; ++import { "" as valueY } from "./arbitraryModuleNamespaceIdentifiers_module"; ++if (valueY !== "someValue") throw "should be someValue"; ++ ++export * as "" from "./arbitraryModuleNamespaceIdentifiers_module"; ++import { "" as valueZ } from "./arbitraryModuleNamespaceIdentifiers_module"; ++if (valueZ[""] !== "someValue") throw "should be someValue"; ++if (valueZ[""] !== "someValue") throw "should be someValue"; ++if (valueZ[""] !== valueZ) throw "should be export namespace"; ++ ++export { type someType as "" }; ++import { type "" as typeA } from "./arbitraryModuleNamespaceIdentifiers_module"; ++const importTest: typeA = "expect error about someType"; ++ ++export { type "" as "" } from "./arbitraryModuleNamespaceIdentifiers_module"; ++import { type "" as typeB } from "./arbitraryModuleNamespaceIdentifiers_module"; ++const reimportTest: typeB = "expect error about someType"; ++ ++export type * as "" from "./arbitraryModuleNamespaceIdentifiers_module"; ++import { type "" as typeC } from "./arbitraryModuleNamespaceIdentifiers_module"; ++export type otherType = "otherType"; ++const importStarTestA: typeC.otherType = "expect error about otherType"; ++ ++ ++//// [arbitraryModuleNamespaceIdentifiers_module.js] ++const someValue = "someValue"; ++export { someValue as "" }; ++import { "" as valueX } from "./arbitraryModuleNamespaceIdentifiers_module"; ++if (valueX !== "someValue") ++ throw "should be someValue"; ++export { "" as "" } from "./arbitraryModuleNamespaceIdentifiers_module"; ++import { "" as valueY } from "./arbitraryModuleNamespaceIdentifiers_module"; ++if (valueY !== "someValue") ++ throw "should be someValue"; ++export * as "" from "./arbitraryModuleNamespaceIdentifiers_module"; ++import { "" as valueZ } from "./arbitraryModuleNamespaceIdentifiers_module"; ++if (valueZ[""] !== "someValue") ++ throw "should be someValue"; ++if (valueZ[""] !== "someValue") ++ throw "should be someValue"; ++if (valueZ[""] !== valueZ) ++ throw "should be export namespace"; ++const importTest = "expect error about someType"; ++const reimportTest = "expect error about someType"; ++const importStarTestA = "expect error about otherType"; ++ ++ ++//// [arbitraryModuleNamespaceIdentifiers_module.d.ts] ++declare const someValue = "someValue"; ++type someType = "someType"; ++export { someValue as "" }; ++export { "" as "" } from "./arbitraryModuleNamespaceIdentifiers_module"; ++export * as "" from "./arbitraryModuleNamespaceIdentifiers_module"; ++export { type someType as "" }; ++export { type "" as "" } from "./arbitraryModuleNamespaceIdentifiers_module"; ++export type * as "" from "./arbitraryModuleNamespaceIdentifiers_module"; ++export type otherType = "otherType"; +diff --git a/tests/baselines/reference/arbitraryModuleNamespaceIdentifiers_module(module=es2020).symbols b/tests/baselines/reference/arbitraryModuleNamespaceIdentifiers_module(module=es2020).symbols +new file mode 100644 +index 000000000..a792b7d3f +--- /dev/null ++++ b/tests/baselines/reference/arbitraryModuleNamespaceIdentifiers_module(module=es2020).symbols +@@ -0,0 +1,82 @@ ++//// [tests/cases/conformance/es2022/arbitraryModuleNamespaceIdentifiers/arbitraryModuleNamespaceIdentifiers_module.ts] //// ++ ++=== arbitraryModuleNamespaceIdentifiers_module.ts === ++const someValue = "someValue"; ++>someValue : Symbol(someValue, Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 0, 5)) ++ ++type someType = "someType"; ++>someType : Symbol(someType, Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 0, 30)) ++ ++export { someValue as "" }; ++>someValue : Symbol(someValue, Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 0, 5)) ++>"" : Symbol(valueZ[""], Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 3, 8)) ++ ++import { "" as valueX } from "./arbitraryModuleNamespaceIdentifiers_module"; ++>valueX : Symbol(valueX, Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 4, 8)) ++ ++if (valueX !== "someValue") throw "should be someValue"; ++>valueX : Symbol(valueX, Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 4, 8)) ++ ++export { "" as "" } from "./arbitraryModuleNamespaceIdentifiers_module"; ++>"" : Symbol(valueZ[""], Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 7, 8)) ++ ++import { "" as valueY } from "./arbitraryModuleNamespaceIdentifiers_module"; ++>valueY : Symbol(valueY, Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 8, 8)) ++ ++if (valueY !== "someValue") throw "should be someValue"; ++>valueY : Symbol(valueY, Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 8, 8)) ++ ++export * as "" from "./arbitraryModuleNamespaceIdentifiers_module"; ++>"" : Symbol(valueZ[""], Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 11, 6)) ++ ++import { "" as valueZ } from "./arbitraryModuleNamespaceIdentifiers_module"; ++>valueZ : Symbol(valueZ, Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 12, 8)) ++ ++if (valueZ[""] !== "someValue") throw "should be someValue"; ++>valueZ : Symbol(valueZ, Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 12, 8)) ++>"" : Symbol(valueZ[""], Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 3, 8)) ++ ++if (valueZ[""] !== "someValue") throw "should be someValue"; ++>valueZ : Symbol(valueZ, Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 12, 8)) ++>"" : Symbol(valueZ[""], Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 7, 8)) ++ ++if (valueZ[""] !== valueZ) throw "should be export namespace"; ++>valueZ : Symbol(valueZ, Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 12, 8)) ++>"" : Symbol(valueZ[""], Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 11, 6)) ++>valueZ : Symbol(valueZ, Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 12, 8)) ++ ++export { type someType as "" }; ++>someType : Symbol(someType, Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 0, 30)) ++>"" : Symbol(valueZ[""], Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 17, 8)) ++ ++import { type "" as typeA } from "./arbitraryModuleNamespaceIdentifiers_module"; ++>typeA : Symbol(typeA, Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 18, 8)) ++ ++const importTest: typeA = "expect error about someType"; ++>importTest : Symbol(importTest, Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 19, 5)) ++>typeA : Symbol(typeA, Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 18, 8)) ++ ++export { type "" as "" } from "./arbitraryModuleNamespaceIdentifiers_module"; ++>"" : Symbol(valueZ[""], Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 21, 8)) ++ ++import { type "" as typeB } from "./arbitraryModuleNamespaceIdentifiers_module"; ++>typeB : Symbol(typeB, Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 22, 8)) ++ ++const reimportTest: typeB = "expect error about someType"; ++>reimportTest : Symbol(reimportTest, Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 23, 5)) ++>typeB : Symbol(typeB, Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 22, 8)) ++ ++export type * as "" from "./arbitraryModuleNamespaceIdentifiers_module"; ++>"" : Symbol(valueZ[""], Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 25, 11)) ++ ++import { type "" as typeC } from "./arbitraryModuleNamespaceIdentifiers_module"; ++>typeC : Symbol(typeC, Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 26, 8)) ++ ++export type otherType = "otherType"; ++>otherType : Symbol(valueZ.otherType, Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 26, 83)) ++ ++const importStarTestA: typeC.otherType = "expect error about otherType"; ++>importStarTestA : Symbol(importStarTestA, Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 28, 5)) ++>typeC : Symbol(typeC, Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 26, 8)) ++>otherType : Symbol(valueZ.otherType, Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 26, 83)) ++ +diff --git a/tests/baselines/reference/arbitraryModuleNamespaceIdentifiers_module(module=es2020).types b/tests/baselines/reference/arbitraryModuleNamespaceIdentifiers_module(module=es2020).types +new file mode 100644 +index 000000000..4574f9754 +--- /dev/null ++++ b/tests/baselines/reference/arbitraryModuleNamespaceIdentifiers_module(module=es2020).types +@@ -0,0 +1,151 @@ ++//// [tests/cases/conformance/es2022/arbitraryModuleNamespaceIdentifiers/arbitraryModuleNamespaceIdentifiers_module.ts] //// ++ ++=== arbitraryModuleNamespaceIdentifiers_module.ts === ++const someValue = "someValue"; ++>someValue : "someValue" ++> : ^^^^^^^^^^^ ++>"someValue" : "someValue" ++> : ^^^^^^^^^^^ ++ ++type someType = "someType"; ++>someType : "someType" ++> : ^^^^^^^^^^ ++ ++export { someValue as "" }; ++>someValue : "someValue" ++> : ^^^^^^^^^^^ ++>"" : "someValue" ++> : ^^^^^^^^^^^ ++ ++import { "" as valueX } from "./arbitraryModuleNamespaceIdentifiers_module"; ++>valueX : "someValue" ++> : ^^^^^^^^^^^ ++ ++if (valueX !== "someValue") throw "should be someValue"; ++>valueX !== "someValue" : boolean ++> : ^^^^^^^ ++>valueX : "someValue" ++> : ^^^^^^^^^^^ ++>"someValue" : "someValue" ++> : ^^^^^^^^^^^ ++>"should be someValue" : "should be someValue" ++> : ^^^^^^^^^^^^^^^^^^^^^ ++ ++export { "" as "" } from "./arbitraryModuleNamespaceIdentifiers_module"; ++>"" : "someValue" ++> : ^^^^^^^^^^^ ++ ++import { "" as valueY } from "./arbitraryModuleNamespaceIdentifiers_module"; ++>valueY : "someValue" ++> : ^^^^^^^^^^^ ++ ++if (valueY !== "someValue") throw "should be someValue"; ++>valueY !== "someValue" : boolean ++> : ^^^^^^^ ++>valueY : "someValue" ++> : ^^^^^^^^^^^ ++>"someValue" : "someValue" ++> : ^^^^^^^^^^^ ++>"should be someValue" : "should be someValue" ++> : ^^^^^^^^^^^^^^^^^^^^^ ++ ++export * as "" from "./arbitraryModuleNamespaceIdentifiers_module"; ++>"" : typeof valueZ ++> : ^^^^^^^^^^^^^ ++ ++import { "" as valueZ } from "./arbitraryModuleNamespaceIdentifiers_module"; ++>valueZ : typeof valueZ ++> : ^^^^^^^^^^^^^ ++ ++if (valueZ[""] !== "someValue") throw "should be someValue"; ++>valueZ[""] !== "someValue" : boolean ++> : ^^^^^^^ ++>valueZ[""] : "someValue" ++> : ^^^^^^^^^^^ ++>valueZ : typeof valueZ ++> : ^^^^^^^^^^^^^ ++>"" : "" ++> : ^^^^^ ++>"someValue" : "someValue" ++> : ^^^^^^^^^^^ ++>"should be someValue" : "should be someValue" ++> : ^^^^^^^^^^^^^^^^^^^^^ ++ ++if (valueZ[""] !== "someValue") throw "should be someValue"; ++>valueZ[""] !== "someValue" : boolean ++> : ^^^^^^^ ++>valueZ[""] : "someValue" ++> : ^^^^^^^^^^^ ++>valueZ : typeof valueZ ++> : ^^^^^^^^^^^^^ ++>"" : "" ++> : ^^^^^ ++>"someValue" : "someValue" ++> : ^^^^^^^^^^^ ++>"should be someValue" : "should be someValue" ++> : ^^^^^^^^^^^^^^^^^^^^^ ++ ++if (valueZ[""] !== valueZ) throw "should be export namespace"; ++>valueZ[""] !== valueZ : boolean ++> : ^^^^^^^ ++>valueZ[""] : typeof valueZ ++> : ^^^^^^^^^^^^^ ++>valueZ : typeof valueZ ++> : ^^^^^^^^^^^^^ ++>"" : "" ++> : ^^^^^ ++>valueZ : typeof valueZ ++> : ^^^^^^^^^^^^^ ++>"should be export namespace" : "should be export namespace" ++> : ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ++ ++export { type someType as "" }; ++>someType : any ++> : ^^^ ++>"" : any ++> : ^^^ ++ ++import { type "" as typeA } from "./arbitraryModuleNamespaceIdentifiers_module"; ++>typeA : any ++> : ^^^ ++ ++const importTest: typeA = "expect error about someType"; ++>importTest : "someType" ++> : ^^^^^^^^^^ ++>"expect error about someType" : "expect error about someType" ++> : ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ++ ++export { type "" as "" } from "./arbitraryModuleNamespaceIdentifiers_module"; ++>"" : any ++> : ^^^ ++ ++import { type "" as typeB } from "./arbitraryModuleNamespaceIdentifiers_module"; ++>typeB : any ++> : ^^^ ++ ++const reimportTest: typeB = "expect error about someType"; ++>reimportTest : "someType" ++> : ^^^^^^^^^^ ++>"expect error about someType" : "expect error about someType" ++> : ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ++ ++export type * as "" from "./arbitraryModuleNamespaceIdentifiers_module"; ++>"" : typeof valueZ ++> : ^^^^^^^^^^^^^ ++ ++import { type "" as typeC } from "./arbitraryModuleNamespaceIdentifiers_module"; ++>typeC : typeof valueZ ++> : ^^^^^^^^^^^^^ ++ ++export type otherType = "otherType"; ++>otherType : "otherType" ++> : ^^^^^^^^^^^ ++ ++const importStarTestA: typeC.otherType = "expect error about otherType"; ++>importStarTestA : "otherType" ++> : ^^^^^^^^^^^ ++>typeC : any ++> : ^^^ ++>"expect error about otherType" : "expect error about otherType" ++> : ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ++ +diff --git a/tests/baselines/reference/arbitraryModuleNamespaceIdentifiers_module(module=es2022).errors.txt b/tests/baselines/reference/arbitraryModuleNamespaceIdentifiers_module(module=es2022).errors.txt +new file mode 100644 +index 000000000..cc359bceb +--- /dev/null ++++ b/tests/baselines/reference/arbitraryModuleNamespaceIdentifiers_module(module=es2022).errors.txt +@@ -0,0 +1,42 @@ ++arbitraryModuleNamespaceIdentifiers_module.ts(20,7): error TS2322: Type '"expect error about someType"' is not assignable to type '"someType"'. ++arbitraryModuleNamespaceIdentifiers_module.ts(24,7): error TS2322: Type '"expect error about someType"' is not assignable to type '"someType"'. ++arbitraryModuleNamespaceIdentifiers_module.ts(29,7): error TS2322: Type '"expect error about otherType"' is not assignable to type '"otherType"'. ++ ++ ++==== arbitraryModuleNamespaceIdentifiers_module.ts (3 errors) ==== ++ const someValue = "someValue"; ++ type someType = "someType"; ++ ++ export { someValue as "" }; ++ import { "" as valueX } from "./arbitraryModuleNamespaceIdentifiers_module"; ++ if (valueX !== "someValue") throw "should be someValue"; ++ ++ export { "" as "" } from "./arbitraryModuleNamespaceIdentifiers_module"; ++ import { "" as valueY } from "./arbitraryModuleNamespaceIdentifiers_module"; ++ if (valueY !== "someValue") throw "should be someValue"; ++ ++ export * as "" from "./arbitraryModuleNamespaceIdentifiers_module"; ++ import { "" as valueZ } from "./arbitraryModuleNamespaceIdentifiers_module"; ++ if (valueZ[""] !== "someValue") throw "should be someValue"; ++ if (valueZ[""] !== "someValue") throw "should be someValue"; ++ if (valueZ[""] !== valueZ) throw "should be export namespace"; ++ ++ export { type someType as "" }; ++ import { type "" as typeA } from "./arbitraryModuleNamespaceIdentifiers_module"; ++ const importTest: typeA = "expect error about someType"; ++ ~~~~~~~~~~ ++!!! error TS2322: Type '"expect error about someType"' is not assignable to type '"someType"'. ++ ++ export { type "" as "" } from "./arbitraryModuleNamespaceIdentifiers_module"; ++ import { type "" as typeB } from "./arbitraryModuleNamespaceIdentifiers_module"; ++ const reimportTest: typeB = "expect error about someType"; ++ ~~~~~~~~~~~~ ++!!! error TS2322: Type '"expect error about someType"' is not assignable to type '"someType"'. ++ ++ export type * as "" from "./arbitraryModuleNamespaceIdentifiers_module"; ++ import { type "" as typeC } from "./arbitraryModuleNamespaceIdentifiers_module"; ++ export type otherType = "otherType"; ++ const importStarTestA: typeC.otherType = "expect error about otherType"; ++ ~~~~~~~~~~~~~~~ ++!!! error TS2322: Type '"expect error about otherType"' is not assignable to type '"otherType"'. ++ +\ No newline at end of file +diff --git a/tests/baselines/reference/arbitraryModuleNamespaceIdentifiers_module(module=es2022).js b/tests/baselines/reference/arbitraryModuleNamespaceIdentifiers_module(module=es2022).js +new file mode 100644 +index 000000000..4964f684a +--- /dev/null ++++ b/tests/baselines/reference/arbitraryModuleNamespaceIdentifiers_module(module=es2022).js +@@ -0,0 +1,67 @@ ++//// [tests/cases/conformance/es2022/arbitraryModuleNamespaceIdentifiers/arbitraryModuleNamespaceIdentifiers_module.ts] //// ++ ++//// [arbitraryModuleNamespaceIdentifiers_module.ts] ++const someValue = "someValue"; ++type someType = "someType"; ++ ++export { someValue as "" }; ++import { "" as valueX } from "./arbitraryModuleNamespaceIdentifiers_module"; ++if (valueX !== "someValue") throw "should be someValue"; ++ ++export { "" as "" } from "./arbitraryModuleNamespaceIdentifiers_module"; ++import { "" as valueY } from "./arbitraryModuleNamespaceIdentifiers_module"; ++if (valueY !== "someValue") throw "should be someValue"; ++ ++export * as "" from "./arbitraryModuleNamespaceIdentifiers_module"; ++import { "" as valueZ } from "./arbitraryModuleNamespaceIdentifiers_module"; ++if (valueZ[""] !== "someValue") throw "should be someValue"; ++if (valueZ[""] !== "someValue") throw "should be someValue"; ++if (valueZ[""] !== valueZ) throw "should be export namespace"; ++ ++export { type someType as "" }; ++import { type "" as typeA } from "./arbitraryModuleNamespaceIdentifiers_module"; ++const importTest: typeA = "expect error about someType"; ++ ++export { type "" as "" } from "./arbitraryModuleNamespaceIdentifiers_module"; ++import { type "" as typeB } from "./arbitraryModuleNamespaceIdentifiers_module"; ++const reimportTest: typeB = "expect error about someType"; ++ ++export type * as "" from "./arbitraryModuleNamespaceIdentifiers_module"; ++import { type "" as typeC } from "./arbitraryModuleNamespaceIdentifiers_module"; ++export type otherType = "otherType"; ++const importStarTestA: typeC.otherType = "expect error about otherType"; ++ ++ ++//// [arbitraryModuleNamespaceIdentifiers_module.js] ++const someValue = "someValue"; ++export { someValue as "" }; ++import { "" as valueX } from "./arbitraryModuleNamespaceIdentifiers_module"; ++if (valueX !== "someValue") ++ throw "should be someValue"; ++export { "" as "" } from "./arbitraryModuleNamespaceIdentifiers_module"; ++import { "" as valueY } from "./arbitraryModuleNamespaceIdentifiers_module"; ++if (valueY !== "someValue") ++ throw "should be someValue"; ++export * as "" from "./arbitraryModuleNamespaceIdentifiers_module"; ++import { "" as valueZ } from "./arbitraryModuleNamespaceIdentifiers_module"; ++if (valueZ[""] !== "someValue") ++ throw "should be someValue"; ++if (valueZ[""] !== "someValue") ++ throw "should be someValue"; ++if (valueZ[""] !== valueZ) ++ throw "should be export namespace"; ++const importTest = "expect error about someType"; ++const reimportTest = "expect error about someType"; ++const importStarTestA = "expect error about otherType"; ++ ++ ++//// [arbitraryModuleNamespaceIdentifiers_module.d.ts] ++declare const someValue = "someValue"; ++type someType = "someType"; ++export { someValue as "" }; ++export { "" as "" } from "./arbitraryModuleNamespaceIdentifiers_module"; ++export * as "" from "./arbitraryModuleNamespaceIdentifiers_module"; ++export { type someType as "" }; ++export { type "" as "" } from "./arbitraryModuleNamespaceIdentifiers_module"; ++export type * as "" from "./arbitraryModuleNamespaceIdentifiers_module"; ++export type otherType = "otherType"; +diff --git a/tests/baselines/reference/arbitraryModuleNamespaceIdentifiers_module(module=es2022).symbols b/tests/baselines/reference/arbitraryModuleNamespaceIdentifiers_module(module=es2022).symbols +new file mode 100644 +index 000000000..a792b7d3f +--- /dev/null ++++ b/tests/baselines/reference/arbitraryModuleNamespaceIdentifiers_module(module=es2022).symbols +@@ -0,0 +1,82 @@ ++//// [tests/cases/conformance/es2022/arbitraryModuleNamespaceIdentifiers/arbitraryModuleNamespaceIdentifiers_module.ts] //// ++ ++=== arbitraryModuleNamespaceIdentifiers_module.ts === ++const someValue = "someValue"; ++>someValue : Symbol(someValue, Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 0, 5)) ++ ++type someType = "someType"; ++>someType : Symbol(someType, Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 0, 30)) ++ ++export { someValue as "" }; ++>someValue : Symbol(someValue, Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 0, 5)) ++>"" : Symbol(valueZ[""], Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 3, 8)) ++ ++import { "" as valueX } from "./arbitraryModuleNamespaceIdentifiers_module"; ++>valueX : Symbol(valueX, Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 4, 8)) ++ ++if (valueX !== "someValue") throw "should be someValue"; ++>valueX : Symbol(valueX, Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 4, 8)) ++ ++export { "" as "" } from "./arbitraryModuleNamespaceIdentifiers_module"; ++>"" : Symbol(valueZ[""], Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 7, 8)) ++ ++import { "" as valueY } from "./arbitraryModuleNamespaceIdentifiers_module"; ++>valueY : Symbol(valueY, Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 8, 8)) ++ ++if (valueY !== "someValue") throw "should be someValue"; ++>valueY : Symbol(valueY, Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 8, 8)) ++ ++export * as "" from "./arbitraryModuleNamespaceIdentifiers_module"; ++>"" : Symbol(valueZ[""], Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 11, 6)) ++ ++import { "" as valueZ } from "./arbitraryModuleNamespaceIdentifiers_module"; ++>valueZ : Symbol(valueZ, Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 12, 8)) ++ ++if (valueZ[""] !== "someValue") throw "should be someValue"; ++>valueZ : Symbol(valueZ, Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 12, 8)) ++>"" : Symbol(valueZ[""], Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 3, 8)) ++ ++if (valueZ[""] !== "someValue") throw "should be someValue"; ++>valueZ : Symbol(valueZ, Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 12, 8)) ++>"" : Symbol(valueZ[""], Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 7, 8)) ++ ++if (valueZ[""] !== valueZ) throw "should be export namespace"; ++>valueZ : Symbol(valueZ, Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 12, 8)) ++>"" : Symbol(valueZ[""], Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 11, 6)) ++>valueZ : Symbol(valueZ, Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 12, 8)) ++ ++export { type someType as "" }; ++>someType : Symbol(someType, Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 0, 30)) ++>"" : Symbol(valueZ[""], Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 17, 8)) ++ ++import { type "" as typeA } from "./arbitraryModuleNamespaceIdentifiers_module"; ++>typeA : Symbol(typeA, Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 18, 8)) ++ ++const importTest: typeA = "expect error about someType"; ++>importTest : Symbol(importTest, Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 19, 5)) ++>typeA : Symbol(typeA, Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 18, 8)) ++ ++export { type "" as "" } from "./arbitraryModuleNamespaceIdentifiers_module"; ++>"" : Symbol(valueZ[""], Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 21, 8)) ++ ++import { type "" as typeB } from "./arbitraryModuleNamespaceIdentifiers_module"; ++>typeB : Symbol(typeB, Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 22, 8)) ++ ++const reimportTest: typeB = "expect error about someType"; ++>reimportTest : Symbol(reimportTest, Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 23, 5)) ++>typeB : Symbol(typeB, Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 22, 8)) ++ ++export type * as "" from "./arbitraryModuleNamespaceIdentifiers_module"; ++>"" : Symbol(valueZ[""], Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 25, 11)) ++ ++import { type "" as typeC } from "./arbitraryModuleNamespaceIdentifiers_module"; ++>typeC : Symbol(typeC, Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 26, 8)) ++ ++export type otherType = "otherType"; ++>otherType : Symbol(valueZ.otherType, Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 26, 83)) ++ ++const importStarTestA: typeC.otherType = "expect error about otherType"; ++>importStarTestA : Symbol(importStarTestA, Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 28, 5)) ++>typeC : Symbol(typeC, Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 26, 8)) ++>otherType : Symbol(valueZ.otherType, Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 26, 83)) ++ +diff --git a/tests/baselines/reference/arbitraryModuleNamespaceIdentifiers_module(module=es2022).types b/tests/baselines/reference/arbitraryModuleNamespaceIdentifiers_module(module=es2022).types +new file mode 100644 +index 000000000..4574f9754 +--- /dev/null ++++ b/tests/baselines/reference/arbitraryModuleNamespaceIdentifiers_module(module=es2022).types +@@ -0,0 +1,151 @@ ++//// [tests/cases/conformance/es2022/arbitraryModuleNamespaceIdentifiers/arbitraryModuleNamespaceIdentifiers_module.ts] //// ++ ++=== arbitraryModuleNamespaceIdentifiers_module.ts === ++const someValue = "someValue"; ++>someValue : "someValue" ++> : ^^^^^^^^^^^ ++>"someValue" : "someValue" ++> : ^^^^^^^^^^^ ++ ++type someType = "someType"; ++>someType : "someType" ++> : ^^^^^^^^^^ ++ ++export { someValue as "" }; ++>someValue : "someValue" ++> : ^^^^^^^^^^^ ++>"" : "someValue" ++> : ^^^^^^^^^^^ ++ ++import { "" as valueX } from "./arbitraryModuleNamespaceIdentifiers_module"; ++>valueX : "someValue" ++> : ^^^^^^^^^^^ ++ ++if (valueX !== "someValue") throw "should be someValue"; ++>valueX !== "someValue" : boolean ++> : ^^^^^^^ ++>valueX : "someValue" ++> : ^^^^^^^^^^^ ++>"someValue" : "someValue" ++> : ^^^^^^^^^^^ ++>"should be someValue" : "should be someValue" ++> : ^^^^^^^^^^^^^^^^^^^^^ ++ ++export { "" as "" } from "./arbitraryModuleNamespaceIdentifiers_module"; ++>"" : "someValue" ++> : ^^^^^^^^^^^ ++ ++import { "" as valueY } from "./arbitraryModuleNamespaceIdentifiers_module"; ++>valueY : "someValue" ++> : ^^^^^^^^^^^ ++ ++if (valueY !== "someValue") throw "should be someValue"; ++>valueY !== "someValue" : boolean ++> : ^^^^^^^ ++>valueY : "someValue" ++> : ^^^^^^^^^^^ ++>"someValue" : "someValue" ++> : ^^^^^^^^^^^ ++>"should be someValue" : "should be someValue" ++> : ^^^^^^^^^^^^^^^^^^^^^ ++ ++export * as "" from "./arbitraryModuleNamespaceIdentifiers_module"; ++>"" : typeof valueZ ++> : ^^^^^^^^^^^^^ ++ ++import { "" as valueZ } from "./arbitraryModuleNamespaceIdentifiers_module"; ++>valueZ : typeof valueZ ++> : ^^^^^^^^^^^^^ ++ ++if (valueZ[""] !== "someValue") throw "should be someValue"; ++>valueZ[""] !== "someValue" : boolean ++> : ^^^^^^^ ++>valueZ[""] : "someValue" ++> : ^^^^^^^^^^^ ++>valueZ : typeof valueZ ++> : ^^^^^^^^^^^^^ ++>"" : "" ++> : ^^^^^ ++>"someValue" : "someValue" ++> : ^^^^^^^^^^^ ++>"should be someValue" : "should be someValue" ++> : ^^^^^^^^^^^^^^^^^^^^^ ++ ++if (valueZ[""] !== "someValue") throw "should be someValue"; ++>valueZ[""] !== "someValue" : boolean ++> : ^^^^^^^ ++>valueZ[""] : "someValue" ++> : ^^^^^^^^^^^ ++>valueZ : typeof valueZ ++> : ^^^^^^^^^^^^^ ++>"" : "" ++> : ^^^^^ ++>"someValue" : "someValue" ++> : ^^^^^^^^^^^ ++>"should be someValue" : "should be someValue" ++> : ^^^^^^^^^^^^^^^^^^^^^ ++ ++if (valueZ[""] !== valueZ) throw "should be export namespace"; ++>valueZ[""] !== valueZ : boolean ++> : ^^^^^^^ ++>valueZ[""] : typeof valueZ ++> : ^^^^^^^^^^^^^ ++>valueZ : typeof valueZ ++> : ^^^^^^^^^^^^^ ++>"" : "" ++> : ^^^^^ ++>valueZ : typeof valueZ ++> : ^^^^^^^^^^^^^ ++>"should be export namespace" : "should be export namespace" ++> : ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ++ ++export { type someType as "" }; ++>someType : any ++> : ^^^ ++>"" : any ++> : ^^^ ++ ++import { type "" as typeA } from "./arbitraryModuleNamespaceIdentifiers_module"; ++>typeA : any ++> : ^^^ ++ ++const importTest: typeA = "expect error about someType"; ++>importTest : "someType" ++> : ^^^^^^^^^^ ++>"expect error about someType" : "expect error about someType" ++> : ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ++ ++export { type "" as "" } from "./arbitraryModuleNamespaceIdentifiers_module"; ++>"" : any ++> : ^^^ ++ ++import { type "" as typeB } from "./arbitraryModuleNamespaceIdentifiers_module"; ++>typeB : any ++> : ^^^ ++ ++const reimportTest: typeB = "expect error about someType"; ++>reimportTest : "someType" ++> : ^^^^^^^^^^ ++>"expect error about someType" : "expect error about someType" ++> : ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ++ ++export type * as "" from "./arbitraryModuleNamespaceIdentifiers_module"; ++>"" : typeof valueZ ++> : ^^^^^^^^^^^^^ ++ ++import { type "" as typeC } from "./arbitraryModuleNamespaceIdentifiers_module"; ++>typeC : typeof valueZ ++> : ^^^^^^^^^^^^^ ++ ++export type otherType = "otherType"; ++>otherType : "otherType" ++> : ^^^^^^^^^^^ ++ ++const importStarTestA: typeC.otherType = "expect error about otherType"; ++>importStarTestA : "otherType" ++> : ^^^^^^^^^^^ ++>typeC : any ++> : ^^^ ++>"expect error about otherType" : "expect error about otherType" ++> : ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ++ +diff --git a/tests/baselines/reference/arbitraryModuleNamespaceIdentifiers_module(module=es6).errors.txt b/tests/baselines/reference/arbitraryModuleNamespaceIdentifiers_module(module=es6).errors.txt +new file mode 100644 +index 000000000..e2a851b5a +--- /dev/null ++++ b/tests/baselines/reference/arbitraryModuleNamespaceIdentifiers_module(module=es6).errors.txt +@@ -0,0 +1,84 @@ ++arbitraryModuleNamespaceIdentifiers_module.ts(4,23): error TS18057: String literal import and export names are not supported when the '--module' flag is set to 'es2015' or 'es2020'. ++arbitraryModuleNamespaceIdentifiers_module.ts(5,10): error TS18057: String literal import and export names are not supported when the '--module' flag is set to 'es2015' or 'es2020'. ++arbitraryModuleNamespaceIdentifiers_module.ts(8,10): error TS18057: String literal import and export names are not supported when the '--module' flag is set to 'es2015' or 'es2020'. ++arbitraryModuleNamespaceIdentifiers_module.ts(8,19): error TS18057: String literal import and export names are not supported when the '--module' flag is set to 'es2015' or 'es2020'. ++arbitraryModuleNamespaceIdentifiers_module.ts(9,10): error TS18057: String literal import and export names are not supported when the '--module' flag is set to 'es2015' or 'es2020'. ++arbitraryModuleNamespaceIdentifiers_module.ts(12,13): error TS18057: String literal import and export names are not supported when the '--module' flag is set to 'es2015' or 'es2020'. ++arbitraryModuleNamespaceIdentifiers_module.ts(13,10): error TS18057: String literal import and export names are not supported when the '--module' flag is set to 'es2015' or 'es2020'. ++arbitraryModuleNamespaceIdentifiers_module.ts(18,27): error TS18057: String literal import and export names are not supported when the '--module' flag is set to 'es2015' or 'es2020'. ++arbitraryModuleNamespaceIdentifiers_module.ts(19,15): error TS18057: String literal import and export names are not supported when the '--module' flag is set to 'es2015' or 'es2020'. ++arbitraryModuleNamespaceIdentifiers_module.ts(20,7): error TS2322: Type '"expect error about someType"' is not assignable to type '"someType"'. ++arbitraryModuleNamespaceIdentifiers_module.ts(22,15): error TS18057: String literal import and export names are not supported when the '--module' flag is set to 'es2015' or 'es2020'. ++arbitraryModuleNamespaceIdentifiers_module.ts(22,24): error TS18057: String literal import and export names are not supported when the '--module' flag is set to 'es2015' or 'es2020'. ++arbitraryModuleNamespaceIdentifiers_module.ts(23,15): error TS18057: String literal import and export names are not supported when the '--module' flag is set to 'es2015' or 'es2020'. ++arbitraryModuleNamespaceIdentifiers_module.ts(24,7): error TS2322: Type '"expect error about someType"' is not assignable to type '"someType"'. ++arbitraryModuleNamespaceIdentifiers_module.ts(26,18): error TS18057: String literal import and export names are not supported when the '--module' flag is set to 'es2015' or 'es2020'. ++arbitraryModuleNamespaceIdentifiers_module.ts(27,15): error TS18057: String literal import and export names are not supported when the '--module' flag is set to 'es2015' or 'es2020'. ++arbitraryModuleNamespaceIdentifiers_module.ts(29,7): error TS2322: Type '"expect error about otherType"' is not assignable to type '"otherType"'. ++ ++ ++==== arbitraryModuleNamespaceIdentifiers_module.ts (17 errors) ==== ++ const someValue = "someValue"; ++ type someType = "someType"; ++ ++ export { someValue as "" }; ++ ~~~~~ ++!!! error TS18057: String literal import and export names are not supported when the '--module' flag is set to 'es2015' or 'es2020'. ++ import { "" as valueX } from "./arbitraryModuleNamespaceIdentifiers_module"; ++ ~~~~~ ++!!! error TS18057: String literal import and export names are not supported when the '--module' flag is set to 'es2015' or 'es2020'. ++ if (valueX !== "someValue") throw "should be someValue"; ++ ++ export { "" as "" } from "./arbitraryModuleNamespaceIdentifiers_module"; ++ ~~~~~ ++!!! error TS18057: String literal import and export names are not supported when the '--module' flag is set to 'es2015' or 'es2020'. ++ ~~~~~ ++!!! error TS18057: String literal import and export names are not supported when the '--module' flag is set to 'es2015' or 'es2020'. ++ import { "" as valueY } from "./arbitraryModuleNamespaceIdentifiers_module"; ++ ~~~~~ ++!!! error TS18057: String literal import and export names are not supported when the '--module' flag is set to 'es2015' or 'es2020'. ++ if (valueY !== "someValue") throw "should be someValue"; ++ ++ export * as "" from "./arbitraryModuleNamespaceIdentifiers_module"; ++ ~~~~~ ++!!! error TS18057: String literal import and export names are not supported when the '--module' flag is set to 'es2015' or 'es2020'. ++ import { "" as valueZ } from "./arbitraryModuleNamespaceIdentifiers_module"; ++ ~~~~~ ++!!! error TS18057: String literal import and export names are not supported when the '--module' flag is set to 'es2015' or 'es2020'. ++ if (valueZ[""] !== "someValue") throw "should be someValue"; ++ if (valueZ[""] !== "someValue") throw "should be someValue"; ++ if (valueZ[""] !== valueZ) throw "should be export namespace"; ++ ++ export { type someType as "" }; ++ ~~~~~ ++!!! error TS18057: String literal import and export names are not supported when the '--module' flag is set to 'es2015' or 'es2020'. ++ import { type "" as typeA } from "./arbitraryModuleNamespaceIdentifiers_module"; ++ ~~~~~ ++!!! error TS18057: String literal import and export names are not supported when the '--module' flag is set to 'es2015' or 'es2020'. ++ const importTest: typeA = "expect error about someType"; ++ ~~~~~~~~~~ ++!!! error TS2322: Type '"expect error about someType"' is not assignable to type '"someType"'. ++ ++ export { type "" as "" } from "./arbitraryModuleNamespaceIdentifiers_module"; ++ ~~~~~ ++!!! error TS18057: String literal import and export names are not supported when the '--module' flag is set to 'es2015' or 'es2020'. ++ ~~~~~ ++!!! error TS18057: String literal import and export names are not supported when the '--module' flag is set to 'es2015' or 'es2020'. ++ import { type "" as typeB } from "./arbitraryModuleNamespaceIdentifiers_module"; ++ ~~~~~ ++!!! error TS18057: String literal import and export names are not supported when the '--module' flag is set to 'es2015' or 'es2020'. ++ const reimportTest: typeB = "expect error about someType"; ++ ~~~~~~~~~~~~ ++!!! error TS2322: Type '"expect error about someType"' is not assignable to type '"someType"'. ++ ++ export type * as "" from "./arbitraryModuleNamespaceIdentifiers_module"; ++ ~~~~~ ++!!! error TS18057: String literal import and export names are not supported when the '--module' flag is set to 'es2015' or 'es2020'. ++ import { type "" as typeC } from "./arbitraryModuleNamespaceIdentifiers_module"; ++ ~~~~~ ++!!! error TS18057: String literal import and export names are not supported when the '--module' flag is set to 'es2015' or 'es2020'. ++ export type otherType = "otherType"; ++ const importStarTestA: typeC.otherType = "expect error about otherType"; ++ ~~~~~~~~~~~~~~~ ++!!! error TS2322: Type '"expect error about otherType"' is not assignable to type '"otherType"'. ++ +\ No newline at end of file +diff --git a/tests/baselines/reference/arbitraryModuleNamespaceIdentifiers_module(module=es6).js b/tests/baselines/reference/arbitraryModuleNamespaceIdentifiers_module(module=es6).js +new file mode 100644 +index 000000000..d6a75c346 +--- /dev/null ++++ b/tests/baselines/reference/arbitraryModuleNamespaceIdentifiers_module(module=es6).js +@@ -0,0 +1,68 @@ ++//// [tests/cases/conformance/es2022/arbitraryModuleNamespaceIdentifiers/arbitraryModuleNamespaceIdentifiers_module.ts] //// ++ ++//// [arbitraryModuleNamespaceIdentifiers_module.ts] ++const someValue = "someValue"; ++type someType = "someType"; ++ ++export { someValue as "" }; ++import { "" as valueX } from "./arbitraryModuleNamespaceIdentifiers_module"; ++if (valueX !== "someValue") throw "should be someValue"; ++ ++export { "" as "" } from "./arbitraryModuleNamespaceIdentifiers_module"; ++import { "" as valueY } from "./arbitraryModuleNamespaceIdentifiers_module"; ++if (valueY !== "someValue") throw "should be someValue"; ++ ++export * as "" from "./arbitraryModuleNamespaceIdentifiers_module"; ++import { "" as valueZ } from "./arbitraryModuleNamespaceIdentifiers_module"; ++if (valueZ[""] !== "someValue") throw "should be someValue"; ++if (valueZ[""] !== "someValue") throw "should be someValue"; ++if (valueZ[""] !== valueZ) throw "should be export namespace"; ++ ++export { type someType as "" }; ++import { type "" as typeA } from "./arbitraryModuleNamespaceIdentifiers_module"; ++const importTest: typeA = "expect error about someType"; ++ ++export { type "" as "" } from "./arbitraryModuleNamespaceIdentifiers_module"; ++import { type "" as typeB } from "./arbitraryModuleNamespaceIdentifiers_module"; ++const reimportTest: typeB = "expect error about someType"; ++ ++export type * as "" from "./arbitraryModuleNamespaceIdentifiers_module"; ++import { type "" as typeC } from "./arbitraryModuleNamespaceIdentifiers_module"; ++export type otherType = "otherType"; ++const importStarTestA: typeC.otherType = "expect error about otherType"; ++ ++ ++//// [arbitraryModuleNamespaceIdentifiers_module.js] ++const someValue = "someValue"; ++export { someValue as "" }; ++import { "" as valueX } from "./arbitraryModuleNamespaceIdentifiers_module"; ++if (valueX !== "someValue") ++ throw "should be someValue"; ++export { "" as "" } from "./arbitraryModuleNamespaceIdentifiers_module"; ++import { "" as valueY } from "./arbitraryModuleNamespaceIdentifiers_module"; ++if (valueY !== "someValue") ++ throw "should be someValue"; ++import * as _a from "./arbitraryModuleNamespaceIdentifiers_module"; ++export { _a as "" }; ++import { "" as valueZ } from "./arbitraryModuleNamespaceIdentifiers_module"; ++if (valueZ[""] !== "someValue") ++ throw "should be someValue"; ++if (valueZ[""] !== "someValue") ++ throw "should be someValue"; ++if (valueZ[""] !== valueZ) ++ throw "should be export namespace"; ++const importTest = "expect error about someType"; ++const reimportTest = "expect error about someType"; ++const importStarTestA = "expect error about otherType"; ++ ++ ++//// [arbitraryModuleNamespaceIdentifiers_module.d.ts] ++declare const someValue = "someValue"; ++type someType = "someType"; ++export { someValue as "" }; ++export { "" as "" } from "./arbitraryModuleNamespaceIdentifiers_module"; ++export * as "" from "./arbitraryModuleNamespaceIdentifiers_module"; ++export { type someType as "" }; ++export { type "" as "" } from "./arbitraryModuleNamespaceIdentifiers_module"; ++export type * as "" from "./arbitraryModuleNamespaceIdentifiers_module"; ++export type otherType = "otherType"; +diff --git a/tests/baselines/reference/arbitraryModuleNamespaceIdentifiers_module(module=es6).symbols b/tests/baselines/reference/arbitraryModuleNamespaceIdentifiers_module(module=es6).symbols +new file mode 100644 +index 000000000..a792b7d3f +--- /dev/null ++++ b/tests/baselines/reference/arbitraryModuleNamespaceIdentifiers_module(module=es6).symbols +@@ -0,0 +1,82 @@ ++//// [tests/cases/conformance/es2022/arbitraryModuleNamespaceIdentifiers/arbitraryModuleNamespaceIdentifiers_module.ts] //// ++ ++=== arbitraryModuleNamespaceIdentifiers_module.ts === ++const someValue = "someValue"; ++>someValue : Symbol(someValue, Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 0, 5)) ++ ++type someType = "someType"; ++>someType : Symbol(someType, Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 0, 30)) ++ ++export { someValue as "" }; ++>someValue : Symbol(someValue, Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 0, 5)) ++>"" : Symbol(valueZ[""], Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 3, 8)) ++ ++import { "" as valueX } from "./arbitraryModuleNamespaceIdentifiers_module"; ++>valueX : Symbol(valueX, Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 4, 8)) ++ ++if (valueX !== "someValue") throw "should be someValue"; ++>valueX : Symbol(valueX, Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 4, 8)) ++ ++export { "" as "" } from "./arbitraryModuleNamespaceIdentifiers_module"; ++>"" : Symbol(valueZ[""], Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 7, 8)) ++ ++import { "" as valueY } from "./arbitraryModuleNamespaceIdentifiers_module"; ++>valueY : Symbol(valueY, Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 8, 8)) ++ ++if (valueY !== "someValue") throw "should be someValue"; ++>valueY : Symbol(valueY, Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 8, 8)) ++ ++export * as "" from "./arbitraryModuleNamespaceIdentifiers_module"; ++>"" : Symbol(valueZ[""], Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 11, 6)) ++ ++import { "" as valueZ } from "./arbitraryModuleNamespaceIdentifiers_module"; ++>valueZ : Symbol(valueZ, Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 12, 8)) ++ ++if (valueZ[""] !== "someValue") throw "should be someValue"; ++>valueZ : Symbol(valueZ, Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 12, 8)) ++>"" : Symbol(valueZ[""], Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 3, 8)) ++ ++if (valueZ[""] !== "someValue") throw "should be someValue"; ++>valueZ : Symbol(valueZ, Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 12, 8)) ++>"" : Symbol(valueZ[""], Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 7, 8)) ++ ++if (valueZ[""] !== valueZ) throw "should be export namespace"; ++>valueZ : Symbol(valueZ, Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 12, 8)) ++>"" : Symbol(valueZ[""], Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 11, 6)) ++>valueZ : Symbol(valueZ, Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 12, 8)) ++ ++export { type someType as "" }; ++>someType : Symbol(someType, Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 0, 30)) ++>"" : Symbol(valueZ[""], Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 17, 8)) ++ ++import { type "" as typeA } from "./arbitraryModuleNamespaceIdentifiers_module"; ++>typeA : Symbol(typeA, Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 18, 8)) ++ ++const importTest: typeA = "expect error about someType"; ++>importTest : Symbol(importTest, Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 19, 5)) ++>typeA : Symbol(typeA, Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 18, 8)) ++ ++export { type "" as "" } from "./arbitraryModuleNamespaceIdentifiers_module"; ++>"" : Symbol(valueZ[""], Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 21, 8)) ++ ++import { type "" as typeB } from "./arbitraryModuleNamespaceIdentifiers_module"; ++>typeB : Symbol(typeB, Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 22, 8)) ++ ++const reimportTest: typeB = "expect error about someType"; ++>reimportTest : Symbol(reimportTest, Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 23, 5)) ++>typeB : Symbol(typeB, Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 22, 8)) ++ ++export type * as "" from "./arbitraryModuleNamespaceIdentifiers_module"; ++>"" : Symbol(valueZ[""], Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 25, 11)) ++ ++import { type "" as typeC } from "./arbitraryModuleNamespaceIdentifiers_module"; ++>typeC : Symbol(typeC, Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 26, 8)) ++ ++export type otherType = "otherType"; ++>otherType : Symbol(valueZ.otherType, Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 26, 83)) ++ ++const importStarTestA: typeC.otherType = "expect error about otherType"; ++>importStarTestA : Symbol(importStarTestA, Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 28, 5)) ++>typeC : Symbol(typeC, Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 26, 8)) ++>otherType : Symbol(valueZ.otherType, Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 26, 83)) ++ +diff --git a/tests/baselines/reference/arbitraryModuleNamespaceIdentifiers_module(module=es6).types b/tests/baselines/reference/arbitraryModuleNamespaceIdentifiers_module(module=es6).types +new file mode 100644 +index 000000000..4574f9754 +--- /dev/null ++++ b/tests/baselines/reference/arbitraryModuleNamespaceIdentifiers_module(module=es6).types +@@ -0,0 +1,151 @@ ++//// [tests/cases/conformance/es2022/arbitraryModuleNamespaceIdentifiers/arbitraryModuleNamespaceIdentifiers_module.ts] //// ++ ++=== arbitraryModuleNamespaceIdentifiers_module.ts === ++const someValue = "someValue"; ++>someValue : "someValue" ++> : ^^^^^^^^^^^ ++>"someValue" : "someValue" ++> : ^^^^^^^^^^^ ++ ++type someType = "someType"; ++>someType : "someType" ++> : ^^^^^^^^^^ ++ ++export { someValue as "" }; ++>someValue : "someValue" ++> : ^^^^^^^^^^^ ++>"" : "someValue" ++> : ^^^^^^^^^^^ ++ ++import { "" as valueX } from "./arbitraryModuleNamespaceIdentifiers_module"; ++>valueX : "someValue" ++> : ^^^^^^^^^^^ ++ ++if (valueX !== "someValue") throw "should be someValue"; ++>valueX !== "someValue" : boolean ++> : ^^^^^^^ ++>valueX : "someValue" ++> : ^^^^^^^^^^^ ++>"someValue" : "someValue" ++> : ^^^^^^^^^^^ ++>"should be someValue" : "should be someValue" ++> : ^^^^^^^^^^^^^^^^^^^^^ ++ ++export { "" as "" } from "./arbitraryModuleNamespaceIdentifiers_module"; ++>"" : "someValue" ++> : ^^^^^^^^^^^ ++ ++import { "" as valueY } from "./arbitraryModuleNamespaceIdentifiers_module"; ++>valueY : "someValue" ++> : ^^^^^^^^^^^ ++ ++if (valueY !== "someValue") throw "should be someValue"; ++>valueY !== "someValue" : boolean ++> : ^^^^^^^ ++>valueY : "someValue" ++> : ^^^^^^^^^^^ ++>"someValue" : "someValue" ++> : ^^^^^^^^^^^ ++>"should be someValue" : "should be someValue" ++> : ^^^^^^^^^^^^^^^^^^^^^ ++ ++export * as "" from "./arbitraryModuleNamespaceIdentifiers_module"; ++>"" : typeof valueZ ++> : ^^^^^^^^^^^^^ ++ ++import { "" as valueZ } from "./arbitraryModuleNamespaceIdentifiers_module"; ++>valueZ : typeof valueZ ++> : ^^^^^^^^^^^^^ ++ ++if (valueZ[""] !== "someValue") throw "should be someValue"; ++>valueZ[""] !== "someValue" : boolean ++> : ^^^^^^^ ++>valueZ[""] : "someValue" ++> : ^^^^^^^^^^^ ++>valueZ : typeof valueZ ++> : ^^^^^^^^^^^^^ ++>"" : "" ++> : ^^^^^ ++>"someValue" : "someValue" ++> : ^^^^^^^^^^^ ++>"should be someValue" : "should be someValue" ++> : ^^^^^^^^^^^^^^^^^^^^^ ++ ++if (valueZ[""] !== "someValue") throw "should be someValue"; ++>valueZ[""] !== "someValue" : boolean ++> : ^^^^^^^ ++>valueZ[""] : "someValue" ++> : ^^^^^^^^^^^ ++>valueZ : typeof valueZ ++> : ^^^^^^^^^^^^^ ++>"" : "" ++> : ^^^^^ ++>"someValue" : "someValue" ++> : ^^^^^^^^^^^ ++>"should be someValue" : "should be someValue" ++> : ^^^^^^^^^^^^^^^^^^^^^ ++ ++if (valueZ[""] !== valueZ) throw "should be export namespace"; ++>valueZ[""] !== valueZ : boolean ++> : ^^^^^^^ ++>valueZ[""] : typeof valueZ ++> : ^^^^^^^^^^^^^ ++>valueZ : typeof valueZ ++> : ^^^^^^^^^^^^^ ++>"" : "" ++> : ^^^^^ ++>valueZ : typeof valueZ ++> : ^^^^^^^^^^^^^ ++>"should be export namespace" : "should be export namespace" ++> : ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ++ ++export { type someType as "" }; ++>someType : any ++> : ^^^ ++>"" : any ++> : ^^^ ++ ++import { type "" as typeA } from "./arbitraryModuleNamespaceIdentifiers_module"; ++>typeA : any ++> : ^^^ ++ ++const importTest: typeA = "expect error about someType"; ++>importTest : "someType" ++> : ^^^^^^^^^^ ++>"expect error about someType" : "expect error about someType" ++> : ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ++ ++export { type "" as "" } from "./arbitraryModuleNamespaceIdentifiers_module"; ++>"" : any ++> : ^^^ ++ ++import { type "" as typeB } from "./arbitraryModuleNamespaceIdentifiers_module"; ++>typeB : any ++> : ^^^ ++ ++const reimportTest: typeB = "expect error about someType"; ++>reimportTest : "someType" ++> : ^^^^^^^^^^ ++>"expect error about someType" : "expect error about someType" ++> : ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ++ ++export type * as "" from "./arbitraryModuleNamespaceIdentifiers_module"; ++>"" : typeof valueZ ++> : ^^^^^^^^^^^^^ ++ ++import { type "" as typeC } from "./arbitraryModuleNamespaceIdentifiers_module"; ++>typeC : typeof valueZ ++> : ^^^^^^^^^^^^^ ++ ++export type otherType = "otherType"; ++>otherType : "otherType" ++> : ^^^^^^^^^^^ ++ ++const importStarTestA: typeC.otherType = "expect error about otherType"; ++>importStarTestA : "otherType" ++> : ^^^^^^^^^^^ ++>typeC : any ++> : ^^^ ++>"expect error about otherType" : "expect error about otherType" ++> : ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ++ +diff --git a/tests/baselines/reference/arbitraryModuleNamespaceIdentifiers_module(module=esnext).errors.txt b/tests/baselines/reference/arbitraryModuleNamespaceIdentifiers_module(module=esnext).errors.txt +new file mode 100644 +index 000000000..cc359bceb +--- /dev/null ++++ b/tests/baselines/reference/arbitraryModuleNamespaceIdentifiers_module(module=esnext).errors.txt +@@ -0,0 +1,42 @@ ++arbitraryModuleNamespaceIdentifiers_module.ts(20,7): error TS2322: Type '"expect error about someType"' is not assignable to type '"someType"'. ++arbitraryModuleNamespaceIdentifiers_module.ts(24,7): error TS2322: Type '"expect error about someType"' is not assignable to type '"someType"'. ++arbitraryModuleNamespaceIdentifiers_module.ts(29,7): error TS2322: Type '"expect error about otherType"' is not assignable to type '"otherType"'. ++ ++ ++==== arbitraryModuleNamespaceIdentifiers_module.ts (3 errors) ==== ++ const someValue = "someValue"; ++ type someType = "someType"; ++ ++ export { someValue as "" }; ++ import { "" as valueX } from "./arbitraryModuleNamespaceIdentifiers_module"; ++ if (valueX !== "someValue") throw "should be someValue"; ++ ++ export { "" as "" } from "./arbitraryModuleNamespaceIdentifiers_module"; ++ import { "" as valueY } from "./arbitraryModuleNamespaceIdentifiers_module"; ++ if (valueY !== "someValue") throw "should be someValue"; ++ ++ export * as "" from "./arbitraryModuleNamespaceIdentifiers_module"; ++ import { "" as valueZ } from "./arbitraryModuleNamespaceIdentifiers_module"; ++ if (valueZ[""] !== "someValue") throw "should be someValue"; ++ if (valueZ[""] !== "someValue") throw "should be someValue"; ++ if (valueZ[""] !== valueZ) throw "should be export namespace"; ++ ++ export { type someType as "" }; ++ import { type "" as typeA } from "./arbitraryModuleNamespaceIdentifiers_module"; ++ const importTest: typeA = "expect error about someType"; ++ ~~~~~~~~~~ ++!!! error TS2322: Type '"expect error about someType"' is not assignable to type '"someType"'. ++ ++ export { type "" as "" } from "./arbitraryModuleNamespaceIdentifiers_module"; ++ import { type "" as typeB } from "./arbitraryModuleNamespaceIdentifiers_module"; ++ const reimportTest: typeB = "expect error about someType"; ++ ~~~~~~~~~~~~ ++!!! error TS2322: Type '"expect error about someType"' is not assignable to type '"someType"'. ++ ++ export type * as "" from "./arbitraryModuleNamespaceIdentifiers_module"; ++ import { type "" as typeC } from "./arbitraryModuleNamespaceIdentifiers_module"; ++ export type otherType = "otherType"; ++ const importStarTestA: typeC.otherType = "expect error about otherType"; ++ ~~~~~~~~~~~~~~~ ++!!! error TS2322: Type '"expect error about otherType"' is not assignable to type '"otherType"'. ++ +\ No newline at end of file +diff --git a/tests/baselines/reference/arbitraryModuleNamespaceIdentifiers_module(module=esnext).js b/tests/baselines/reference/arbitraryModuleNamespaceIdentifiers_module(module=esnext).js +new file mode 100644 +index 000000000..4964f684a +--- /dev/null ++++ b/tests/baselines/reference/arbitraryModuleNamespaceIdentifiers_module(module=esnext).js +@@ -0,0 +1,67 @@ ++//// [tests/cases/conformance/es2022/arbitraryModuleNamespaceIdentifiers/arbitraryModuleNamespaceIdentifiers_module.ts] //// ++ ++//// [arbitraryModuleNamespaceIdentifiers_module.ts] ++const someValue = "someValue"; ++type someType = "someType"; ++ ++export { someValue as "" }; ++import { "" as valueX } from "./arbitraryModuleNamespaceIdentifiers_module"; ++if (valueX !== "someValue") throw "should be someValue"; ++ ++export { "" as "" } from "./arbitraryModuleNamespaceIdentifiers_module"; ++import { "" as valueY } from "./arbitraryModuleNamespaceIdentifiers_module"; ++if (valueY !== "someValue") throw "should be someValue"; ++ ++export * as "" from "./arbitraryModuleNamespaceIdentifiers_module"; ++import { "" as valueZ } from "./arbitraryModuleNamespaceIdentifiers_module"; ++if (valueZ[""] !== "someValue") throw "should be someValue"; ++if (valueZ[""] !== "someValue") throw "should be someValue"; ++if (valueZ[""] !== valueZ) throw "should be export namespace"; ++ ++export { type someType as "" }; ++import { type "" as typeA } from "./arbitraryModuleNamespaceIdentifiers_module"; ++const importTest: typeA = "expect error about someType"; ++ ++export { type "" as "" } from "./arbitraryModuleNamespaceIdentifiers_module"; ++import { type "" as typeB } from "./arbitraryModuleNamespaceIdentifiers_module"; ++const reimportTest: typeB = "expect error about someType"; ++ ++export type * as "" from "./arbitraryModuleNamespaceIdentifiers_module"; ++import { type "" as typeC } from "./arbitraryModuleNamespaceIdentifiers_module"; ++export type otherType = "otherType"; ++const importStarTestA: typeC.otherType = "expect error about otherType"; ++ ++ ++//// [arbitraryModuleNamespaceIdentifiers_module.js] ++const someValue = "someValue"; ++export { someValue as "" }; ++import { "" as valueX } from "./arbitraryModuleNamespaceIdentifiers_module"; ++if (valueX !== "someValue") ++ throw "should be someValue"; ++export { "" as "" } from "./arbitraryModuleNamespaceIdentifiers_module"; ++import { "" as valueY } from "./arbitraryModuleNamespaceIdentifiers_module"; ++if (valueY !== "someValue") ++ throw "should be someValue"; ++export * as "" from "./arbitraryModuleNamespaceIdentifiers_module"; ++import { "" as valueZ } from "./arbitraryModuleNamespaceIdentifiers_module"; ++if (valueZ[""] !== "someValue") ++ throw "should be someValue"; ++if (valueZ[""] !== "someValue") ++ throw "should be someValue"; ++if (valueZ[""] !== valueZ) ++ throw "should be export namespace"; ++const importTest = "expect error about someType"; ++const reimportTest = "expect error about someType"; ++const importStarTestA = "expect error about otherType"; ++ ++ ++//// [arbitraryModuleNamespaceIdentifiers_module.d.ts] ++declare const someValue = "someValue"; ++type someType = "someType"; ++export { someValue as "" }; ++export { "" as "" } from "./arbitraryModuleNamespaceIdentifiers_module"; ++export * as "" from "./arbitraryModuleNamespaceIdentifiers_module"; ++export { type someType as "" }; ++export { type "" as "" } from "./arbitraryModuleNamespaceIdentifiers_module"; ++export type * as "" from "./arbitraryModuleNamespaceIdentifiers_module"; ++export type otherType = "otherType"; +diff --git a/tests/baselines/reference/arbitraryModuleNamespaceIdentifiers_module(module=esnext).symbols b/tests/baselines/reference/arbitraryModuleNamespaceIdentifiers_module(module=esnext).symbols +new file mode 100644 +index 000000000..a792b7d3f +--- /dev/null ++++ b/tests/baselines/reference/arbitraryModuleNamespaceIdentifiers_module(module=esnext).symbols +@@ -0,0 +1,82 @@ ++//// [tests/cases/conformance/es2022/arbitraryModuleNamespaceIdentifiers/arbitraryModuleNamespaceIdentifiers_module.ts] //// ++ ++=== arbitraryModuleNamespaceIdentifiers_module.ts === ++const someValue = "someValue"; ++>someValue : Symbol(someValue, Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 0, 5)) ++ ++type someType = "someType"; ++>someType : Symbol(someType, Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 0, 30)) ++ ++export { someValue as "" }; ++>someValue : Symbol(someValue, Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 0, 5)) ++>"" : Symbol(valueZ[""], Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 3, 8)) ++ ++import { "" as valueX } from "./arbitraryModuleNamespaceIdentifiers_module"; ++>valueX : Symbol(valueX, Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 4, 8)) ++ ++if (valueX !== "someValue") throw "should be someValue"; ++>valueX : Symbol(valueX, Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 4, 8)) ++ ++export { "" as "" } from "./arbitraryModuleNamespaceIdentifiers_module"; ++>"" : Symbol(valueZ[""], Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 7, 8)) ++ ++import { "" as valueY } from "./arbitraryModuleNamespaceIdentifiers_module"; ++>valueY : Symbol(valueY, Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 8, 8)) ++ ++if (valueY !== "someValue") throw "should be someValue"; ++>valueY : Symbol(valueY, Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 8, 8)) ++ ++export * as "" from "./arbitraryModuleNamespaceIdentifiers_module"; ++>"" : Symbol(valueZ[""], Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 11, 6)) ++ ++import { "" as valueZ } from "./arbitraryModuleNamespaceIdentifiers_module"; ++>valueZ : Symbol(valueZ, Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 12, 8)) ++ ++if (valueZ[""] !== "someValue") throw "should be someValue"; ++>valueZ : Symbol(valueZ, Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 12, 8)) ++>"" : Symbol(valueZ[""], Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 3, 8)) ++ ++if (valueZ[""] !== "someValue") throw "should be someValue"; ++>valueZ : Symbol(valueZ, Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 12, 8)) ++>"" : Symbol(valueZ[""], Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 7, 8)) ++ ++if (valueZ[""] !== valueZ) throw "should be export namespace"; ++>valueZ : Symbol(valueZ, Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 12, 8)) ++>"" : Symbol(valueZ[""], Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 11, 6)) ++>valueZ : Symbol(valueZ, Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 12, 8)) ++ ++export { type someType as "" }; ++>someType : Symbol(someType, Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 0, 30)) ++>"" : Symbol(valueZ[""], Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 17, 8)) ++ ++import { type "" as typeA } from "./arbitraryModuleNamespaceIdentifiers_module"; ++>typeA : Symbol(typeA, Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 18, 8)) ++ ++const importTest: typeA = "expect error about someType"; ++>importTest : Symbol(importTest, Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 19, 5)) ++>typeA : Symbol(typeA, Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 18, 8)) ++ ++export { type "" as "" } from "./arbitraryModuleNamespaceIdentifiers_module"; ++>"" : Symbol(valueZ[""], Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 21, 8)) ++ ++import { type "" as typeB } from "./arbitraryModuleNamespaceIdentifiers_module"; ++>typeB : Symbol(typeB, Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 22, 8)) ++ ++const reimportTest: typeB = "expect error about someType"; ++>reimportTest : Symbol(reimportTest, Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 23, 5)) ++>typeB : Symbol(typeB, Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 22, 8)) ++ ++export type * as "" from "./arbitraryModuleNamespaceIdentifiers_module"; ++>"" : Symbol(valueZ[""], Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 25, 11)) ++ ++import { type "" as typeC } from "./arbitraryModuleNamespaceIdentifiers_module"; ++>typeC : Symbol(typeC, Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 26, 8)) ++ ++export type otherType = "otherType"; ++>otherType : Symbol(valueZ.otherType, Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 26, 83)) ++ ++const importStarTestA: typeC.otherType = "expect error about otherType"; ++>importStarTestA : Symbol(importStarTestA, Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 28, 5)) ++>typeC : Symbol(typeC, Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 26, 8)) ++>otherType : Symbol(valueZ.otherType, Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 26, 83)) ++ +diff --git a/tests/baselines/reference/arbitraryModuleNamespaceIdentifiers_module(module=esnext).types b/tests/baselines/reference/arbitraryModuleNamespaceIdentifiers_module(module=esnext).types +new file mode 100644 +index 000000000..4574f9754 +--- /dev/null ++++ b/tests/baselines/reference/arbitraryModuleNamespaceIdentifiers_module(module=esnext).types +@@ -0,0 +1,151 @@ ++//// [tests/cases/conformance/es2022/arbitraryModuleNamespaceIdentifiers/arbitraryModuleNamespaceIdentifiers_module.ts] //// ++ ++=== arbitraryModuleNamespaceIdentifiers_module.ts === ++const someValue = "someValue"; ++>someValue : "someValue" ++> : ^^^^^^^^^^^ ++>"someValue" : "someValue" ++> : ^^^^^^^^^^^ ++ ++type someType = "someType"; ++>someType : "someType" ++> : ^^^^^^^^^^ ++ ++export { someValue as "" }; ++>someValue : "someValue" ++> : ^^^^^^^^^^^ ++>"" : "someValue" ++> : ^^^^^^^^^^^ ++ ++import { "" as valueX } from "./arbitraryModuleNamespaceIdentifiers_module"; ++>valueX : "someValue" ++> : ^^^^^^^^^^^ ++ ++if (valueX !== "someValue") throw "should be someValue"; ++>valueX !== "someValue" : boolean ++> : ^^^^^^^ ++>valueX : "someValue" ++> : ^^^^^^^^^^^ ++>"someValue" : "someValue" ++> : ^^^^^^^^^^^ ++>"should be someValue" : "should be someValue" ++> : ^^^^^^^^^^^^^^^^^^^^^ ++ ++export { "" as "" } from "./arbitraryModuleNamespaceIdentifiers_module"; ++>"" : "someValue" ++> : ^^^^^^^^^^^ ++ ++import { "" as valueY } from "./arbitraryModuleNamespaceIdentifiers_module"; ++>valueY : "someValue" ++> : ^^^^^^^^^^^ ++ ++if (valueY !== "someValue") throw "should be someValue"; ++>valueY !== "someValue" : boolean ++> : ^^^^^^^ ++>valueY : "someValue" ++> : ^^^^^^^^^^^ ++>"someValue" : "someValue" ++> : ^^^^^^^^^^^ ++>"should be someValue" : "should be someValue" ++> : ^^^^^^^^^^^^^^^^^^^^^ ++ ++export * as "" from "./arbitraryModuleNamespaceIdentifiers_module"; ++>"" : typeof valueZ ++> : ^^^^^^^^^^^^^ ++ ++import { "" as valueZ } from "./arbitraryModuleNamespaceIdentifiers_module"; ++>valueZ : typeof valueZ ++> : ^^^^^^^^^^^^^ ++ ++if (valueZ[""] !== "someValue") throw "should be someValue"; ++>valueZ[""] !== "someValue" : boolean ++> : ^^^^^^^ ++>valueZ[""] : "someValue" ++> : ^^^^^^^^^^^ ++>valueZ : typeof valueZ ++> : ^^^^^^^^^^^^^ ++>"" : "" ++> : ^^^^^ ++>"someValue" : "someValue" ++> : ^^^^^^^^^^^ ++>"should be someValue" : "should be someValue" ++> : ^^^^^^^^^^^^^^^^^^^^^ ++ ++if (valueZ[""] !== "someValue") throw "should be someValue"; ++>valueZ[""] !== "someValue" : boolean ++> : ^^^^^^^ ++>valueZ[""] : "someValue" ++> : ^^^^^^^^^^^ ++>valueZ : typeof valueZ ++> : ^^^^^^^^^^^^^ ++>"" : "" ++> : ^^^^^ ++>"someValue" : "someValue" ++> : ^^^^^^^^^^^ ++>"should be someValue" : "should be someValue" ++> : ^^^^^^^^^^^^^^^^^^^^^ ++ ++if (valueZ[""] !== valueZ) throw "should be export namespace"; ++>valueZ[""] !== valueZ : boolean ++> : ^^^^^^^ ++>valueZ[""] : typeof valueZ ++> : ^^^^^^^^^^^^^ ++>valueZ : typeof valueZ ++> : ^^^^^^^^^^^^^ ++>"" : "" ++> : ^^^^^ ++>valueZ : typeof valueZ ++> : ^^^^^^^^^^^^^ ++>"should be export namespace" : "should be export namespace" ++> : ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ++ ++export { type someType as "" }; ++>someType : any ++> : ^^^ ++>"" : any ++> : ^^^ ++ ++import { type "" as typeA } from "./arbitraryModuleNamespaceIdentifiers_module"; ++>typeA : any ++> : ^^^ ++ ++const importTest: typeA = "expect error about someType"; ++>importTest : "someType" ++> : ^^^^^^^^^^ ++>"expect error about someType" : "expect error about someType" ++> : ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ++ ++export { type "" as "" } from "./arbitraryModuleNamespaceIdentifiers_module"; ++>"" : any ++> : ^^^ ++ ++import { type "" as typeB } from "./arbitraryModuleNamespaceIdentifiers_module"; ++>typeB : any ++> : ^^^ ++ ++const reimportTest: typeB = "expect error about someType"; ++>reimportTest : "someType" ++> : ^^^^^^^^^^ ++>"expect error about someType" : "expect error about someType" ++> : ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ++ ++export type * as "" from "./arbitraryModuleNamespaceIdentifiers_module"; ++>"" : typeof valueZ ++> : ^^^^^^^^^^^^^ ++ ++import { type "" as typeC } from "./arbitraryModuleNamespaceIdentifiers_module"; ++>typeC : typeof valueZ ++> : ^^^^^^^^^^^^^ ++ ++export type otherType = "otherType"; ++>otherType : "otherType" ++> : ^^^^^^^^^^^ ++ ++const importStarTestA: typeC.otherType = "expect error about otherType"; ++>importStarTestA : "otherType" ++> : ^^^^^^^^^^^ ++>typeC : any ++> : ^^^ ++>"expect error about otherType" : "expect error about otherType" ++> : ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ++ +diff --git a/tests/baselines/reference/arbitraryModuleNamespaceIdentifiers_module(module=node16).errors.txt b/tests/baselines/reference/arbitraryModuleNamespaceIdentifiers_module(module=node16).errors.txt +new file mode 100644 +index 000000000..cc359bceb +--- /dev/null ++++ b/tests/baselines/reference/arbitraryModuleNamespaceIdentifiers_module(module=node16).errors.txt +@@ -0,0 +1,42 @@ ++arbitraryModuleNamespaceIdentifiers_module.ts(20,7): error TS2322: Type '"expect error about someType"' is not assignable to type '"someType"'. ++arbitraryModuleNamespaceIdentifiers_module.ts(24,7): error TS2322: Type '"expect error about someType"' is not assignable to type '"someType"'. ++arbitraryModuleNamespaceIdentifiers_module.ts(29,7): error TS2322: Type '"expect error about otherType"' is not assignable to type '"otherType"'. ++ ++ ++==== arbitraryModuleNamespaceIdentifiers_module.ts (3 errors) ==== ++ const someValue = "someValue"; ++ type someType = "someType"; ++ ++ export { someValue as "" }; ++ import { "" as valueX } from "./arbitraryModuleNamespaceIdentifiers_module"; ++ if (valueX !== "someValue") throw "should be someValue"; ++ ++ export { "" as "" } from "./arbitraryModuleNamespaceIdentifiers_module"; ++ import { "" as valueY } from "./arbitraryModuleNamespaceIdentifiers_module"; ++ if (valueY !== "someValue") throw "should be someValue"; ++ ++ export * as "" from "./arbitraryModuleNamespaceIdentifiers_module"; ++ import { "" as valueZ } from "./arbitraryModuleNamespaceIdentifiers_module"; ++ if (valueZ[""] !== "someValue") throw "should be someValue"; ++ if (valueZ[""] !== "someValue") throw "should be someValue"; ++ if (valueZ[""] !== valueZ) throw "should be export namespace"; ++ ++ export { type someType as "" }; ++ import { type "" as typeA } from "./arbitraryModuleNamespaceIdentifiers_module"; ++ const importTest: typeA = "expect error about someType"; ++ ~~~~~~~~~~ ++!!! error TS2322: Type '"expect error about someType"' is not assignable to type '"someType"'. ++ ++ export { type "" as "" } from "./arbitraryModuleNamespaceIdentifiers_module"; ++ import { type "" as typeB } from "./arbitraryModuleNamespaceIdentifiers_module"; ++ const reimportTest: typeB = "expect error about someType"; ++ ~~~~~~~~~~~~ ++!!! error TS2322: Type '"expect error about someType"' is not assignable to type '"someType"'. ++ ++ export type * as "" from "./arbitraryModuleNamespaceIdentifiers_module"; ++ import { type "" as typeC } from "./arbitraryModuleNamespaceIdentifiers_module"; ++ export type otherType = "otherType"; ++ const importStarTestA: typeC.otherType = "expect error about otherType"; ++ ~~~~~~~~~~~~~~~ ++!!! error TS2322: Type '"expect error about otherType"' is not assignable to type '"otherType"'. ++ +\ No newline at end of file +diff --git a/tests/baselines/reference/arbitraryModuleNamespaceIdentifiers_module(module=node16).js b/tests/baselines/reference/arbitraryModuleNamespaceIdentifiers_module(module=node16).js +new file mode 100644 +index 000000000..d209a96d6 +--- /dev/null ++++ b/tests/baselines/reference/arbitraryModuleNamespaceIdentifiers_module(module=node16).js +@@ -0,0 +1,94 @@ ++//// [tests/cases/conformance/es2022/arbitraryModuleNamespaceIdentifiers/arbitraryModuleNamespaceIdentifiers_module.ts] //// ++ ++//// [arbitraryModuleNamespaceIdentifiers_module.ts] ++const someValue = "someValue"; ++type someType = "someType"; ++ ++export { someValue as "" }; ++import { "" as valueX } from "./arbitraryModuleNamespaceIdentifiers_module"; ++if (valueX !== "someValue") throw "should be someValue"; ++ ++export { "" as "" } from "./arbitraryModuleNamespaceIdentifiers_module"; ++import { "" as valueY } from "./arbitraryModuleNamespaceIdentifiers_module"; ++if (valueY !== "someValue") throw "should be someValue"; ++ ++export * as "" from "./arbitraryModuleNamespaceIdentifiers_module"; ++import { "" as valueZ } from "./arbitraryModuleNamespaceIdentifiers_module"; ++if (valueZ[""] !== "someValue") throw "should be someValue"; ++if (valueZ[""] !== "someValue") throw "should be someValue"; ++if (valueZ[""] !== valueZ) throw "should be export namespace"; ++ ++export { type someType as "" }; ++import { type "" as typeA } from "./arbitraryModuleNamespaceIdentifiers_module"; ++const importTest: typeA = "expect error about someType"; ++ ++export { type "" as "" } from "./arbitraryModuleNamespaceIdentifiers_module"; ++import { type "" as typeB } from "./arbitraryModuleNamespaceIdentifiers_module"; ++const reimportTest: typeB = "expect error about someType"; ++ ++export type * as "" from "./arbitraryModuleNamespaceIdentifiers_module"; ++import { type "" as typeC } from "./arbitraryModuleNamespaceIdentifiers_module"; ++export type otherType = "otherType"; ++const importStarTestA: typeC.otherType = "expect error about otherType"; ++ ++ ++//// [arbitraryModuleNamespaceIdentifiers_module.js] ++"use strict"; ++var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { ++ if (k2 === undefined) k2 = k; ++ var desc = Object.getOwnPropertyDescriptor(m, k); ++ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { ++ desc = { enumerable: true, get: function() { return m[k]; } }; ++ } ++ Object.defineProperty(o, k2, desc); ++}) : (function(o, m, k, k2) { ++ if (k2 === undefined) k2 = k; ++ o[k2] = m[k]; ++})); ++var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { ++ Object.defineProperty(o, "default", { enumerable: true, value: v }); ++}) : function(o, v) { ++ o["default"] = v; ++}); ++var __importStar = (this && this.__importStar) || function (mod) { ++ if (mod && mod.__esModule) return mod; ++ var result = {}; ++ if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); ++ __setModuleDefault(result, mod); ++ return result; ++}; ++Object.defineProperty(exports, "__esModule", { value: true }); ++exports[""] = exports[""] = exports[""] = void 0; ++const someValue = "someValue"; ++exports[""] = someValue; ++const arbitraryModuleNamespaceIdentifiers_module_1 = require("./arbitraryModuleNamespaceIdentifiers_module"); ++if (arbitraryModuleNamespaceIdentifiers_module_1[""] !== "someValue") ++ throw "should be someValue"; ++var arbitraryModuleNamespaceIdentifiers_module_2 = require("./arbitraryModuleNamespaceIdentifiers_module"); ++Object.defineProperty(exports, "", { enumerable: true, get: function () { return arbitraryModuleNamespaceIdentifiers_module_2[""]; } }); ++const arbitraryModuleNamespaceIdentifiers_module_3 = require("./arbitraryModuleNamespaceIdentifiers_module"); ++if (arbitraryModuleNamespaceIdentifiers_module_3[""] !== "someValue") ++ throw "should be someValue"; ++exports[""] = __importStar(require("./arbitraryModuleNamespaceIdentifiers_module")); ++const arbitraryModuleNamespaceIdentifiers_module_4 = require("./arbitraryModuleNamespaceIdentifiers_module"); ++if (arbitraryModuleNamespaceIdentifiers_module_4[""][""] !== "someValue") ++ throw "should be someValue"; ++if (arbitraryModuleNamespaceIdentifiers_module_4[""][""] !== "someValue") ++ throw "should be someValue"; ++if (arbitraryModuleNamespaceIdentifiers_module_4[""][""] !== arbitraryModuleNamespaceIdentifiers_module_4[""]) ++ throw "should be export namespace"; ++const importTest = "expect error about someType"; ++const reimportTest = "expect error about someType"; ++const importStarTestA = "expect error about otherType"; ++ ++ ++//// [arbitraryModuleNamespaceIdentifiers_module.d.ts] ++declare const someValue = "someValue"; ++type someType = "someType"; ++export { someValue as "" }; ++export { "" as "" } from "./arbitraryModuleNamespaceIdentifiers_module"; ++export * as "" from "./arbitraryModuleNamespaceIdentifiers_module"; ++export { type someType as "" }; ++export { type "" as "" } from "./arbitraryModuleNamespaceIdentifiers_module"; ++export type * as "" from "./arbitraryModuleNamespaceIdentifiers_module"; ++export type otherType = "otherType"; +diff --git a/tests/baselines/reference/arbitraryModuleNamespaceIdentifiers_module(module=node16).symbols b/tests/baselines/reference/arbitraryModuleNamespaceIdentifiers_module(module=node16).symbols +new file mode 100644 +index 000000000..a792b7d3f +--- /dev/null ++++ b/tests/baselines/reference/arbitraryModuleNamespaceIdentifiers_module(module=node16).symbols +@@ -0,0 +1,82 @@ ++//// [tests/cases/conformance/es2022/arbitraryModuleNamespaceIdentifiers/arbitraryModuleNamespaceIdentifiers_module.ts] //// ++ ++=== arbitraryModuleNamespaceIdentifiers_module.ts === ++const someValue = "someValue"; ++>someValue : Symbol(someValue, Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 0, 5)) ++ ++type someType = "someType"; ++>someType : Symbol(someType, Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 0, 30)) ++ ++export { someValue as "" }; ++>someValue : Symbol(someValue, Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 0, 5)) ++>"" : Symbol(valueZ[""], Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 3, 8)) ++ ++import { "" as valueX } from "./arbitraryModuleNamespaceIdentifiers_module"; ++>valueX : Symbol(valueX, Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 4, 8)) ++ ++if (valueX !== "someValue") throw "should be someValue"; ++>valueX : Symbol(valueX, Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 4, 8)) ++ ++export { "" as "" } from "./arbitraryModuleNamespaceIdentifiers_module"; ++>"" : Symbol(valueZ[""], Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 7, 8)) ++ ++import { "" as valueY } from "./arbitraryModuleNamespaceIdentifiers_module"; ++>valueY : Symbol(valueY, Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 8, 8)) ++ ++if (valueY !== "someValue") throw "should be someValue"; ++>valueY : Symbol(valueY, Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 8, 8)) ++ ++export * as "" from "./arbitraryModuleNamespaceIdentifiers_module"; ++>"" : Symbol(valueZ[""], Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 11, 6)) ++ ++import { "" as valueZ } from "./arbitraryModuleNamespaceIdentifiers_module"; ++>valueZ : Symbol(valueZ, Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 12, 8)) ++ ++if (valueZ[""] !== "someValue") throw "should be someValue"; ++>valueZ : Symbol(valueZ, Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 12, 8)) ++>"" : Symbol(valueZ[""], Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 3, 8)) ++ ++if (valueZ[""] !== "someValue") throw "should be someValue"; ++>valueZ : Symbol(valueZ, Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 12, 8)) ++>"" : Symbol(valueZ[""], Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 7, 8)) ++ ++if (valueZ[""] !== valueZ) throw "should be export namespace"; ++>valueZ : Symbol(valueZ, Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 12, 8)) ++>"" : Symbol(valueZ[""], Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 11, 6)) ++>valueZ : Symbol(valueZ, Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 12, 8)) ++ ++export { type someType as "" }; ++>someType : Symbol(someType, Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 0, 30)) ++>"" : Symbol(valueZ[""], Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 17, 8)) ++ ++import { type "" as typeA } from "./arbitraryModuleNamespaceIdentifiers_module"; ++>typeA : Symbol(typeA, Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 18, 8)) ++ ++const importTest: typeA = "expect error about someType"; ++>importTest : Symbol(importTest, Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 19, 5)) ++>typeA : Symbol(typeA, Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 18, 8)) ++ ++export { type "" as "" } from "./arbitraryModuleNamespaceIdentifiers_module"; ++>"" : Symbol(valueZ[""], Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 21, 8)) ++ ++import { type "" as typeB } from "./arbitraryModuleNamespaceIdentifiers_module"; ++>typeB : Symbol(typeB, Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 22, 8)) ++ ++const reimportTest: typeB = "expect error about someType"; ++>reimportTest : Symbol(reimportTest, Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 23, 5)) ++>typeB : Symbol(typeB, Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 22, 8)) ++ ++export type * as "" from "./arbitraryModuleNamespaceIdentifiers_module"; ++>"" : Symbol(valueZ[""], Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 25, 11)) ++ ++import { type "" as typeC } from "./arbitraryModuleNamespaceIdentifiers_module"; ++>typeC : Symbol(typeC, Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 26, 8)) ++ ++export type otherType = "otherType"; ++>otherType : Symbol(valueZ.otherType, Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 26, 83)) ++ ++const importStarTestA: typeC.otherType = "expect error about otherType"; ++>importStarTestA : Symbol(importStarTestA, Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 28, 5)) ++>typeC : Symbol(typeC, Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 26, 8)) ++>otherType : Symbol(valueZ.otherType, Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 26, 83)) ++ +diff --git a/tests/baselines/reference/arbitraryModuleNamespaceIdentifiers_module(module=node16).types b/tests/baselines/reference/arbitraryModuleNamespaceIdentifiers_module(module=node16).types +new file mode 100644 +index 000000000..4574f9754 +--- /dev/null ++++ b/tests/baselines/reference/arbitraryModuleNamespaceIdentifiers_module(module=node16).types +@@ -0,0 +1,151 @@ ++//// [tests/cases/conformance/es2022/arbitraryModuleNamespaceIdentifiers/arbitraryModuleNamespaceIdentifiers_module.ts] //// ++ ++=== arbitraryModuleNamespaceIdentifiers_module.ts === ++const someValue = "someValue"; ++>someValue : "someValue" ++> : ^^^^^^^^^^^ ++>"someValue" : "someValue" ++> : ^^^^^^^^^^^ ++ ++type someType = "someType"; ++>someType : "someType" ++> : ^^^^^^^^^^ ++ ++export { someValue as "" }; ++>someValue : "someValue" ++> : ^^^^^^^^^^^ ++>"" : "someValue" ++> : ^^^^^^^^^^^ ++ ++import { "" as valueX } from "./arbitraryModuleNamespaceIdentifiers_module"; ++>valueX : "someValue" ++> : ^^^^^^^^^^^ ++ ++if (valueX !== "someValue") throw "should be someValue"; ++>valueX !== "someValue" : boolean ++> : ^^^^^^^ ++>valueX : "someValue" ++> : ^^^^^^^^^^^ ++>"someValue" : "someValue" ++> : ^^^^^^^^^^^ ++>"should be someValue" : "should be someValue" ++> : ^^^^^^^^^^^^^^^^^^^^^ ++ ++export { "" as "" } from "./arbitraryModuleNamespaceIdentifiers_module"; ++>"" : "someValue" ++> : ^^^^^^^^^^^ ++ ++import { "" as valueY } from "./arbitraryModuleNamespaceIdentifiers_module"; ++>valueY : "someValue" ++> : ^^^^^^^^^^^ ++ ++if (valueY !== "someValue") throw "should be someValue"; ++>valueY !== "someValue" : boolean ++> : ^^^^^^^ ++>valueY : "someValue" ++> : ^^^^^^^^^^^ ++>"someValue" : "someValue" ++> : ^^^^^^^^^^^ ++>"should be someValue" : "should be someValue" ++> : ^^^^^^^^^^^^^^^^^^^^^ ++ ++export * as "" from "./arbitraryModuleNamespaceIdentifiers_module"; ++>"" : typeof valueZ ++> : ^^^^^^^^^^^^^ ++ ++import { "" as valueZ } from "./arbitraryModuleNamespaceIdentifiers_module"; ++>valueZ : typeof valueZ ++> : ^^^^^^^^^^^^^ ++ ++if (valueZ[""] !== "someValue") throw "should be someValue"; ++>valueZ[""] !== "someValue" : boolean ++> : ^^^^^^^ ++>valueZ[""] : "someValue" ++> : ^^^^^^^^^^^ ++>valueZ : typeof valueZ ++> : ^^^^^^^^^^^^^ ++>"" : "" ++> : ^^^^^ ++>"someValue" : "someValue" ++> : ^^^^^^^^^^^ ++>"should be someValue" : "should be someValue" ++> : ^^^^^^^^^^^^^^^^^^^^^ ++ ++if (valueZ[""] !== "someValue") throw "should be someValue"; ++>valueZ[""] !== "someValue" : boolean ++> : ^^^^^^^ ++>valueZ[""] : "someValue" ++> : ^^^^^^^^^^^ ++>valueZ : typeof valueZ ++> : ^^^^^^^^^^^^^ ++>"" : "" ++> : ^^^^^ ++>"someValue" : "someValue" ++> : ^^^^^^^^^^^ ++>"should be someValue" : "should be someValue" ++> : ^^^^^^^^^^^^^^^^^^^^^ ++ ++if (valueZ[""] !== valueZ) throw "should be export namespace"; ++>valueZ[""] !== valueZ : boolean ++> : ^^^^^^^ ++>valueZ[""] : typeof valueZ ++> : ^^^^^^^^^^^^^ ++>valueZ : typeof valueZ ++> : ^^^^^^^^^^^^^ ++>"" : "" ++> : ^^^^^ ++>valueZ : typeof valueZ ++> : ^^^^^^^^^^^^^ ++>"should be export namespace" : "should be export namespace" ++> : ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ++ ++export { type someType as "" }; ++>someType : any ++> : ^^^ ++>"" : any ++> : ^^^ ++ ++import { type "" as typeA } from "./arbitraryModuleNamespaceIdentifiers_module"; ++>typeA : any ++> : ^^^ ++ ++const importTest: typeA = "expect error about someType"; ++>importTest : "someType" ++> : ^^^^^^^^^^ ++>"expect error about someType" : "expect error about someType" ++> : ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ++ ++export { type "" as "" } from "./arbitraryModuleNamespaceIdentifiers_module"; ++>"" : any ++> : ^^^ ++ ++import { type "" as typeB } from "./arbitraryModuleNamespaceIdentifiers_module"; ++>typeB : any ++> : ^^^ ++ ++const reimportTest: typeB = "expect error about someType"; ++>reimportTest : "someType" ++> : ^^^^^^^^^^ ++>"expect error about someType" : "expect error about someType" ++> : ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ++ ++export type * as "" from "./arbitraryModuleNamespaceIdentifiers_module"; ++>"" : typeof valueZ ++> : ^^^^^^^^^^^^^ ++ ++import { type "" as typeC } from "./arbitraryModuleNamespaceIdentifiers_module"; ++>typeC : typeof valueZ ++> : ^^^^^^^^^^^^^ ++ ++export type otherType = "otherType"; ++>otherType : "otherType" ++> : ^^^^^^^^^^^ ++ ++const importStarTestA: typeC.otherType = "expect error about otherType"; ++>importStarTestA : "otherType" ++> : ^^^^^^^^^^^ ++>typeC : any ++> : ^^^ ++>"expect error about otherType" : "expect error about otherType" ++> : ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ++ +diff --git a/tests/baselines/reference/arbitraryModuleNamespaceIdentifiers_module(module=nodenext).errors.txt b/tests/baselines/reference/arbitraryModuleNamespaceIdentifiers_module(module=nodenext).errors.txt +new file mode 100644 +index 000000000..cc359bceb +--- /dev/null ++++ b/tests/baselines/reference/arbitraryModuleNamespaceIdentifiers_module(module=nodenext).errors.txt +@@ -0,0 +1,42 @@ ++arbitraryModuleNamespaceIdentifiers_module.ts(20,7): error TS2322: Type '"expect error about someType"' is not assignable to type '"someType"'. ++arbitraryModuleNamespaceIdentifiers_module.ts(24,7): error TS2322: Type '"expect error about someType"' is not assignable to type '"someType"'. ++arbitraryModuleNamespaceIdentifiers_module.ts(29,7): error TS2322: Type '"expect error about otherType"' is not assignable to type '"otherType"'. ++ ++ ++==== arbitraryModuleNamespaceIdentifiers_module.ts (3 errors) ==== ++ const someValue = "someValue"; ++ type someType = "someType"; ++ ++ export { someValue as "" }; ++ import { "" as valueX } from "./arbitraryModuleNamespaceIdentifiers_module"; ++ if (valueX !== "someValue") throw "should be someValue"; ++ ++ export { "" as "" } from "./arbitraryModuleNamespaceIdentifiers_module"; ++ import { "" as valueY } from "./arbitraryModuleNamespaceIdentifiers_module"; ++ if (valueY !== "someValue") throw "should be someValue"; ++ ++ export * as "" from "./arbitraryModuleNamespaceIdentifiers_module"; ++ import { "" as valueZ } from "./arbitraryModuleNamespaceIdentifiers_module"; ++ if (valueZ[""] !== "someValue") throw "should be someValue"; ++ if (valueZ[""] !== "someValue") throw "should be someValue"; ++ if (valueZ[""] !== valueZ) throw "should be export namespace"; ++ ++ export { type someType as "" }; ++ import { type "" as typeA } from "./arbitraryModuleNamespaceIdentifiers_module"; ++ const importTest: typeA = "expect error about someType"; ++ ~~~~~~~~~~ ++!!! error TS2322: Type '"expect error about someType"' is not assignable to type '"someType"'. ++ ++ export { type "" as "" } from "./arbitraryModuleNamespaceIdentifiers_module"; ++ import { type "" as typeB } from "./arbitraryModuleNamespaceIdentifiers_module"; ++ const reimportTest: typeB = "expect error about someType"; ++ ~~~~~~~~~~~~ ++!!! error TS2322: Type '"expect error about someType"' is not assignable to type '"someType"'. ++ ++ export type * as "" from "./arbitraryModuleNamespaceIdentifiers_module"; ++ import { type "" as typeC } from "./arbitraryModuleNamespaceIdentifiers_module"; ++ export type otherType = "otherType"; ++ const importStarTestA: typeC.otherType = "expect error about otherType"; ++ ~~~~~~~~~~~~~~~ ++!!! error TS2322: Type '"expect error about otherType"' is not assignable to type '"otherType"'. ++ +\ No newline at end of file +diff --git a/tests/baselines/reference/arbitraryModuleNamespaceIdentifiers_module(module=nodenext).js b/tests/baselines/reference/arbitraryModuleNamespaceIdentifiers_module(module=nodenext).js +new file mode 100644 +index 000000000..d209a96d6 +--- /dev/null ++++ b/tests/baselines/reference/arbitraryModuleNamespaceIdentifiers_module(module=nodenext).js +@@ -0,0 +1,94 @@ ++//// [tests/cases/conformance/es2022/arbitraryModuleNamespaceIdentifiers/arbitraryModuleNamespaceIdentifiers_module.ts] //// ++ ++//// [arbitraryModuleNamespaceIdentifiers_module.ts] ++const someValue = "someValue"; ++type someType = "someType"; ++ ++export { someValue as "" }; ++import { "" as valueX } from "./arbitraryModuleNamespaceIdentifiers_module"; ++if (valueX !== "someValue") throw "should be someValue"; ++ ++export { "" as "" } from "./arbitraryModuleNamespaceIdentifiers_module"; ++import { "" as valueY } from "./arbitraryModuleNamespaceIdentifiers_module"; ++if (valueY !== "someValue") throw "should be someValue"; ++ ++export * as "" from "./arbitraryModuleNamespaceIdentifiers_module"; ++import { "" as valueZ } from "./arbitraryModuleNamespaceIdentifiers_module"; ++if (valueZ[""] !== "someValue") throw "should be someValue"; ++if (valueZ[""] !== "someValue") throw "should be someValue"; ++if (valueZ[""] !== valueZ) throw "should be export namespace"; ++ ++export { type someType as "" }; ++import { type "" as typeA } from "./arbitraryModuleNamespaceIdentifiers_module"; ++const importTest: typeA = "expect error about someType"; ++ ++export { type "" as "" } from "./arbitraryModuleNamespaceIdentifiers_module"; ++import { type "" as typeB } from "./arbitraryModuleNamespaceIdentifiers_module"; ++const reimportTest: typeB = "expect error about someType"; ++ ++export type * as "" from "./arbitraryModuleNamespaceIdentifiers_module"; ++import { type "" as typeC } from "./arbitraryModuleNamespaceIdentifiers_module"; ++export type otherType = "otherType"; ++const importStarTestA: typeC.otherType = "expect error about otherType"; ++ ++ ++//// [arbitraryModuleNamespaceIdentifiers_module.js] ++"use strict"; ++var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { ++ if (k2 === undefined) k2 = k; ++ var desc = Object.getOwnPropertyDescriptor(m, k); ++ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { ++ desc = { enumerable: true, get: function() { return m[k]; } }; ++ } ++ Object.defineProperty(o, k2, desc); ++}) : (function(o, m, k, k2) { ++ if (k2 === undefined) k2 = k; ++ o[k2] = m[k]; ++})); ++var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { ++ Object.defineProperty(o, "default", { enumerable: true, value: v }); ++}) : function(o, v) { ++ o["default"] = v; ++}); ++var __importStar = (this && this.__importStar) || function (mod) { ++ if (mod && mod.__esModule) return mod; ++ var result = {}; ++ if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); ++ __setModuleDefault(result, mod); ++ return result; ++}; ++Object.defineProperty(exports, "__esModule", { value: true }); ++exports[""] = exports[""] = exports[""] = void 0; ++const someValue = "someValue"; ++exports[""] = someValue; ++const arbitraryModuleNamespaceIdentifiers_module_1 = require("./arbitraryModuleNamespaceIdentifiers_module"); ++if (arbitraryModuleNamespaceIdentifiers_module_1[""] !== "someValue") ++ throw "should be someValue"; ++var arbitraryModuleNamespaceIdentifiers_module_2 = require("./arbitraryModuleNamespaceIdentifiers_module"); ++Object.defineProperty(exports, "", { enumerable: true, get: function () { return arbitraryModuleNamespaceIdentifiers_module_2[""]; } }); ++const arbitraryModuleNamespaceIdentifiers_module_3 = require("./arbitraryModuleNamespaceIdentifiers_module"); ++if (arbitraryModuleNamespaceIdentifiers_module_3[""] !== "someValue") ++ throw "should be someValue"; ++exports[""] = __importStar(require("./arbitraryModuleNamespaceIdentifiers_module")); ++const arbitraryModuleNamespaceIdentifiers_module_4 = require("./arbitraryModuleNamespaceIdentifiers_module"); ++if (arbitraryModuleNamespaceIdentifiers_module_4[""][""] !== "someValue") ++ throw "should be someValue"; ++if (arbitraryModuleNamespaceIdentifiers_module_4[""][""] !== "someValue") ++ throw "should be someValue"; ++if (arbitraryModuleNamespaceIdentifiers_module_4[""][""] !== arbitraryModuleNamespaceIdentifiers_module_4[""]) ++ throw "should be export namespace"; ++const importTest = "expect error about someType"; ++const reimportTest = "expect error about someType"; ++const importStarTestA = "expect error about otherType"; ++ ++ ++//// [arbitraryModuleNamespaceIdentifiers_module.d.ts] ++declare const someValue = "someValue"; ++type someType = "someType"; ++export { someValue as "" }; ++export { "" as "" } from "./arbitraryModuleNamespaceIdentifiers_module"; ++export * as "" from "./arbitraryModuleNamespaceIdentifiers_module"; ++export { type someType as "" }; ++export { type "" as "" } from "./arbitraryModuleNamespaceIdentifiers_module"; ++export type * as "" from "./arbitraryModuleNamespaceIdentifiers_module"; ++export type otherType = "otherType"; +diff --git a/tests/baselines/reference/arbitraryModuleNamespaceIdentifiers_module(module=nodenext).symbols b/tests/baselines/reference/arbitraryModuleNamespaceIdentifiers_module(module=nodenext).symbols +new file mode 100644 +index 000000000..a792b7d3f +--- /dev/null ++++ b/tests/baselines/reference/arbitraryModuleNamespaceIdentifiers_module(module=nodenext).symbols +@@ -0,0 +1,82 @@ ++//// [tests/cases/conformance/es2022/arbitraryModuleNamespaceIdentifiers/arbitraryModuleNamespaceIdentifiers_module.ts] //// ++ ++=== arbitraryModuleNamespaceIdentifiers_module.ts === ++const someValue = "someValue"; ++>someValue : Symbol(someValue, Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 0, 5)) ++ ++type someType = "someType"; ++>someType : Symbol(someType, Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 0, 30)) ++ ++export { someValue as "" }; ++>someValue : Symbol(someValue, Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 0, 5)) ++>"" : Symbol(valueZ[""], Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 3, 8)) ++ ++import { "" as valueX } from "./arbitraryModuleNamespaceIdentifiers_module"; ++>valueX : Symbol(valueX, Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 4, 8)) ++ ++if (valueX !== "someValue") throw "should be someValue"; ++>valueX : Symbol(valueX, Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 4, 8)) ++ ++export { "" as "" } from "./arbitraryModuleNamespaceIdentifiers_module"; ++>"" : Symbol(valueZ[""], Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 7, 8)) ++ ++import { "" as valueY } from "./arbitraryModuleNamespaceIdentifiers_module"; ++>valueY : Symbol(valueY, Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 8, 8)) ++ ++if (valueY !== "someValue") throw "should be someValue"; ++>valueY : Symbol(valueY, Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 8, 8)) ++ ++export * as "" from "./arbitraryModuleNamespaceIdentifiers_module"; ++>"" : Symbol(valueZ[""], Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 11, 6)) ++ ++import { "" as valueZ } from "./arbitraryModuleNamespaceIdentifiers_module"; ++>valueZ : Symbol(valueZ, Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 12, 8)) ++ ++if (valueZ[""] !== "someValue") throw "should be someValue"; ++>valueZ : Symbol(valueZ, Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 12, 8)) ++>"" : Symbol(valueZ[""], Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 3, 8)) ++ ++if (valueZ[""] !== "someValue") throw "should be someValue"; ++>valueZ : Symbol(valueZ, Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 12, 8)) ++>"" : Symbol(valueZ[""], Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 7, 8)) ++ ++if (valueZ[""] !== valueZ) throw "should be export namespace"; ++>valueZ : Symbol(valueZ, Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 12, 8)) ++>"" : Symbol(valueZ[""], Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 11, 6)) ++>valueZ : Symbol(valueZ, Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 12, 8)) ++ ++export { type someType as "" }; ++>someType : Symbol(someType, Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 0, 30)) ++>"" : Symbol(valueZ[""], Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 17, 8)) ++ ++import { type "" as typeA } from "./arbitraryModuleNamespaceIdentifiers_module"; ++>typeA : Symbol(typeA, Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 18, 8)) ++ ++const importTest: typeA = "expect error about someType"; ++>importTest : Symbol(importTest, Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 19, 5)) ++>typeA : Symbol(typeA, Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 18, 8)) ++ ++export { type "" as "" } from "./arbitraryModuleNamespaceIdentifiers_module"; ++>"" : Symbol(valueZ[""], Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 21, 8)) ++ ++import { type "" as typeB } from "./arbitraryModuleNamespaceIdentifiers_module"; ++>typeB : Symbol(typeB, Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 22, 8)) ++ ++const reimportTest: typeB = "expect error about someType"; ++>reimportTest : Symbol(reimportTest, Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 23, 5)) ++>typeB : Symbol(typeB, Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 22, 8)) ++ ++export type * as "" from "./arbitraryModuleNamespaceIdentifiers_module"; ++>"" : Symbol(valueZ[""], Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 25, 11)) ++ ++import { type "" as typeC } from "./arbitraryModuleNamespaceIdentifiers_module"; ++>typeC : Symbol(typeC, Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 26, 8)) ++ ++export type otherType = "otherType"; ++>otherType : Symbol(valueZ.otherType, Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 26, 83)) ++ ++const importStarTestA: typeC.otherType = "expect error about otherType"; ++>importStarTestA : Symbol(importStarTestA, Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 28, 5)) ++>typeC : Symbol(typeC, Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 26, 8)) ++>otherType : Symbol(valueZ.otherType, Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 26, 83)) ++ +diff --git a/tests/baselines/reference/arbitraryModuleNamespaceIdentifiers_module(module=nodenext).types b/tests/baselines/reference/arbitraryModuleNamespaceIdentifiers_module(module=nodenext).types +new file mode 100644 +index 000000000..4574f9754 +--- /dev/null ++++ b/tests/baselines/reference/arbitraryModuleNamespaceIdentifiers_module(module=nodenext).types +@@ -0,0 +1,151 @@ ++//// [tests/cases/conformance/es2022/arbitraryModuleNamespaceIdentifiers/arbitraryModuleNamespaceIdentifiers_module.ts] //// ++ ++=== arbitraryModuleNamespaceIdentifiers_module.ts === ++const someValue = "someValue"; ++>someValue : "someValue" ++> : ^^^^^^^^^^^ ++>"someValue" : "someValue" ++> : ^^^^^^^^^^^ ++ ++type someType = "someType"; ++>someType : "someType" ++> : ^^^^^^^^^^ ++ ++export { someValue as "" }; ++>someValue : "someValue" ++> : ^^^^^^^^^^^ ++>"" : "someValue" ++> : ^^^^^^^^^^^ ++ ++import { "" as valueX } from "./arbitraryModuleNamespaceIdentifiers_module"; ++>valueX : "someValue" ++> : ^^^^^^^^^^^ ++ ++if (valueX !== "someValue") throw "should be someValue"; ++>valueX !== "someValue" : boolean ++> : ^^^^^^^ ++>valueX : "someValue" ++> : ^^^^^^^^^^^ ++>"someValue" : "someValue" ++> : ^^^^^^^^^^^ ++>"should be someValue" : "should be someValue" ++> : ^^^^^^^^^^^^^^^^^^^^^ ++ ++export { "" as "" } from "./arbitraryModuleNamespaceIdentifiers_module"; ++>"" : "someValue" ++> : ^^^^^^^^^^^ ++ ++import { "" as valueY } from "./arbitraryModuleNamespaceIdentifiers_module"; ++>valueY : "someValue" ++> : ^^^^^^^^^^^ ++ ++if (valueY !== "someValue") throw "should be someValue"; ++>valueY !== "someValue" : boolean ++> : ^^^^^^^ ++>valueY : "someValue" ++> : ^^^^^^^^^^^ ++>"someValue" : "someValue" ++> : ^^^^^^^^^^^ ++>"should be someValue" : "should be someValue" ++> : ^^^^^^^^^^^^^^^^^^^^^ ++ ++export * as "" from "./arbitraryModuleNamespaceIdentifiers_module"; ++>"" : typeof valueZ ++> : ^^^^^^^^^^^^^ ++ ++import { "" as valueZ } from "./arbitraryModuleNamespaceIdentifiers_module"; ++>valueZ : typeof valueZ ++> : ^^^^^^^^^^^^^ ++ ++if (valueZ[""] !== "someValue") throw "should be someValue"; ++>valueZ[""] !== "someValue" : boolean ++> : ^^^^^^^ ++>valueZ[""] : "someValue" ++> : ^^^^^^^^^^^ ++>valueZ : typeof valueZ ++> : ^^^^^^^^^^^^^ ++>"" : "" ++> : ^^^^^ ++>"someValue" : "someValue" ++> : ^^^^^^^^^^^ ++>"should be someValue" : "should be someValue" ++> : ^^^^^^^^^^^^^^^^^^^^^ ++ ++if (valueZ[""] !== "someValue") throw "should be someValue"; ++>valueZ[""] !== "someValue" : boolean ++> : ^^^^^^^ ++>valueZ[""] : "someValue" ++> : ^^^^^^^^^^^ ++>valueZ : typeof valueZ ++> : ^^^^^^^^^^^^^ ++>"" : "" ++> : ^^^^^ ++>"someValue" : "someValue" ++> : ^^^^^^^^^^^ ++>"should be someValue" : "should be someValue" ++> : ^^^^^^^^^^^^^^^^^^^^^ ++ ++if (valueZ[""] !== valueZ) throw "should be export namespace"; ++>valueZ[""] !== valueZ : boolean ++> : ^^^^^^^ ++>valueZ[""] : typeof valueZ ++> : ^^^^^^^^^^^^^ ++>valueZ : typeof valueZ ++> : ^^^^^^^^^^^^^ ++>"" : "" ++> : ^^^^^ ++>valueZ : typeof valueZ ++> : ^^^^^^^^^^^^^ ++>"should be export namespace" : "should be export namespace" ++> : ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ++ ++export { type someType as "" }; ++>someType : any ++> : ^^^ ++>"" : any ++> : ^^^ ++ ++import { type "" as typeA } from "./arbitraryModuleNamespaceIdentifiers_module"; ++>typeA : any ++> : ^^^ ++ ++const importTest: typeA = "expect error about someType"; ++>importTest : "someType" ++> : ^^^^^^^^^^ ++>"expect error about someType" : "expect error about someType" ++> : ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ++ ++export { type "" as "" } from "./arbitraryModuleNamespaceIdentifiers_module"; ++>"" : any ++> : ^^^ ++ ++import { type "" as typeB } from "./arbitraryModuleNamespaceIdentifiers_module"; ++>typeB : any ++> : ^^^ ++ ++const reimportTest: typeB = "expect error about someType"; ++>reimportTest : "someType" ++> : ^^^^^^^^^^ ++>"expect error about someType" : "expect error about someType" ++> : ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ++ ++export type * as "" from "./arbitraryModuleNamespaceIdentifiers_module"; ++>"" : typeof valueZ ++> : ^^^^^^^^^^^^^ ++ ++import { type "" as typeC } from "./arbitraryModuleNamespaceIdentifiers_module"; ++>typeC : typeof valueZ ++> : ^^^^^^^^^^^^^ ++ ++export type otherType = "otherType"; ++>otherType : "otherType" ++> : ^^^^^^^^^^^ ++ ++const importStarTestA: typeC.otherType = "expect error about otherType"; ++>importStarTestA : "otherType" ++> : ^^^^^^^^^^^ ++>typeC : any ++> : ^^^ ++>"expect error about otherType" : "expect error about otherType" ++> : ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ++ +diff --git a/tests/baselines/reference/arbitraryModuleNamespaceIdentifiers_module(module=none).errors.txt b/tests/baselines/reference/arbitraryModuleNamespaceIdentifiers_module(module=none).errors.txt +new file mode 100644 +index 000000000..cc359bceb +--- /dev/null ++++ b/tests/baselines/reference/arbitraryModuleNamespaceIdentifiers_module(module=none).errors.txt +@@ -0,0 +1,42 @@ ++arbitraryModuleNamespaceIdentifiers_module.ts(20,7): error TS2322: Type '"expect error about someType"' is not assignable to type '"someType"'. ++arbitraryModuleNamespaceIdentifiers_module.ts(24,7): error TS2322: Type '"expect error about someType"' is not assignable to type '"someType"'. ++arbitraryModuleNamespaceIdentifiers_module.ts(29,7): error TS2322: Type '"expect error about otherType"' is not assignable to type '"otherType"'. ++ ++ ++==== arbitraryModuleNamespaceIdentifiers_module.ts (3 errors) ==== ++ const someValue = "someValue"; ++ type someType = "someType"; ++ ++ export { someValue as "" }; ++ import { "" as valueX } from "./arbitraryModuleNamespaceIdentifiers_module"; ++ if (valueX !== "someValue") throw "should be someValue"; ++ ++ export { "" as "" } from "./arbitraryModuleNamespaceIdentifiers_module"; ++ import { "" as valueY } from "./arbitraryModuleNamespaceIdentifiers_module"; ++ if (valueY !== "someValue") throw "should be someValue"; ++ ++ export * as "" from "./arbitraryModuleNamespaceIdentifiers_module"; ++ import { "" as valueZ } from "./arbitraryModuleNamespaceIdentifiers_module"; ++ if (valueZ[""] !== "someValue") throw "should be someValue"; ++ if (valueZ[""] !== "someValue") throw "should be someValue"; ++ if (valueZ[""] !== valueZ) throw "should be export namespace"; ++ ++ export { type someType as "" }; ++ import { type "" as typeA } from "./arbitraryModuleNamespaceIdentifiers_module"; ++ const importTest: typeA = "expect error about someType"; ++ ~~~~~~~~~~ ++!!! error TS2322: Type '"expect error about someType"' is not assignable to type '"someType"'. ++ ++ export { type "" as "" } from "./arbitraryModuleNamespaceIdentifiers_module"; ++ import { type "" as typeB } from "./arbitraryModuleNamespaceIdentifiers_module"; ++ const reimportTest: typeB = "expect error about someType"; ++ ~~~~~~~~~~~~ ++!!! error TS2322: Type '"expect error about someType"' is not assignable to type '"someType"'. ++ ++ export type * as "" from "./arbitraryModuleNamespaceIdentifiers_module"; ++ import { type "" as typeC } from "./arbitraryModuleNamespaceIdentifiers_module"; ++ export type otherType = "otherType"; ++ const importStarTestA: typeC.otherType = "expect error about otherType"; ++ ~~~~~~~~~~~~~~~ ++!!! error TS2322: Type '"expect error about otherType"' is not assignable to type '"otherType"'. ++ +\ No newline at end of file +diff --git a/tests/baselines/reference/arbitraryModuleNamespaceIdentifiers_module(module=none).js b/tests/baselines/reference/arbitraryModuleNamespaceIdentifiers_module(module=none).js +new file mode 100644 +index 000000000..43f954515 +--- /dev/null ++++ b/tests/baselines/reference/arbitraryModuleNamespaceIdentifiers_module(module=none).js +@@ -0,0 +1,71 @@ ++//// [tests/cases/conformance/es2022/arbitraryModuleNamespaceIdentifiers/arbitraryModuleNamespaceIdentifiers_module.ts] //// ++ ++//// [arbitraryModuleNamespaceIdentifiers_module.ts] ++const someValue = "someValue"; ++type someType = "someType"; ++ ++export { someValue as "" }; ++import { "" as valueX } from "./arbitraryModuleNamespaceIdentifiers_module"; ++if (valueX !== "someValue") throw "should be someValue"; ++ ++export { "" as "" } from "./arbitraryModuleNamespaceIdentifiers_module"; ++import { "" as valueY } from "./arbitraryModuleNamespaceIdentifiers_module"; ++if (valueY !== "someValue") throw "should be someValue"; ++ ++export * as "" from "./arbitraryModuleNamespaceIdentifiers_module"; ++import { "" as valueZ } from "./arbitraryModuleNamespaceIdentifiers_module"; ++if (valueZ[""] !== "someValue") throw "should be someValue"; ++if (valueZ[""] !== "someValue") throw "should be someValue"; ++if (valueZ[""] !== valueZ) throw "should be export namespace"; ++ ++export { type someType as "" }; ++import { type "" as typeA } from "./arbitraryModuleNamespaceIdentifiers_module"; ++const importTest: typeA = "expect error about someType"; ++ ++export { type "" as "" } from "./arbitraryModuleNamespaceIdentifiers_module"; ++import { type "" as typeB } from "./arbitraryModuleNamespaceIdentifiers_module"; ++const reimportTest: typeB = "expect error about someType"; ++ ++export type * as "" from "./arbitraryModuleNamespaceIdentifiers_module"; ++import { type "" as typeC } from "./arbitraryModuleNamespaceIdentifiers_module"; ++export type otherType = "otherType"; ++const importStarTestA: typeC.otherType = "expect error about otherType"; ++ ++ ++//// [arbitraryModuleNamespaceIdentifiers_module.js] ++"use strict"; ++Object.defineProperty(exports, "__esModule", { value: true }); ++exports[""] = exports[""] = exports[""] = void 0; ++const someValue = "someValue"; ++exports[""] = someValue; ++const arbitraryModuleNamespaceIdentifiers_module_1 = require("./arbitraryModuleNamespaceIdentifiers_module"); ++if (arbitraryModuleNamespaceIdentifiers_module_1[""] !== "someValue") ++ throw "should be someValue"; ++var arbitraryModuleNamespaceIdentifiers_module_2 = require("./arbitraryModuleNamespaceIdentifiers_module"); ++Object.defineProperty(exports, "", { enumerable: true, get: function () { return arbitraryModuleNamespaceIdentifiers_module_2[""]; } }); ++const arbitraryModuleNamespaceIdentifiers_module_3 = require("./arbitraryModuleNamespaceIdentifiers_module"); ++if (arbitraryModuleNamespaceIdentifiers_module_3[""] !== "someValue") ++ throw "should be someValue"; ++exports[""] = require("./arbitraryModuleNamespaceIdentifiers_module"); ++const arbitraryModuleNamespaceIdentifiers_module_4 = require("./arbitraryModuleNamespaceIdentifiers_module"); ++if (arbitraryModuleNamespaceIdentifiers_module_4[""][""] !== "someValue") ++ throw "should be someValue"; ++if (arbitraryModuleNamespaceIdentifiers_module_4[""][""] !== "someValue") ++ throw "should be someValue"; ++if (arbitraryModuleNamespaceIdentifiers_module_4[""][""] !== arbitraryModuleNamespaceIdentifiers_module_4[""]) ++ throw "should be export namespace"; ++const importTest = "expect error about someType"; ++const reimportTest = "expect error about someType"; ++const importStarTestA = "expect error about otherType"; ++ ++ ++//// [arbitraryModuleNamespaceIdentifiers_module.d.ts] ++declare const someValue = "someValue"; ++type someType = "someType"; ++export { someValue as "" }; ++export { "" as "" } from "./arbitraryModuleNamespaceIdentifiers_module"; ++export * as "" from "./arbitraryModuleNamespaceIdentifiers_module"; ++export { type someType as "" }; ++export { type "" as "" } from "./arbitraryModuleNamespaceIdentifiers_module"; ++export type * as "" from "./arbitraryModuleNamespaceIdentifiers_module"; ++export type otherType = "otherType"; +diff --git a/tests/baselines/reference/arbitraryModuleNamespaceIdentifiers_module(module=none).symbols b/tests/baselines/reference/arbitraryModuleNamespaceIdentifiers_module(module=none).symbols +new file mode 100644 +index 000000000..a792b7d3f +--- /dev/null ++++ b/tests/baselines/reference/arbitraryModuleNamespaceIdentifiers_module(module=none).symbols +@@ -0,0 +1,82 @@ ++//// [tests/cases/conformance/es2022/arbitraryModuleNamespaceIdentifiers/arbitraryModuleNamespaceIdentifiers_module.ts] //// ++ ++=== arbitraryModuleNamespaceIdentifiers_module.ts === ++const someValue = "someValue"; ++>someValue : Symbol(someValue, Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 0, 5)) ++ ++type someType = "someType"; ++>someType : Symbol(someType, Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 0, 30)) ++ ++export { someValue as "" }; ++>someValue : Symbol(someValue, Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 0, 5)) ++>"" : Symbol(valueZ[""], Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 3, 8)) ++ ++import { "" as valueX } from "./arbitraryModuleNamespaceIdentifiers_module"; ++>valueX : Symbol(valueX, Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 4, 8)) ++ ++if (valueX !== "someValue") throw "should be someValue"; ++>valueX : Symbol(valueX, Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 4, 8)) ++ ++export { "" as "" } from "./arbitraryModuleNamespaceIdentifiers_module"; ++>"" : Symbol(valueZ[""], Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 7, 8)) ++ ++import { "" as valueY } from "./arbitraryModuleNamespaceIdentifiers_module"; ++>valueY : Symbol(valueY, Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 8, 8)) ++ ++if (valueY !== "someValue") throw "should be someValue"; ++>valueY : Symbol(valueY, Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 8, 8)) ++ ++export * as "" from "./arbitraryModuleNamespaceIdentifiers_module"; ++>"" : Symbol(valueZ[""], Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 11, 6)) ++ ++import { "" as valueZ } from "./arbitraryModuleNamespaceIdentifiers_module"; ++>valueZ : Symbol(valueZ, Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 12, 8)) ++ ++if (valueZ[""] !== "someValue") throw "should be someValue"; ++>valueZ : Symbol(valueZ, Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 12, 8)) ++>"" : Symbol(valueZ[""], Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 3, 8)) ++ ++if (valueZ[""] !== "someValue") throw "should be someValue"; ++>valueZ : Symbol(valueZ, Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 12, 8)) ++>"" : Symbol(valueZ[""], Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 7, 8)) ++ ++if (valueZ[""] !== valueZ) throw "should be export namespace"; ++>valueZ : Symbol(valueZ, Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 12, 8)) ++>"" : Symbol(valueZ[""], Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 11, 6)) ++>valueZ : Symbol(valueZ, Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 12, 8)) ++ ++export { type someType as "" }; ++>someType : Symbol(someType, Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 0, 30)) ++>"" : Symbol(valueZ[""], Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 17, 8)) ++ ++import { type "" as typeA } from "./arbitraryModuleNamespaceIdentifiers_module"; ++>typeA : Symbol(typeA, Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 18, 8)) ++ ++const importTest: typeA = "expect error about someType"; ++>importTest : Symbol(importTest, Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 19, 5)) ++>typeA : Symbol(typeA, Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 18, 8)) ++ ++export { type "" as "" } from "./arbitraryModuleNamespaceIdentifiers_module"; ++>"" : Symbol(valueZ[""], Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 21, 8)) ++ ++import { type "" as typeB } from "./arbitraryModuleNamespaceIdentifiers_module"; ++>typeB : Symbol(typeB, Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 22, 8)) ++ ++const reimportTest: typeB = "expect error about someType"; ++>reimportTest : Symbol(reimportTest, Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 23, 5)) ++>typeB : Symbol(typeB, Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 22, 8)) ++ ++export type * as "" from "./arbitraryModuleNamespaceIdentifiers_module"; ++>"" : Symbol(valueZ[""], Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 25, 11)) ++ ++import { type "" as typeC } from "./arbitraryModuleNamespaceIdentifiers_module"; ++>typeC : Symbol(typeC, Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 26, 8)) ++ ++export type otherType = "otherType"; ++>otherType : Symbol(valueZ.otherType, Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 26, 83)) ++ ++const importStarTestA: typeC.otherType = "expect error about otherType"; ++>importStarTestA : Symbol(importStarTestA, Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 28, 5)) ++>typeC : Symbol(typeC, Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 26, 8)) ++>otherType : Symbol(valueZ.otherType, Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 26, 83)) ++ +diff --git a/tests/baselines/reference/arbitraryModuleNamespaceIdentifiers_module(module=none).types b/tests/baselines/reference/arbitraryModuleNamespaceIdentifiers_module(module=none).types +new file mode 100644 +index 000000000..4574f9754 +--- /dev/null ++++ b/tests/baselines/reference/arbitraryModuleNamespaceIdentifiers_module(module=none).types +@@ -0,0 +1,151 @@ ++//// [tests/cases/conformance/es2022/arbitraryModuleNamespaceIdentifiers/arbitraryModuleNamespaceIdentifiers_module.ts] //// ++ ++=== arbitraryModuleNamespaceIdentifiers_module.ts === ++const someValue = "someValue"; ++>someValue : "someValue" ++> : ^^^^^^^^^^^ ++>"someValue" : "someValue" ++> : ^^^^^^^^^^^ ++ ++type someType = "someType"; ++>someType : "someType" ++> : ^^^^^^^^^^ ++ ++export { someValue as "" }; ++>someValue : "someValue" ++> : ^^^^^^^^^^^ ++>"" : "someValue" ++> : ^^^^^^^^^^^ ++ ++import { "" as valueX } from "./arbitraryModuleNamespaceIdentifiers_module"; ++>valueX : "someValue" ++> : ^^^^^^^^^^^ ++ ++if (valueX !== "someValue") throw "should be someValue"; ++>valueX !== "someValue" : boolean ++> : ^^^^^^^ ++>valueX : "someValue" ++> : ^^^^^^^^^^^ ++>"someValue" : "someValue" ++> : ^^^^^^^^^^^ ++>"should be someValue" : "should be someValue" ++> : ^^^^^^^^^^^^^^^^^^^^^ ++ ++export { "" as "" } from "./arbitraryModuleNamespaceIdentifiers_module"; ++>"" : "someValue" ++> : ^^^^^^^^^^^ ++ ++import { "" as valueY } from "./arbitraryModuleNamespaceIdentifiers_module"; ++>valueY : "someValue" ++> : ^^^^^^^^^^^ ++ ++if (valueY !== "someValue") throw "should be someValue"; ++>valueY !== "someValue" : boolean ++> : ^^^^^^^ ++>valueY : "someValue" ++> : ^^^^^^^^^^^ ++>"someValue" : "someValue" ++> : ^^^^^^^^^^^ ++>"should be someValue" : "should be someValue" ++> : ^^^^^^^^^^^^^^^^^^^^^ ++ ++export * as "" from "./arbitraryModuleNamespaceIdentifiers_module"; ++>"" : typeof valueZ ++> : ^^^^^^^^^^^^^ ++ ++import { "" as valueZ } from "./arbitraryModuleNamespaceIdentifiers_module"; ++>valueZ : typeof valueZ ++> : ^^^^^^^^^^^^^ ++ ++if (valueZ[""] !== "someValue") throw "should be someValue"; ++>valueZ[""] !== "someValue" : boolean ++> : ^^^^^^^ ++>valueZ[""] : "someValue" ++> : ^^^^^^^^^^^ ++>valueZ : typeof valueZ ++> : ^^^^^^^^^^^^^ ++>"" : "" ++> : ^^^^^ ++>"someValue" : "someValue" ++> : ^^^^^^^^^^^ ++>"should be someValue" : "should be someValue" ++> : ^^^^^^^^^^^^^^^^^^^^^ ++ ++if (valueZ[""] !== "someValue") throw "should be someValue"; ++>valueZ[""] !== "someValue" : boolean ++> : ^^^^^^^ ++>valueZ[""] : "someValue" ++> : ^^^^^^^^^^^ ++>valueZ : typeof valueZ ++> : ^^^^^^^^^^^^^ ++>"" : "" ++> : ^^^^^ ++>"someValue" : "someValue" ++> : ^^^^^^^^^^^ ++>"should be someValue" : "should be someValue" ++> : ^^^^^^^^^^^^^^^^^^^^^ ++ ++if (valueZ[""] !== valueZ) throw "should be export namespace"; ++>valueZ[""] !== valueZ : boolean ++> : ^^^^^^^ ++>valueZ[""] : typeof valueZ ++> : ^^^^^^^^^^^^^ ++>valueZ : typeof valueZ ++> : ^^^^^^^^^^^^^ ++>"" : "" ++> : ^^^^^ ++>valueZ : typeof valueZ ++> : ^^^^^^^^^^^^^ ++>"should be export namespace" : "should be export namespace" ++> : ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ++ ++export { type someType as "" }; ++>someType : any ++> : ^^^ ++>"" : any ++> : ^^^ ++ ++import { type "" as typeA } from "./arbitraryModuleNamespaceIdentifiers_module"; ++>typeA : any ++> : ^^^ ++ ++const importTest: typeA = "expect error about someType"; ++>importTest : "someType" ++> : ^^^^^^^^^^ ++>"expect error about someType" : "expect error about someType" ++> : ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ++ ++export { type "" as "" } from "./arbitraryModuleNamespaceIdentifiers_module"; ++>"" : any ++> : ^^^ ++ ++import { type "" as typeB } from "./arbitraryModuleNamespaceIdentifiers_module"; ++>typeB : any ++> : ^^^ ++ ++const reimportTest: typeB = "expect error about someType"; ++>reimportTest : "someType" ++> : ^^^^^^^^^^ ++>"expect error about someType" : "expect error about someType" ++> : ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ++ ++export type * as "" from "./arbitraryModuleNamespaceIdentifiers_module"; ++>"" : typeof valueZ ++> : ^^^^^^^^^^^^^ ++ ++import { type "" as typeC } from "./arbitraryModuleNamespaceIdentifiers_module"; ++>typeC : typeof valueZ ++> : ^^^^^^^^^^^^^ ++ ++export type otherType = "otherType"; ++>otherType : "otherType" ++> : ^^^^^^^^^^^ ++ ++const importStarTestA: typeC.otherType = "expect error about otherType"; ++>importStarTestA : "otherType" ++> : ^^^^^^^^^^^ ++>typeC : any ++> : ^^^ ++>"expect error about otherType" : "expect error about otherType" ++> : ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ++ +diff --git a/tests/baselines/reference/arbitraryModuleNamespaceIdentifiers_module(module=preserve).errors.txt b/tests/baselines/reference/arbitraryModuleNamespaceIdentifiers_module(module=preserve).errors.txt +new file mode 100644 +index 000000000..cc359bceb +--- /dev/null ++++ b/tests/baselines/reference/arbitraryModuleNamespaceIdentifiers_module(module=preserve).errors.txt +@@ -0,0 +1,42 @@ ++arbitraryModuleNamespaceIdentifiers_module.ts(20,7): error TS2322: Type '"expect error about someType"' is not assignable to type '"someType"'. ++arbitraryModuleNamespaceIdentifiers_module.ts(24,7): error TS2322: Type '"expect error about someType"' is not assignable to type '"someType"'. ++arbitraryModuleNamespaceIdentifiers_module.ts(29,7): error TS2322: Type '"expect error about otherType"' is not assignable to type '"otherType"'. ++ ++ ++==== arbitraryModuleNamespaceIdentifiers_module.ts (3 errors) ==== ++ const someValue = "someValue"; ++ type someType = "someType"; ++ ++ export { someValue as "" }; ++ import { "" as valueX } from "./arbitraryModuleNamespaceIdentifiers_module"; ++ if (valueX !== "someValue") throw "should be someValue"; ++ ++ export { "" as "" } from "./arbitraryModuleNamespaceIdentifiers_module"; ++ import { "" as valueY } from "./arbitraryModuleNamespaceIdentifiers_module"; ++ if (valueY !== "someValue") throw "should be someValue"; ++ ++ export * as "" from "./arbitraryModuleNamespaceIdentifiers_module"; ++ import { "" as valueZ } from "./arbitraryModuleNamespaceIdentifiers_module"; ++ if (valueZ[""] !== "someValue") throw "should be someValue"; ++ if (valueZ[""] !== "someValue") throw "should be someValue"; ++ if (valueZ[""] !== valueZ) throw "should be export namespace"; ++ ++ export { type someType as "" }; ++ import { type "" as typeA } from "./arbitraryModuleNamespaceIdentifiers_module"; ++ const importTest: typeA = "expect error about someType"; ++ ~~~~~~~~~~ ++!!! error TS2322: Type '"expect error about someType"' is not assignable to type '"someType"'. ++ ++ export { type "" as "" } from "./arbitraryModuleNamespaceIdentifiers_module"; ++ import { type "" as typeB } from "./arbitraryModuleNamespaceIdentifiers_module"; ++ const reimportTest: typeB = "expect error about someType"; ++ ~~~~~~~~~~~~ ++!!! error TS2322: Type '"expect error about someType"' is not assignable to type '"someType"'. ++ ++ export type * as "" from "./arbitraryModuleNamespaceIdentifiers_module"; ++ import { type "" as typeC } from "./arbitraryModuleNamespaceIdentifiers_module"; ++ export type otherType = "otherType"; ++ const importStarTestA: typeC.otherType = "expect error about otherType"; ++ ~~~~~~~~~~~~~~~ ++!!! error TS2322: Type '"expect error about otherType"' is not assignable to type '"otherType"'. ++ +\ No newline at end of file +diff --git a/tests/baselines/reference/arbitraryModuleNamespaceIdentifiers_module(module=preserve).js b/tests/baselines/reference/arbitraryModuleNamespaceIdentifiers_module(module=preserve).js +new file mode 100644 +index 000000000..4964f684a +--- /dev/null ++++ b/tests/baselines/reference/arbitraryModuleNamespaceIdentifiers_module(module=preserve).js +@@ -0,0 +1,67 @@ ++//// [tests/cases/conformance/es2022/arbitraryModuleNamespaceIdentifiers/arbitraryModuleNamespaceIdentifiers_module.ts] //// ++ ++//// [arbitraryModuleNamespaceIdentifiers_module.ts] ++const someValue = "someValue"; ++type someType = "someType"; ++ ++export { someValue as "" }; ++import { "" as valueX } from "./arbitraryModuleNamespaceIdentifiers_module"; ++if (valueX !== "someValue") throw "should be someValue"; ++ ++export { "" as "" } from "./arbitraryModuleNamespaceIdentifiers_module"; ++import { "" as valueY } from "./arbitraryModuleNamespaceIdentifiers_module"; ++if (valueY !== "someValue") throw "should be someValue"; ++ ++export * as "" from "./arbitraryModuleNamespaceIdentifiers_module"; ++import { "" as valueZ } from "./arbitraryModuleNamespaceIdentifiers_module"; ++if (valueZ[""] !== "someValue") throw "should be someValue"; ++if (valueZ[""] !== "someValue") throw "should be someValue"; ++if (valueZ[""] !== valueZ) throw "should be export namespace"; ++ ++export { type someType as "" }; ++import { type "" as typeA } from "./arbitraryModuleNamespaceIdentifiers_module"; ++const importTest: typeA = "expect error about someType"; ++ ++export { type "" as "" } from "./arbitraryModuleNamespaceIdentifiers_module"; ++import { type "" as typeB } from "./arbitraryModuleNamespaceIdentifiers_module"; ++const reimportTest: typeB = "expect error about someType"; ++ ++export type * as "" from "./arbitraryModuleNamespaceIdentifiers_module"; ++import { type "" as typeC } from "./arbitraryModuleNamespaceIdentifiers_module"; ++export type otherType = "otherType"; ++const importStarTestA: typeC.otherType = "expect error about otherType"; ++ ++ ++//// [arbitraryModuleNamespaceIdentifiers_module.js] ++const someValue = "someValue"; ++export { someValue as "" }; ++import { "" as valueX } from "./arbitraryModuleNamespaceIdentifiers_module"; ++if (valueX !== "someValue") ++ throw "should be someValue"; ++export { "" as "" } from "./arbitraryModuleNamespaceIdentifiers_module"; ++import { "" as valueY } from "./arbitraryModuleNamespaceIdentifiers_module"; ++if (valueY !== "someValue") ++ throw "should be someValue"; ++export * as "" from "./arbitraryModuleNamespaceIdentifiers_module"; ++import { "" as valueZ } from "./arbitraryModuleNamespaceIdentifiers_module"; ++if (valueZ[""] !== "someValue") ++ throw "should be someValue"; ++if (valueZ[""] !== "someValue") ++ throw "should be someValue"; ++if (valueZ[""] !== valueZ) ++ throw "should be export namespace"; ++const importTest = "expect error about someType"; ++const reimportTest = "expect error about someType"; ++const importStarTestA = "expect error about otherType"; ++ ++ ++//// [arbitraryModuleNamespaceIdentifiers_module.d.ts] ++declare const someValue = "someValue"; ++type someType = "someType"; ++export { someValue as "" }; ++export { "" as "" } from "./arbitraryModuleNamespaceIdentifiers_module"; ++export * as "" from "./arbitraryModuleNamespaceIdentifiers_module"; ++export { type someType as "" }; ++export { type "" as "" } from "./arbitraryModuleNamespaceIdentifiers_module"; ++export type * as "" from "./arbitraryModuleNamespaceIdentifiers_module"; ++export type otherType = "otherType"; +diff --git a/tests/baselines/reference/arbitraryModuleNamespaceIdentifiers_module(module=preserve).symbols b/tests/baselines/reference/arbitraryModuleNamespaceIdentifiers_module(module=preserve).symbols +new file mode 100644 +index 000000000..a792b7d3f +--- /dev/null ++++ b/tests/baselines/reference/arbitraryModuleNamespaceIdentifiers_module(module=preserve).symbols +@@ -0,0 +1,82 @@ ++//// [tests/cases/conformance/es2022/arbitraryModuleNamespaceIdentifiers/arbitraryModuleNamespaceIdentifiers_module.ts] //// ++ ++=== arbitraryModuleNamespaceIdentifiers_module.ts === ++const someValue = "someValue"; ++>someValue : Symbol(someValue, Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 0, 5)) ++ ++type someType = "someType"; ++>someType : Symbol(someType, Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 0, 30)) ++ ++export { someValue as "" }; ++>someValue : Symbol(someValue, Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 0, 5)) ++>"" : Symbol(valueZ[""], Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 3, 8)) ++ ++import { "" as valueX } from "./arbitraryModuleNamespaceIdentifiers_module"; ++>valueX : Symbol(valueX, Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 4, 8)) ++ ++if (valueX !== "someValue") throw "should be someValue"; ++>valueX : Symbol(valueX, Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 4, 8)) ++ ++export { "" as "" } from "./arbitraryModuleNamespaceIdentifiers_module"; ++>"" : Symbol(valueZ[""], Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 7, 8)) ++ ++import { "" as valueY } from "./arbitraryModuleNamespaceIdentifiers_module"; ++>valueY : Symbol(valueY, Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 8, 8)) ++ ++if (valueY !== "someValue") throw "should be someValue"; ++>valueY : Symbol(valueY, Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 8, 8)) ++ ++export * as "" from "./arbitraryModuleNamespaceIdentifiers_module"; ++>"" : Symbol(valueZ[""], Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 11, 6)) ++ ++import { "" as valueZ } from "./arbitraryModuleNamespaceIdentifiers_module"; ++>valueZ : Symbol(valueZ, Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 12, 8)) ++ ++if (valueZ[""] !== "someValue") throw "should be someValue"; ++>valueZ : Symbol(valueZ, Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 12, 8)) ++>"" : Symbol(valueZ[""], Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 3, 8)) ++ ++if (valueZ[""] !== "someValue") throw "should be someValue"; ++>valueZ : Symbol(valueZ, Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 12, 8)) ++>"" : Symbol(valueZ[""], Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 7, 8)) ++ ++if (valueZ[""] !== valueZ) throw "should be export namespace"; ++>valueZ : Symbol(valueZ, Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 12, 8)) ++>"" : Symbol(valueZ[""], Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 11, 6)) ++>valueZ : Symbol(valueZ, Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 12, 8)) ++ ++export { type someType as "" }; ++>someType : Symbol(someType, Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 0, 30)) ++>"" : Symbol(valueZ[""], Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 17, 8)) ++ ++import { type "" as typeA } from "./arbitraryModuleNamespaceIdentifiers_module"; ++>typeA : Symbol(typeA, Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 18, 8)) ++ ++const importTest: typeA = "expect error about someType"; ++>importTest : Symbol(importTest, Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 19, 5)) ++>typeA : Symbol(typeA, Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 18, 8)) ++ ++export { type "" as "" } from "./arbitraryModuleNamespaceIdentifiers_module"; ++>"" : Symbol(valueZ[""], Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 21, 8)) ++ ++import { type "" as typeB } from "./arbitraryModuleNamespaceIdentifiers_module"; ++>typeB : Symbol(typeB, Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 22, 8)) ++ ++const reimportTest: typeB = "expect error about someType"; ++>reimportTest : Symbol(reimportTest, Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 23, 5)) ++>typeB : Symbol(typeB, Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 22, 8)) ++ ++export type * as "" from "./arbitraryModuleNamespaceIdentifiers_module"; ++>"" : Symbol(valueZ[""], Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 25, 11)) ++ ++import { type "" as typeC } from "./arbitraryModuleNamespaceIdentifiers_module"; ++>typeC : Symbol(typeC, Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 26, 8)) ++ ++export type otherType = "otherType"; ++>otherType : Symbol(valueZ.otherType, Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 26, 83)) ++ ++const importStarTestA: typeC.otherType = "expect error about otherType"; ++>importStarTestA : Symbol(importStarTestA, Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 28, 5)) ++>typeC : Symbol(typeC, Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 26, 8)) ++>otherType : Symbol(valueZ.otherType, Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 26, 83)) ++ +diff --git a/tests/baselines/reference/arbitraryModuleNamespaceIdentifiers_module(module=preserve).types b/tests/baselines/reference/arbitraryModuleNamespaceIdentifiers_module(module=preserve).types +new file mode 100644 +index 000000000..4574f9754 +--- /dev/null ++++ b/tests/baselines/reference/arbitraryModuleNamespaceIdentifiers_module(module=preserve).types +@@ -0,0 +1,151 @@ ++//// [tests/cases/conformance/es2022/arbitraryModuleNamespaceIdentifiers/arbitraryModuleNamespaceIdentifiers_module.ts] //// ++ ++=== arbitraryModuleNamespaceIdentifiers_module.ts === ++const someValue = "someValue"; ++>someValue : "someValue" ++> : ^^^^^^^^^^^ ++>"someValue" : "someValue" ++> : ^^^^^^^^^^^ ++ ++type someType = "someType"; ++>someType : "someType" ++> : ^^^^^^^^^^ ++ ++export { someValue as "" }; ++>someValue : "someValue" ++> : ^^^^^^^^^^^ ++>"" : "someValue" ++> : ^^^^^^^^^^^ ++ ++import { "" as valueX } from "./arbitraryModuleNamespaceIdentifiers_module"; ++>valueX : "someValue" ++> : ^^^^^^^^^^^ ++ ++if (valueX !== "someValue") throw "should be someValue"; ++>valueX !== "someValue" : boolean ++> : ^^^^^^^ ++>valueX : "someValue" ++> : ^^^^^^^^^^^ ++>"someValue" : "someValue" ++> : ^^^^^^^^^^^ ++>"should be someValue" : "should be someValue" ++> : ^^^^^^^^^^^^^^^^^^^^^ ++ ++export { "" as "" } from "./arbitraryModuleNamespaceIdentifiers_module"; ++>"" : "someValue" ++> : ^^^^^^^^^^^ ++ ++import { "" as valueY } from "./arbitraryModuleNamespaceIdentifiers_module"; ++>valueY : "someValue" ++> : ^^^^^^^^^^^ ++ ++if (valueY !== "someValue") throw "should be someValue"; ++>valueY !== "someValue" : boolean ++> : ^^^^^^^ ++>valueY : "someValue" ++> : ^^^^^^^^^^^ ++>"someValue" : "someValue" ++> : ^^^^^^^^^^^ ++>"should be someValue" : "should be someValue" ++> : ^^^^^^^^^^^^^^^^^^^^^ ++ ++export * as "" from "./arbitraryModuleNamespaceIdentifiers_module"; ++>"" : typeof valueZ ++> : ^^^^^^^^^^^^^ ++ ++import { "" as valueZ } from "./arbitraryModuleNamespaceIdentifiers_module"; ++>valueZ : typeof valueZ ++> : ^^^^^^^^^^^^^ ++ ++if (valueZ[""] !== "someValue") throw "should be someValue"; ++>valueZ[""] !== "someValue" : boolean ++> : ^^^^^^^ ++>valueZ[""] : "someValue" ++> : ^^^^^^^^^^^ ++>valueZ : typeof valueZ ++> : ^^^^^^^^^^^^^ ++>"" : "" ++> : ^^^^^ ++>"someValue" : "someValue" ++> : ^^^^^^^^^^^ ++>"should be someValue" : "should be someValue" ++> : ^^^^^^^^^^^^^^^^^^^^^ ++ ++if (valueZ[""] !== "someValue") throw "should be someValue"; ++>valueZ[""] !== "someValue" : boolean ++> : ^^^^^^^ ++>valueZ[""] : "someValue" ++> : ^^^^^^^^^^^ ++>valueZ : typeof valueZ ++> : ^^^^^^^^^^^^^ ++>"" : "" ++> : ^^^^^ ++>"someValue" : "someValue" ++> : ^^^^^^^^^^^ ++>"should be someValue" : "should be someValue" ++> : ^^^^^^^^^^^^^^^^^^^^^ ++ ++if (valueZ[""] !== valueZ) throw "should be export namespace"; ++>valueZ[""] !== valueZ : boolean ++> : ^^^^^^^ ++>valueZ[""] : typeof valueZ ++> : ^^^^^^^^^^^^^ ++>valueZ : typeof valueZ ++> : ^^^^^^^^^^^^^ ++>"" : "" ++> : ^^^^^ ++>valueZ : typeof valueZ ++> : ^^^^^^^^^^^^^ ++>"should be export namespace" : "should be export namespace" ++> : ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ++ ++export { type someType as "" }; ++>someType : any ++> : ^^^ ++>"" : any ++> : ^^^ ++ ++import { type "" as typeA } from "./arbitraryModuleNamespaceIdentifiers_module"; ++>typeA : any ++> : ^^^ ++ ++const importTest: typeA = "expect error about someType"; ++>importTest : "someType" ++> : ^^^^^^^^^^ ++>"expect error about someType" : "expect error about someType" ++> : ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ++ ++export { type "" as "" } from "./arbitraryModuleNamespaceIdentifiers_module"; ++>"" : any ++> : ^^^ ++ ++import { type "" as typeB } from "./arbitraryModuleNamespaceIdentifiers_module"; ++>typeB : any ++> : ^^^ ++ ++const reimportTest: typeB = "expect error about someType"; ++>reimportTest : "someType" ++> : ^^^^^^^^^^ ++>"expect error about someType" : "expect error about someType" ++> : ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ++ ++export type * as "" from "./arbitraryModuleNamespaceIdentifiers_module"; ++>"" : typeof valueZ ++> : ^^^^^^^^^^^^^ ++ ++import { type "" as typeC } from "./arbitraryModuleNamespaceIdentifiers_module"; ++>typeC : typeof valueZ ++> : ^^^^^^^^^^^^^ ++ ++export type otherType = "otherType"; ++>otherType : "otherType" ++> : ^^^^^^^^^^^ ++ ++const importStarTestA: typeC.otherType = "expect error about otherType"; ++>importStarTestA : "otherType" ++> : ^^^^^^^^^^^ ++>typeC : any ++> : ^^^ ++>"expect error about otherType" : "expect error about otherType" ++> : ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ++ +diff --git a/tests/baselines/reference/arbitraryModuleNamespaceIdentifiers_module(module=system).errors.txt b/tests/baselines/reference/arbitraryModuleNamespaceIdentifiers_module(module=system).errors.txt +new file mode 100644 +index 000000000..cc359bceb +--- /dev/null ++++ b/tests/baselines/reference/arbitraryModuleNamespaceIdentifiers_module(module=system).errors.txt +@@ -0,0 +1,42 @@ ++arbitraryModuleNamespaceIdentifiers_module.ts(20,7): error TS2322: Type '"expect error about someType"' is not assignable to type '"someType"'. ++arbitraryModuleNamespaceIdentifiers_module.ts(24,7): error TS2322: Type '"expect error about someType"' is not assignable to type '"someType"'. ++arbitraryModuleNamespaceIdentifiers_module.ts(29,7): error TS2322: Type '"expect error about otherType"' is not assignable to type '"otherType"'. ++ ++ ++==== arbitraryModuleNamespaceIdentifiers_module.ts (3 errors) ==== ++ const someValue = "someValue"; ++ type someType = "someType"; ++ ++ export { someValue as "" }; ++ import { "" as valueX } from "./arbitraryModuleNamespaceIdentifiers_module"; ++ if (valueX !== "someValue") throw "should be someValue"; ++ ++ export { "" as "" } from "./arbitraryModuleNamespaceIdentifiers_module"; ++ import { "" as valueY } from "./arbitraryModuleNamespaceIdentifiers_module"; ++ if (valueY !== "someValue") throw "should be someValue"; ++ ++ export * as "" from "./arbitraryModuleNamespaceIdentifiers_module"; ++ import { "" as valueZ } from "./arbitraryModuleNamespaceIdentifiers_module"; ++ if (valueZ[""] !== "someValue") throw "should be someValue"; ++ if (valueZ[""] !== "someValue") throw "should be someValue"; ++ if (valueZ[""] !== valueZ) throw "should be export namespace"; ++ ++ export { type someType as "" }; ++ import { type "" as typeA } from "./arbitraryModuleNamespaceIdentifiers_module"; ++ const importTest: typeA = "expect error about someType"; ++ ~~~~~~~~~~ ++!!! error TS2322: Type '"expect error about someType"' is not assignable to type '"someType"'. ++ ++ export { type "" as "" } from "./arbitraryModuleNamespaceIdentifiers_module"; ++ import { type "" as typeB } from "./arbitraryModuleNamespaceIdentifiers_module"; ++ const reimportTest: typeB = "expect error about someType"; ++ ~~~~~~~~~~~~ ++!!! error TS2322: Type '"expect error about someType"' is not assignable to type '"someType"'. ++ ++ export type * as "" from "./arbitraryModuleNamespaceIdentifiers_module"; ++ import { type "" as typeC } from "./arbitraryModuleNamespaceIdentifiers_module"; ++ export type otherType = "otherType"; ++ const importStarTestA: typeC.otherType = "expect error about otherType"; ++ ~~~~~~~~~~~~~~~ ++!!! error TS2322: Type '"expect error about otherType"' is not assignable to type '"otherType"'. ++ +\ No newline at end of file +diff --git a/tests/baselines/reference/arbitraryModuleNamespaceIdentifiers_module(module=system).js b/tests/baselines/reference/arbitraryModuleNamespaceIdentifiers_module(module=system).js +new file mode 100644 +index 000000000..c746a3ba3 +--- /dev/null ++++ b/tests/baselines/reference/arbitraryModuleNamespaceIdentifiers_module(module=system).js +@@ -0,0 +1,82 @@ ++//// [tests/cases/conformance/es2022/arbitraryModuleNamespaceIdentifiers/arbitraryModuleNamespaceIdentifiers_module.ts] //// ++ ++//// [arbitraryModuleNamespaceIdentifiers_module.ts] ++const someValue = "someValue"; ++type someType = "someType"; ++ ++export { someValue as "" }; ++import { "" as valueX } from "./arbitraryModuleNamespaceIdentifiers_module"; ++if (valueX !== "someValue") throw "should be someValue"; ++ ++export { "" as "" } from "./arbitraryModuleNamespaceIdentifiers_module"; ++import { "" as valueY } from "./arbitraryModuleNamespaceIdentifiers_module"; ++if (valueY !== "someValue") throw "should be someValue"; ++ ++export * as "" from "./arbitraryModuleNamespaceIdentifiers_module"; ++import { "" as valueZ } from "./arbitraryModuleNamespaceIdentifiers_module"; ++if (valueZ[""] !== "someValue") throw "should be someValue"; ++if (valueZ[""] !== "someValue") throw "should be someValue"; ++if (valueZ[""] !== valueZ) throw "should be export namespace"; ++ ++export { type someType as "" }; ++import { type "" as typeA } from "./arbitraryModuleNamespaceIdentifiers_module"; ++const importTest: typeA = "expect error about someType"; ++ ++export { type "" as "" } from "./arbitraryModuleNamespaceIdentifiers_module"; ++import { type "" as typeB } from "./arbitraryModuleNamespaceIdentifiers_module"; ++const reimportTest: typeB = "expect error about someType"; ++ ++export type * as "" from "./arbitraryModuleNamespaceIdentifiers_module"; ++import { type "" as typeC } from "./arbitraryModuleNamespaceIdentifiers_module"; ++export type otherType = "otherType"; ++const importStarTestA: typeC.otherType = "expect error about otherType"; ++ ++ ++//// [arbitraryModuleNamespaceIdentifiers_module.js] ++System.register(["./arbitraryModuleNamespaceIdentifiers_module"], function (exports_1, context_1) { ++ "use strict"; ++ var someValue, arbitraryModuleNamespaceIdentifiers_module_1, arbitraryModuleNamespaceIdentifiers_module_2, arbitraryModuleNamespaceIdentifiers_module_3, importTest, reimportTest, importStarTestA; ++ var __moduleName = context_1 && context_1.id; ++ return { ++ setters: [ ++ function (arbitraryModuleNamespaceIdentifiers_module_1_1) { ++ arbitraryModuleNamespaceIdentifiers_module_1 = arbitraryModuleNamespaceIdentifiers_module_1_1; ++ exports_1({ ++ "": arbitraryModuleNamespaceIdentifiers_module_1_1[""] ++ }); ++ arbitraryModuleNamespaceIdentifiers_module_2 = arbitraryModuleNamespaceIdentifiers_module_1_1; ++ exports_1("", arbitraryModuleNamespaceIdentifiers_module_1_1); ++ arbitraryModuleNamespaceIdentifiers_module_3 = arbitraryModuleNamespaceIdentifiers_module_1_1; ++ } ++ ], ++ execute: function () { ++ someValue = "someValue"; ++ exports_1("", someValue); ++ if (arbitraryModuleNamespaceIdentifiers_module_1[""] !== "someValue") ++ throw "should be someValue"; ++ if (arbitraryModuleNamespaceIdentifiers_module_2[""] !== "someValue") ++ throw "should be someValue"; ++ if (arbitraryModuleNamespaceIdentifiers_module_3[""][""] !== "someValue") ++ throw "should be someValue"; ++ if (arbitraryModuleNamespaceIdentifiers_module_3[""][""] !== "someValue") ++ throw "should be someValue"; ++ if (arbitraryModuleNamespaceIdentifiers_module_3[""][""] !== arbitraryModuleNamespaceIdentifiers_module_3[""]) ++ throw "should be export namespace"; ++ importTest = "expect error about someType"; ++ reimportTest = "expect error about someType"; ++ importStarTestA = "expect error about otherType"; ++ } ++ }; ++}); ++ ++ ++//// [arbitraryModuleNamespaceIdentifiers_module.d.ts] ++declare const someValue = "someValue"; ++type someType = "someType"; ++export { someValue as "" }; ++export { "" as "" } from "./arbitraryModuleNamespaceIdentifiers_module"; ++export * as "" from "./arbitraryModuleNamespaceIdentifiers_module"; ++export { type someType as "" }; ++export { type "" as "" } from "./arbitraryModuleNamespaceIdentifiers_module"; ++export type * as "" from "./arbitraryModuleNamespaceIdentifiers_module"; ++export type otherType = "otherType"; +diff --git a/tests/baselines/reference/arbitraryModuleNamespaceIdentifiers_module(module=system).symbols b/tests/baselines/reference/arbitraryModuleNamespaceIdentifiers_module(module=system).symbols +new file mode 100644 +index 000000000..a792b7d3f +--- /dev/null ++++ b/tests/baselines/reference/arbitraryModuleNamespaceIdentifiers_module(module=system).symbols +@@ -0,0 +1,82 @@ ++//// [tests/cases/conformance/es2022/arbitraryModuleNamespaceIdentifiers/arbitraryModuleNamespaceIdentifiers_module.ts] //// ++ ++=== arbitraryModuleNamespaceIdentifiers_module.ts === ++const someValue = "someValue"; ++>someValue : Symbol(someValue, Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 0, 5)) ++ ++type someType = "someType"; ++>someType : Symbol(someType, Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 0, 30)) ++ ++export { someValue as "" }; ++>someValue : Symbol(someValue, Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 0, 5)) ++>"" : Symbol(valueZ[""], Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 3, 8)) ++ ++import { "" as valueX } from "./arbitraryModuleNamespaceIdentifiers_module"; ++>valueX : Symbol(valueX, Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 4, 8)) ++ ++if (valueX !== "someValue") throw "should be someValue"; ++>valueX : Symbol(valueX, Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 4, 8)) ++ ++export { "" as "" } from "./arbitraryModuleNamespaceIdentifiers_module"; ++>"" : Symbol(valueZ[""], Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 7, 8)) ++ ++import { "" as valueY } from "./arbitraryModuleNamespaceIdentifiers_module"; ++>valueY : Symbol(valueY, Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 8, 8)) ++ ++if (valueY !== "someValue") throw "should be someValue"; ++>valueY : Symbol(valueY, Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 8, 8)) ++ ++export * as "" from "./arbitraryModuleNamespaceIdentifiers_module"; ++>"" : Symbol(valueZ[""], Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 11, 6)) ++ ++import { "" as valueZ } from "./arbitraryModuleNamespaceIdentifiers_module"; ++>valueZ : Symbol(valueZ, Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 12, 8)) ++ ++if (valueZ[""] !== "someValue") throw "should be someValue"; ++>valueZ : Symbol(valueZ, Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 12, 8)) ++>"" : Symbol(valueZ[""], Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 3, 8)) ++ ++if (valueZ[""] !== "someValue") throw "should be someValue"; ++>valueZ : Symbol(valueZ, Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 12, 8)) ++>"" : Symbol(valueZ[""], Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 7, 8)) ++ ++if (valueZ[""] !== valueZ) throw "should be export namespace"; ++>valueZ : Symbol(valueZ, Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 12, 8)) ++>"" : Symbol(valueZ[""], Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 11, 6)) ++>valueZ : Symbol(valueZ, Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 12, 8)) ++ ++export { type someType as "" }; ++>someType : Symbol(someType, Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 0, 30)) ++>"" : Symbol(valueZ[""], Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 17, 8)) ++ ++import { type "" as typeA } from "./arbitraryModuleNamespaceIdentifiers_module"; ++>typeA : Symbol(typeA, Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 18, 8)) ++ ++const importTest: typeA = "expect error about someType"; ++>importTest : Symbol(importTest, Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 19, 5)) ++>typeA : Symbol(typeA, Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 18, 8)) ++ ++export { type "" as "" } from "./arbitraryModuleNamespaceIdentifiers_module"; ++>"" : Symbol(valueZ[""], Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 21, 8)) ++ ++import { type "" as typeB } from "./arbitraryModuleNamespaceIdentifiers_module"; ++>typeB : Symbol(typeB, Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 22, 8)) ++ ++const reimportTest: typeB = "expect error about someType"; ++>reimportTest : Symbol(reimportTest, Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 23, 5)) ++>typeB : Symbol(typeB, Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 22, 8)) ++ ++export type * as "" from "./arbitraryModuleNamespaceIdentifiers_module"; ++>"" : Symbol(valueZ[""], Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 25, 11)) ++ ++import { type "" as typeC } from "./arbitraryModuleNamespaceIdentifiers_module"; ++>typeC : Symbol(typeC, Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 26, 8)) ++ ++export type otherType = "otherType"; ++>otherType : Symbol(valueZ.otherType, Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 26, 83)) ++ ++const importStarTestA: typeC.otherType = "expect error about otherType"; ++>importStarTestA : Symbol(importStarTestA, Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 28, 5)) ++>typeC : Symbol(typeC, Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 26, 8)) ++>otherType : Symbol(valueZ.otherType, Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 26, 83)) ++ +diff --git a/tests/baselines/reference/arbitraryModuleNamespaceIdentifiers_module(module=system).types b/tests/baselines/reference/arbitraryModuleNamespaceIdentifiers_module(module=system).types +new file mode 100644 +index 000000000..4574f9754 +--- /dev/null ++++ b/tests/baselines/reference/arbitraryModuleNamespaceIdentifiers_module(module=system).types +@@ -0,0 +1,151 @@ ++//// [tests/cases/conformance/es2022/arbitraryModuleNamespaceIdentifiers/arbitraryModuleNamespaceIdentifiers_module.ts] //// ++ ++=== arbitraryModuleNamespaceIdentifiers_module.ts === ++const someValue = "someValue"; ++>someValue : "someValue" ++> : ^^^^^^^^^^^ ++>"someValue" : "someValue" ++> : ^^^^^^^^^^^ ++ ++type someType = "someType"; ++>someType : "someType" ++> : ^^^^^^^^^^ ++ ++export { someValue as "" }; ++>someValue : "someValue" ++> : ^^^^^^^^^^^ ++>"" : "someValue" ++> : ^^^^^^^^^^^ ++ ++import { "" as valueX } from "./arbitraryModuleNamespaceIdentifiers_module"; ++>valueX : "someValue" ++> : ^^^^^^^^^^^ ++ ++if (valueX !== "someValue") throw "should be someValue"; ++>valueX !== "someValue" : boolean ++> : ^^^^^^^ ++>valueX : "someValue" ++> : ^^^^^^^^^^^ ++>"someValue" : "someValue" ++> : ^^^^^^^^^^^ ++>"should be someValue" : "should be someValue" ++> : ^^^^^^^^^^^^^^^^^^^^^ ++ ++export { "" as "" } from "./arbitraryModuleNamespaceIdentifiers_module"; ++>"" : "someValue" ++> : ^^^^^^^^^^^ ++ ++import { "" as valueY } from "./arbitraryModuleNamespaceIdentifiers_module"; ++>valueY : "someValue" ++> : ^^^^^^^^^^^ ++ ++if (valueY !== "someValue") throw "should be someValue"; ++>valueY !== "someValue" : boolean ++> : ^^^^^^^ ++>valueY : "someValue" ++> : ^^^^^^^^^^^ ++>"someValue" : "someValue" ++> : ^^^^^^^^^^^ ++>"should be someValue" : "should be someValue" ++> : ^^^^^^^^^^^^^^^^^^^^^ ++ ++export * as "" from "./arbitraryModuleNamespaceIdentifiers_module"; ++>"" : typeof valueZ ++> : ^^^^^^^^^^^^^ ++ ++import { "" as valueZ } from "./arbitraryModuleNamespaceIdentifiers_module"; ++>valueZ : typeof valueZ ++> : ^^^^^^^^^^^^^ ++ ++if (valueZ[""] !== "someValue") throw "should be someValue"; ++>valueZ[""] !== "someValue" : boolean ++> : ^^^^^^^ ++>valueZ[""] : "someValue" ++> : ^^^^^^^^^^^ ++>valueZ : typeof valueZ ++> : ^^^^^^^^^^^^^ ++>"" : "" ++> : ^^^^^ ++>"someValue" : "someValue" ++> : ^^^^^^^^^^^ ++>"should be someValue" : "should be someValue" ++> : ^^^^^^^^^^^^^^^^^^^^^ ++ ++if (valueZ[""] !== "someValue") throw "should be someValue"; ++>valueZ[""] !== "someValue" : boolean ++> : ^^^^^^^ ++>valueZ[""] : "someValue" ++> : ^^^^^^^^^^^ ++>valueZ : typeof valueZ ++> : ^^^^^^^^^^^^^ ++>"" : "" ++> : ^^^^^ ++>"someValue" : "someValue" ++> : ^^^^^^^^^^^ ++>"should be someValue" : "should be someValue" ++> : ^^^^^^^^^^^^^^^^^^^^^ ++ ++if (valueZ[""] !== valueZ) throw "should be export namespace"; ++>valueZ[""] !== valueZ : boolean ++> : ^^^^^^^ ++>valueZ[""] : typeof valueZ ++> : ^^^^^^^^^^^^^ ++>valueZ : typeof valueZ ++> : ^^^^^^^^^^^^^ ++>"" : "" ++> : ^^^^^ ++>valueZ : typeof valueZ ++> : ^^^^^^^^^^^^^ ++>"should be export namespace" : "should be export namespace" ++> : ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ++ ++export { type someType as "" }; ++>someType : any ++> : ^^^ ++>"" : any ++> : ^^^ ++ ++import { type "" as typeA } from "./arbitraryModuleNamespaceIdentifiers_module"; ++>typeA : any ++> : ^^^ ++ ++const importTest: typeA = "expect error about someType"; ++>importTest : "someType" ++> : ^^^^^^^^^^ ++>"expect error about someType" : "expect error about someType" ++> : ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ++ ++export { type "" as "" } from "./arbitraryModuleNamespaceIdentifiers_module"; ++>"" : any ++> : ^^^ ++ ++import { type "" as typeB } from "./arbitraryModuleNamespaceIdentifiers_module"; ++>typeB : any ++> : ^^^ ++ ++const reimportTest: typeB = "expect error about someType"; ++>reimportTest : "someType" ++> : ^^^^^^^^^^ ++>"expect error about someType" : "expect error about someType" ++> : ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ++ ++export type * as "" from "./arbitraryModuleNamespaceIdentifiers_module"; ++>"" : typeof valueZ ++> : ^^^^^^^^^^^^^ ++ ++import { type "" as typeC } from "./arbitraryModuleNamespaceIdentifiers_module"; ++>typeC : typeof valueZ ++> : ^^^^^^^^^^^^^ ++ ++export type otherType = "otherType"; ++>otherType : "otherType" ++> : ^^^^^^^^^^^ ++ ++const importStarTestA: typeC.otherType = "expect error about otherType"; ++>importStarTestA : "otherType" ++> : ^^^^^^^^^^^ ++>typeC : any ++> : ^^^ ++>"expect error about otherType" : "expect error about otherType" ++> : ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ++ +diff --git a/tests/baselines/reference/arbitraryModuleNamespaceIdentifiers_module(module=umd).errors.txt b/tests/baselines/reference/arbitraryModuleNamespaceIdentifiers_module(module=umd).errors.txt +new file mode 100644 +index 000000000..cc359bceb +--- /dev/null ++++ b/tests/baselines/reference/arbitraryModuleNamespaceIdentifiers_module(module=umd).errors.txt +@@ -0,0 +1,42 @@ ++arbitraryModuleNamespaceIdentifiers_module.ts(20,7): error TS2322: Type '"expect error about someType"' is not assignable to type '"someType"'. ++arbitraryModuleNamespaceIdentifiers_module.ts(24,7): error TS2322: Type '"expect error about someType"' is not assignable to type '"someType"'. ++arbitraryModuleNamespaceIdentifiers_module.ts(29,7): error TS2322: Type '"expect error about otherType"' is not assignable to type '"otherType"'. ++ ++ ++==== arbitraryModuleNamespaceIdentifiers_module.ts (3 errors) ==== ++ const someValue = "someValue"; ++ type someType = "someType"; ++ ++ export { someValue as "" }; ++ import { "" as valueX } from "./arbitraryModuleNamespaceIdentifiers_module"; ++ if (valueX !== "someValue") throw "should be someValue"; ++ ++ export { "" as "" } from "./arbitraryModuleNamespaceIdentifiers_module"; ++ import { "" as valueY } from "./arbitraryModuleNamespaceIdentifiers_module"; ++ if (valueY !== "someValue") throw "should be someValue"; ++ ++ export * as "" from "./arbitraryModuleNamespaceIdentifiers_module"; ++ import { "" as valueZ } from "./arbitraryModuleNamespaceIdentifiers_module"; ++ if (valueZ[""] !== "someValue") throw "should be someValue"; ++ if (valueZ[""] !== "someValue") throw "should be someValue"; ++ if (valueZ[""] !== valueZ) throw "should be export namespace"; ++ ++ export { type someType as "" }; ++ import { type "" as typeA } from "./arbitraryModuleNamespaceIdentifiers_module"; ++ const importTest: typeA = "expect error about someType"; ++ ~~~~~~~~~~ ++!!! error TS2322: Type '"expect error about someType"' is not assignable to type '"someType"'. ++ ++ export { type "" as "" } from "./arbitraryModuleNamespaceIdentifiers_module"; ++ import { type "" as typeB } from "./arbitraryModuleNamespaceIdentifiers_module"; ++ const reimportTest: typeB = "expect error about someType"; ++ ~~~~~~~~~~~~ ++!!! error TS2322: Type '"expect error about someType"' is not assignable to type '"someType"'. ++ ++ export type * as "" from "./arbitraryModuleNamespaceIdentifiers_module"; ++ import { type "" as typeC } from "./arbitraryModuleNamespaceIdentifiers_module"; ++ export type otherType = "otherType"; ++ const importStarTestA: typeC.otherType = "expect error about otherType"; ++ ~~~~~~~~~~~~~~~ ++!!! error TS2322: Type '"expect error about otherType"' is not assignable to type '"otherType"'. ++ +\ No newline at end of file +diff --git a/tests/baselines/reference/arbitraryModuleNamespaceIdentifiers_module(module=umd).js b/tests/baselines/reference/arbitraryModuleNamespaceIdentifiers_module(module=umd).js +new file mode 100644 +index 000000000..a21466756 +--- /dev/null ++++ b/tests/baselines/reference/arbitraryModuleNamespaceIdentifiers_module(module=umd).js +@@ -0,0 +1,81 @@ ++//// [tests/cases/conformance/es2022/arbitraryModuleNamespaceIdentifiers/arbitraryModuleNamespaceIdentifiers_module.ts] //// ++ ++//// [arbitraryModuleNamespaceIdentifiers_module.ts] ++const someValue = "someValue"; ++type someType = "someType"; ++ ++export { someValue as "" }; ++import { "" as valueX } from "./arbitraryModuleNamespaceIdentifiers_module"; ++if (valueX !== "someValue") throw "should be someValue"; ++ ++export { "" as "" } from "./arbitraryModuleNamespaceIdentifiers_module"; ++import { "" as valueY } from "./arbitraryModuleNamespaceIdentifiers_module"; ++if (valueY !== "someValue") throw "should be someValue"; ++ ++export * as "" from "./arbitraryModuleNamespaceIdentifiers_module"; ++import { "" as valueZ } from "./arbitraryModuleNamespaceIdentifiers_module"; ++if (valueZ[""] !== "someValue") throw "should be someValue"; ++if (valueZ[""] !== "someValue") throw "should be someValue"; ++if (valueZ[""] !== valueZ) throw "should be export namespace"; ++ ++export { type someType as "" }; ++import { type "" as typeA } from "./arbitraryModuleNamespaceIdentifiers_module"; ++const importTest: typeA = "expect error about someType"; ++ ++export { type "" as "" } from "./arbitraryModuleNamespaceIdentifiers_module"; ++import { type "" as typeB } from "./arbitraryModuleNamespaceIdentifiers_module"; ++const reimportTest: typeB = "expect error about someType"; ++ ++export type * as "" from "./arbitraryModuleNamespaceIdentifiers_module"; ++import { type "" as typeC } from "./arbitraryModuleNamespaceIdentifiers_module"; ++export type otherType = "otherType"; ++const importStarTestA: typeC.otherType = "expect error about otherType"; ++ ++ ++//// [arbitraryModuleNamespaceIdentifiers_module.js] ++(function (factory) { ++ if (typeof module === "object" && typeof module.exports === "object") { ++ var v = factory(require, exports); ++ if (v !== undefined) module.exports = v; ++ } ++ else if (typeof define === "function" && define.amd) { ++ define(["require", "exports", "./arbitraryModuleNamespaceIdentifiers_module", "./arbitraryModuleNamespaceIdentifiers_module", "./arbitraryModuleNamespaceIdentifiers_module", "./arbitraryModuleNamespaceIdentifiers_module", "./arbitraryModuleNamespaceIdentifiers_module"], factory); ++ } ++})(function (require, exports) { ++ "use strict"; ++ Object.defineProperty(exports, "__esModule", { value: true }); ++ exports[""] = exports[""] = exports[""] = void 0; ++ const someValue = "someValue"; ++ exports[""] = someValue; ++ const arbitraryModuleNamespaceIdentifiers_module_1 = require("./arbitraryModuleNamespaceIdentifiers_module"); ++ if (arbitraryModuleNamespaceIdentifiers_module_1[""] !== "someValue") ++ throw "should be someValue"; ++ var arbitraryModuleNamespaceIdentifiers_module_2 = require("./arbitraryModuleNamespaceIdentifiers_module"); ++ Object.defineProperty(exports, "", { enumerable: true, get: function () { return arbitraryModuleNamespaceIdentifiers_module_2[""]; } }); ++ const arbitraryModuleNamespaceIdentifiers_module_3 = require("./arbitraryModuleNamespaceIdentifiers_module"); ++ if (arbitraryModuleNamespaceIdentifiers_module_3[""] !== "someValue") ++ throw "should be someValue"; ++ exports[""] = require("./arbitraryModuleNamespaceIdentifiers_module"); ++ const arbitraryModuleNamespaceIdentifiers_module_4 = require("./arbitraryModuleNamespaceIdentifiers_module"); ++ if (arbitraryModuleNamespaceIdentifiers_module_4[""][""] !== "someValue") ++ throw "should be someValue"; ++ if (arbitraryModuleNamespaceIdentifiers_module_4[""][""] !== "someValue") ++ throw "should be someValue"; ++ if (arbitraryModuleNamespaceIdentifiers_module_4[""][""] !== arbitraryModuleNamespaceIdentifiers_module_4[""]) ++ throw "should be export namespace"; ++ const importTest = "expect error about someType"; ++ const reimportTest = "expect error about someType"; ++ const importStarTestA = "expect error about otherType"; ++}); ++ ++ ++//// [arbitraryModuleNamespaceIdentifiers_module.d.ts] ++declare const someValue = "someValue"; ++type someType = "someType"; ++export { someValue as "" }; ++export { "" as "" } from "./arbitraryModuleNamespaceIdentifiers_module"; ++export * as "" from "./arbitraryModuleNamespaceIdentifiers_module"; ++export { type someType as "" }; ++export { type "" as "" } from "./arbitraryModuleNamespaceIdentifiers_module"; ++export type * as "" from "./arbitraryModuleNamespaceIdentifiers_module"; ++export type otherType = "otherType"; +diff --git a/tests/baselines/reference/arbitraryModuleNamespaceIdentifiers_module(module=umd).symbols b/tests/baselines/reference/arbitraryModuleNamespaceIdentifiers_module(module=umd).symbols +new file mode 100644 +index 000000000..a792b7d3f +--- /dev/null ++++ b/tests/baselines/reference/arbitraryModuleNamespaceIdentifiers_module(module=umd).symbols +@@ -0,0 +1,82 @@ ++//// [tests/cases/conformance/es2022/arbitraryModuleNamespaceIdentifiers/arbitraryModuleNamespaceIdentifiers_module.ts] //// ++ ++=== arbitraryModuleNamespaceIdentifiers_module.ts === ++const someValue = "someValue"; ++>someValue : Symbol(someValue, Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 0, 5)) ++ ++type someType = "someType"; ++>someType : Symbol(someType, Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 0, 30)) ++ ++export { someValue as "" }; ++>someValue : Symbol(someValue, Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 0, 5)) ++>"" : Symbol(valueZ[""], Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 3, 8)) ++ ++import { "" as valueX } from "./arbitraryModuleNamespaceIdentifiers_module"; ++>valueX : Symbol(valueX, Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 4, 8)) ++ ++if (valueX !== "someValue") throw "should be someValue"; ++>valueX : Symbol(valueX, Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 4, 8)) ++ ++export { "" as "" } from "./arbitraryModuleNamespaceIdentifiers_module"; ++>"" : Symbol(valueZ[""], Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 7, 8)) ++ ++import { "" as valueY } from "./arbitraryModuleNamespaceIdentifiers_module"; ++>valueY : Symbol(valueY, Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 8, 8)) ++ ++if (valueY !== "someValue") throw "should be someValue"; ++>valueY : Symbol(valueY, Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 8, 8)) ++ ++export * as "" from "./arbitraryModuleNamespaceIdentifiers_module"; ++>"" : Symbol(valueZ[""], Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 11, 6)) ++ ++import { "" as valueZ } from "./arbitraryModuleNamespaceIdentifiers_module"; ++>valueZ : Symbol(valueZ, Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 12, 8)) ++ ++if (valueZ[""] !== "someValue") throw "should be someValue"; ++>valueZ : Symbol(valueZ, Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 12, 8)) ++>"" : Symbol(valueZ[""], Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 3, 8)) ++ ++if (valueZ[""] !== "someValue") throw "should be someValue"; ++>valueZ : Symbol(valueZ, Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 12, 8)) ++>"" : Symbol(valueZ[""], Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 7, 8)) ++ ++if (valueZ[""] !== valueZ) throw "should be export namespace"; ++>valueZ : Symbol(valueZ, Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 12, 8)) ++>"" : Symbol(valueZ[""], Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 11, 6)) ++>valueZ : Symbol(valueZ, Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 12, 8)) ++ ++export { type someType as "" }; ++>someType : Symbol(someType, Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 0, 30)) ++>"" : Symbol(valueZ[""], Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 17, 8)) ++ ++import { type "" as typeA } from "./arbitraryModuleNamespaceIdentifiers_module"; ++>typeA : Symbol(typeA, Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 18, 8)) ++ ++const importTest: typeA = "expect error about someType"; ++>importTest : Symbol(importTest, Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 19, 5)) ++>typeA : Symbol(typeA, Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 18, 8)) ++ ++export { type "" as "" } from "./arbitraryModuleNamespaceIdentifiers_module"; ++>"" : Symbol(valueZ[""], Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 21, 8)) ++ ++import { type "" as typeB } from "./arbitraryModuleNamespaceIdentifiers_module"; ++>typeB : Symbol(typeB, Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 22, 8)) ++ ++const reimportTest: typeB = "expect error about someType"; ++>reimportTest : Symbol(reimportTest, Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 23, 5)) ++>typeB : Symbol(typeB, Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 22, 8)) ++ ++export type * as "" from "./arbitraryModuleNamespaceIdentifiers_module"; ++>"" : Symbol(valueZ[""], Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 25, 11)) ++ ++import { type "" as typeC } from "./arbitraryModuleNamespaceIdentifiers_module"; ++>typeC : Symbol(typeC, Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 26, 8)) ++ ++export type otherType = "otherType"; ++>otherType : Symbol(valueZ.otherType, Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 26, 83)) ++ ++const importStarTestA: typeC.otherType = "expect error about otherType"; ++>importStarTestA : Symbol(importStarTestA, Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 28, 5)) ++>typeC : Symbol(typeC, Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 26, 8)) ++>otherType : Symbol(valueZ.otherType, Decl(arbitraryModuleNamespaceIdentifiers_module.ts, 26, 83)) ++ +diff --git a/tests/baselines/reference/arbitraryModuleNamespaceIdentifiers_module(module=umd).types b/tests/baselines/reference/arbitraryModuleNamespaceIdentifiers_module(module=umd).types +new file mode 100644 +index 000000000..4574f9754 +--- /dev/null ++++ b/tests/baselines/reference/arbitraryModuleNamespaceIdentifiers_module(module=umd).types +@@ -0,0 +1,151 @@ ++//// [tests/cases/conformance/es2022/arbitraryModuleNamespaceIdentifiers/arbitraryModuleNamespaceIdentifiers_module.ts] //// ++ ++=== arbitraryModuleNamespaceIdentifiers_module.ts === ++const someValue = "someValue"; ++>someValue : "someValue" ++> : ^^^^^^^^^^^ ++>"someValue" : "someValue" ++> : ^^^^^^^^^^^ ++ ++type someType = "someType"; ++>someType : "someType" ++> : ^^^^^^^^^^ ++ ++export { someValue as "" }; ++>someValue : "someValue" ++> : ^^^^^^^^^^^ ++>"" : "someValue" ++> : ^^^^^^^^^^^ ++ ++import { "" as valueX } from "./arbitraryModuleNamespaceIdentifiers_module"; ++>valueX : "someValue" ++> : ^^^^^^^^^^^ ++ ++if (valueX !== "someValue") throw "should be someValue"; ++>valueX !== "someValue" : boolean ++> : ^^^^^^^ ++>valueX : "someValue" ++> : ^^^^^^^^^^^ ++>"someValue" : "someValue" ++> : ^^^^^^^^^^^ ++>"should be someValue" : "should be someValue" ++> : ^^^^^^^^^^^^^^^^^^^^^ ++ ++export { "" as "" } from "./arbitraryModuleNamespaceIdentifiers_module"; ++>"" : "someValue" ++> : ^^^^^^^^^^^ ++ ++import { "" as valueY } from "./arbitraryModuleNamespaceIdentifiers_module"; ++>valueY : "someValue" ++> : ^^^^^^^^^^^ ++ ++if (valueY !== "someValue") throw "should be someValue"; ++>valueY !== "someValue" : boolean ++> : ^^^^^^^ ++>valueY : "someValue" ++> : ^^^^^^^^^^^ ++>"someValue" : "someValue" ++> : ^^^^^^^^^^^ ++>"should be someValue" : "should be someValue" ++> : ^^^^^^^^^^^^^^^^^^^^^ ++ ++export * as "" from "./arbitraryModuleNamespaceIdentifiers_module"; ++>"" : typeof valueZ ++> : ^^^^^^^^^^^^^ ++ ++import { "" as valueZ } from "./arbitraryModuleNamespaceIdentifiers_module"; ++>valueZ : typeof valueZ ++> : ^^^^^^^^^^^^^ ++ ++if (valueZ[""] !== "someValue") throw "should be someValue"; ++>valueZ[""] !== "someValue" : boolean ++> : ^^^^^^^ ++>valueZ[""] : "someValue" ++> : ^^^^^^^^^^^ ++>valueZ : typeof valueZ ++> : ^^^^^^^^^^^^^ ++>"" : "" ++> : ^^^^^ ++>"someValue" : "someValue" ++> : ^^^^^^^^^^^ ++>"should be someValue" : "should be someValue" ++> : ^^^^^^^^^^^^^^^^^^^^^ ++ ++if (valueZ[""] !== "someValue") throw "should be someValue"; ++>valueZ[""] !== "someValue" : boolean ++> : ^^^^^^^ ++>valueZ[""] : "someValue" ++> : ^^^^^^^^^^^ ++>valueZ : typeof valueZ ++> : ^^^^^^^^^^^^^ ++>"" : "" ++> : ^^^^^ ++>"someValue" : "someValue" ++> : ^^^^^^^^^^^ ++>"should be someValue" : "should be someValue" ++> : ^^^^^^^^^^^^^^^^^^^^^ ++ ++if (valueZ[""] !== valueZ) throw "should be export namespace"; ++>valueZ[""] !== valueZ : boolean ++> : ^^^^^^^ ++>valueZ[""] : typeof valueZ ++> : ^^^^^^^^^^^^^ ++>valueZ : typeof valueZ ++> : ^^^^^^^^^^^^^ ++>"" : "" ++> : ^^^^^ ++>valueZ : typeof valueZ ++> : ^^^^^^^^^^^^^ ++>"should be export namespace" : "should be export namespace" ++> : ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ++ ++export { type someType as "" }; ++>someType : any ++> : ^^^ ++>"" : any ++> : ^^^ ++ ++import { type "" as typeA } from "./arbitraryModuleNamespaceIdentifiers_module"; ++>typeA : any ++> : ^^^ ++ ++const importTest: typeA = "expect error about someType"; ++>importTest : "someType" ++> : ^^^^^^^^^^ ++>"expect error about someType" : "expect error about someType" ++> : ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ++ ++export { type "" as "" } from "./arbitraryModuleNamespaceIdentifiers_module"; ++>"" : any ++> : ^^^ ++ ++import { type "" as typeB } from "./arbitraryModuleNamespaceIdentifiers_module"; ++>typeB : any ++> : ^^^ ++ ++const reimportTest: typeB = "expect error about someType"; ++>reimportTest : "someType" ++> : ^^^^^^^^^^ ++>"expect error about someType" : "expect error about someType" ++> : ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ++ ++export type * as "" from "./arbitraryModuleNamespaceIdentifiers_module"; ++>"" : typeof valueZ ++> : ^^^^^^^^^^^^^ ++ ++import { type "" as typeC } from "./arbitraryModuleNamespaceIdentifiers_module"; ++>typeC : typeof valueZ ++> : ^^^^^^^^^^^^^ ++ ++export type otherType = "otherType"; ++>otherType : "otherType" ++> : ^^^^^^^^^^^ ++ ++const importStarTestA: typeC.otherType = "expect error about otherType"; ++>importStarTestA : "otherType" ++> : ^^^^^^^^^^^ ++>typeC : any ++> : ^^^ ++>"expect error about otherType" : "expect error about otherType" ++> : ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ++ +diff --git a/tests/baselines/reference/arbitraryModuleNamespaceIdentifiers_syntax.errors.txt b/tests/baselines/reference/arbitraryModuleNamespaceIdentifiers_syntax.errors.txt +new file mode 100644 +index 000000000..e5307689d +--- /dev/null ++++ b/tests/baselines/reference/arbitraryModuleNamespaceIdentifiers_syntax.errors.txt +@@ -0,0 +1,107 @@ ++type-clause-bad-export.ts(1,15): error TS1003: Identifier expected. ++type-clause-bad-import.ts(1,22): error TS1003: Identifier expected. ++type-clause-no-as.ts(1,15): error TS1003: Identifier expected. ++type-clause-type-as-as.ts(1,15): error TS2305: Module '"./type-clause-valid"' has no exported member 'as'. ++type-clause-type-as-as.ts(1,21): error TS1003: Identifier expected. ++type-decls-bad-export.ts(1,15): error TS1003: Identifier expected. ++type-decls-bad-import.ts(1,22): error TS1003: Identifier expected. ++type-decls-no-as.ts(1,15): error TS1003: Identifier expected. ++type-decls-type-as.ts(1,15): error TS2305: Module '"./type-decls-valid"' has no exported member 'type'. ++type-decls-type-as.ts(1,23): error TS1003: Identifier expected. ++values-bad-export.ts(1,10): error TS1003: Identifier expected. ++values-bad-import.ts(1,17): error TS1003: Identifier expected. ++values-no-as.ts(1,10): error TS1003: Identifier expected. ++values-type-as.ts(1,10): error TS2305: Module '"./values-valid"' has no exported member 'type'. ++values-type-as.ts(1,18): error TS1003: Identifier expected. ++ ++ ++==== values-valid.ts (0 errors) ==== ++ export const foo = 123; ++ export { foo as "valid 1" }; ++ import { "valid 1" as bar } from "./values-valid"; ++ export { "valid 1" as "valid 2" } from "./values-valid"; ++ export { foo as "valid 3" } from "./values-valid"; ++ export * as "valid 4" from "./values-valid"; ++ ++==== values-bad-import.ts (1 errors) ==== ++ import { foo as "invalid 2" } from "./values-valid"; ++ ~~~~~~~~~~~ ++!!! error TS1003: Identifier expected. ++ ++==== values-bad-export.ts (1 errors) ==== ++ export { "invalid 3" as baz }; ++ ~~~~~~~~~~~ ++!!! error TS1003: Identifier expected. ++ ++==== values-no-as.ts (1 errors) ==== ++ import { "invalid 1" } from "./values-valid"; ++ ~~~~~~~~~~~ ++!!! error TS1003: Identifier expected. ++ ++==== values-type-as.ts (2 errors) ==== ++ import { type as "invalid 4" } from "./values-valid"; ++ ~~~~ ++!!! error TS2305: Module '"./values-valid"' has no exported member 'type'. ++ ~~~~~~~~~~~ ++!!! error TS1003: Identifier expected. ++ ++ ++==== type-decls-valid.ts (0 errors) ==== ++ export type foo = 123; ++ export type { foo as "valid 1" }; ++ import type { "valid 1" as bar } from "./type-decls-valid"; ++ export type { "valid 1" as "valid 2" } from "./type-decls-valid"; ++ export type { foo as "valid 3" } from "./type-decls-valid"; ++ export type * as "valid 4" from "./type-decls-valid"; ++ ++==== type-decls-bad-import.ts (1 errors) ==== ++ import type { foo as "invalid 2" } from "./type-decls-valid"; ++ ~~~~~~~~~~~ ++!!! error TS1003: Identifier expected. ++ ++==== type-decls-bad-export.ts (1 errors) ==== ++ export type { "invalid 3" as baz }; ++ ~~~~~~~~~~~ ++!!! error TS1003: Identifier expected. ++ ++==== type-decls-no-as.ts (1 errors) ==== ++ import type { "invalid 1" } from "./type-decls-valid"; ++ ~~~~~~~~~~~ ++!!! error TS1003: Identifier expected. ++ ++==== type-decls-type-as.ts (2 errors) ==== ++ import type { type as "invalid 4" } from "./type-decls-valid"; ++ ~~~~ ++!!! error TS2305: Module '"./type-decls-valid"' has no exported member 'type'. ++ ~~~~~~~~~~~ ++!!! error TS1003: Identifier expected. ++ ++==== type-clause-valid.ts (0 errors) ==== ++ export type foo = 123; ++ export { type foo as "valid 1" }; ++ import { type "valid 1" as bar } from "./type-clause-valid"; ++ export { type "valid 1" as "valid 2" } from "./type-clause-valid"; ++ export { type foo as "valid 3" } from "./type-clause-valid"; ++ ++==== type-clause-bad-import.ts (1 errors) ==== ++ import { type foo as "invalid 2" } from "./type-clause-valid"; ++ ~~~~~~~~~~~ ++!!! error TS1003: Identifier expected. ++ ++==== type-clause-bad-export.ts (1 errors) ==== ++ export { type "invalid 3" as baz }; ++ ~~~~~~~~~~~ ++!!! error TS1003: Identifier expected. ++ ++==== type-clause-no-as.ts (1 errors) ==== ++ import { type "invalid 1" } from "./type-clause-valid"; ++ ~~~~~~~~~~~ ++!!! error TS1003: Identifier expected. ++ ++==== type-clause-type-as-as.ts (2 errors) ==== ++ import { type as as "invalid 4" } from "./type-clause-valid"; ++ ~~ ++!!! error TS2305: Module '"./type-clause-valid"' has no exported member 'as'. ++ ~~~~~~~~~~~ ++!!! error TS1003: Identifier expected. ++ +\ No newline at end of file +diff --git a/tests/baselines/reference/arbitraryModuleNamespaceIdentifiers_syntax.js b/tests/baselines/reference/arbitraryModuleNamespaceIdentifiers_syntax.js +new file mode 100644 +index 000000000..03103be74 +--- /dev/null ++++ b/tests/baselines/reference/arbitraryModuleNamespaceIdentifiers_syntax.js +@@ -0,0 +1,140 @@ ++//// [tests/cases/conformance/es2022/arbitraryModuleNamespaceIdentifiers/arbitraryModuleNamespaceIdentifiers_syntax.ts] //// ++ ++//// [values-valid.ts] ++export const foo = 123; ++export { foo as "valid 1" }; ++import { "valid 1" as bar } from "./values-valid"; ++export { "valid 1" as "valid 2" } from "./values-valid"; ++export { foo as "valid 3" } from "./values-valid"; ++export * as "valid 4" from "./values-valid"; ++ ++//// [values-bad-import.ts] ++import { foo as "invalid 2" } from "./values-valid"; ++ ++//// [values-bad-export.ts] ++export { "invalid 3" as baz }; ++ ++//// [values-no-as.ts] ++import { "invalid 1" } from "./values-valid"; ++ ++//// [values-type-as.ts] ++import { type as "invalid 4" } from "./values-valid"; ++ ++ ++//// [type-decls-valid.ts] ++export type foo = 123; ++export type { foo as "valid 1" }; ++import type { "valid 1" as bar } from "./type-decls-valid"; ++export type { "valid 1" as "valid 2" } from "./type-decls-valid"; ++export type { foo as "valid 3" } from "./type-decls-valid"; ++export type * as "valid 4" from "./type-decls-valid"; ++ ++//// [type-decls-bad-import.ts] ++import type { foo as "invalid 2" } from "./type-decls-valid"; ++ ++//// [type-decls-bad-export.ts] ++export type { "invalid 3" as baz }; ++ ++//// [type-decls-no-as.ts] ++import type { "invalid 1" } from "./type-decls-valid"; ++ ++//// [type-decls-type-as.ts] ++import type { type as "invalid 4" } from "./type-decls-valid"; ++ ++//// [type-clause-valid.ts] ++export type foo = 123; ++export { type foo as "valid 1" }; ++import { type "valid 1" as bar } from "./type-clause-valid"; ++export { type "valid 1" as "valid 2" } from "./type-clause-valid"; ++export { type foo as "valid 3" } from "./type-clause-valid"; ++ ++//// [type-clause-bad-import.ts] ++import { type foo as "invalid 2" } from "./type-clause-valid"; ++ ++//// [type-clause-bad-export.ts] ++export { type "invalid 3" as baz }; ++ ++//// [type-clause-no-as.ts] ++import { type "invalid 1" } from "./type-clause-valid"; ++ ++//// [type-clause-type-as-as.ts] ++import { type as as "invalid 4" } from "./type-clause-valid"; ++ ++ ++//// [values-valid.js] ++export const foo = 123; ++export { foo as "valid 1" }; ++export { "valid 1" as "valid 2" } from "./values-valid"; ++export { foo as "valid 3" } from "./values-valid"; ++export * as "valid 4" from "./values-valid"; ++//// [values-bad-import.js] ++export {}; ++//// [values-bad-export.js] ++export { "invalid 3" as baz }; ++//// [values-no-as.js] ++export {}; ++//// [values-type-as.js] ++export {}; ++//// [type-decls-valid.js] ++export {}; ++//// [type-decls-bad-import.js] ++export {}; ++//// [type-decls-bad-export.js] ++export {}; ++//// [type-decls-no-as.js] ++export {}; ++//// [type-decls-type-as.js] ++export {}; ++//// [type-clause-valid.js] ++export {}; ++//// [type-clause-bad-import.js] ++export {}; ++//// [type-clause-bad-export.js] ++export {}; ++//// [type-clause-no-as.js] ++export {}; ++//// [type-clause-type-as-as.js] ++export {}; ++ ++ ++//// [values-valid.d.ts] ++export declare const foo = 123; ++export { foo as "valid 1" }; ++export { "valid 1" as "valid 2" } from "./values-valid"; ++export { foo as "valid 3" } from "./values-valid"; ++export * as "valid 4" from "./values-valid"; ++//// [values-bad-import.d.ts] ++export {}; ++//// [values-bad-export.d.ts] ++export { "invalid 3" as baz }; ++//// [values-no-as.d.ts] ++export {}; ++//// [values-type-as.d.ts] ++export {}; ++//// [type-decls-valid.d.ts] ++export type foo = 123; ++export type { foo as "valid 1" }; ++export type { "valid 1" as "valid 2" } from "./type-decls-valid"; ++export type { foo as "valid 3" } from "./type-decls-valid"; ++export type * as "valid 4" from "./type-decls-valid"; ++//// [type-decls-bad-import.d.ts] ++export {}; ++//// [type-decls-bad-export.d.ts] ++export type { "invalid 3" as baz }; ++//// [type-decls-no-as.d.ts] ++export {}; ++//// [type-decls-type-as.d.ts] ++export {}; ++//// [type-clause-valid.d.ts] ++export type foo = 123; ++export { type foo as "valid 1" }; ++export { type "valid 1" as "valid 2" } from "./type-clause-valid"; ++export { type foo as "valid 3" } from "./type-clause-valid"; ++//// [type-clause-bad-import.d.ts] ++export {}; ++//// [type-clause-bad-export.d.ts] ++export { type "invalid 3" as baz }; ++//// [type-clause-no-as.d.ts] ++export {}; ++//// [type-clause-type-as-as.d.ts] ++export {}; +diff --git a/tests/baselines/reference/arbitraryModuleNamespaceIdentifiers_syntax.symbols b/tests/baselines/reference/arbitraryModuleNamespaceIdentifiers_syntax.symbols +new file mode 100644 +index 000000000..e1a127e15 +--- /dev/null ++++ b/tests/baselines/reference/arbitraryModuleNamespaceIdentifiers_syntax.symbols +@@ -0,0 +1,114 @@ ++//// [tests/cases/conformance/es2022/arbitraryModuleNamespaceIdentifiers/arbitraryModuleNamespaceIdentifiers_syntax.ts] //// ++ ++=== values-valid.ts === ++export const foo = 123; ++>foo : Symbol(foo, Decl(values-valid.ts, 0, 12)) ++ ++export { foo as "valid 1" }; ++>foo : Symbol(foo, Decl(values-valid.ts, 0, 12)) ++>"valid 1" : Symbol("valid 1", Decl(values-valid.ts, 1, 8)) ++ ++import { "valid 1" as bar } from "./values-valid"; ++>bar : Symbol(bar, Decl(values-valid.ts, 2, 8)) ++ ++export { "valid 1" as "valid 2" } from "./values-valid"; ++>"valid 2" : Symbol("valid 2", Decl(values-valid.ts, 3, 8)) ++ ++export { foo as "valid 3" } from "./values-valid"; ++>foo : Symbol(foo, Decl(values-valid.ts, 0, 12)) ++>"valid 3" : Symbol("valid 3", Decl(values-valid.ts, 4, 8)) ++ ++export * as "valid 4" from "./values-valid"; ++>"valid 4" : Symbol("valid 4", Decl(values-valid.ts, 5, 6)) ++ ++=== values-bad-import.ts === ++import { foo as "invalid 2" } from "./values-valid"; ++>foo : Symbol((Missing), Decl(values-valid.ts, 0, 12)) ++> : Symbol((Missing), Decl(values-bad-import.ts, 0, 8)) ++ ++=== values-bad-export.ts === ++export { "invalid 3" as baz }; ++>baz : Symbol(baz, Decl(values-bad-export.ts, 0, 8)) ++ ++=== values-no-as.ts === ++import { "invalid 1" } from "./values-valid"; ++> : Symbol((Missing), Decl(values-no-as.ts, 0, 8)) ++ ++=== values-type-as.ts === ++import { type as "invalid 4" } from "./values-valid"; ++> : Symbol((Missing), Decl(values-type-as.ts, 0, 8)) ++ ++ ++=== type-decls-valid.ts === ++export type foo = 123; ++>foo : Symbol(foo, Decl(type-decls-valid.ts, 0, 0)) ++ ++export type { foo as "valid 1" }; ++>foo : Symbol(foo, Decl(type-decls-valid.ts, 0, 0)) ++>"valid 1" : Symbol("valid 1", Decl(type-decls-valid.ts, 1, 13)) ++ ++import type { "valid 1" as bar } from "./type-decls-valid"; ++>bar : Symbol(bar, Decl(type-decls-valid.ts, 2, 13)) ++ ++export type { "valid 1" as "valid 2" } from "./type-decls-valid"; ++>"valid 2" : Symbol("valid 2", Decl(type-decls-valid.ts, 3, 13)) ++ ++export type { foo as "valid 3" } from "./type-decls-valid"; ++>foo : Symbol(foo, Decl(type-decls-valid.ts, 0, 0)) ++>"valid 3" : Symbol("valid 3", Decl(type-decls-valid.ts, 4, 13)) ++ ++export type * as "valid 4" from "./type-decls-valid"; ++>"valid 4" : Symbol("valid 4", Decl(type-decls-valid.ts, 5, 11)) ++ ++=== type-decls-bad-import.ts === ++import type { foo as "invalid 2" } from "./type-decls-valid"; ++>foo : Symbol((Missing), Decl(type-decls-valid.ts, 0, 0)) ++> : Symbol((Missing), Decl(type-decls-bad-import.ts, 0, 13)) ++ ++=== type-decls-bad-export.ts === ++export type { "invalid 3" as baz }; ++>baz : Symbol(baz, Decl(type-decls-bad-export.ts, 0, 13)) ++ ++=== type-decls-no-as.ts === ++import type { "invalid 1" } from "./type-decls-valid"; ++> : Symbol((Missing), Decl(type-decls-no-as.ts, 0, 13)) ++ ++=== type-decls-type-as.ts === ++import type { type as "invalid 4" } from "./type-decls-valid"; ++> : Symbol((Missing), Decl(type-decls-type-as.ts, 0, 13)) ++ ++=== type-clause-valid.ts === ++export type foo = 123; ++>foo : Symbol(foo, Decl(type-clause-valid.ts, 0, 0)) ++ ++export { type foo as "valid 1" }; ++>foo : Symbol(foo, Decl(type-clause-valid.ts, 0, 0)) ++>"valid 1" : Symbol("valid 1", Decl(type-clause-valid.ts, 1, 8)) ++ ++import { type "valid 1" as bar } from "./type-clause-valid"; ++>bar : Symbol(bar, Decl(type-clause-valid.ts, 2, 8)) ++ ++export { type "valid 1" as "valid 2" } from "./type-clause-valid"; ++>"valid 2" : Symbol("valid 2", Decl(type-clause-valid.ts, 3, 8)) ++ ++export { type foo as "valid 3" } from "./type-clause-valid"; ++>foo : Symbol(foo, Decl(type-clause-valid.ts, 0, 0)) ++>"valid 3" : Symbol("valid 3", Decl(type-clause-valid.ts, 4, 8)) ++ ++=== type-clause-bad-import.ts === ++import { type foo as "invalid 2" } from "./type-clause-valid"; ++>foo : Symbol((Missing), Decl(type-clause-valid.ts, 0, 0)) ++> : Symbol((Missing), Decl(type-clause-bad-import.ts, 0, 8)) ++ ++=== type-clause-bad-export.ts === ++export { type "invalid 3" as baz }; ++>baz : Symbol(baz, Decl(type-clause-bad-export.ts, 0, 8)) ++ ++=== type-clause-no-as.ts === ++import { type "invalid 1" } from "./type-clause-valid"; ++> : Symbol((Missing), Decl(type-clause-no-as.ts, 0, 8)) ++ ++=== type-clause-type-as-as.ts === ++import { type as as "invalid 4" } from "./type-clause-valid"; ++> : Symbol((Missing), Decl(type-clause-type-as-as.ts, 0, 8)) ++ +diff --git a/tests/baselines/reference/arbitraryModuleNamespaceIdentifiers_syntax.types b/tests/baselines/reference/arbitraryModuleNamespaceIdentifiers_syntax.types +new file mode 100644 +index 000000000..6129efe31 +--- /dev/null ++++ b/tests/baselines/reference/arbitraryModuleNamespaceIdentifiers_syntax.types +@@ -0,0 +1,160 @@ ++//// [tests/cases/conformance/es2022/arbitraryModuleNamespaceIdentifiers/arbitraryModuleNamespaceIdentifiers_syntax.ts] //// ++ ++=== values-valid.ts === ++export const foo = 123; ++>foo : 123 ++> : ^^^ ++>123 : 123 ++> : ^^^ ++ ++export { foo as "valid 1" }; ++>foo : 123 ++> : ^^^ ++>"valid 1" : 123 ++> : ^^^ ++ ++import { "valid 1" as bar } from "./values-valid"; ++>bar : 123 ++> : ^^^ ++ ++export { "valid 1" as "valid 2" } from "./values-valid"; ++>"valid 2" : 123 ++> : ^^^ ++ ++export { foo as "valid 3" } from "./values-valid"; ++>foo : 123 ++> : ^^^ ++>"valid 3" : 123 ++> : ^^^ ++ ++export * as "valid 4" from "./values-valid"; ++>"valid 4" : typeof import("values-valid") ++> : ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ++ ++=== values-bad-import.ts === ++import { foo as "invalid 2" } from "./values-valid"; ++>foo : 123 ++> : ^^^ ++> : 123 ++> : ^^^ ++ ++=== values-bad-export.ts === ++export { "invalid 3" as baz }; ++>baz : any ++> : ^^^ ++ ++=== values-no-as.ts === ++import { "invalid 1" } from "./values-valid"; ++> : any ++> : ^^^ ++ ++=== values-type-as.ts === ++import { type as "invalid 4" } from "./values-valid"; ++>type : any ++> : ^^^ ++> : any ++> : ^^^ ++ ++ ++=== type-decls-valid.ts === ++export type foo = 123; ++>foo : 123 ++> : ^^^ ++ ++export type { foo as "valid 1" }; ++>foo : any ++> : ^^^ ++>"valid 1" : any ++> : ^^^ ++ ++import type { "valid 1" as bar } from "./type-decls-valid"; ++>bar : 123 ++> : ^^^ ++ ++export type { "valid 1" as "valid 2" } from "./type-decls-valid"; ++>"valid 2" : any ++> : ^^^ ++ ++export type { foo as "valid 3" } from "./type-decls-valid"; ++>foo : any ++> : ^^^ ++>"valid 3" : any ++> : ^^^ ++ ++export type * as "valid 4" from "./type-decls-valid"; ++>"valid 4" : typeof import("type-decls-valid") ++> : ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ++ ++=== type-decls-bad-import.ts === ++import type { foo as "invalid 2" } from "./type-decls-valid"; ++>foo : any ++> : ^^^ ++> : 123 ++> : ^^^ ++ ++=== type-decls-bad-export.ts === ++export type { "invalid 3" as baz }; ++>baz : any ++> : ^^^ ++ ++=== type-decls-no-as.ts === ++import type { "invalid 1" } from "./type-decls-valid"; ++> : any ++> : ^^^ ++ ++=== type-decls-type-as.ts === ++import type { type as "invalid 4" } from "./type-decls-valid"; ++>type : any ++> : ^^^ ++> : any ++> : ^^^ ++ ++=== type-clause-valid.ts === ++export type foo = 123; ++>foo : 123 ++> : ^^^ ++ ++export { type foo as "valid 1" }; ++>foo : any ++> : ^^^ ++>"valid 1" : any ++> : ^^^ ++ ++import { type "valid 1" as bar } from "./type-clause-valid"; ++>bar : any ++> : ^^^ ++ ++export { type "valid 1" as "valid 2" } from "./type-clause-valid"; ++>"valid 2" : any ++> : ^^^ ++ ++export { type foo as "valid 3" } from "./type-clause-valid"; ++>foo : any ++> : ^^^ ++>"valid 3" : any ++> : ^^^ ++ ++=== type-clause-bad-import.ts === ++import { type foo as "invalid 2" } from "./type-clause-valid"; ++>foo : any ++> : ^^^ ++> : any ++> : ^^^ ++ ++=== type-clause-bad-export.ts === ++export { type "invalid 3" as baz }; ++>baz : any ++> : ^^^ ++ ++=== type-clause-no-as.ts === ++import { type "invalid 1" } from "./type-clause-valid"; ++> : any ++> : ^^^ ++ ++=== type-clause-type-as-as.ts === ++import { type as as "invalid 4" } from "./type-clause-valid"; ++>as : any ++> : ^^^ ++> : any ++> : ^^^ ++ +diff --git a/tests/baselines/reference/arbitraryModuleNamespaceIdentifiers_types.baseline.jsonc b/tests/baselines/reference/arbitraryModuleNamespaceIdentifiers_types.baseline.jsonc +new file mode 100644 +index 000000000..544a2769a +--- /dev/null ++++ b/tests/baselines/reference/arbitraryModuleNamespaceIdentifiers_types.baseline.jsonc +@@ -0,0 +1,1712 @@ ++// === findRenameLocations === ++// === /foo.ts === ++// type foo = "foo"; ++// <|export { type foo as "/*RENAME*/[|__RENAME|]" };|> ++// <|import { type "[|__RENAME|]" as bar } from "./foo";|> ++// const testBar: bar = "foo"; ++ ++// === /bar.ts === ++// <|import { type "[|__RENAME|]" as first } from "./foo";|> ++// <|export { type "[|__RENAME|]" as "" } from "./foo";|> ++// import { type "" as second } from "./bar"; ++// const testFirst: first = "foo"; ++// const testSecond: second = "foo"; ++ ++ ++ ++// === findRenameLocations === ++// === /foo.ts === ++// type foo = "foo"; ++// <|export { type foo as "[|__RENAME|]" };|> ++// <|import { type "/*RENAME*/[|__RENAME|]" as bar } from "./foo";|> ++// const testBar: bar = "foo"; ++ ++// === /bar.ts === ++// <|import { type "[|__RENAME|]" as first } from "./foo";|> ++// <|export { type "[|__RENAME|]" as "" } from "./foo";|> ++// import { type "" as second } from "./bar"; ++// const testFirst: first = "foo"; ++// const testSecond: second = "foo"; ++ ++ ++ ++// === findRenameLocations === ++// === /foo.ts === ++// type foo = "foo"; ++// <|export { type foo as "[|__RENAME|]" };|> ++// <|import { type "[|__RENAME|]" as bar } from "./foo";|> ++// const testBar: bar = "foo"; ++ ++// === /bar.ts === ++// <|import { type "/*RENAME*/[|__RENAME|]" as first } from "./foo";|> ++// <|export { type "[|__RENAME|]" as "" } from "./foo";|> ++// import { type "" as second } from "./bar"; ++// const testFirst: first = "foo"; ++// const testSecond: second = "foo"; ++ ++ ++ ++// === findRenameLocations === ++// === /foo.ts === ++// type foo = "foo"; ++// <|export { type foo as "[|__RENAME|]" };|> ++// <|import { type "[|__RENAME|]" as bar } from "./foo";|> ++// const testBar: bar = "foo"; ++ ++// === /bar.ts === ++// <|import { type "[|__RENAME|]" as first } from "./foo";|> ++// <|export { type "/*RENAME*/[|__RENAME|]" as "" } from "./foo";|> ++// import { type "" as second } from "./bar"; ++// const testFirst: first = "foo"; ++// const testSecond: second = "foo"; ++ ++ ++ ++// === goToDefinition === ++// === /foo.ts === ++// <|type [|foo|] = "foo";|> ++// export { type foo as "/*GOTO DEF*/__" }; ++// import { type "__" as bar } from "./foo"; ++// const testBar: bar = "foo"; ++ ++ // === Details === ++ [ ++ { ++ "kind": "type", ++ "name": "foo", ++ "containerName": "", ++ "isLocal": true, ++ "isAmbient": false, ++ "unverified": false ++ } ++ ] ++ ++ ++ ++// === goToDefinition === ++// === /foo.ts === ++// <|type [|foo|] = "foo";|> ++// export { type foo as "__" }; ++// import { type "/*GOTO DEF*/__" as bar } from "./foo"; ++// const testBar: bar = "foo"; ++ ++ // === Details === ++ [ ++ { ++ "kind": "type", ++ "name": "foo", ++ "containerName": "", ++ "isLocal": true, ++ "isAmbient": false, ++ "unverified": false ++ } ++ ] ++ ++ ++ ++// === goToDefinition === ++// === /foo.ts === ++// <|type [|foo|] = "foo";|> ++// export { type foo as "__" }; ++// import { type "__" as bar } from "./foo"; ++// const testBar: bar = "foo"; ++ ++// === /bar.ts === ++// import { type [|"/*GOTO DEF*/__"|] as first } from "./foo"; ++// export { type "__" as "" } from "./foo"; ++// import { type "" as second } from "./bar"; ++// const testFirst: first = "foo"; ++// const testSecond: second = "foo"; ++ ++ // === Details === ++ [ ++ { ++ "kind": "type", ++ "name": "foo", ++ "containerName": "", ++ "isLocal": true, ++ "isAmbient": false, ++ "unverified": false ++ } ++ ] ++ ++ ++ ++// === goToDefinition === ++// === /foo.ts === ++// <|type [|foo|] = "foo";|> ++// export { type foo as "__" }; ++// import { type "__" as bar } from "./foo"; ++// const testBar: bar = "foo"; ++ ++// === /bar.ts === ++// import { type "__" as first } from "./foo"; ++// export { type [|"/*GOTO DEF*/__"|] as "" } from "./foo"; ++// import { type "" as second } from "./bar"; ++// const testFirst: first = "foo"; ++// const testSecond: second = "foo"; ++ ++ // === Details === ++ [ ++ { ++ "kind": "type", ++ "name": "foo", ++ "containerName": "", ++ "isLocal": true, ++ "isAmbient": false, ++ "unverified": false ++ } ++ ] ++ ++ ++ ++// === findAllReferences === ++// === /foo.ts === ++// type foo = "foo"; ++// <|export { type foo as "/*FIND ALL REFS*/[|{| defId: 0, isWriteAccess: true, isDefinition: true |}__|]" };|> ++// <|<|import { type "[|{| contextId: 1, defId: 0 |}__|]" as [|{| contextId: 2, defId: 1, isWriteAccess: true |}bar|] } from "./foo";|>|> ++// const testBar: [|{| defId: 1 |}bar|] = "foo"; ++ ++// === /bar.ts === ++// <|<|import { type "[|{| contextId: 3, defId: 0 |}__|]" as [|{| contextId: 4, defId: 2, isWriteAccess: true |}first|] } from "./foo";|>|> ++// <|<|export { type "[|{| contextId: 5, defId: 0 |}__|]" as "[|{| contextId: 6, defId: 3, isWriteAccess: true |}|]" } from "./foo";|>|> ++// <|<|import { type "[|{| contextId: 7, defId: 3 |}|]" as [|{| contextId: 8, defId: 4, isWriteAccess: true |}second|] } from "./bar";|>|> ++// const testFirst: [|{| defId: 2 |}first|] = "foo"; ++// const testSecond: [|{| defId: 4 |}second|] = "foo"; ++ ++ // === Definitions === ++ // === /foo.ts === ++ // type foo = "foo"; ++ // <|export { type foo as "/*FIND ALL REFS*/[|{| defId: 0 |}__|]" };|> ++ // <|import { type "__" as [|{| defId: 1 |}bar|] } from "./foo";|> ++ // const testBar: bar = "foo"; ++ ++ // === /bar.ts === ++ // <|import { type "__" as [|{| defId: 2 |}first|] } from "./foo";|> ++ // <|export { type "__" as "[|{| defId: 3 |}|]" } from "./foo";|> ++ // <|import { type "" as [|{| defId: 4 |}second|] } from "./bar";|> ++ // const testFirst: first = "foo"; ++ // const testSecond: second = "foo"; ++ ++ // === Details === ++ [ ++ { ++ "defId": 0, ++ "containerKind": "", ++ "containerName": "", ++ "kind": "alias", ++ "name": "(alias) type \"__\" = \"foo\"\nexport \"__\"", ++ "displayParts": [ ++ { ++ "text": "(", ++ "kind": "punctuation" ++ }, ++ { ++ "text": "alias", ++ "kind": "text" ++ }, ++ { ++ "text": ")", ++ "kind": "punctuation" ++ }, ++ { ++ "text": " ", ++ "kind": "space" ++ }, ++ { ++ "text": "type", ++ "kind": "keyword" ++ }, ++ { ++ "text": " ", ++ "kind": "space" ++ }, ++ { ++ "text": "\"__\"", ++ "kind": "aliasName" ++ }, ++ { ++ "text": " ", ++ "kind": "space" ++ }, ++ { ++ "text": "=", ++ "kind": "operator" ++ }, ++ { ++ "text": " ", ++ "kind": "space" ++ }, ++ { ++ "text": "\"foo\"", ++ "kind": "stringLiteral" ++ }, ++ { ++ "text": "\n", ++ "kind": "lineBreak" ++ }, ++ { ++ "text": "export", ++ "kind": "keyword" ++ }, ++ { ++ "text": " ", ++ "kind": "space" ++ }, ++ { ++ "text": "\"__\"", ++ "kind": "aliasName" ++ } ++ ] ++ }, ++ { ++ "defId": 1, ++ "containerKind": "", ++ "containerName": "", ++ "kind": "alias", ++ "name": "(alias) type bar = \"foo\"\nimport bar", ++ "displayParts": [ ++ { ++ "text": "(", ++ "kind": "punctuation" ++ }, ++ { ++ "text": "alias", ++ "kind": "text" ++ }, ++ { ++ "text": ")", ++ "kind": "punctuation" ++ }, ++ { ++ "text": " ", ++ "kind": "space" ++ }, ++ { ++ "text": "type", ++ "kind": "keyword" ++ }, ++ { ++ "text": " ", ++ "kind": "space" ++ }, ++ { ++ "text": "bar", ++ "kind": "aliasName" ++ }, ++ { ++ "text": " ", ++ "kind": "space" ++ }, ++ { ++ "text": "=", ++ "kind": "operator" ++ }, ++ { ++ "text": " ", ++ "kind": "space" ++ }, ++ { ++ "text": "\"foo\"", ++ "kind": "stringLiteral" ++ }, ++ { ++ "text": "\n", ++ "kind": "lineBreak" ++ }, ++ { ++ "text": "import", ++ "kind": "keyword" ++ }, ++ { ++ "text": " ", ++ "kind": "space" ++ }, ++ { ++ "text": "bar", ++ "kind": "aliasName" ++ } ++ ] ++ }, ++ { ++ "defId": 2, ++ "containerKind": "", ++ "containerName": "", ++ "kind": "alias", ++ "name": "(alias) type first = \"foo\"\nimport first", ++ "displayParts": [ ++ { ++ "text": "(", ++ "kind": "punctuation" ++ }, ++ { ++ "text": "alias", ++ "kind": "text" ++ }, ++ { ++ "text": ")", ++ "kind": "punctuation" ++ }, ++ { ++ "text": " ", ++ "kind": "space" ++ }, ++ { ++ "text": "type", ++ "kind": "keyword" ++ }, ++ { ++ "text": " ", ++ "kind": "space" ++ }, ++ { ++ "text": "first", ++ "kind": "aliasName" ++ }, ++ { ++ "text": " ", ++ "kind": "space" ++ }, ++ { ++ "text": "=", ++ "kind": "operator" ++ }, ++ { ++ "text": " ", ++ "kind": "space" ++ }, ++ { ++ "text": "\"foo\"", ++ "kind": "stringLiteral" ++ }, ++ { ++ "text": "\n", ++ "kind": "lineBreak" ++ }, ++ { ++ "text": "import", ++ "kind": "keyword" ++ }, ++ { ++ "text": " ", ++ "kind": "space" ++ }, ++ { ++ "text": "first", ++ "kind": "aliasName" ++ } ++ ] ++ }, ++ { ++ "defId": 3, ++ "containerKind": "", ++ "containerName": "", ++ "kind": "alias", ++ "name": "(alias) type \"\" = \"foo\"\nexport \"\"", ++ "displayParts": [ ++ { ++ "text": "(", ++ "kind": "punctuation" ++ }, ++ { ++ "text": "alias", ++ "kind": "text" ++ }, ++ { ++ "text": ")", ++ "kind": "punctuation" ++ }, ++ { ++ "text": " ", ++ "kind": "space" ++ }, ++ { ++ "text": "type", ++ "kind": "keyword" ++ }, ++ { ++ "text": " ", ++ "kind": "space" ++ }, ++ { ++ "text": "\"\"", ++ "kind": "aliasName" ++ }, ++ { ++ "text": " ", ++ "kind": "space" ++ }, ++ { ++ "text": "=", ++ "kind": "operator" ++ }, ++ { ++ "text": " ", ++ "kind": "space" ++ }, ++ { ++ "text": "\"foo\"", ++ "kind": "stringLiteral" ++ }, ++ { ++ "text": "\n", ++ "kind": "lineBreak" ++ }, ++ { ++ "text": "export", ++ "kind": "keyword" ++ }, ++ { ++ "text": " ", ++ "kind": "space" ++ }, ++ { ++ "text": "\"\"", ++ "kind": "aliasName" ++ } ++ ] ++ }, ++ { ++ "defId": 4, ++ "containerKind": "", ++ "containerName": "", ++ "kind": "alias", ++ "name": "(alias) type second = \"foo\"\nimport second", ++ "displayParts": [ ++ { ++ "text": "(", ++ "kind": "punctuation" ++ }, ++ { ++ "text": "alias", ++ "kind": "text" ++ }, ++ { ++ "text": ")", ++ "kind": "punctuation" ++ }, ++ { ++ "text": " ", ++ "kind": "space" ++ }, ++ { ++ "text": "type", ++ "kind": "keyword" ++ }, ++ { ++ "text": " ", ++ "kind": "space" ++ }, ++ { ++ "text": "second", ++ "kind": "aliasName" ++ }, ++ { ++ "text": " ", ++ "kind": "space" ++ }, ++ { ++ "text": "=", ++ "kind": "operator" ++ }, ++ { ++ "text": " ", ++ "kind": "space" ++ }, ++ { ++ "text": "\"foo\"", ++ "kind": "stringLiteral" ++ }, ++ { ++ "text": "\n", ++ "kind": "lineBreak" ++ }, ++ { ++ "text": "import", ++ "kind": "keyword" ++ }, ++ { ++ "text": " ", ++ "kind": "space" ++ }, ++ { ++ "text": "second", ++ "kind": "aliasName" ++ } ++ ] ++ } ++ ] ++ ++ ++ ++// === findAllReferences === ++// === /foo.ts === ++// type foo = "foo"; ++// <|export { type foo as "[|{| defId: 0, isWriteAccess: true |}__|]" };|> ++// <|<|import { type "/*FIND ALL REFS*/[|{| contextId: 1, defId: 0 |}__|]" as [|{| contextId: 2, defId: 1, isWriteAccess: true |}bar|] } from "./foo";|>|> ++// const testBar: [|{| defId: 1 |}bar|] = "foo"; ++ ++// === /bar.ts === ++// <|<|import { type "[|{| contextId: 3, defId: 0 |}__|]" as [|{| contextId: 4, defId: 2, isWriteAccess: true |}first|] } from "./foo";|>|> ++// <|<|export { type "[|{| contextId: 5, defId: 0 |}__|]" as "[|{| contextId: 6, defId: 3, isWriteAccess: true |}|]" } from "./foo";|>|> ++// <|<|import { type "[|{| contextId: 7, defId: 3 |}|]" as [|{| contextId: 8, defId: 4, isWriteAccess: true |}second|] } from "./bar";|>|> ++// const testFirst: [|{| defId: 2 |}first|] = "foo"; ++// const testSecond: [|{| defId: 4 |}second|] = "foo"; ++ ++ // === Definitions === ++ // === /foo.ts === ++ // type foo = "foo"; ++ // <|export { type foo as "[|{| defId: 0 |}__|]" };|> ++ // <|import { type "/*FIND ALL REFS*/__" as [|{| defId: 1 |}bar|] } from "./foo";|> ++ // const testBar: bar = "foo"; ++ ++ // === /bar.ts === ++ // <|import { type "__" as [|{| defId: 2 |}first|] } from "./foo";|> ++ // <|export { type "__" as "[|{| defId: 3 |}|]" } from "./foo";|> ++ // <|import { type "" as [|{| defId: 4 |}second|] } from "./bar";|> ++ // const testFirst: first = "foo"; ++ // const testSecond: second = "foo"; ++ ++ // === Details === ++ [ ++ { ++ "defId": 0, ++ "containerKind": "", ++ "containerName": "", ++ "kind": "alias", ++ "name": "(alias) type \"__\" = \"foo\"\nexport \"__\"", ++ "displayParts": [ ++ { ++ "text": "(", ++ "kind": "punctuation" ++ }, ++ { ++ "text": "alias", ++ "kind": "text" ++ }, ++ { ++ "text": ")", ++ "kind": "punctuation" ++ }, ++ { ++ "text": " ", ++ "kind": "space" ++ }, ++ { ++ "text": "type", ++ "kind": "keyword" ++ }, ++ { ++ "text": " ", ++ "kind": "space" ++ }, ++ { ++ "text": "\"__\"", ++ "kind": "aliasName" ++ }, ++ { ++ "text": " ", ++ "kind": "space" ++ }, ++ { ++ "text": "=", ++ "kind": "operator" ++ }, ++ { ++ "text": " ", ++ "kind": "space" ++ }, ++ { ++ "text": "\"foo\"", ++ "kind": "stringLiteral" ++ }, ++ { ++ "text": "\n", ++ "kind": "lineBreak" ++ }, ++ { ++ "text": "export", ++ "kind": "keyword" ++ }, ++ { ++ "text": " ", ++ "kind": "space" ++ }, ++ { ++ "text": "\"__\"", ++ "kind": "aliasName" ++ } ++ ] ++ }, ++ { ++ "defId": 1, ++ "containerKind": "", ++ "containerName": "", ++ "kind": "alias", ++ "name": "(alias) type bar = \"foo\"\nimport bar", ++ "displayParts": [ ++ { ++ "text": "(", ++ "kind": "punctuation" ++ }, ++ { ++ "text": "alias", ++ "kind": "text" ++ }, ++ { ++ "text": ")", ++ "kind": "punctuation" ++ }, ++ { ++ "text": " ", ++ "kind": "space" ++ }, ++ { ++ "text": "type", ++ "kind": "keyword" ++ }, ++ { ++ "text": " ", ++ "kind": "space" ++ }, ++ { ++ "text": "bar", ++ "kind": "aliasName" ++ }, ++ { ++ "text": " ", ++ "kind": "space" ++ }, ++ { ++ "text": "=", ++ "kind": "operator" ++ }, ++ { ++ "text": " ", ++ "kind": "space" ++ }, ++ { ++ "text": "\"foo\"", ++ "kind": "stringLiteral" ++ }, ++ { ++ "text": "\n", ++ "kind": "lineBreak" ++ }, ++ { ++ "text": "import", ++ "kind": "keyword" ++ }, ++ { ++ "text": " ", ++ "kind": "space" ++ }, ++ { ++ "text": "bar", ++ "kind": "aliasName" ++ } ++ ] ++ }, ++ { ++ "defId": 2, ++ "containerKind": "", ++ "containerName": "", ++ "kind": "alias", ++ "name": "(alias) type first = \"foo\"\nimport first", ++ "displayParts": [ ++ { ++ "text": "(", ++ "kind": "punctuation" ++ }, ++ { ++ "text": "alias", ++ "kind": "text" ++ }, ++ { ++ "text": ")", ++ "kind": "punctuation" ++ }, ++ { ++ "text": " ", ++ "kind": "space" ++ }, ++ { ++ "text": "type", ++ "kind": "keyword" ++ }, ++ { ++ "text": " ", ++ "kind": "space" ++ }, ++ { ++ "text": "first", ++ "kind": "aliasName" ++ }, ++ { ++ "text": " ", ++ "kind": "space" ++ }, ++ { ++ "text": "=", ++ "kind": "operator" ++ }, ++ { ++ "text": " ", ++ "kind": "space" ++ }, ++ { ++ "text": "\"foo\"", ++ "kind": "stringLiteral" ++ }, ++ { ++ "text": "\n", ++ "kind": "lineBreak" ++ }, ++ { ++ "text": "import", ++ "kind": "keyword" ++ }, ++ { ++ "text": " ", ++ "kind": "space" ++ }, ++ { ++ "text": "first", ++ "kind": "aliasName" ++ } ++ ] ++ }, ++ { ++ "defId": 3, ++ "containerKind": "", ++ "containerName": "", ++ "kind": "alias", ++ "name": "(alias) type \"\" = \"foo\"\nexport \"\"", ++ "displayParts": [ ++ { ++ "text": "(", ++ "kind": "punctuation" ++ }, ++ { ++ "text": "alias", ++ "kind": "text" ++ }, ++ { ++ "text": ")", ++ "kind": "punctuation" ++ }, ++ { ++ "text": " ", ++ "kind": "space" ++ }, ++ { ++ "text": "type", ++ "kind": "keyword" ++ }, ++ { ++ "text": " ", ++ "kind": "space" ++ }, ++ { ++ "text": "\"\"", ++ "kind": "aliasName" ++ }, ++ { ++ "text": " ", ++ "kind": "space" ++ }, ++ { ++ "text": "=", ++ "kind": "operator" ++ }, ++ { ++ "text": " ", ++ "kind": "space" ++ }, ++ { ++ "text": "\"foo\"", ++ "kind": "stringLiteral" ++ }, ++ { ++ "text": "\n", ++ "kind": "lineBreak" ++ }, ++ { ++ "text": "export", ++ "kind": "keyword" ++ }, ++ { ++ "text": " ", ++ "kind": "space" ++ }, ++ { ++ "text": "\"\"", ++ "kind": "aliasName" ++ } ++ ] ++ }, ++ { ++ "defId": 4, ++ "containerKind": "", ++ "containerName": "", ++ "kind": "alias", ++ "name": "(alias) type second = \"foo\"\nimport second", ++ "displayParts": [ ++ { ++ "text": "(", ++ "kind": "punctuation" ++ }, ++ { ++ "text": "alias", ++ "kind": "text" ++ }, ++ { ++ "text": ")", ++ "kind": "punctuation" ++ }, ++ { ++ "text": " ", ++ "kind": "space" ++ }, ++ { ++ "text": "type", ++ "kind": "keyword" ++ }, ++ { ++ "text": " ", ++ "kind": "space" ++ }, ++ { ++ "text": "second", ++ "kind": "aliasName" ++ }, ++ { ++ "text": " ", ++ "kind": "space" ++ }, ++ { ++ "text": "=", ++ "kind": "operator" ++ }, ++ { ++ "text": " ", ++ "kind": "space" ++ }, ++ { ++ "text": "\"foo\"", ++ "kind": "stringLiteral" ++ }, ++ { ++ "text": "\n", ++ "kind": "lineBreak" ++ }, ++ { ++ "text": "import", ++ "kind": "keyword" ++ }, ++ { ++ "text": " ", ++ "kind": "space" ++ }, ++ { ++ "text": "second", ++ "kind": "aliasName" ++ } ++ ] ++ } ++ ] ++ ++ ++ ++// === findAllReferences === ++// === /foo.ts === ++// type foo = "foo"; ++// <|export { type foo as "[|{| defId: 0, isWriteAccess: true |}__|]" };|> ++// <|<|import { type "[|{| contextId: 1, defId: 0 |}__|]" as [|{| contextId: 2, defId: 1, isWriteAccess: true |}bar|] } from "./foo";|>|> ++// const testBar: [|{| defId: 1 |}bar|] = "foo"; ++ ++// === /bar.ts === ++// <|<|import { type "/*FIND ALL REFS*/[|{| contextId: 3, defId: 0 |}__|]" as [|{| contextId: 4, defId: 2, isWriteAccess: true |}first|] } from "./foo";|>|> ++// <|<|export { type "[|{| contextId: 5, defId: 0 |}__|]" as "[|{| contextId: 6, defId: 3, isWriteAccess: true |}|]" } from "./foo";|>|> ++// <|<|import { type "[|{| contextId: 7, defId: 3 |}|]" as [|{| contextId: 8, defId: 4, isWriteAccess: true |}second|] } from "./bar";|>|> ++// const testFirst: [|{| defId: 2 |}first|] = "foo"; ++// const testSecond: [|{| defId: 4 |}second|] = "foo"; ++ ++ // === Definitions === ++ // === /foo.ts === ++ // type foo = "foo"; ++ // <|export { type foo as "[|{| defId: 0 |}__|]" };|> ++ // <|import { type "__" as [|{| defId: 1 |}bar|] } from "./foo";|> ++ // const testBar: bar = "foo"; ++ ++ // === /bar.ts === ++ // <|import { type "/*FIND ALL REFS*/__" as [|{| defId: 2 |}first|] } from "./foo";|> ++ // <|export { type "__" as "[|{| defId: 3 |}|]" } from "./foo";|> ++ // <|import { type "" as [|{| defId: 4 |}second|] } from "./bar";|> ++ // const testFirst: first = "foo"; ++ // const testSecond: second = "foo"; ++ ++ // === Details === ++ [ ++ { ++ "defId": 0, ++ "containerKind": "", ++ "containerName": "", ++ "kind": "alias", ++ "name": "(alias) type \"__\" = \"foo\"\nexport \"__\"", ++ "displayParts": [ ++ { ++ "text": "(", ++ "kind": "punctuation" ++ }, ++ { ++ "text": "alias", ++ "kind": "text" ++ }, ++ { ++ "text": ")", ++ "kind": "punctuation" ++ }, ++ { ++ "text": " ", ++ "kind": "space" ++ }, ++ { ++ "text": "type", ++ "kind": "keyword" ++ }, ++ { ++ "text": " ", ++ "kind": "space" ++ }, ++ { ++ "text": "\"__\"", ++ "kind": "aliasName" ++ }, ++ { ++ "text": " ", ++ "kind": "space" ++ }, ++ { ++ "text": "=", ++ "kind": "operator" ++ }, ++ { ++ "text": " ", ++ "kind": "space" ++ }, ++ { ++ "text": "\"foo\"", ++ "kind": "stringLiteral" ++ }, ++ { ++ "text": "\n", ++ "kind": "lineBreak" ++ }, ++ { ++ "text": "export", ++ "kind": "keyword" ++ }, ++ { ++ "text": " ", ++ "kind": "space" ++ }, ++ { ++ "text": "\"__\"", ++ "kind": "aliasName" ++ } ++ ] ++ }, ++ { ++ "defId": 1, ++ "containerKind": "", ++ "containerName": "", ++ "kind": "alias", ++ "name": "(alias) type bar = \"foo\"\nimport bar", ++ "displayParts": [ ++ { ++ "text": "(", ++ "kind": "punctuation" ++ }, ++ { ++ "text": "alias", ++ "kind": "text" ++ }, ++ { ++ "text": ")", ++ "kind": "punctuation" ++ }, ++ { ++ "text": " ", ++ "kind": "space" ++ }, ++ { ++ "text": "type", ++ "kind": "keyword" ++ }, ++ { ++ "text": " ", ++ "kind": "space" ++ }, ++ { ++ "text": "bar", ++ "kind": "aliasName" ++ }, ++ { ++ "text": " ", ++ "kind": "space" ++ }, ++ { ++ "text": "=", ++ "kind": "operator" ++ }, ++ { ++ "text": " ", ++ "kind": "space" ++ }, ++ { ++ "text": "\"foo\"", ++ "kind": "stringLiteral" ++ }, ++ { ++ "text": "\n", ++ "kind": "lineBreak" ++ }, ++ { ++ "text": "import", ++ "kind": "keyword" ++ }, ++ { ++ "text": " ", ++ "kind": "space" ++ }, ++ { ++ "text": "bar", ++ "kind": "aliasName" ++ } ++ ] ++ }, ++ { ++ "defId": 2, ++ "containerKind": "", ++ "containerName": "", ++ "kind": "alias", ++ "name": "(alias) type first = \"foo\"\nimport first", ++ "displayParts": [ ++ { ++ "text": "(", ++ "kind": "punctuation" ++ }, ++ { ++ "text": "alias", ++ "kind": "text" ++ }, ++ { ++ "text": ")", ++ "kind": "punctuation" ++ }, ++ { ++ "text": " ", ++ "kind": "space" ++ }, ++ { ++ "text": "type", ++ "kind": "keyword" ++ }, ++ { ++ "text": " ", ++ "kind": "space" ++ }, ++ { ++ "text": "first", ++ "kind": "aliasName" ++ }, ++ { ++ "text": " ", ++ "kind": "space" ++ }, ++ { ++ "text": "=", ++ "kind": "operator" ++ }, ++ { ++ "text": " ", ++ "kind": "space" ++ }, ++ { ++ "text": "\"foo\"", ++ "kind": "stringLiteral" ++ }, ++ { ++ "text": "\n", ++ "kind": "lineBreak" ++ }, ++ { ++ "text": "import", ++ "kind": "keyword" ++ }, ++ { ++ "text": " ", ++ "kind": "space" ++ }, ++ { ++ "text": "first", ++ "kind": "aliasName" ++ } ++ ] ++ }, ++ { ++ "defId": 3, ++ "containerKind": "", ++ "containerName": "", ++ "kind": "alias", ++ "name": "(alias) type \"\" = \"foo\"\nexport \"\"", ++ "displayParts": [ ++ { ++ "text": "(", ++ "kind": "punctuation" ++ }, ++ { ++ "text": "alias", ++ "kind": "text" ++ }, ++ { ++ "text": ")", ++ "kind": "punctuation" ++ }, ++ { ++ "text": " ", ++ "kind": "space" ++ }, ++ { ++ "text": "type", ++ "kind": "keyword" ++ }, ++ { ++ "text": " ", ++ "kind": "space" ++ }, ++ { ++ "text": "\"\"", ++ "kind": "aliasName" ++ }, ++ { ++ "text": " ", ++ "kind": "space" ++ }, ++ { ++ "text": "=", ++ "kind": "operator" ++ }, ++ { ++ "text": " ", ++ "kind": "space" ++ }, ++ { ++ "text": "\"foo\"", ++ "kind": "stringLiteral" ++ }, ++ { ++ "text": "\n", ++ "kind": "lineBreak" ++ }, ++ { ++ "text": "export", ++ "kind": "keyword" ++ }, ++ { ++ "text": " ", ++ "kind": "space" ++ }, ++ { ++ "text": "\"\"", ++ "kind": "aliasName" ++ } ++ ] ++ }, ++ { ++ "defId": 4, ++ "containerKind": "", ++ "containerName": "", ++ "kind": "alias", ++ "name": "(alias) type second = \"foo\"\nimport second", ++ "displayParts": [ ++ { ++ "text": "(", ++ "kind": "punctuation" ++ }, ++ { ++ "text": "alias", ++ "kind": "text" ++ }, ++ { ++ "text": ")", ++ "kind": "punctuation" ++ }, ++ { ++ "text": " ", ++ "kind": "space" ++ }, ++ { ++ "text": "type", ++ "kind": "keyword" ++ }, ++ { ++ "text": " ", ++ "kind": "space" ++ }, ++ { ++ "text": "second", ++ "kind": "aliasName" ++ }, ++ { ++ "text": " ", ++ "kind": "space" ++ }, ++ { ++ "text": "=", ++ "kind": "operator" ++ }, ++ { ++ "text": " ", ++ "kind": "space" ++ }, ++ { ++ "text": "\"foo\"", ++ "kind": "stringLiteral" ++ }, ++ { ++ "text": "\n", ++ "kind": "lineBreak" ++ }, ++ { ++ "text": "import", ++ "kind": "keyword" ++ }, ++ { ++ "text": " ", ++ "kind": "space" ++ }, ++ { ++ "text": "second", ++ "kind": "aliasName" ++ } ++ ] ++ } ++ ] ++ ++ ++ ++// === findAllReferences === ++// === /foo.ts === ++// <|type [|{| defId: 0, isWriteAccess: true |}foo|] = "foo";|> ++// <|<|export { type [|{| contextId: 1, defId: 0 |}foo|] as "[|{| contextId: 2, defId: 1, isWriteAccess: true |}__|]" };|>|> ++// <|<|import { type "[|{| contextId: 3, defId: 1 |}__|]" as [|{| contextId: 4, defId: 2, isWriteAccess: true |}bar|] } from "./foo";|>|> ++// const testBar: [|{| defId: 2 |}bar|] = "foo"; ++ ++// === /bar.ts === ++// <|<|import { type "[|{| contextId: 5, defId: 1 |}__|]" as [|{| contextId: 6, defId: 3, isWriteAccess: true |}first|] } from "./foo";|>|> ++// <|<|export { type "/*FIND ALL REFS*/[|{| contextId: 7, defId: 1 |}__|]" as "[|{| contextId: 8, defId: 4, isWriteAccess: true |}|]" } from "./foo";|>|> ++// <|<|import { type "[|{| contextId: 9, defId: 4 |}|]" as [|{| contextId: 10, defId: 5, isWriteAccess: true |}second|] } from "./bar";|>|> ++// const testFirst: [|{| defId: 3 |}first|] = "foo"; ++// const testSecond: [|{| defId: 5 |}second|] = "foo"; ++ ++ // === Definitions === ++ // === /foo.ts === ++ // <|type [|{| defId: 0 |}foo|] = "foo";|> ++ // <|export { type foo as "[|{| defId: 1 |}__|]" };|> ++ // <|import { type "__" as [|{| defId: 2 |}bar|] } from "./foo";|> ++ // const testBar: bar = "foo"; ++ ++ // === /bar.ts === ++ // <|import { type "__" as [|{| defId: 3 |}first|] } from "./foo";|> ++ // <|export { type "/*FIND ALL REFS*/__" as "[|{| defId: 4 |}|]" } from "./foo";|> ++ // <|import { type "" as [|{| defId: 5 |}second|] } from "./bar";|> ++ // const testFirst: first = "foo"; ++ // const testSecond: second = "foo"; ++ ++ // === Details === ++ [ ++ { ++ "defId": 0, ++ "containerKind": "", ++ "containerName": "", ++ "kind": "type", ++ "name": "type foo = \"foo\"", ++ "displayParts": [ ++ { ++ "text": "type", ++ "kind": "keyword" ++ }, ++ { ++ "text": " ", ++ "kind": "space" ++ }, ++ { ++ "text": "foo", ++ "kind": "aliasName" ++ }, ++ { ++ "text": " ", ++ "kind": "space" ++ }, ++ { ++ "text": "=", ++ "kind": "operator" ++ }, ++ { ++ "text": " ", ++ "kind": "space" ++ }, ++ { ++ "text": "\"foo\"", ++ "kind": "stringLiteral" ++ } ++ ] ++ }, ++ { ++ "defId": 1, ++ "containerKind": "", ++ "containerName": "", ++ "kind": "alias", ++ "name": "(alias) type \"__\" = \"foo\"\nexport \"__\"", ++ "displayParts": [ ++ { ++ "text": "(", ++ "kind": "punctuation" ++ }, ++ { ++ "text": "alias", ++ "kind": "text" ++ }, ++ { ++ "text": ")", ++ "kind": "punctuation" ++ }, ++ { ++ "text": " ", ++ "kind": "space" ++ }, ++ { ++ "text": "type", ++ "kind": "keyword" ++ }, ++ { ++ "text": " ", ++ "kind": "space" ++ }, ++ { ++ "text": "\"__\"", ++ "kind": "aliasName" ++ }, ++ { ++ "text": " ", ++ "kind": "space" ++ }, ++ { ++ "text": "=", ++ "kind": "operator" ++ }, ++ { ++ "text": " ", ++ "kind": "space" ++ }, ++ { ++ "text": "\"foo\"", ++ "kind": "stringLiteral" ++ }, ++ { ++ "text": "\n", ++ "kind": "lineBreak" ++ }, ++ { ++ "text": "export", ++ "kind": "keyword" ++ }, ++ { ++ "text": " ", ++ "kind": "space" ++ }, ++ { ++ "text": "\"__\"", ++ "kind": "aliasName" ++ } ++ ] ++ }, ++ { ++ "defId": 2, ++ "containerKind": "", ++ "containerName": "", ++ "kind": "alias", ++ "name": "(alias) type bar = \"foo\"\nimport bar", ++ "displayParts": [ ++ { ++ "text": "(", ++ "kind": "punctuation" ++ }, ++ { ++ "text": "alias", ++ "kind": "text" ++ }, ++ { ++ "text": ")", ++ "kind": "punctuation" ++ }, ++ { ++ "text": " ", ++ "kind": "space" ++ }, ++ { ++ "text": "type", ++ "kind": "keyword" ++ }, ++ { ++ "text": " ", ++ "kind": "space" ++ }, ++ { ++ "text": "bar", ++ "kind": "aliasName" ++ }, ++ { ++ "text": " ", ++ "kind": "space" ++ }, ++ { ++ "text": "=", ++ "kind": "operator" ++ }, ++ { ++ "text": " ", ++ "kind": "space" ++ }, ++ { ++ "text": "\"foo\"", ++ "kind": "stringLiteral" ++ }, ++ { ++ "text": "\n", ++ "kind": "lineBreak" ++ }, ++ { ++ "text": "import", ++ "kind": "keyword" ++ }, ++ { ++ "text": " ", ++ "kind": "space" ++ }, ++ { ++ "text": "bar", ++ "kind": "aliasName" ++ } ++ ] ++ }, ++ { ++ "defId": 3, ++ "containerKind": "", ++ "containerName": "", ++ "kind": "alias", ++ "name": "(alias) type first = \"foo\"\nimport first", ++ "displayParts": [ ++ { ++ "text": "(", ++ "kind": "punctuation" ++ }, ++ { ++ "text": "alias", ++ "kind": "text" ++ }, ++ { ++ "text": ")", ++ "kind": "punctuation" ++ }, ++ { ++ "text": " ", ++ "kind": "space" ++ }, ++ { ++ "text": "type", ++ "kind": "keyword" ++ }, ++ { ++ "text": " ", ++ "kind": "space" ++ }, ++ { ++ "text": "first", ++ "kind": "aliasName" ++ }, ++ { ++ "text": " ", ++ "kind": "space" ++ }, ++ { ++ "text": "=", ++ "kind": "operator" ++ }, ++ { ++ "text": " ", ++ "kind": "space" ++ }, ++ { ++ "text": "\"foo\"", ++ "kind": "stringLiteral" ++ }, ++ { ++ "text": "\n", ++ "kind": "lineBreak" ++ }, ++ { ++ "text": "import", ++ "kind": "keyword" ++ }, ++ { ++ "text": " ", ++ "kind": "space" ++ }, ++ { ++ "text": "first", ++ "kind": "aliasName" ++ } ++ ] ++ }, ++ { ++ "defId": 4, ++ "containerKind": "", ++ "containerName": "", ++ "kind": "alias", ++ "name": "(alias) type \"\" = \"foo\"\nexport \"\"", ++ "displayParts": [ ++ { ++ "text": "(", ++ "kind": "punctuation" ++ }, ++ { ++ "text": "alias", ++ "kind": "text" ++ }, ++ { ++ "text": ")", ++ "kind": "punctuation" ++ }, ++ { ++ "text": " ", ++ "kind": "space" ++ }, ++ { ++ "text": "type", ++ "kind": "keyword" ++ }, ++ { ++ "text": " ", ++ "kind": "space" ++ }, ++ { ++ "text": "\"\"", ++ "kind": "aliasName" ++ }, ++ { ++ "text": " ", ++ "kind": "space" ++ }, ++ { ++ "text": "=", ++ "kind": "operator" ++ }, ++ { ++ "text": " ", ++ "kind": "space" ++ }, ++ { ++ "text": "\"foo\"", ++ "kind": "stringLiteral" ++ }, ++ { ++ "text": "\n", ++ "kind": "lineBreak" ++ }, ++ { ++ "text": "export", ++ "kind": "keyword" ++ }, ++ { ++ "text": " ", ++ "kind": "space" ++ }, ++ { ++ "text": "\"\"", ++ "kind": "aliasName" ++ } ++ ] ++ }, ++ { ++ "defId": 5, ++ "containerKind": "", ++ "containerName": "", ++ "kind": "alias", ++ "name": "(alias) type second = \"foo\"\nimport second", ++ "displayParts": [ ++ { ++ "text": "(", ++ "kind": "punctuation" ++ }, ++ { ++ "text": "alias", ++ "kind": "text" ++ }, ++ { ++ "text": ")", ++ "kind": "punctuation" ++ }, ++ { ++ "text": " ", ++ "kind": "space" ++ }, ++ { ++ "text": "type", ++ "kind": "keyword" ++ }, ++ { ++ "text": " ", ++ "kind": "space" ++ }, ++ { ++ "text": "second", ++ "kind": "aliasName" ++ }, ++ { ++ "text": " ", ++ "kind": "space" ++ }, ++ { ++ "text": "=", ++ "kind": "operator" ++ }, ++ { ++ "text": " ", ++ "kind": "space" ++ }, ++ { ++ "text": "\"foo\"", ++ "kind": "stringLiteral" ++ }, ++ { ++ "text": "\n", ++ "kind": "lineBreak" ++ }, ++ { ++ "text": "import", ++ "kind": "keyword" ++ }, ++ { ++ "text": " ", ++ "kind": "space" ++ }, ++ { ++ "text": "second", ++ "kind": "aliasName" ++ } ++ ] ++ } ++ ] +\ No newline at end of file +diff --git a/tests/baselines/reference/arbitraryModuleNamespaceIdentifiers_values.baseline.jsonc b/tests/baselines/reference/arbitraryModuleNamespaceIdentifiers_values.baseline.jsonc +new file mode 100644 +index 000000000..a992bc704 +--- /dev/null ++++ b/tests/baselines/reference/arbitraryModuleNamespaceIdentifiers_values.baseline.jsonc +@@ -0,0 +1,1628 @@ ++// === findRenameLocations === ++// === /foo.ts === ++// const foo = "foo"; ++// <|export { foo as "/*RENAME*/[|__RENAME|]" };|> ++// <|import { "[|__RENAME|]" as bar } from "./foo";|> ++// if (bar !== "foo") throw bar; ++ ++// === /bar.ts === ++// <|import { "[|__RENAME|]" as first } from "./foo";|> ++// <|export { "[|__RENAME|]" as "" } from "./foo";|> ++// import { "" as second } from "./bar"; ++// if (first !== "foo") throw first; ++// if (second !== "foo") throw second; ++ ++ ++ ++// === findRenameLocations === ++// === /foo.ts === ++// const foo = "foo"; ++// <|export { foo as "[|__RENAME|]" };|> ++// <|import { "/*RENAME*/[|__RENAME|]" as bar } from "./foo";|> ++// if (bar !== "foo") throw bar; ++ ++// === /bar.ts === ++// <|import { "[|__RENAME|]" as first } from "./foo";|> ++// <|export { "[|__RENAME|]" as "" } from "./foo";|> ++// import { "" as second } from "./bar"; ++// if (first !== "foo") throw first; ++// if (second !== "foo") throw second; ++ ++ ++ ++// === findRenameLocations === ++// === /foo.ts === ++// const foo = "foo"; ++// <|export { foo as "[|__RENAME|]" };|> ++// <|import { "[|__RENAME|]" as bar } from "./foo";|> ++// if (bar !== "foo") throw bar; ++ ++// === /bar.ts === ++// <|import { "/*RENAME*/[|__RENAME|]" as first } from "./foo";|> ++// <|export { "[|__RENAME|]" as "" } from "./foo";|> ++// import { "" as second } from "./bar"; ++// if (first !== "foo") throw first; ++// if (second !== "foo") throw second; ++ ++ ++ ++// === findRenameLocations === ++// === /foo.ts === ++// const foo = "foo"; ++// <|export { foo as "[|__RENAME|]" };|> ++// <|import { "[|__RENAME|]" as bar } from "./foo";|> ++// if (bar !== "foo") throw bar; ++ ++// === /bar.ts === ++// <|import { "[|__RENAME|]" as first } from "./foo";|> ++// <|export { "/*RENAME*/[|__RENAME|]" as "" } from "./foo";|> ++// import { "" as second } from "./bar"; ++// if (first !== "foo") throw first; ++// if (second !== "foo") throw second; ++ ++ ++ ++// === goToDefinition === ++// === /foo.ts === ++// <|const [|foo|] = "foo";|> ++// export { foo as "/*GOTO DEF*/__" }; ++// import { "__" as bar } from "./foo"; ++// if (bar !== "foo") throw bar; ++ ++ // === Details === ++ [ ++ { ++ "kind": "const", ++ "name": "foo", ++ "containerName": "", ++ "isLocal": true, ++ "isAmbient": false, ++ "unverified": false ++ } ++ ] ++ ++ ++ ++// === goToDefinition === ++// === /foo.ts === ++// <|const [|foo|] = "foo";|> ++// export { foo as "__" }; ++// import { "/*GOTO DEF*/__" as bar } from "./foo"; ++// if (bar !== "foo") throw bar; ++ ++ // === Details === ++ [ ++ { ++ "kind": "const", ++ "name": "foo", ++ "containerName": "", ++ "isLocal": true, ++ "isAmbient": false, ++ "unverified": false ++ } ++ ] ++ ++ ++ ++// === goToDefinition === ++// === /foo.ts === ++// <|const [|foo|] = "foo";|> ++// export { foo as "__" }; ++// import { "__" as bar } from "./foo"; ++// if (bar !== "foo") throw bar; ++ ++// === /bar.ts === ++// import { [|"/*GOTO DEF*/__"|] as first } from "./foo"; ++// export { "__" as "" } from "./foo"; ++// import { "" as second } from "./bar"; ++// if (first !== "foo") throw first; ++// if (second !== "foo") throw second; ++ ++ // === Details === ++ [ ++ { ++ "kind": "const", ++ "name": "foo", ++ "containerName": "", ++ "isLocal": true, ++ "isAmbient": false, ++ "unverified": false ++ } ++ ] ++ ++ ++ ++// === goToDefinition === ++// === /foo.ts === ++// <|const [|foo|] = "foo";|> ++// export { foo as "__" }; ++// import { "__" as bar } from "./foo"; ++// if (bar !== "foo") throw bar; ++ ++// === /bar.ts === ++// import { "__" as first } from "./foo"; ++// export { [|"/*GOTO DEF*/__"|] as "" } from "./foo"; ++// import { "" as second } from "./bar"; ++// if (first !== "foo") throw first; ++// if (second !== "foo") throw second; ++ ++ // === Details === ++ [ ++ { ++ "kind": "const", ++ "name": "foo", ++ "containerName": "", ++ "isLocal": true, ++ "isAmbient": false, ++ "unverified": false ++ } ++ ] ++ ++ ++ ++// === findAllReferences === ++// === /foo.ts === ++// const foo = "foo"; ++// <|export { foo as "/*FIND ALL REFS*/[|{| defId: 0, isWriteAccess: true, isDefinition: true |}__|]" };|> ++// <|<|import { "[|{| contextId: 1, defId: 0 |}__|]" as [|{| contextId: 2, defId: 1, isWriteAccess: true |}bar|] } from "./foo";|>|> ++// if ([|{| defId: 1 |}bar|] !== "foo") throw [|{| defId: 1 |}bar|]; ++ ++// === /bar.ts === ++// <|<|import { "[|{| contextId: 3, defId: 0 |}__|]" as [|{| contextId: 4, defId: 2, isWriteAccess: true |}first|] } from "./foo";|>|> ++// <|<|export { "[|{| contextId: 5, defId: 0 |}__|]" as "[|{| contextId: 6, defId: 3, isWriteAccess: true |}|]" } from "./foo";|>|> ++// <|<|import { "[|{| contextId: 7, defId: 3 |}|]" as [|{| contextId: 8, defId: 4, isWriteAccess: true |}second|] } from "./bar";|>|> ++// if ([|{| defId: 2 |}first|] !== "foo") throw [|{| defId: 2 |}first|]; ++// if ([|{| defId: 4 |}second|] !== "foo") throw [|{| defId: 4 |}second|]; ++ ++ // === Definitions === ++ // === /foo.ts === ++ // const foo = "foo"; ++ // <|export { foo as "/*FIND ALL REFS*/[|{| defId: 0 |}__|]" };|> ++ // <|import { "__" as [|{| defId: 1 |}bar|] } from "./foo";|> ++ // if (bar !== "foo") throw bar; ++ ++ // === /bar.ts === ++ // <|import { "__" as [|{| defId: 2 |}first|] } from "./foo";|> ++ // <|export { "__" as "[|{| defId: 3 |}|]" } from "./foo";|> ++ // <|import { "" as [|{| defId: 4 |}second|] } from "./bar";|> ++ // if (first !== "foo") throw first; ++ // if (second !== "foo") throw second; ++ ++ // === Details === ++ [ ++ { ++ "defId": 0, ++ "containerKind": "", ++ "containerName": "", ++ "kind": "alias", ++ "name": "(alias) const \"__\": \"foo\"\nexport \"__\"", ++ "displayParts": [ ++ { ++ "text": "(", ++ "kind": "punctuation" ++ }, ++ { ++ "text": "alias", ++ "kind": "text" ++ }, ++ { ++ "text": ")", ++ "kind": "punctuation" ++ }, ++ { ++ "text": " ", ++ "kind": "space" ++ }, ++ { ++ "text": "const", ++ "kind": "keyword" ++ }, ++ { ++ "text": " ", ++ "kind": "space" ++ }, ++ { ++ "text": "\"__\"", ++ "kind": "aliasName" ++ }, ++ { ++ "text": ":", ++ "kind": "punctuation" ++ }, ++ { ++ "text": " ", ++ "kind": "space" ++ }, ++ { ++ "text": "\"foo\"", ++ "kind": "stringLiteral" ++ }, ++ { ++ "text": "\n", ++ "kind": "lineBreak" ++ }, ++ { ++ "text": "export", ++ "kind": "keyword" ++ }, ++ { ++ "text": " ", ++ "kind": "space" ++ }, ++ { ++ "text": "\"__\"", ++ "kind": "aliasName" ++ } ++ ] ++ }, ++ { ++ "defId": 1, ++ "containerKind": "", ++ "containerName": "", ++ "kind": "alias", ++ "name": "(alias) const bar: \"foo\"\nimport bar", ++ "displayParts": [ ++ { ++ "text": "(", ++ "kind": "punctuation" ++ }, ++ { ++ "text": "alias", ++ "kind": "text" ++ }, ++ { ++ "text": ")", ++ "kind": "punctuation" ++ }, ++ { ++ "text": " ", ++ "kind": "space" ++ }, ++ { ++ "text": "const", ++ "kind": "keyword" ++ }, ++ { ++ "text": " ", ++ "kind": "space" ++ }, ++ { ++ "text": "bar", ++ "kind": "aliasName" ++ }, ++ { ++ "text": ":", ++ "kind": "punctuation" ++ }, ++ { ++ "text": " ", ++ "kind": "space" ++ }, ++ { ++ "text": "\"foo\"", ++ "kind": "stringLiteral" ++ }, ++ { ++ "text": "\n", ++ "kind": "lineBreak" ++ }, ++ { ++ "text": "import", ++ "kind": "keyword" ++ }, ++ { ++ "text": " ", ++ "kind": "space" ++ }, ++ { ++ "text": "bar", ++ "kind": "aliasName" ++ } ++ ] ++ }, ++ { ++ "defId": 2, ++ "containerKind": "", ++ "containerName": "", ++ "kind": "alias", ++ "name": "(alias) const first: \"foo\"\nimport first", ++ "displayParts": [ ++ { ++ "text": "(", ++ "kind": "punctuation" ++ }, ++ { ++ "text": "alias", ++ "kind": "text" ++ }, ++ { ++ "text": ")", ++ "kind": "punctuation" ++ }, ++ { ++ "text": " ", ++ "kind": "space" ++ }, ++ { ++ "text": "const", ++ "kind": "keyword" ++ }, ++ { ++ "text": " ", ++ "kind": "space" ++ }, ++ { ++ "text": "first", ++ "kind": "aliasName" ++ }, ++ { ++ "text": ":", ++ "kind": "punctuation" ++ }, ++ { ++ "text": " ", ++ "kind": "space" ++ }, ++ { ++ "text": "\"foo\"", ++ "kind": "stringLiteral" ++ }, ++ { ++ "text": "\n", ++ "kind": "lineBreak" ++ }, ++ { ++ "text": "import", ++ "kind": "keyword" ++ }, ++ { ++ "text": " ", ++ "kind": "space" ++ }, ++ { ++ "text": "first", ++ "kind": "aliasName" ++ } ++ ] ++ }, ++ { ++ "defId": 3, ++ "containerKind": "", ++ "containerName": "", ++ "kind": "alias", ++ "name": "(alias) const \"\": \"foo\"\nexport \"\"", ++ "displayParts": [ ++ { ++ "text": "(", ++ "kind": "punctuation" ++ }, ++ { ++ "text": "alias", ++ "kind": "text" ++ }, ++ { ++ "text": ")", ++ "kind": "punctuation" ++ }, ++ { ++ "text": " ", ++ "kind": "space" ++ }, ++ { ++ "text": "const", ++ "kind": "keyword" ++ }, ++ { ++ "text": " ", ++ "kind": "space" ++ }, ++ { ++ "text": "\"\"", ++ "kind": "aliasName" ++ }, ++ { ++ "text": ":", ++ "kind": "punctuation" ++ }, ++ { ++ "text": " ", ++ "kind": "space" ++ }, ++ { ++ "text": "\"foo\"", ++ "kind": "stringLiteral" ++ }, ++ { ++ "text": "\n", ++ "kind": "lineBreak" ++ }, ++ { ++ "text": "export", ++ "kind": "keyword" ++ }, ++ { ++ "text": " ", ++ "kind": "space" ++ }, ++ { ++ "text": "\"\"", ++ "kind": "aliasName" ++ } ++ ] ++ }, ++ { ++ "defId": 4, ++ "containerKind": "", ++ "containerName": "", ++ "kind": "alias", ++ "name": "(alias) const second: \"foo\"\nimport second", ++ "displayParts": [ ++ { ++ "text": "(", ++ "kind": "punctuation" ++ }, ++ { ++ "text": "alias", ++ "kind": "text" ++ }, ++ { ++ "text": ")", ++ "kind": "punctuation" ++ }, ++ { ++ "text": " ", ++ "kind": "space" ++ }, ++ { ++ "text": "const", ++ "kind": "keyword" ++ }, ++ { ++ "text": " ", ++ "kind": "space" ++ }, ++ { ++ "text": "second", ++ "kind": "aliasName" ++ }, ++ { ++ "text": ":", ++ "kind": "punctuation" ++ }, ++ { ++ "text": " ", ++ "kind": "space" ++ }, ++ { ++ "text": "\"foo\"", ++ "kind": "stringLiteral" ++ }, ++ { ++ "text": "\n", ++ "kind": "lineBreak" ++ }, ++ { ++ "text": "import", ++ "kind": "keyword" ++ }, ++ { ++ "text": " ", ++ "kind": "space" ++ }, ++ { ++ "text": "second", ++ "kind": "aliasName" ++ } ++ ] ++ } ++ ] ++ ++ ++ ++// === findAllReferences === ++// === /foo.ts === ++// const foo = "foo"; ++// <|export { foo as "[|{| defId: 0, isWriteAccess: true |}__|]" };|> ++// <|<|import { "/*FIND ALL REFS*/[|{| contextId: 1, defId: 0 |}__|]" as [|{| contextId: 2, defId: 1, isWriteAccess: true |}bar|] } from "./foo";|>|> ++// if ([|{| defId: 1 |}bar|] !== "foo") throw [|{| defId: 1 |}bar|]; ++ ++// === /bar.ts === ++// <|<|import { "[|{| contextId: 3, defId: 0 |}__|]" as [|{| contextId: 4, defId: 2, isWriteAccess: true |}first|] } from "./foo";|>|> ++// <|<|export { "[|{| contextId: 5, defId: 0 |}__|]" as "[|{| contextId: 6, defId: 3, isWriteAccess: true |}|]" } from "./foo";|>|> ++// <|<|import { "[|{| contextId: 7, defId: 3 |}|]" as [|{| contextId: 8, defId: 4, isWriteAccess: true |}second|] } from "./bar";|>|> ++// if ([|{| defId: 2 |}first|] !== "foo") throw [|{| defId: 2 |}first|]; ++// if ([|{| defId: 4 |}second|] !== "foo") throw [|{| defId: 4 |}second|]; ++ ++ // === Definitions === ++ // === /foo.ts === ++ // const foo = "foo"; ++ // <|export { foo as "[|{| defId: 0 |}__|]" };|> ++ // <|import { "/*FIND ALL REFS*/__" as [|{| defId: 1 |}bar|] } from "./foo";|> ++ // if (bar !== "foo") throw bar; ++ ++ // === /bar.ts === ++ // <|import { "__" as [|{| defId: 2 |}first|] } from "./foo";|> ++ // <|export { "__" as "[|{| defId: 3 |}|]" } from "./foo";|> ++ // <|import { "" as [|{| defId: 4 |}second|] } from "./bar";|> ++ // if (first !== "foo") throw first; ++ // if (second !== "foo") throw second; ++ ++ // === Details === ++ [ ++ { ++ "defId": 0, ++ "containerKind": "", ++ "containerName": "", ++ "kind": "alias", ++ "name": "(alias) const \"__\": \"foo\"\nexport \"__\"", ++ "displayParts": [ ++ { ++ "text": "(", ++ "kind": "punctuation" ++ }, ++ { ++ "text": "alias", ++ "kind": "text" ++ }, ++ { ++ "text": ")", ++ "kind": "punctuation" ++ }, ++ { ++ "text": " ", ++ "kind": "space" ++ }, ++ { ++ "text": "const", ++ "kind": "keyword" ++ }, ++ { ++ "text": " ", ++ "kind": "space" ++ }, ++ { ++ "text": "\"__\"", ++ "kind": "aliasName" ++ }, ++ { ++ "text": ":", ++ "kind": "punctuation" ++ }, ++ { ++ "text": " ", ++ "kind": "space" ++ }, ++ { ++ "text": "\"foo\"", ++ "kind": "stringLiteral" ++ }, ++ { ++ "text": "\n", ++ "kind": "lineBreak" ++ }, ++ { ++ "text": "export", ++ "kind": "keyword" ++ }, ++ { ++ "text": " ", ++ "kind": "space" ++ }, ++ { ++ "text": "\"__\"", ++ "kind": "aliasName" ++ } ++ ] ++ }, ++ { ++ "defId": 1, ++ "containerKind": "", ++ "containerName": "", ++ "kind": "alias", ++ "name": "(alias) const bar: \"foo\"\nimport bar", ++ "displayParts": [ ++ { ++ "text": "(", ++ "kind": "punctuation" ++ }, ++ { ++ "text": "alias", ++ "kind": "text" ++ }, ++ { ++ "text": ")", ++ "kind": "punctuation" ++ }, ++ { ++ "text": " ", ++ "kind": "space" ++ }, ++ { ++ "text": "const", ++ "kind": "keyword" ++ }, ++ { ++ "text": " ", ++ "kind": "space" ++ }, ++ { ++ "text": "bar", ++ "kind": "aliasName" ++ }, ++ { ++ "text": ":", ++ "kind": "punctuation" ++ }, ++ { ++ "text": " ", ++ "kind": "space" ++ }, ++ { ++ "text": "\"foo\"", ++ "kind": "stringLiteral" ++ }, ++ { ++ "text": "\n", ++ "kind": "lineBreak" ++ }, ++ { ++ "text": "import", ++ "kind": "keyword" ++ }, ++ { ++ "text": " ", ++ "kind": "space" ++ }, ++ { ++ "text": "bar", ++ "kind": "aliasName" ++ } ++ ] ++ }, ++ { ++ "defId": 2, ++ "containerKind": "", ++ "containerName": "", ++ "kind": "alias", ++ "name": "(alias) const first: \"foo\"\nimport first", ++ "displayParts": [ ++ { ++ "text": "(", ++ "kind": "punctuation" ++ }, ++ { ++ "text": "alias", ++ "kind": "text" ++ }, ++ { ++ "text": ")", ++ "kind": "punctuation" ++ }, ++ { ++ "text": " ", ++ "kind": "space" ++ }, ++ { ++ "text": "const", ++ "kind": "keyword" ++ }, ++ { ++ "text": " ", ++ "kind": "space" ++ }, ++ { ++ "text": "first", ++ "kind": "aliasName" ++ }, ++ { ++ "text": ":", ++ "kind": "punctuation" ++ }, ++ { ++ "text": " ", ++ "kind": "space" ++ }, ++ { ++ "text": "\"foo\"", ++ "kind": "stringLiteral" ++ }, ++ { ++ "text": "\n", ++ "kind": "lineBreak" ++ }, ++ { ++ "text": "import", ++ "kind": "keyword" ++ }, ++ { ++ "text": " ", ++ "kind": "space" ++ }, ++ { ++ "text": "first", ++ "kind": "aliasName" ++ } ++ ] ++ }, ++ { ++ "defId": 3, ++ "containerKind": "", ++ "containerName": "", ++ "kind": "alias", ++ "name": "(alias) const \"\": \"foo\"\nexport \"\"", ++ "displayParts": [ ++ { ++ "text": "(", ++ "kind": "punctuation" ++ }, ++ { ++ "text": "alias", ++ "kind": "text" ++ }, ++ { ++ "text": ")", ++ "kind": "punctuation" ++ }, ++ { ++ "text": " ", ++ "kind": "space" ++ }, ++ { ++ "text": "const", ++ "kind": "keyword" ++ }, ++ { ++ "text": " ", ++ "kind": "space" ++ }, ++ { ++ "text": "\"\"", ++ "kind": "aliasName" ++ }, ++ { ++ "text": ":", ++ "kind": "punctuation" ++ }, ++ { ++ "text": " ", ++ "kind": "space" ++ }, ++ { ++ "text": "\"foo\"", ++ "kind": "stringLiteral" ++ }, ++ { ++ "text": "\n", ++ "kind": "lineBreak" ++ }, ++ { ++ "text": "export", ++ "kind": "keyword" ++ }, ++ { ++ "text": " ", ++ "kind": "space" ++ }, ++ { ++ "text": "\"\"", ++ "kind": "aliasName" ++ } ++ ] ++ }, ++ { ++ "defId": 4, ++ "containerKind": "", ++ "containerName": "", ++ "kind": "alias", ++ "name": "(alias) const second: \"foo\"\nimport second", ++ "displayParts": [ ++ { ++ "text": "(", ++ "kind": "punctuation" ++ }, ++ { ++ "text": "alias", ++ "kind": "text" ++ }, ++ { ++ "text": ")", ++ "kind": "punctuation" ++ }, ++ { ++ "text": " ", ++ "kind": "space" ++ }, ++ { ++ "text": "const", ++ "kind": "keyword" ++ }, ++ { ++ "text": " ", ++ "kind": "space" ++ }, ++ { ++ "text": "second", ++ "kind": "aliasName" ++ }, ++ { ++ "text": ":", ++ "kind": "punctuation" ++ }, ++ { ++ "text": " ", ++ "kind": "space" ++ }, ++ { ++ "text": "\"foo\"", ++ "kind": "stringLiteral" ++ }, ++ { ++ "text": "\n", ++ "kind": "lineBreak" ++ }, ++ { ++ "text": "import", ++ "kind": "keyword" ++ }, ++ { ++ "text": " ", ++ "kind": "space" ++ }, ++ { ++ "text": "second", ++ "kind": "aliasName" ++ } ++ ] ++ } ++ ] ++ ++ ++ ++// === findAllReferences === ++// === /foo.ts === ++// const foo = "foo"; ++// <|export { foo as "[|{| defId: 0, isWriteAccess: true |}__|]" };|> ++// <|<|import { "[|{| contextId: 1, defId: 0 |}__|]" as [|{| contextId: 2, defId: 1, isWriteAccess: true |}bar|] } from "./foo";|>|> ++// if ([|{| defId: 1 |}bar|] !== "foo") throw [|{| defId: 1 |}bar|]; ++ ++// === /bar.ts === ++// <|<|import { "/*FIND ALL REFS*/[|{| contextId: 3, defId: 0 |}__|]" as [|{| contextId: 4, defId: 2, isWriteAccess: true |}first|] } from "./foo";|>|> ++// <|<|export { "[|{| contextId: 5, defId: 0 |}__|]" as "[|{| contextId: 6, defId: 3, isWriteAccess: true |}|]" } from "./foo";|>|> ++// <|<|import { "[|{| contextId: 7, defId: 3 |}|]" as [|{| contextId: 8, defId: 4, isWriteAccess: true |}second|] } from "./bar";|>|> ++// if ([|{| defId: 2 |}first|] !== "foo") throw [|{| defId: 2 |}first|]; ++// if ([|{| defId: 4 |}second|] !== "foo") throw [|{| defId: 4 |}second|]; ++ ++ // === Definitions === ++ // === /foo.ts === ++ // const foo = "foo"; ++ // <|export { foo as "[|{| defId: 0 |}__|]" };|> ++ // <|import { "__" as [|{| defId: 1 |}bar|] } from "./foo";|> ++ // if (bar !== "foo") throw bar; ++ ++ // === /bar.ts === ++ // <|import { "/*FIND ALL REFS*/__" as [|{| defId: 2 |}first|] } from "./foo";|> ++ // <|export { "__" as "[|{| defId: 3 |}|]" } from "./foo";|> ++ // <|import { "" as [|{| defId: 4 |}second|] } from "./bar";|> ++ // if (first !== "foo") throw first; ++ // if (second !== "foo") throw second; ++ ++ // === Details === ++ [ ++ { ++ "defId": 0, ++ "containerKind": "", ++ "containerName": "", ++ "kind": "alias", ++ "name": "(alias) const \"__\": \"foo\"\nexport \"__\"", ++ "displayParts": [ ++ { ++ "text": "(", ++ "kind": "punctuation" ++ }, ++ { ++ "text": "alias", ++ "kind": "text" ++ }, ++ { ++ "text": ")", ++ "kind": "punctuation" ++ }, ++ { ++ "text": " ", ++ "kind": "space" ++ }, ++ { ++ "text": "const", ++ "kind": "keyword" ++ }, ++ { ++ "text": " ", ++ "kind": "space" ++ }, ++ { ++ "text": "\"__\"", ++ "kind": "aliasName" ++ }, ++ { ++ "text": ":", ++ "kind": "punctuation" ++ }, ++ { ++ "text": " ", ++ "kind": "space" ++ }, ++ { ++ "text": "\"foo\"", ++ "kind": "stringLiteral" ++ }, ++ { ++ "text": "\n", ++ "kind": "lineBreak" ++ }, ++ { ++ "text": "export", ++ "kind": "keyword" ++ }, ++ { ++ "text": " ", ++ "kind": "space" ++ }, ++ { ++ "text": "\"__\"", ++ "kind": "aliasName" ++ } ++ ] ++ }, ++ { ++ "defId": 1, ++ "containerKind": "", ++ "containerName": "", ++ "kind": "alias", ++ "name": "(alias) const bar: \"foo\"\nimport bar", ++ "displayParts": [ ++ { ++ "text": "(", ++ "kind": "punctuation" ++ }, ++ { ++ "text": "alias", ++ "kind": "text" ++ }, ++ { ++ "text": ")", ++ "kind": "punctuation" ++ }, ++ { ++ "text": " ", ++ "kind": "space" ++ }, ++ { ++ "text": "const", ++ "kind": "keyword" ++ }, ++ { ++ "text": " ", ++ "kind": "space" ++ }, ++ { ++ "text": "bar", ++ "kind": "aliasName" ++ }, ++ { ++ "text": ":", ++ "kind": "punctuation" ++ }, ++ { ++ "text": " ", ++ "kind": "space" ++ }, ++ { ++ "text": "\"foo\"", ++ "kind": "stringLiteral" ++ }, ++ { ++ "text": "\n", ++ "kind": "lineBreak" ++ }, ++ { ++ "text": "import", ++ "kind": "keyword" ++ }, ++ { ++ "text": " ", ++ "kind": "space" ++ }, ++ { ++ "text": "bar", ++ "kind": "aliasName" ++ } ++ ] ++ }, ++ { ++ "defId": 2, ++ "containerKind": "", ++ "containerName": "", ++ "kind": "alias", ++ "name": "(alias) const first: \"foo\"\nimport first", ++ "displayParts": [ ++ { ++ "text": "(", ++ "kind": "punctuation" ++ }, ++ { ++ "text": "alias", ++ "kind": "text" ++ }, ++ { ++ "text": ")", ++ "kind": "punctuation" ++ }, ++ { ++ "text": " ", ++ "kind": "space" ++ }, ++ { ++ "text": "const", ++ "kind": "keyword" ++ }, ++ { ++ "text": " ", ++ "kind": "space" ++ }, ++ { ++ "text": "first", ++ "kind": "aliasName" ++ }, ++ { ++ "text": ":", ++ "kind": "punctuation" ++ }, ++ { ++ "text": " ", ++ "kind": "space" ++ }, ++ { ++ "text": "\"foo\"", ++ "kind": "stringLiteral" ++ }, ++ { ++ "text": "\n", ++ "kind": "lineBreak" ++ }, ++ { ++ "text": "import", ++ "kind": "keyword" ++ }, ++ { ++ "text": " ", ++ "kind": "space" ++ }, ++ { ++ "text": "first", ++ "kind": "aliasName" ++ } ++ ] ++ }, ++ { ++ "defId": 3, ++ "containerKind": "", ++ "containerName": "", ++ "kind": "alias", ++ "name": "(alias) const \"\": \"foo\"\nexport \"\"", ++ "displayParts": [ ++ { ++ "text": "(", ++ "kind": "punctuation" ++ }, ++ { ++ "text": "alias", ++ "kind": "text" ++ }, ++ { ++ "text": ")", ++ "kind": "punctuation" ++ }, ++ { ++ "text": " ", ++ "kind": "space" ++ }, ++ { ++ "text": "const", ++ "kind": "keyword" ++ }, ++ { ++ "text": " ", ++ "kind": "space" ++ }, ++ { ++ "text": "\"\"", ++ "kind": "aliasName" ++ }, ++ { ++ "text": ":", ++ "kind": "punctuation" ++ }, ++ { ++ "text": " ", ++ "kind": "space" ++ }, ++ { ++ "text": "\"foo\"", ++ "kind": "stringLiteral" ++ }, ++ { ++ "text": "\n", ++ "kind": "lineBreak" ++ }, ++ { ++ "text": "export", ++ "kind": "keyword" ++ }, ++ { ++ "text": " ", ++ "kind": "space" ++ }, ++ { ++ "text": "\"\"", ++ "kind": "aliasName" ++ } ++ ] ++ }, ++ { ++ "defId": 4, ++ "containerKind": "", ++ "containerName": "", ++ "kind": "alias", ++ "name": "(alias) const second: \"foo\"\nimport second", ++ "displayParts": [ ++ { ++ "text": "(", ++ "kind": "punctuation" ++ }, ++ { ++ "text": "alias", ++ "kind": "text" ++ }, ++ { ++ "text": ")", ++ "kind": "punctuation" ++ }, ++ { ++ "text": " ", ++ "kind": "space" ++ }, ++ { ++ "text": "const", ++ "kind": "keyword" ++ }, ++ { ++ "text": " ", ++ "kind": "space" ++ }, ++ { ++ "text": "second", ++ "kind": "aliasName" ++ }, ++ { ++ "text": ":", ++ "kind": "punctuation" ++ }, ++ { ++ "text": " ", ++ "kind": "space" ++ }, ++ { ++ "text": "\"foo\"", ++ "kind": "stringLiteral" ++ }, ++ { ++ "text": "\n", ++ "kind": "lineBreak" ++ }, ++ { ++ "text": "import", ++ "kind": "keyword" ++ }, ++ { ++ "text": " ", ++ "kind": "space" ++ }, ++ { ++ "text": "second", ++ "kind": "aliasName" ++ } ++ ] ++ } ++ ] ++ ++ ++ ++// === findAllReferences === ++// === /foo.ts === ++// <|const [|{| defId: 0, isWriteAccess: true |}foo|] = "foo";|> ++// <|<|export { [|{| contextId: 1, defId: 0 |}foo|] as "[|{| contextId: 2, defId: 1, isWriteAccess: true |}__|]" };|>|> ++// <|<|import { "[|{| contextId: 3, defId: 1 |}__|]" as [|{| contextId: 4, defId: 2, isWriteAccess: true |}bar|] } from "./foo";|>|> ++// if ([|{| defId: 2 |}bar|] !== "foo") throw [|{| defId: 2 |}bar|]; ++ ++// === /bar.ts === ++// <|<|import { "[|{| contextId: 5, defId: 1 |}__|]" as [|{| contextId: 6, defId: 3, isWriteAccess: true |}first|] } from "./foo";|>|> ++// <|<|export { "/*FIND ALL REFS*/[|{| contextId: 7, defId: 1 |}__|]" as "[|{| contextId: 8, defId: 4, isWriteAccess: true |}|]" } from "./foo";|>|> ++// <|<|import { "[|{| contextId: 9, defId: 4 |}|]" as [|{| contextId: 10, defId: 5, isWriteAccess: true |}second|] } from "./bar";|>|> ++// if ([|{| defId: 3 |}first|] !== "foo") throw [|{| defId: 3 |}first|]; ++// if ([|{| defId: 5 |}second|] !== "foo") throw [|{| defId: 5 |}second|]; ++ ++ // === Definitions === ++ // === /foo.ts === ++ // <|const [|{| defId: 0 |}foo|] = "foo";|> ++ // <|export { foo as "[|{| defId: 1 |}__|]" };|> ++ // <|import { "__" as [|{| defId: 2 |}bar|] } from "./foo";|> ++ // if (bar !== "foo") throw bar; ++ ++ // === /bar.ts === ++ // <|import { "__" as [|{| defId: 3 |}first|] } from "./foo";|> ++ // <|export { "/*FIND ALL REFS*/__" as "[|{| defId: 4 |}|]" } from "./foo";|> ++ // <|import { "" as [|{| defId: 5 |}second|] } from "./bar";|> ++ // if (first !== "foo") throw first; ++ // if (second !== "foo") throw second; ++ ++ // === Details === ++ [ ++ { ++ "defId": 0, ++ "containerKind": "", ++ "containerName": "", ++ "kind": "const", ++ "name": "const foo: \"foo\"", ++ "displayParts": [ ++ { ++ "text": "const", ++ "kind": "keyword" ++ }, ++ { ++ "text": " ", ++ "kind": "space" ++ }, ++ { ++ "text": "foo", ++ "kind": "localName" ++ }, ++ { ++ "text": ":", ++ "kind": "punctuation" ++ }, ++ { ++ "text": " ", ++ "kind": "space" ++ }, ++ { ++ "text": "\"foo\"", ++ "kind": "stringLiteral" ++ } ++ ] ++ }, ++ { ++ "defId": 1, ++ "containerKind": "", ++ "containerName": "", ++ "kind": "alias", ++ "name": "(alias) const \"__\": \"foo\"\nexport \"__\"", ++ "displayParts": [ ++ { ++ "text": "(", ++ "kind": "punctuation" ++ }, ++ { ++ "text": "alias", ++ "kind": "text" ++ }, ++ { ++ "text": ")", ++ "kind": "punctuation" ++ }, ++ { ++ "text": " ", ++ "kind": "space" ++ }, ++ { ++ "text": "const", ++ "kind": "keyword" ++ }, ++ { ++ "text": " ", ++ "kind": "space" ++ }, ++ { ++ "text": "\"__\"", ++ "kind": "aliasName" ++ }, ++ { ++ "text": ":", ++ "kind": "punctuation" ++ }, ++ { ++ "text": " ", ++ "kind": "space" ++ }, ++ { ++ "text": "\"foo\"", ++ "kind": "stringLiteral" ++ }, ++ { ++ "text": "\n", ++ "kind": "lineBreak" ++ }, ++ { ++ "text": "export", ++ "kind": "keyword" ++ }, ++ { ++ "text": " ", ++ "kind": "space" ++ }, ++ { ++ "text": "\"__\"", ++ "kind": "aliasName" ++ } ++ ] ++ }, ++ { ++ "defId": 2, ++ "containerKind": "", ++ "containerName": "", ++ "kind": "alias", ++ "name": "(alias) const bar: \"foo\"\nimport bar", ++ "displayParts": [ ++ { ++ "text": "(", ++ "kind": "punctuation" ++ }, ++ { ++ "text": "alias", ++ "kind": "text" ++ }, ++ { ++ "text": ")", ++ "kind": "punctuation" ++ }, ++ { ++ "text": " ", ++ "kind": "space" ++ }, ++ { ++ "text": "const", ++ "kind": "keyword" ++ }, ++ { ++ "text": " ", ++ "kind": "space" ++ }, ++ { ++ "text": "bar", ++ "kind": "aliasName" ++ }, ++ { ++ "text": ":", ++ "kind": "punctuation" ++ }, ++ { ++ "text": " ", ++ "kind": "space" ++ }, ++ { ++ "text": "\"foo\"", ++ "kind": "stringLiteral" ++ }, ++ { ++ "text": "\n", ++ "kind": "lineBreak" ++ }, ++ { ++ "text": "import", ++ "kind": "keyword" ++ }, ++ { ++ "text": " ", ++ "kind": "space" ++ }, ++ { ++ "text": "bar", ++ "kind": "aliasName" ++ } ++ ] ++ }, ++ { ++ "defId": 3, ++ "containerKind": "", ++ "containerName": "", ++ "kind": "alias", ++ "name": "(alias) const first: \"foo\"\nimport first", ++ "displayParts": [ ++ { ++ "text": "(", ++ "kind": "punctuation" ++ }, ++ { ++ "text": "alias", ++ "kind": "text" ++ }, ++ { ++ "text": ")", ++ "kind": "punctuation" ++ }, ++ { ++ "text": " ", ++ "kind": "space" ++ }, ++ { ++ "text": "const", ++ "kind": "keyword" ++ }, ++ { ++ "text": " ", ++ "kind": "space" ++ }, ++ { ++ "text": "first", ++ "kind": "aliasName" ++ }, ++ { ++ "text": ":", ++ "kind": "punctuation" ++ }, ++ { ++ "text": " ", ++ "kind": "space" ++ }, ++ { ++ "text": "\"foo\"", ++ "kind": "stringLiteral" ++ }, ++ { ++ "text": "\n", ++ "kind": "lineBreak" ++ }, ++ { ++ "text": "import", ++ "kind": "keyword" ++ }, ++ { ++ "text": " ", ++ "kind": "space" ++ }, ++ { ++ "text": "first", ++ "kind": "aliasName" ++ } ++ ] ++ }, ++ { ++ "defId": 4, ++ "containerKind": "", ++ "containerName": "", ++ "kind": "alias", ++ "name": "(alias) const \"\": \"foo\"\nexport \"\"", ++ "displayParts": [ ++ { ++ "text": "(", ++ "kind": "punctuation" ++ }, ++ { ++ "text": "alias", ++ "kind": "text" ++ }, ++ { ++ "text": ")", ++ "kind": "punctuation" ++ }, ++ { ++ "text": " ", ++ "kind": "space" ++ }, ++ { ++ "text": "const", ++ "kind": "keyword" ++ }, ++ { ++ "text": " ", ++ "kind": "space" ++ }, ++ { ++ "text": "\"\"", ++ "kind": "aliasName" ++ }, ++ { ++ "text": ":", ++ "kind": "punctuation" ++ }, ++ { ++ "text": " ", ++ "kind": "space" ++ }, ++ { ++ "text": "\"foo\"", ++ "kind": "stringLiteral" ++ }, ++ { ++ "text": "\n", ++ "kind": "lineBreak" ++ }, ++ { ++ "text": "export", ++ "kind": "keyword" ++ }, ++ { ++ "text": " ", ++ "kind": "space" ++ }, ++ { ++ "text": "\"\"", ++ "kind": "aliasName" ++ } ++ ] ++ }, ++ { ++ "defId": 5, ++ "containerKind": "", ++ "containerName": "", ++ "kind": "alias", ++ "name": "(alias) const second: \"foo\"\nimport second", ++ "displayParts": [ ++ { ++ "text": "(", ++ "kind": "punctuation" ++ }, ++ { ++ "text": "alias", ++ "kind": "text" ++ }, ++ { ++ "text": ")", ++ "kind": "punctuation" ++ }, ++ { ++ "text": " ", ++ "kind": "space" ++ }, ++ { ++ "text": "const", ++ "kind": "keyword" ++ }, ++ { ++ "text": " ", ++ "kind": "space" ++ }, ++ { ++ "text": "second", ++ "kind": "aliasName" ++ }, ++ { ++ "text": ":", ++ "kind": "punctuation" ++ }, ++ { ++ "text": " ", ++ "kind": "space" ++ }, ++ { ++ "text": "\"foo\"", ++ "kind": "stringLiteral" ++ }, ++ { ++ "text": "\n", ++ "kind": "lineBreak" ++ }, ++ { ++ "text": "import", ++ "kind": "keyword" ++ }, ++ { ++ "text": " ", ++ "kind": "space" ++ }, ++ { ++ "text": "second", ++ "kind": "aliasName" ++ } ++ ] ++ } ++ ] +\ No newline at end of file +diff --git a/tests/cases/conformance/es2022/arbitraryModuleNamespaceIdentifiers/arbitraryModuleNamespaceIdentifiers_exportEmpty.ts b/tests/cases/conformance/es2022/arbitraryModuleNamespaceIdentifiers/arbitraryModuleNamespaceIdentifiers_exportEmpty.ts +new file mode 100644 +index 000000000..2f1d66936 +--- /dev/null ++++ b/tests/cases/conformance/es2022/arbitraryModuleNamespaceIdentifiers/arbitraryModuleNamespaceIdentifiers_exportEmpty.ts +@@ -0,0 +1,10 @@ ++//@module: ES2022 ++//@target: ES2022 ++//@declaration: true ++ ++// This should result in a type error. In particular, the empty string is a now ++// a valid module export name, and should be treated as such here. ++const empty = "empty"; ++export { empty as "" }; ++import { "" as foo } from "./arbitraryModuleNamespaceIdentifiers_exportEmpty"; ++const bar: "type error expected here" = foo; +diff --git a/tests/cases/conformance/es2022/arbitraryModuleNamespaceIdentifiers/arbitraryModuleNamespaceIdentifiers_importEmpty.ts b/tests/cases/conformance/es2022/arbitraryModuleNamespaceIdentifiers/arbitraryModuleNamespaceIdentifiers_importEmpty.ts +new file mode 100644 +index 000000000..42023ae44 +--- /dev/null ++++ b/tests/cases/conformance/es2022/arbitraryModuleNamespaceIdentifiers/arbitraryModuleNamespaceIdentifiers_importEmpty.ts +@@ -0,0 +1,12 @@ ++//@module: ES2022 ++//@target: ES2022 ++//@declaration: true ++ ++// These should all be errors. In particular, the empty string is a now a valid ++// module export name, and should be treated as such here. ++import { ++ "missing" as x, ++ "(missing)" as y, ++ "" as z, ++} from "./arbitraryModuleNamespaceIdentifiers_importEmpty"; ++const xyz = [x, y, z]; +diff --git a/tests/cases/conformance/es2022/arbitraryModuleNamespaceIdentifiers/arbitraryModuleNamespaceIdentifiers_module.ts b/tests/cases/conformance/es2022/arbitraryModuleNamespaceIdentifiers/arbitraryModuleNamespaceIdentifiers_module.ts +new file mode 100644 +index 000000000..e69f71ef7 +--- /dev/null ++++ b/tests/cases/conformance/es2022/arbitraryModuleNamespaceIdentifiers/arbitraryModuleNamespaceIdentifiers_module.ts +@@ -0,0 +1,33 @@ ++//@module: * ++//@target: ES2022 ++//@declaration: true ++ ++const someValue = "someValue"; ++type someType = "someType"; ++ ++export { someValue as "" }; ++import { "" as valueX } from "./arbitraryModuleNamespaceIdentifiers_module"; ++if (valueX !== "someValue") throw "should be someValue"; ++ ++export { "" as "" } from "./arbitraryModuleNamespaceIdentifiers_module"; ++import { "" as valueY } from "./arbitraryModuleNamespaceIdentifiers_module"; ++if (valueY !== "someValue") throw "should be someValue"; ++ ++export * as "" from "./arbitraryModuleNamespaceIdentifiers_module"; ++import { "" as valueZ } from "./arbitraryModuleNamespaceIdentifiers_module"; ++if (valueZ[""] !== "someValue") throw "should be someValue"; ++if (valueZ[""] !== "someValue") throw "should be someValue"; ++if (valueZ[""] !== valueZ) throw "should be export namespace"; ++ ++export { type someType as "" }; ++import { type "" as typeA } from "./arbitraryModuleNamespaceIdentifiers_module"; ++const importTest: typeA = "expect error about someType"; ++ ++export { type "" as "" } from "./arbitraryModuleNamespaceIdentifiers_module"; ++import { type "" as typeB } from "./arbitraryModuleNamespaceIdentifiers_module"; ++const reimportTest: typeB = "expect error about someType"; ++ ++export type * as "" from "./arbitraryModuleNamespaceIdentifiers_module"; ++import { type "" as typeC } from "./arbitraryModuleNamespaceIdentifiers_module"; ++export type otherType = "otherType"; ++const importStarTestA: typeC.otherType = "expect error about otherType"; +diff --git a/tests/cases/conformance/es2022/arbitraryModuleNamespaceIdentifiers/arbitraryModuleNamespaceIdentifiers_syntax.ts b/tests/cases/conformance/es2022/arbitraryModuleNamespaceIdentifiers/arbitraryModuleNamespaceIdentifiers_syntax.ts +new file mode 100644 +index 000000000..d4bb2ffd3 +--- /dev/null ++++ b/tests/cases/conformance/es2022/arbitraryModuleNamespaceIdentifiers/arbitraryModuleNamespaceIdentifiers_syntax.ts +@@ -0,0 +1,64 @@ ++//@module: ES2022 ++//@target: ES2022 ++//@declaration: true ++ ++ ++// @filename: values-valid.ts ++export const foo = 123; ++export { foo as "valid 1" }; ++import { "valid 1" as bar } from "./values-valid"; ++export { "valid 1" as "valid 2" } from "./values-valid"; ++export { foo as "valid 3" } from "./values-valid"; ++export * as "valid 4" from "./values-valid"; ++ ++// @filename: values-bad-import.ts ++import { foo as "invalid 2" } from "./values-valid"; ++ ++// @filename: values-bad-export.ts ++export { "invalid 3" as baz }; ++ ++// @filename: values-no-as.ts ++import { "invalid 1" } from "./values-valid"; ++ ++// @filename: values-type-as.ts ++import { type as "invalid 4" } from "./values-valid"; ++ ++ ++// @filename: type-decls-valid.ts ++export type foo = 123; ++export type { foo as "valid 1" }; ++import type { "valid 1" as bar } from "./type-decls-valid"; ++export type { "valid 1" as "valid 2" } from "./type-decls-valid"; ++export type { foo as "valid 3" } from "./type-decls-valid"; ++export type * as "valid 4" from "./type-decls-valid"; ++ ++// @filename: type-decls-bad-import.ts ++import type { foo as "invalid 2" } from "./type-decls-valid"; ++ ++// @filename: type-decls-bad-export.ts ++export type { "invalid 3" as baz }; ++ ++// @filename: type-decls-no-as.ts ++import type { "invalid 1" } from "./type-decls-valid"; ++ ++// @filename: type-decls-type-as.ts ++import type { type as "invalid 4" } from "./type-decls-valid"; ++ ++// @filename: type-clause-valid.ts ++export type foo = 123; ++export { type foo as "valid 1" }; ++import { type "valid 1" as bar } from "./type-clause-valid"; ++export { type "valid 1" as "valid 2" } from "./type-clause-valid"; ++export { type foo as "valid 3" } from "./type-clause-valid"; ++ ++// @filename: type-clause-bad-import.ts ++import { type foo as "invalid 2" } from "./type-clause-valid"; ++ ++// @filename: type-clause-bad-export.ts ++export { type "invalid 3" as baz }; ++ ++// @filename: type-clause-no-as.ts ++import { type "invalid 1" } from "./type-clause-valid"; ++ ++// @filename: type-clause-type-as-as.ts ++import { type as as "invalid 4" } from "./type-clause-valid"; +diff --git a/tests/cases/fourslash/arbitraryModuleNamespaceIdentifiers_types.ts b/tests/cases/fourslash/arbitraryModuleNamespaceIdentifiers_types.ts +new file mode 100644 +index 000000000..be380d0d5 +--- /dev/null ++++ b/tests/cases/fourslash/arbitraryModuleNamespaceIdentifiers_types.ts +@@ -0,0 +1,19 @@ ++/// ++ ++// @Filename: /foo.ts ++////type foo = "foo"; ++////export { type foo as "[|__|]" }; ++////import { type "[|__|]" as bar } from "./foo"; ++////const testBar: bar = "foo"; ++ ++// @Filename: /bar.ts ++////import { type "[|__|]" as first } from "./foo"; ++////export { type "[|__|]" as "" } from "./foo"; ++////import { type "" as second } from "./bar"; ++////const testFirst: first = "foo"; ++////const testSecond: second = "foo"; ++ ++verify.noErrors(); ++verify.baselineRename(test.ranges()); ++verify.baselineGoToDefinition(...test.ranges()); ++verify.baselineFindAllReferences(...test.ranges()); +diff --git a/tests/cases/fourslash/arbitraryModuleNamespaceIdentifiers_values.ts b/tests/cases/fourslash/arbitraryModuleNamespaceIdentifiers_values.ts +new file mode 100644 +index 000000000..bab23a943 +--- /dev/null ++++ b/tests/cases/fourslash/arbitraryModuleNamespaceIdentifiers_values.ts +@@ -0,0 +1,19 @@ ++/// ++ ++// @Filename: /foo.ts ++////const foo = "foo"; ++////export { foo as "[|__|]" }; ++////import { "[|__|]" as bar } from "./foo"; ++////if (bar !== "foo") throw bar; ++ ++// @Filename: /bar.ts ++////import { "[|__|]" as first } from "./foo"; ++////export { "[|__|]" as "" } from "./foo"; ++////import { "" as second } from "./bar"; ++////if (first !== "foo") throw first; ++////if (second !== "foo") throw second; ++ ++verify.noErrors(); ++verify.baselineRename(test.ranges()); ++verify.baselineGoToDefinition(...test.ranges()); ++verify.baselineFindAllReferences(...test.ranges()); +diff --git a/tests/cases/fourslash/completionsImportOrExportSpecifier.ts b/tests/cases/fourslash/completionsImportOrExportSpecifier.ts +new file mode 100644 +index 000000000..533c6f315 +--- /dev/null ++++ b/tests/cases/fourslash/completionsImportOrExportSpecifier.ts +@@ -0,0 +1,58 @@ ++/// ++ ++// @Filename: exports.ts ++//// export let foo = 1; ++//// let someValue = 2; ++//// let someType = 3; ++//// export { ++//// someValue as "__some value", ++//// someType as "__some type", ++//// }; ++ ++// @Filename: values.ts ++//// import { /*valueImport0*/ } from "./exports"; ++//// import { /*valueImport1*/ as valueImport1 } from "./exports"; ++//// import { foo as /*valueImport2*/ } from "./exports"; ++//// import { foo, /*valueImport3*/ as valueImport3 } from "./exports"; ++//// ++//// export { /*valueExport0*/ } from "./exports"; ++//// export { /*valueExport1*/ as valueExport1 } from "./exports"; ++//// export { foo as /*valueExport2*/ } from "./exports"; ++//// export { foo, /*valueExport3*/ } from "./exports"; ++ ++// @Filename: types.ts ++//// import { type /*typeImport0*/ } from "./exports"; ++//// import { type /*typeImport1*/ as typeImport1 } from "./exports"; ++//// import { type foo as /*typeImport2*/ } from "./exports"; ++//// import { type foo, type /*typeImport3*/ as typeImport3 } from "./exports"; ++//// ++//// export { type /*typeExport0*/ } from "./exports"; ++//// export { type /*typeExport1*/ as typeExport1 } from "./exports"; ++//// export { type foo as /*typeExport2*/ } from "./exports"; ++//// export { type foo, type /*typeExport3*/ } from "./exports"; ++ ++const __some_type = { name: "__some type", insertText: '"__some type"' } ++const __some_value = { name: "__some value", insertText: '"__some value"' } ++const __some_type_as = { name: "__some type", insertText: '"__some type" as __some_type' } ++const __some_value_as = { name: "__some value", insertText: '"__some value" as __some_value' } ++const typeKeyword = { name: "type", sortText: completion.SortText.GlobalsOrKeywords } ++ ++verify.completions({ marker: "valueImport0", exact: [__some_type_as, __some_value_as, "foo", typeKeyword] }); ++verify.completions({ marker: "valueImport1", exact: [__some_type_as, __some_value_as, "foo", typeKeyword] }); ++verify.completions({ marker: "valueImport2", exact: [] }); ++verify.completions({ marker: "valueImport3", exact: [__some_type_as, __some_value_as, typeKeyword] }); ++ ++verify.completions({ marker: "valueExport0", exact: [__some_type, __some_value, "foo", typeKeyword] }); ++verify.completions({ marker: "valueExport1", exact: [__some_type, __some_value, "foo", typeKeyword] }); ++verify.completions({ marker: "valueExport2", exact: [] }); ++verify.completions({ marker: "valueExport3", exact: [__some_type, __some_value, typeKeyword] }); ++ ++verify.completions({ marker: "typeImport0", exact: [__some_type_as, __some_value_as, "foo"] }); ++verify.completions({ marker: "typeImport1", exact: [__some_type_as, __some_value_as, "foo"] }); ++verify.completions({ marker: "typeImport2", exact: [] }); ++verify.completions({ marker: "typeImport3", exact: [__some_type_as, __some_value_as] }); ++ ++verify.completions({ marker: "typeExport0", exact: [] }); ++verify.completions({ marker: "typeExport1", exact: [__some_type, __some_value, "foo"] }); ++verify.completions({ marker: "typeExport2", exact: [] }); ++verify.completions({ marker: "typeExport3", exact: [] }); +diff --git a/tests/cases/fourslash/refactorConvertImport_namedToNamespaceStringLiteral.ts b/tests/cases/fourslash/refactorConvertImport_namedToNamespaceStringLiteral.ts +new file mode 100644 +index 000000000..3cca0fe31 +--- /dev/null ++++ b/tests/cases/fourslash/refactorConvertImport_namedToNamespaceStringLiteral.ts +@@ -0,0 +1,17 @@ ++/// ++ ++/////*a*/import { "__" as Value, "__" as Type } from "foo";/*b*/ ++////export { Value, Type }; // Need a named import for this ++////const foo: Type = Value; ++ ++goTo.select("a", "b"); ++edit.applyRefactor({ ++ refactorName: "Convert import", ++ actionName: "Convert named imports to namespace import", ++ actionDescription: "Convert named imports to namespace import", ++ newContent: ++`import * as foo_1 from "foo"; ++import { "__" as Value, "__" as Type } from "foo"; ++export { Value, Type }; // Need a named import for this ++const foo: foo_1["__"] = foo_1["__"];`, ++}); +diff --git a/tests/cases/fourslash/stringCompletionsImportOrExportSpecifier.ts b/tests/cases/fourslash/stringCompletionsImportOrExportSpecifier.ts +new file mode 100644 +index 000000000..ead04bb57 +--- /dev/null ++++ b/tests/cases/fourslash/stringCompletionsImportOrExportSpecifier.ts +@@ -0,0 +1,52 @@ ++/// ++ ++// @Filename: exports.ts ++//// export let foo = 1; ++//// let someValue = 2; ++//// let someType = 3; ++//// export { ++//// someValue as "__some value", ++//// someType as "__some type", ++//// }; ++ ++// @Filename: values.ts ++//// import { "/*valueImport0*/" } from "./exports"; ++//// import { "/*valueImport1*/" as valueImport1 } from "./exports"; ++//// import { foo as "/*valueImport2*/" } from "./exports"; ++//// import { foo, "/*valueImport3*/" as valueImport3 } from "./exports"; ++//// ++//// export { "/*valueExport0*/" } from "./exports"; ++//// export { "/*valueExport1*/" as valueExport1 } from "./exports"; ++//// export { foo as "/*valueExport2*/" } from "./exports"; ++//// export { foo, "/*valueExport3*/" } from "./exports"; ++ ++// @Filename: types.ts ++//// import { type "/*typeImport0*/" } from "./exports"; ++//// import { type "/*typeImport1*/" as typeImport1 } from "./exports"; ++//// import { type foo as "/*typeImport2*/" } from "./exports"; ++//// import { type foo, type "/*typeImport3*/" as typeImport3 } from "./exports"; ++//// ++//// export { type "/*typeExport0*/" } from "./exports"; ++//// export { type "/*typeExport1*/" as typeExport1 } from "./exports"; ++//// export { type foo as "/*typeExport2*/" } from "./exports"; ++//// export { type foo, type "/*typeExport3*/" } from "./exports"; ++ ++verify.completions({ marker: "valueImport0", exact: ["__some type", "__some value", "foo"] }); ++verify.completions({ marker: "valueImport1", exact: ["__some type", "__some value", "foo"] }); ++verify.completions({ marker: "valueImport2", exact: [] }); ++verify.completions({ marker: "valueImport3", exact: ["__some type", "__some value"] }); ++ ++verify.completions({ marker: "valueExport0", exact: ["__some type", "__some value", "foo"] }); ++verify.completions({ marker: "valueExport1", exact: ["__some type", "__some value", "foo"] }); ++verify.completions({ marker: "valueExport2", exact: [] }); ++verify.completions({ marker: "valueExport3", exact: ["__some type", "__some value"] }); ++ ++verify.completions({ marker: "typeImport0", exact: ["__some type", "__some value", "foo"] }); ++verify.completions({ marker: "typeImport1", exact: ["__some type", "__some value", "foo"] }); ++verify.completions({ marker: "typeImport2", exact: [] }); ++verify.completions({ marker: "typeImport3", exact: ["__some type", "__some value"] }); ++ ++verify.completions({ marker: "typeExport0", exact: ["__some type", "__some value", "foo"] }); ++verify.completions({ marker: "typeExport1", exact: ["__some type", "__some value", "foo"] }); ++verify.completions({ marker: "typeExport2", exact: [] }); ++verify.completions({ marker: "typeExport3", exact: ["__some type", "__some value"] }); diff --git a/TypeScript_3/tests/private/eval_tests_aug.patch b/TypeScript_3/tests/private/eval_tests_aug.patch new file mode 100644 index 0000000000000000000000000000000000000000..0c97d69ce5523153d29818e783c758b905d29fcc --- /dev/null +++ b/TypeScript_3/tests/private/eval_tests_aug.patch @@ -0,0 +1,321 @@ +diff --git a/tests/cases/fourslash/arbitraryModuleNamespaceIdentifiersAugCompilerApi.ts b/tests/cases/fourslash/arbitraryModuleNamespaceIdentifiersAugCompilerApi.ts +new file mode 100644 +index 0000000000..1111111111 +--- /dev/null ++++ b/tests/cases/fourslash/arbitraryModuleNamespaceIdentifiersAugCompilerApi.ts +@@ -0,0 +1,198 @@ ++/// ++ ++////const placeholder = 0; ++ ++function assertIncludes(text: string, expected: string) { ++ assert.ok( ++ text.includes(expected), ++ `Expected text to include ${JSON.stringify(expected)}.\nActual:\n${text}`, ++ ); ++} ++ ++function assertHasDiagnostic(actual: string[], expected: string) { ++ assert.ok( ++ actual.some(message => message.includes(expected)), ++ `Expected diagnostic containing ${JSON.stringify(expected)}, got:\n${actual.join("\n")}`, ++ ); ++} ++ ++function assertNoDiagnostics(actual: string[]) { ++ assert.deepStrictEqual(actual, []); ++} ++ ++function diagnostics(files: Record, options: ts.CompilerOptions = {}): string[] { ++ const compilerOptions: ts.CompilerOptions = { ++ target: ts.ScriptTarget.ES2022, ++ module: ts.ModuleKind.ESNext, ++ strict: true, ++ types: [], ++ ...options, ++ }; ++ const normalized = new Map(Object.entries(files).map(([name, text]) => [ ++ name.startsWith("/") ? name : `/${name}`, ++ text, ++ ])); ++ const rootNames = [...normalized.keys()]; ++ const host = ts.createCompilerHost(compilerOptions); ++ const readFile = host.readFile.bind(host); ++ const fileExists = host.fileExists.bind(host); ++ ++ host.readFile = file => normalized.get(file) ?? readFile(file); ++ host.fileExists = file => normalized.has(file) || fileExists(file); ++ host.getSourceFile = (file, languageVersion) => { ++ const text = normalized.get(file) ?? readFile(file); ++ return text === undefined ? undefined : ts.createSourceFile(file, text, languageVersion, true); ++ }; ++ ++ const program = ts.createProgram(rootNames, compilerOptions, host); ++ return ts.getPreEmitDiagnostics(program).map(diagnostic => ++ ts.flattenDiagnosticMessageText(diagnostic.messageText, "\n") ++ ); ++} ++ ++function emit(source: string, options: ts.CompilerOptions = {}): string { ++ return ts.transpileModule(source, { ++ compilerOptions: { ++ target: ts.ScriptTarget.ES2022, ++ module: ts.ModuleKind.CommonJS, ++ ...options, ++ }, ++ }).outputText; ++} ++ ++const parsed = ts.createSourceFile( ++ "arbitraryNames.ts", ++ ` ++const value = 1; ++export { value as "not id" }; ++import { "not id" as imported } from "./arbitraryNames"; ++`, ++ ts.ScriptTarget.Latest, ++ true, ++); ++ ++const parsedExport = parsed.statements.find((statement): statement is ts.ExportDeclaration => ++ ts.isExportDeclaration(statement) && !!statement.exportClause && ts.isNamedExports(statement.exportClause) ++)!; ++const parsedExportSpecifier = (parsedExport.exportClause as ts.NamedExports).elements[0]; ++assert.strictEqual(parsedExportSpecifier.name.kind, ts.SyntaxKind.StringLiteral); ++assert.strictEqual((parsedExportSpecifier.name as ts.StringLiteral).text, "not id"); ++ ++const parsedImport = parsed.statements.find(ts.isImportDeclaration)!; ++const parsedImportClause = parsedImport.importClause!.namedBindings as ts.NamedImports; ++const parsedImportSpecifier = parsedImportClause.elements[0]; ++assert.strictEqual(parsedImportSpecifier.propertyName!.kind, ts.SyntaxKind.StringLiteral); ++assert.strictEqual(parsedImportSpecifier.name.kind, ts.SyntaxKind.Identifier); ++ ++const parsedWithNamespace = ts.createSourceFile( ++ "arbitraryNamespace.ts", ++ `export * as "space ns" from "./arbitraryNames";`, ++ ts.ScriptTarget.Latest, ++ true, ++); ++const parsedNamespaceExport = parsedWithNamespace.statements.find((statement): statement is ts.ExportDeclaration => ++ ts.isExportDeclaration(statement) && !!statement.exportClause && statement.exportClause.kind === ts.SyntaxKind.NamespaceExport ++)!; ++assert.strictEqual((parsedNamespaceExport.exportClause as ts.NamespaceExport).name.kind, ts.SyntaxKind.StringLiteral); ++ ++const transformed = ts.transform(parsed, [context => sourceFile => ts.visitEachChild(sourceFile, child => child, context)]); ++try { ++ const printed = ts.createPrinter().printFile(transformed.transformed[0] as ts.SourceFile); ++ assertIncludes(printed, 'export { value as "not id" };'); ++ assertIncludes(printed, 'import { "not id" as imported } from "./arbitraryNames";'); ++} ++finally { ++ transformed.dispose(); ++} ++ ++const renamed = ts.transform(parsed, [context => { ++ const visitor: ts.Visitor = node => { ++ if ( ++ ts.isStringLiteral(node) && ++ ( ++ ts.isExportSpecifier(node.parent) || ++ ts.isImportSpecifier(node.parent) ++ ) ++ ) { ++ return context.factory.createStringLiteral("changed name"); ++ } ++ return ts.visitEachChild(node, visitor, context); ++ }; ++ return sourceFile => ts.visitNode(sourceFile, visitor) as ts.SourceFile; ++}]); ++try { ++ const printed = ts.createPrinter().printFile(renamed.transformed[0] as ts.SourceFile); ++ assertIncludes(printed, 'export { value as "changed name" };'); ++ assertIncludes(printed, 'import { "changed name" as imported } from "./arbitraryNames";'); ++} ++finally { ++ renamed.dispose(); ++} ++ ++assertNoDiagnostics(diagnostics({ ++ "/dep.ts": ` ++export const value = "remote" as const; ++export { value as "not id", value as "default" }; ++export * as "space ns" from "./other"; ++`, ++ "/other.ts": `export const nested = 1 as const;`, ++ "/main.ts": ` ++import defaultValue, { "default" as defaultNamed, "not id" as imported, "space ns" as ns } from "./dep"; ++const a: "remote" = imported; ++const b: "remote" = defaultValue; ++const c: "remote" = defaultNamed; ++const d: 1 = ns.nested; ++`, ++})); ++ ++assertNoDiagnostics(diagnostics({ ++ "/dep.ts": `export const value = 1 as const;`, ++ "/barrel.ts": `export * as "default" from "./dep";`, ++ "/main.ts": ` ++import dep from "./barrel"; ++const check: 1 = dep.value; ++`, ++})); ++ ++assertNoDiagnostics(diagnostics({ ++ "/empty.ts": ` ++const empty = "empty" as const; ++export { empty as "" }; ++import { "" as imported } from "./empty"; ++const check: "empty" = imported; ++`, ++})); ++ ++assertHasDiagnostic( ++ diagnostics({ ++ "/dep.ts": `export const remote = 1;`, ++ "/main.ts": `import { "remote" as "local" } from "./dep";`, ++ }), ++ "Identifier expected.", ++); ++ ++assertHasDiagnostic( ++ diagnostics({ ++ "/main.ts": ` ++const value = 1; ++export { value as "not id" }; ++`, ++ }, { module: ts.ModuleKind.ES2015 }), ++ "String literal import and export names are not supported when the '--module' flag is set to 'es2015' or 'es2020'.", ++); ++ ++const commonJs = emit(` ++import { "not id" as imported } from "./dep"; ++export const value = imported; ++export { value as "not id" }; ++`); ++ ++assertIncludes(commonJs, 'dep_1["not id"]'); ++assertIncludes(commonJs, 'exports["not id"] ='); ++ ++const defaultInterop = emit(` ++import { "default" as value } from "./dep"; ++console.log(value); ++`, { esModuleInterop: true }); ++ ++assertIncludes(defaultInterop, '__importDefault(require("./dep"))'); +diff --git a/tests/cases/fourslash/arbitraryModuleNamespaceIdentifiersAugServices.ts b/tests/cases/fourslash/arbitraryModuleNamespaceIdentifiersAugServices.ts +new file mode 100644 +index 0000000000..1111111111 +--- /dev/null ++++ b/tests/cases/fourslash/arbitraryModuleNamespaceIdentifiersAugServices.ts +@@ -0,0 +1,53 @@ ++/// ++ ++// @Filename: exports.ts ++//// export let foo = 1; ++//// let someValue = 2; ++//// let someType = 3; ++//// export { ++//// someValue as "__some value", ++//// someType as "__some type", ++//// }; ++ ++// @Filename: values.ts ++//// import { /*valueImport*/ } from "./exports"; ++//// import { foo, /*valueImportAfterExisting*/ as valueImportAfterExisting } from "./exports"; ++//// export { /*valueExport*/ } from "./exports"; ++//// export { foo, /*valueExportAfterExisting*/ } from "./exports"; ++//// import { "/*stringValueImport*/" } from "./exports"; ++//// export { "/*stringValueExport*/" } from "./exports"; ++ ++// @Filename: types.ts ++//// import { type /*typeImport*/ } from "./exports"; ++//// export { type /*typeExport*/ as typeExport } from "./exports"; ++//// import { type "/*stringTypeImport*/" as importedType } from "./exports"; ++//// export { type "/*stringTypeExport*/" as exportedType } from "./exports"; ++ ++const __some_type = { name: "__some type", insertText: '"__some type"' }; ++const __some_value = { name: "__some value", insertText: '"__some value"' }; ++const __some_type_as = { name: "__some type", insertText: '"__some type" as __some_type' }; ++const __some_value_as = { name: "__some value", insertText: '"__some value" as __some_value' }; ++const typeKeyword = { name: "type", sortText: completion.SortText.GlobalsOrKeywords }; ++ ++verify.completions({ ++ marker: "valueImport", ++ exact: [__some_type_as, __some_value_as, "foo", typeKeyword], ++}); ++verify.completions({ ++ marker: "valueImportAfterExisting", ++ exact: [__some_type_as, __some_value_as, typeKeyword], ++}); ++verify.completions({ ++ marker: "valueExport", ++ exact: [__some_type, __some_value, "foo", typeKeyword], ++}); ++verify.completions({ ++ marker: "valueExportAfterExisting", ++ exact: [__some_type, __some_value, typeKeyword], ++}); ++verify.completions({ marker: "typeImport", exact: [__some_type_as, __some_value_as, "foo"] }); ++verify.completions({ marker: "typeExport", exact: [__some_type, __some_value, "foo"] }); ++ ++verify.completions({ marker: "stringValueImport", exact: ["__some type", "__some value", "foo"] }); ++verify.completions({ marker: "stringValueExport", exact: ["__some type", "__some value", "foo"] }); ++verify.completions({ marker: "stringTypeImport", exact: ["__some type", "__some value", "foo"] }); ++verify.completions({ marker: "stringTypeExport", exact: ["__some type", "__some value", "foo"] }); +diff --git a/tests/cases/fourslash/arbitraryModuleNamespaceIdentifiersAugNamedImportP2P.ts b/tests/cases/fourslash/arbitraryModuleNamespaceIdentifiersAugNamedImportP2P.ts +new file mode 100644 +index 0000000000..1111111111 +--- /dev/null ++++ b/tests/cases/fourslash/arbitraryModuleNamespaceIdentifiersAugNamedImportP2P.ts +@@ -0,0 +1,16 @@ ++/// ++ ++// @Filename: exports.ts ++//// export const value = 1; ++//// export type Shape = { name: string }; ++//// export { value as renamed }; ++ ++// @Filename: consumer.ts ++//// import { renamed, type Shape } from "./exports"; ++//// const /*computed*/computed = renamed + 1; ++//// const /*shape*/shape: Shape = { name: "ok" }; ++//// export { renamed as ordinaryAlias }; ++ ++verify.quickInfoAt("computed", "const computed: number"); ++verify.quickInfoAt("shape", "const shape: Shape"); ++verify.noErrors(); +diff --git a/tests/cases/fourslash/arbitraryModuleNamespaceIdentifiersAugCommonJsP2P.ts b/tests/cases/fourslash/arbitraryModuleNamespaceIdentifiersAugCommonJsP2P.ts +new file mode 100644 +index 0000000000..1111111111 +--- /dev/null ++++ b/tests/cases/fourslash/arbitraryModuleNamespaceIdentifiersAugCommonJsP2P.ts +@@ -0,0 +1,29 @@ ++/// ++ ++////const placeholder = 0; ++ ++function emit(source: string): string { ++ return ts.transpileModule(source, { ++ compilerOptions: { ++ target: ts.ScriptTarget.ES2020, ++ module: ts.ModuleKind.CommonJS, ++ }, ++ }).outputText; ++} ++ ++function assertIncludes(text: string, expected: string) { ++ assert.ok( ++ text.includes(expected), ++ `Expected emitted text to include ${JSON.stringify(expected)}.\nActual:\n${text}`, ++ ); ++} ++ ++const output = emit(` ++import { value as renamed } from "./dep"; ++export const doubled = renamed * 2; ++export { doubled as ordinaryAlias }; ++`); ++ ++assertIncludes(output, 'const dep_1 = require("./dep");'); ++assertIncludes(output, "exports.doubled = dep_1.value * 2;"); ++assertIncludes(output, "exports.ordinaryAlias = exports.doubled;"); diff --git a/TypeScript_3/tests/private/f2p.txt b/TypeScript_3/tests/private/f2p.txt new file mode 100644 index 0000000000000000000000000000000000000000..02b5a3ee9b1e9f158c855b5bf6292fb69b7f90d6 --- /dev/null +++ b/TypeScript_3/tests/private/f2p.txt @@ -0,0 +1,4 @@ +tests/cases/conformance/es2022/arbitraryModuleNamespaceIdentifiers/arbitraryModuleNamespaceIdentifiers_exportEmpty.ts +tests/cases/conformance/es2022/arbitraryModuleNamespaceIdentifiers/arbitraryModuleNamespaceIdentifiers_importEmpty.ts +tests/cases/conformance/es2022/arbitraryModuleNamespaceIdentifiers/arbitraryModuleNamespaceIdentifiers_module.ts +tests/cases/conformance/es2022/arbitraryModuleNamespaceIdentifiers/arbitraryModuleNamespaceIdentifiers_syntax.ts diff --git a/TypeScript_3/tests/private/f2p_aug.txt b/TypeScript_3/tests/private/f2p_aug.txt new file mode 100644 index 0000000000000000000000000000000000000000..183e5fcd27e08560237e63b7f2ad2e9d69d94500 --- /dev/null +++ b/TypeScript_3/tests/private/f2p_aug.txt @@ -0,0 +1,2 @@ +tests/cases/fourslash/arbitraryModuleNamespaceIdentifiersAugCompilerApi.ts +tests/cases/fourslash/arbitraryModuleNamespaceIdentifiersAugServices.ts diff --git a/TypeScript_3/tests/private/p2p.txt b/TypeScript_3/tests/private/p2p.txt new file mode 100644 index 0000000000000000000000000000000000000000..b028a1501a3bd6fc1f9d8464d18982d155346ff0 --- /dev/null +++ b/TypeScript_3/tests/private/p2p.txt @@ -0,0 +1,50 @@ +tests/cases/conformance/externalModules/exportAssignmentAndDeclaration.ts +tests/cases/conformance/externalModules/exportAssignmentGenericType.ts +tests/cases/conformance/externalModules/duplicateExportAssignments.ts +tests/cases/conformance/externalModules/exportAssignImportedIdentifier.ts +tests/cases/conformance/externalModules/commonJSImportAsPrimaryExpression.ts +tests/cases/conformance/externalModules/commonJSImportNotAsPrimaryExpression.ts +tests/cases/conformance/es6/moduleExportsCommonjs/anonymousDefaultExportsCommonjs.ts +tests/cases/conformance/es6/moduleExportsCommonjs/defaultExportsGetExportedCommonjs.ts +tests/cases/conformance/es6/moduleExportsCommonjs/decoratedDefaultExportsGetExportedCommonjs.ts +tests/cases/conformance/externalModules/amdImportAsPrimaryExpression.ts +tests/cases/conformance/externalModules/amdImportNotAsPrimaryExpression.ts +tests/cases/conformance/externalModules/asiPreventsParsingAsAmbientExternalModule01.ts +tests/cases/conformance/externalModules/asiPreventsParsingAsAmbientExternalModule02.ts +tests/cases/conformance/externalModules/circularReference.ts +tests/cases/conformance/externalModules/commonJsImportBindingElementNarrowType.ts +tests/cases/conformance/externalModules/es6/es6modulekind.ts +tests/cases/conformance/externalModules/es6/es6modulekindExportClassNameWithObject.ts +tests/cases/conformance/externalModules/es6/es6modulekindWithES2015Target.ts +tests/cases/conformance/externalModules/es6/es6modulekindWithES5Target.ts +tests/cases/conformance/externalModules/es6/es6modulekindWithES5Target10.ts +tests/cases/conformance/externalModules/es6/es6modulekindWithES5Target11.ts +tests/cases/conformance/externalModules/es6/es6modulekindWithES5Target12.ts +tests/cases/conformance/externalModules/es6/es6modulekindWithES5Target2.ts +tests/cases/conformance/externalModules/es6/es6modulekindWithES5Target3.ts +tests/cases/conformance/externalModules/es6/es6modulekindWithES5Target4.ts +tests/cases/conformance/externalModules/es6/es6modulekindWithES5Target5.ts +tests/cases/conformance/externalModules/es6/es6modulekindWithES5Target6.ts +tests/cases/conformance/externalModules/es6/es6modulekindWithES5Target7.ts +tests/cases/conformance/externalModules/es6/es6modulekindWithES5Target8.ts +tests/cases/conformance/externalModules/es6/es6modulekindWithES5Target9.ts +tests/cases/conformance/externalModules/esnext/esnextmodulekind.ts +tests/cases/conformance/externalModules/esnext/esnextmodulekindWithES2015Target.ts +tests/cases/conformance/externalModules/esnext/esnextmodulekindWithES5Target.ts +tests/cases/conformance/externalModules/esnext/esnextmodulekindWithES5Target10.ts +tests/cases/conformance/externalModules/esnext/esnextmodulekindWithES5Target11.ts +tests/cases/conformance/externalModules/esnext/esnextmodulekindWithES5Target12.ts +tests/cases/conformance/externalModules/esnext/esnextmodulekindWithES5Target2.ts +tests/cases/conformance/externalModules/esnext/esnextmodulekindWithES5Target3.ts +tests/cases/conformance/externalModules/esnext/esnextmodulekindWithES5Target4.ts +tests/cases/conformance/externalModules/esnext/esnextmodulekindWithES5Target5.ts +tests/cases/conformance/externalModules/esnext/esnextmodulekindWithES5Target6.ts +tests/cases/conformance/externalModules/esnext/esnextmodulekindWithES5Target7.ts +tests/cases/conformance/externalModules/esnext/esnextmodulekindWithES5Target8.ts +tests/cases/conformance/externalModules/esnext/esnextmodulekindWithES5Target9.ts +tests/cases/conformance/externalModules/esnext/exnextmodulekindExportClassNameWithObject.ts +tests/cases/conformance/externalModules/exportAmbientClassNameWithObject.ts +tests/cases/conformance/externalModules/exportAssignDottedName.ts +tests/cases/conformance/externalModules/exportAssignNonIdentifier.ts +tests/cases/conformance/externalModules/exportAssignTypes.ts +tests/cases/conformance/externalModules/exportAssignmentCircularModules.ts diff --git a/TypeScript_3/tests/private/p2p_aug.txt b/TypeScript_3/tests/private/p2p_aug.txt new file mode 100644 index 0000000000000000000000000000000000000000..afd1b49ec9d9e0f3a5fdeb4481909cc00b219bc2 --- /dev/null +++ b/TypeScript_3/tests/private/p2p_aug.txt @@ -0,0 +1,2 @@ +tests/cases/fourslash/arbitraryModuleNamespaceIdentifiersAugNamedImportP2P.ts +tests/cases/fourslash/arbitraryModuleNamespaceIdentifiersAugCommonJsP2P.ts diff --git a/TypeScript_3/tests/private/run_tests.sh b/TypeScript_3/tests/private/run_tests.sh new file mode 100644 index 0000000000000000000000000000000000000000..1ad2da90d4a17ca830ebc56689a51c09b1bf4f84 --- /dev/null +++ b/TypeScript_3/tests/private/run_tests.sh @@ -0,0 +1,337 @@ +#!/usr/bin/env bash +# LoLBench runner for microsoft/TypeScript PR-46827 (satisfies operator). +# +# Eval contract: +# docker run --rm --network=none \ +# -v $(pwd)/solution.patch:/in/solution.patch:ro \ +# -v $(pwd)/out:/out \ +# lolbench/apache-ts-pr-58640:1 +# → /out/agent_report.json (sanitized). +# +# Validation modes: +# LOLBENCH_MODE=validate_pre # F2P FAIL (parser doesn't know `satisfies`), P2P PASS +# LOLBENCH_MODE=validate_post # all PASS + +set -uo pipefail +PRIV=/opt/lolbench/private +WS=/workspace +TS=$WS/typescript +MODE=${LOLBENCH_MODE:-eval} +SUITE=${LOLBENCH_SUITE:-orig} + +case "$SUITE" in + orig|aug|union) ;; + *) echo "[run_tests $MODE] FATAL: unknown LOLBENCH_SUITE=$SUITE" >&2; exit 2 ;; +esac + +HAS_AUG=0 +if [ -f "$PRIV/eval_tests_aug.patch" ] \ + && [ -f "$PRIV/f2p_aug.txt" ] \ + && [ -f "$PRIV/p2p_aug.txt" ]; then + HAS_AUG=1 +fi +if [ "$SUITE" != "orig" ] && [ "$HAS_AUG" -eq 0 ]; then + echo "[run_tests $MODE/$SUITE] WARN: no augmented sidecar shipped; falling back to orig" >&2 + SUITE=orig +fi + +log() { echo "[run_tests $MODE/$SUITE] $*" >&2; } +die() { log "FATAL: $*"; emit_error harness_error false skipped; exit 0; } + +FAIL_TO_PASS=() +PASS_TO_PASS=() + +emit_error() { + local cat=$1 applied=$2 build_status=$3 + local f2p_n=${#FAIL_TO_PASS[@]} + local p2p_n=${#PASS_TO_PASS[@]} + python3 - "$cat" "$applied" "$build_status" "$f2p_n" "$p2p_n" "$SUITE" "$HAS_AUG" <<'EOF' >/out/agent_report.json +import json, sys +cat, applied_s, build_s, f2p_n, p2p_n, suite, has_aug_s = sys.argv[1:8] +applied = applied_s.lower() == "true" +print(json.dumps({ + "instance_id": "TypeScript_PR-58640_Arbitrary-Module-Namespace-Identifiers", + "suite": suite, + "augmentation_available": has_aug_s == "1", + "applied": applied, + "build": {"status": build_s}, + "f2p": {"passed":0,"failed":0,"errored":int(f2p_n),"skipped":0,"total":int(f2p_n)}, + "p2p": {"passed":0,"failed":0,"errored":int(p2p_n),"skipped":0,"total":int(p2p_n)}, + "resolved": False, + "error_categories": [cat] +}, indent=2)) +EOF +} + +mapfile -t FAIL_TO_PASS_ORIG < <(grep -v '^\s*$' "$PRIV/f2p.txt") +mapfile -t PASS_TO_PASS_ORIG < <(grep -v '^\s*$' "$PRIV/p2p.txt") +FAIL_TO_PASS_AUG=() +PASS_TO_PASS_AUG=() +if [ "$HAS_AUG" -eq 1 ]; then + mapfile -t FAIL_TO_PASS_AUG < <(grep -v '^\s*$' "$PRIV/f2p_aug.txt") + mapfile -t PASS_TO_PASS_AUG < <(grep -v '^\s*$' "$PRIV/p2p_aug.txt") +fi + +case "$SUITE" in + orig) + FAIL_TO_PASS=("${FAIL_TO_PASS_ORIG[@]}") + PASS_TO_PASS=("${PASS_TO_PASS_ORIG[@]}") + ;; + aug) + FAIL_TO_PASS=("${FAIL_TO_PASS_AUG[@]}") + PASS_TO_PASS=("${PASS_TO_PASS_AUG[@]}") + ;; + union) + FAIL_TO_PASS=("${FAIL_TO_PASS_ORIG[@]}" "${FAIL_TO_PASS_AUG[@]}") + PASS_TO_PASS=("${PASS_TO_PASS_ORIG[@]}" "${PASS_TO_PASS_AUG[@]}") + ;; +esac + +F2P_EFFECTIVE=$WS/.f2p_effective.txt +P2P_EFFECTIVE=$WS/.p2p_effective.txt +printf '%s\n' "${FAIL_TO_PASS[@]}" >"$F2P_EFFECTIVE" +printf '%s\n' "${PASS_TO_PASS[@]}" >"$P2P_EFFECTIVE" + +# Sanity-check spec ↔ selectors agree +python3 - "$PRIV/spec.json" "$PRIV/f2p.txt" "$PRIV/p2p.txt" "$F2P_EFFECTIVE" "$P2P_EFFECTIVE" "$SUITE" <<'EOF' || die "spec/selector mismatch" +import json, sys +spec = json.load(open(sys.argv[1])) +orig_f2p = [l.strip() for l in open(sys.argv[2]) if l.strip()] +orig_p2p = [l.strip() for l in open(sys.argv[3]) if l.strip()] +eff_f2p = [l.strip() for l in open(sys.argv[4]) if l.strip()] +eff_p2p = [l.strip() for l in open(sys.argv[5]) if l.strip()] +suite = sys.argv[6] +aug = spec.get("augmented", {}) +expected = { + "orig": (spec["fail_to_pass"], spec["pass_to_pass"]), + "aug": (aug.get("fail_to_pass", []), aug.get("pass_to_pass", [])), + "union": (orig_f2p + aug.get("fail_to_pass", []), orig_p2p + aug.get("pass_to_pass", [])), +}[suite] +sys.exit(0 if expected == (eff_f2p, eff_p2p) else 1) +EOF + +# ---- pick source-side patch by mode --------------------------------- +SRC_PATCH="" +case "$MODE" in + validate_pre) SRC_PATCH="" ;; + validate_post) + if [ -f /solution/solution.patch ]; then + SRC_PATCH=/solution/solution.patch + else + SRC_PATCH="$PRIV/solution.patch" + fi ;; + eval) + if [ ! -f /in/solution.patch ]; then + log "no /in/solution.patch mounted" + emit_error missing_solution_patch false skipped + exit 0 + fi + AGENT_PATCH=/tmp/lolbench_agent_patch.diff + cp /in/solution.patch "$AGENT_PATCH" + chmod 0600 "$AGENT_PATCH" + SRC_PATCH="$AGENT_PATCH" ;; + *) + die "unknown LOLBENCH_MODE=$MODE" ;; +esac + +# ---- reset workspace + apply patches -------------------------------- +cd "$TS" +git config --global --add safe.directory "$TS" +git reset --hard >/dev/null 2>&1 +git clean -fdx -e node_modules -e built >/dev/null 2>&1 + +if [ -n "$SRC_PATCH" ]; then + if ! git apply --check "$SRC_PATCH" 2>/tmp/apply.err; then + log "source patch did not apply cleanly:"; cat /tmp/apply.err >&2 + emit_error patch_apply_failure false skipped; exit 0 + fi + git apply "$SRC_PATCH" + # LoLBench eval-patch-collision guard (re-verify remediation): if the agent patch touched files the + # eval test patches own (test fixtures the agent must not modify), restore + # those paths (both sides of every diff/rename) to the base state so + # eval_tests(.aug).patch always applies. Agent source changes are preserved. + for _lb_ep in "$PRIV/eval_helpers.patch" "$PRIV/eval_tests.patch" "$PRIV/eval_tests_aug.patch"; do + [ -f "$_lb_ep" ] || continue + { sed -n 's|^diff --git a/\(.*\) b/\(.*\)$|\1\n\2|p' "$_lb_ep" + sed -n 's|^rename from \(.*\)$|\1|p' "$_lb_ep" + sed -n 's|^rename to \(.*\)$|\1|p' "$_lb_ep"; } | sort -u | while read -r _lb_f; do + [ -n "$_lb_f" ] || continue + git checkout HEAD -- "$_lb_f" >/dev/null 2>&1 || rm -f "$_lb_f" >/dev/null 2>&1 || true + done + done +fi + +# eval_tests.patch is ALWAYS applied — the test files + baselines it +# adds are needed in BOTH pre- and post-state. In pre-state without +# solution.patch, running the new tests produces baseline mismatches +# (parser doesn't tokenize `satisfies` → bogus errors in .errors.txt) +# which is exactly the FAIL behavior §7 requires. +if ! git apply --check "$PRIV/eval_tests.patch" 2>/tmp/apply.err; then + log "eval_tests.patch did not apply cleanly:"; cat /tmp/apply.err >&2 + emit_error eval_patch_apply_failure true skipped; exit 0 +fi +git apply "$PRIV/eval_tests.patch" +if [ "$HAS_AUG" -eq 1 ] && [ "$SUITE" != "orig" ]; then + if ! git apply --check "$PRIV/eval_tests_aug.patch" 2>/tmp/apply.err; then + log "eval_tests_aug.patch did not apply cleanly:"; cat /tmp/apply.err >&2 + emit_error eval_aug_patch_apply_failure true skipped; exit 0 + fi + git apply "$PRIV/eval_tests_aug.patch" +fi + +# ---- rebuild local tsc + test infra after patches ---------------------- +BUILD_LOG=$WS/.build.log +TEST_LOG=$WS/.test.log +: >"$BUILD_LOG" >"$TEST_LOG" + +log "running 'npx hereby local' to rebuild tsc with patches applied" +npx hereby local >"$BUILD_LOG" 2>&1 +build_rc=$? +if [ "$build_rc" -ne 0 ]; then + log "build failed (rc=$build_rc); tail:"; tail -30 "$BUILD_LOG" >&2 + emit_error build_failure true failed; exit 0 +fi + +log "running 'npx hereby tests' to rebuild the test runner harness" +npx hereby tests >>"$BUILD_LOG" 2>&1 +tests_build_rc=$? +if [ "$tests_build_rc" -ne 0 ]; then + log "test-harness build failed (rc=$tests_build_rc); tail:"; tail -30 "$BUILD_LOG" >&2 + emit_error build_failure true failed; exit 0 +fi + +# ---- build the regex selector that runtests --tests=... accepts ----- +# TypeScript's runtests uses a regex matched against mocha test names. +# For conformance tests the name typically contains the source path +# fragment, e.g. for tests/cases/conformance/expressions/typeSatisfaction/typeSatisfaction.ts +# the test name includes "typeSatisfaction" / "typeSatisfaction.ts". +# +# Strategy: union of UNIQUE BASENAMES (without .ts) — every selector's +# basename is unique among the 13+24 we ship. The resulting regex is +# matched anywhere within the test name (not anchored), so subdir +# selectors stay correct. +RUNTESTS_REGEX=$(python3 - "$F2P_EFFECTIVE" "$P2P_EFFECTIVE" <<'PY' +import os, sys +ids = [] +for p in sys.argv[1:]: + for l in open(p): + l = l.strip() + if l: + base = os.path.splitext(os.path.basename(l))[0] + ids.append(base) +# Sort longest-first so e.g. `typeSatisfaction_contextualTyping1` matches +# before the shorter `typeSatisfaction`. +ids = sorted(set(ids), key=len, reverse=True) +print("|".join(map(__import__("re").escape, ids))) +PY +) +log "runtests selector regex: ${RUNTESTS_REGEX:0:80}..." + +# ---- run the union of F2P + P2P tests ---------------------------------- +# TS 5.5+ uses hereby (replaced gulp around TS 5.0). hereby's runtests +# task reads --tests and --reporter from cmdLineOptions and dispatches +# to runConsoleTests, which spawns mocha internally with the right +# reporter. Unlike gulp, hereby's runtests has no post-test eslint +# dependency, so we don't need to bypass it like we did for PR-46827. +log "running 'npx hereby runtests --tests= --reporter=tap'" +( cd "$TS" && npx hereby runtests \ + --tests="$RUNTESTS_REGEX" \ + --reporter=tap \ + --no-color ) \ + >>"$TEST_LOG" 2>&1 || true + +# ---- parse the TAP output + emit reports ------------------------------- +python3 - "$F2P_EFFECTIVE" "$P2P_EFFECTIVE" "$MODE" "$SUITE" "$HAS_AUG" "$TEST_LOG" <<'PYEOF' +"""Parse mocha's TAP-style output and bucket per-selector PASS/FAIL. + +mocha's TAP reporter emits lines like: + ok 151 conformance tests conformance tests for tests/cases/conformance/expressions/typeSatisfaction/typeSatisfaction.ts Correct errors for tests/cases/conformance/expressions/typeSatisfaction/typeSatisfaction.ts + not ok 152 ... + +Note: NO `-` separator between the number and description, despite +the TAP spec. We extract the .ts path from anywhere in the line. + +Each .ts file produces ~6 sub-tests (Correct errors / module +resolution tracing / sourcemap content / JS output / Sourcemap +output / type/symbol baselines). A .ts file PASSES iff every +sub-test PASSES. +""" +import json, os, re, sys +f2p_file, p2p_file, mode, suite, has_aug_s, log_path = sys.argv[1:7] +has_aug = has_aug_s == "1" + +f2p_ids = [l.strip() for l in open(f2p_file) if l.strip()] +p2p_ids = [l.strip() for l in open(p2p_file) if l.strip()] + +# Map path → set of statuses observed for that path's sub-tests. +file_statuses = {sid: set() for sid in f2p_ids + p2p_ids} +spec_paths = {sid for sid in f2p_ids + p2p_ids} + +try: + log = open(log_path).read() +except FileNotFoundError: + log = "" + +# mocha TAP output: "ok N " or "not ok N ". +TAP_LINE = re.compile(r'^(ok|not ok)\s+\d+\s+(.*)$') +# Extract a tests/cases/... .ts path from the description. +TS_PATH = re.compile(r'(tests/cases/[^\s]+?\.ts)') + +for line in log.splitlines(): + m = TAP_LINE.match(line) + if not m: + continue + verdict, desc = m.group(1), m.group(2) + # Find ALL .ts paths in the description — usually 2 (e.g. "conformance + # tests for X Correct errors for X"). All point to the same file. + paths = set(TS_PATH.findall(desc)) + for p in paths: + if p not in spec_paths: + continue + if " # SKIP" in desc.upper() or " # TODO" in desc.upper(): + file_statuses[p].add("SKIPPED") + elif verdict == "ok": + file_statuses[p].add("PASSED") + else: + file_statuses[p].add("FAILED") + +results = {} +for p, statuses in file_statuses.items(): + if not statuses: + results[p] = "ERROR" # no sub-tests matched → test never ran + elif "FAILED" in statuses: + results[p] = "FAILED" + elif "SKIPPED" in statuses and "PASSED" not in statuses: + results[p] = "SKIPPED" + else: + results[p] = "PASSED" + +def bucket(ids): + out = {"PASSED": [], "FAILED": [], "ERROR": [], "SKIPPED": []} + for sid in ids: + out[results.get(sid, "ERROR")].append(sid) + return out + +f2p = bucket(f2p_ids) +p2p = bucket(p2p_ids) +resolved = (len(f2p["PASSED"]) == len(f2p_ids) + and len(p2p["PASSED"]) == len(p2p_ids)) + +grader = { + "instance_id": "TypeScript_PR-58640_Arbitrary-Module-Namespace-Identifiers", + "mode": mode, "suite": suite, "augmentation_available": has_aug, "applied": True, "build": {"status": "ok"}, + "f2p": f2p, "p2p": p2p, "resolved": resolved +} +def cnts(d, ids): + return {"passed":len(d["PASSED"]),"failed":len(d["FAILED"]), + "errored":len(d["ERROR"]),"skipped":len(d["SKIPPED"]),"total":len(ids)} +agent = { + "instance_id": "TypeScript_PR-58640_Arbitrary-Module-Namespace-Identifiers", + "suite": suite, "augmentation_available": has_aug, "applied": True, "build": {"status": "ok"}, + "f2p": cnts(f2p, f2p_ids), "p2p": cnts(p2p, p2p_ids), + "resolved": resolved, "error_categories": [] +} +json.dump(grader, open("/out/grader_report.json","w"), indent=2) +json.dump(agent, open("/out/agent_report.json","w"), indent=2) +print(json.dumps(grader, indent=2)) +PYEOF diff --git a/TypeScript_3/tests/private/spec.json b/TypeScript_3/tests/private/spec.json new file mode 100644 index 0000000000000000000000000000000000000000..f3db4fca71536c60a20cb71f41b2d37e191e8c1a --- /dev/null +++ b/TypeScript_3/tests/private/spec.json @@ -0,0 +1,301 @@ +{ + "instance_id": "TypeScript_PR-58640_Arbitrary-Module-Namespace-Identifiers", + "project": "microsoft/TypeScript", + "requirement_doc": "https://github.com/tc39/ecma262/pull/2154", + "requirement_doc_note": "ECMA-262 PR 2154 added 'Arbitrary Module Namespace Identifier Names' to ES2022 \u2014 allows arbitrary string literals as import/export specifiers (e.g. `export { foo as 'foo bar' } from 'x'`). This TypeScript PR implements the spec in tsc.", + "pr_link": "https://github.com/microsoft/TypeScript/pull/58640", + "pr_merge_date": "2024-06-04", + "language": "TypeScript", + "build_system": "npm + hereby (TS 5.5-era)", + "scope": { + "pr_touched_modules": [ + "src/compiler", + "src/services", + "tests/cases/conformance/es2022", + "tests/cases/fourslash", + "tests/baselines/reference" + ], + "in_scope_modules": [ + "src/compiler", + "src/services" + ], + "build_modules": [ + "src" + ], + "p2p_modules": [ + "tests/cases/conformance/externalModules", + "tests/cases/conformance/es6/moduleExportsCommonjs" + ], + "pr_total_files_changed": 93, + "in_scope_production_files": 21, + "in_scope_test_files": 72, + "out_of_scope_files_dropped": 0, + "out_of_scope_summary": "No files dropped \u2014 all 93 PR files are either compiler/service source (21) or test cases + baselines (72)." + }, + "base_commit": "112e860602b2b46f7a1f179a8f6357f6e4db2370", + "base_commit_note": "Parent of the squash-merge commit on main. PR-58640 was squash-merged: merge_commit 8d62e2f1 has one parent 112e8606. Use parent..merge for the patch content.", + "merge_commit_sha": "8d62e2f175b592239096a450943d7f401c2925c2", + "pr_head_sha": "ff8217073661987cd62923fd596e18e40de62740", + "pr_base_sha_github": "59e6620260ee3bbaba3e56c8c306c8858d477228", + "merge_style": "squash-merge \u2014 merge_commit_sha (8d62e2f1) has one parent (112e8606); the PR's 13 individual commits were squashed.", + "diff_source": "Patches reconstructed via `git diff 112e8606..8d62e2f1` (parent..squash-merge on main). GitHub PR base/head SHAs preserved for provenance audit only.", + "solution_patch_sha256": "25aa95fba3abec485193dcdfcbe1abb1de6fde9d7c9fc434ba892f3ee71e5969", + "eval_tests_patch_sha256": "58526b7f0c184ce41327121430d832dbc33b5cd3f760ccd8066f0d726491ad5a", + "toolchain": { + "node": "18.x (TS 5.5-era; check src/.node-version)", + "build": "npm install + npx hereby local + npx hereby tests", + "test_framework": "TypeScript's mocha-based runtests; each .ts file in tests/cases/ is a baseline-comparison test against tests/baselines/reference/", + "host_target": "linux/amd64", + "base_image": "lolbench/typescript-base-node18:1 (NEW \u2014 Ubuntu 22.04 + Node 18 + npm + git + python3)" + }, + "fail_to_pass": [ + "tests/cases/conformance/es2022/arbitraryModuleNamespaceIdentifiers/arbitraryModuleNamespaceIdentifiers_exportEmpty.ts", + "tests/cases/conformance/es2022/arbitraryModuleNamespaceIdentifiers/arbitraryModuleNamespaceIdentifiers_importEmpty.ts", + "tests/cases/conformance/es2022/arbitraryModuleNamespaceIdentifiers/arbitraryModuleNamespaceIdentifiers_module.ts", + "tests/cases/conformance/es2022/arbitraryModuleNamespaceIdentifiers/arbitraryModuleNamespaceIdentifiers_syntax.ts" + ], + "pass_to_pass": [ + "tests/cases/conformance/externalModules/exportAssignmentAndDeclaration.ts", + "tests/cases/conformance/externalModules/exportAssignmentGenericType.ts", + "tests/cases/conformance/externalModules/duplicateExportAssignments.ts", + "tests/cases/conformance/externalModules/exportAssignImportedIdentifier.ts", + "tests/cases/conformance/externalModules/commonJSImportAsPrimaryExpression.ts", + "tests/cases/conformance/externalModules/commonJSImportNotAsPrimaryExpression.ts", + "tests/cases/conformance/es6/moduleExportsCommonjs/anonymousDefaultExportsCommonjs.ts", + "tests/cases/conformance/es6/moduleExportsCommonjs/defaultExportsGetExportedCommonjs.ts", + "tests/cases/conformance/es6/moduleExportsCommonjs/decoratedDefaultExportsGetExportedCommonjs.ts", + "tests/cases/conformance/externalModules/amdImportAsPrimaryExpression.ts", + "tests/cases/conformance/externalModules/amdImportNotAsPrimaryExpression.ts", + "tests/cases/conformance/externalModules/asiPreventsParsingAsAmbientExternalModule01.ts", + "tests/cases/conformance/externalModules/asiPreventsParsingAsAmbientExternalModule02.ts", + "tests/cases/conformance/externalModules/circularReference.ts", + "tests/cases/conformance/externalModules/commonJsImportBindingElementNarrowType.ts", + "tests/cases/conformance/externalModules/es6/es6modulekind.ts", + "tests/cases/conformance/externalModules/es6/es6modulekindExportClassNameWithObject.ts", + "tests/cases/conformance/externalModules/es6/es6modulekindWithES2015Target.ts", + "tests/cases/conformance/externalModules/es6/es6modulekindWithES5Target.ts", + "tests/cases/conformance/externalModules/es6/es6modulekindWithES5Target10.ts", + "tests/cases/conformance/externalModules/es6/es6modulekindWithES5Target11.ts", + "tests/cases/conformance/externalModules/es6/es6modulekindWithES5Target12.ts", + "tests/cases/conformance/externalModules/es6/es6modulekindWithES5Target2.ts", + "tests/cases/conformance/externalModules/es6/es6modulekindWithES5Target3.ts", + "tests/cases/conformance/externalModules/es6/es6modulekindWithES5Target4.ts", + "tests/cases/conformance/externalModules/es6/es6modulekindWithES5Target5.ts", + "tests/cases/conformance/externalModules/es6/es6modulekindWithES5Target6.ts", + "tests/cases/conformance/externalModules/es6/es6modulekindWithES5Target7.ts", + "tests/cases/conformance/externalModules/es6/es6modulekindWithES5Target8.ts", + "tests/cases/conformance/externalModules/es6/es6modulekindWithES5Target9.ts", + "tests/cases/conformance/externalModules/esnext/esnextmodulekind.ts", + "tests/cases/conformance/externalModules/esnext/esnextmodulekindWithES2015Target.ts", + "tests/cases/conformance/externalModules/esnext/esnextmodulekindWithES5Target.ts", + "tests/cases/conformance/externalModules/esnext/esnextmodulekindWithES5Target10.ts", + "tests/cases/conformance/externalModules/esnext/esnextmodulekindWithES5Target11.ts", + "tests/cases/conformance/externalModules/esnext/esnextmodulekindWithES5Target12.ts", + "tests/cases/conformance/externalModules/esnext/esnextmodulekindWithES5Target2.ts", + "tests/cases/conformance/externalModules/esnext/esnextmodulekindWithES5Target3.ts", + "tests/cases/conformance/externalModules/esnext/esnextmodulekindWithES5Target4.ts", + "tests/cases/conformance/externalModules/esnext/esnextmodulekindWithES5Target5.ts", + "tests/cases/conformance/externalModules/esnext/esnextmodulekindWithES5Target6.ts", + "tests/cases/conformance/externalModules/esnext/esnextmodulekindWithES5Target7.ts", + "tests/cases/conformance/externalModules/esnext/esnextmodulekindWithES5Target8.ts", + "tests/cases/conformance/externalModules/esnext/esnextmodulekindWithES5Target9.ts", + "tests/cases/conformance/externalModules/esnext/exnextmodulekindExportClassNameWithObject.ts", + "tests/cases/conformance/externalModules/exportAmbientClassNameWithObject.ts", + "tests/cases/conformance/externalModules/exportAssignDottedName.ts", + "tests/cases/conformance/externalModules/exportAssignNonIdentifier.ts", + "tests/cases/conformance/externalModules/exportAssignTypes.ts", + "tests/cases/conformance/externalModules/exportAssignmentCircularModules.ts" + ], + "triage": { + "test_level_policy": "Every F2P and P2P entry is a single .ts file under tests/cases/conformance/. TypeScript's runtests harness compiles each file end-to-end with the freshly-built tsc and compares the emitted .js / .types / .symbols / .errors.txt against tests/baselines/reference/. System-level by construction.", + "f2p_test_classes": { + "system_e2e": { + "arbitraryModuleNamespaceIdentifiers conformance (4)": "tests/cases/conformance/es2022/arbitraryModuleNamespaceIdentifiers/*.ts \u2014 4 NEW conformance tests: import-empty, export-empty, module emit, syntax. Each compiles a module that uses arbitrary string-literal namespace identifiers (e.g. `export { foo as 'foo bar' }`) and asserts on the emitter output + diagnostics." + }, + "module_level": {}, + "f2p_test_classes_excluded_as_unit": [ + "tests/cases/fourslash/arbitraryModuleNamespaceIdentifiers_{types,values}.ts \u2014 fourslash tests that probe goToDefinition + hover behavior via the language-service API. Narrower than full-compile baseline tests; excluded per the system-level rule.", + "tests/cases/fourslash/completionsImportOrExportSpecifier.ts \u2014 language-service completion test, same exclusion rationale.", + "tests/cases/fourslash/refactorConvertImport_namedToNamespaceStringLiteral.ts \u2014 refactor test, same rationale.", + "tests/cases/fourslash/stringCompletionsImportOrExportSpecifier.ts \u2014 string-literal completion test, same rationale." + ] + }, + "test_compile_failure_pre_state": "Expected: at base, the parser rejects string literals as export/import specifier names. Compiling any F2P test produces a SyntaxError; baseline comparison fails. Every F2P surfaces as FAIL.", + "p2p_isolation": "All 50 original P2P selectors are in tests/cases/conformance/externalModules/ and tests/cases/conformance/es6/moduleExportsCommonjs/. The 42 selectors added on 2026-06-15 are pre-existing module import/export tests that do not appear in solution.patch or eval_tests.patch. They exercise the same module-import/export code paths solution.patch touches (parser.ts, checker.ts module resolution, transformers/module.ts), on UNCHANGED test files. No taint surface (baseline tests are file-level isolated).", + "p2p_helper_taint_audit": "No shared helpers \u2014 TypeScript baseline tests are self-contained .ts files." + }, + "f2p_entry_count": 4, + "p2p_entry_count": 50, + "validated_at": "2026-06-15", + "augmented": { + "suite_support": { + "env": "LOLBENCH_SUITE", + "modes": [ + "orig", + "aug", + "union" + ], + "default": "orig" + }, + "eval_tests_patch": "eval_tests_aug.patch", + "eval_tests_aug_patch_sha256": "0ebfd7636c76c4b5efee805067526232834955410ece049b250eced04913038f", + "f2p_aug_sha256": "4e925301ee8eee5ba6c0c168ecc72d23b344e7669d2f10ccfacf3d4946d09de4", + "p2p_aug_sha256": "a04b914d81a15d86ca4d907c55cb9d83598e0768cd58e716333c7c264926ffba", + "fail_to_pass": [ + "tests/cases/fourslash/arbitraryModuleNamespaceIdentifiersAugCompilerApi.ts", + "tests/cases/fourslash/arbitraryModuleNamespaceIdentifiersAugServices.ts" + ], + "pass_to_pass": [ + "tests/cases/fourslash/arbitraryModuleNamespaceIdentifiersAugNamedImportP2P.ts", + "tests/cases/fourslash/arbitraryModuleNamespaceIdentifiersAugCommonJsP2P.ts" + ], + "targets_mutants": [ + "mutant_001_can_parse_module_export_name_identifier_only", + "mutant_002_parse_module_export_name_as_identifier", + "mutant_003_import_local_string_binding_allowed", + "mutant_004_import_property_string_disallowed", + "mutant_005_export_string_name_disallowed", + "mutant_006_namespace_export_string_disallowed", + "mutant_007_es2015_es2020_module_diagnostic_deleted", + "mutant_008_empty_string_export_not_resolved", + "mutant_009_string_default_not_recognized", + "mutant_010_visitor_rejects_string_module_export_names", + "mutant_011_commonjs_export_string_written_to_wrong_key", + "mutant_012_commonjs_import_string_reads_wrong_key", + "mutant_013_completion_import_alias_omitted", + "mutant_014_non_identifier_alias_completion_hidden", + "mutant_015_string_literal_specifier_completions_disabled", + "mutant_016_namespace_export_parser_identifier_only" + ], + "coverage_gate": { + "minimum_line_coverage_percent": 80, + "status": "passed", + "coverage_report": "coverage_out/coverage_report_union.json", + "baseline_coverage_report": "coverage_out/coverage_report_orig.json", + "augmented_coverage_report": "coverage_out/coverage_report_aug.json", + "measurement_note": "TypeScript coverage runner estimates executable solution.patch line coverage from successful public harness runs for the selected suite. Refreshed 2026-06-15 after expanding original P2P to 50 pre-existing selectors.", + "baseline_union_line_coverage_percent": 100.0, + "augmented_only_union_line_coverage_percent": 100.0, + "union_line_coverage_percent": 100.0, + "executable_lines_in_patch": 350, + "union_covered_lines": 350, + "coverage_complete": true + }, + "triage": { + "test_level_policy": "Augmented F2P and P2P entries are TypeScript fourslash tests. They drive public compiler APIs, emitted JavaScript, language-service completions, quick-info, and diagnostics through the normal TypeScript test harness; no augmented selector imports or calls project-private compiler helpers.", + "requirement_section_source": "No requirement_pr_pairs mapping file exists for this instance in requirement_pr_pairs/. The section string below uses the exact requirement PR title from https://github.com/tc39/ecma262/pull/2154.", + "fail_to_pass": { + "tests/cases/fourslash/arbitraryModuleNamespaceIdentifiersAugCompilerApi.ts": { + "requirement_sections": [ + "Normative: Arbitrary module namespace identifier names" + ], + "public_surface": "TypeScript public compiler API: ts.createSourceFile, ts.transform, ts.createProgram, ts.getPreEmitDiagnostics, ts.transpileModule, public SyntaxKind, public ModuleKind, and emitted CommonJS output.", + "mutants_targeted": [ + "mutant_001_can_parse_module_export_name_identifier_only", + "mutant_002_parse_module_export_name_as_identifier", + "mutant_003_import_local_string_binding_allowed", + "mutant_004_import_property_string_disallowed", + "mutant_005_export_string_name_disallowed", + "mutant_006_namespace_export_string_disallowed", + "mutant_007_es2015_es2020_module_diagnostic_deleted", + "mutant_008_empty_string_export_not_resolved", + "mutant_009_string_default_not_recognized", + "mutant_010_visitor_rejects_string_module_export_names", + "mutant_011_commonjs_export_string_written_to_wrong_key", + "mutant_012_commonjs_import_string_reads_wrong_key", + "mutant_016_namespace_export_parser_identifier_only" + ], + "rationale": "Checks the public parser, checker, transformer, and CommonJS emitter contract for arbitrary module namespace identifier names: string-literal import/export specifiers parse as StringLiteral nodes, quoted local import bindings remain invalid, quoted names are accepted under supported module targets, ES2015/ES2020 reject them with the documented diagnostic, empty-string and quoted default exports resolve correctly, visitEachChild preserves quoted module export names, and CommonJS emit reads/writes the exact quoted property key." + }, + "tests/cases/fourslash/arbitraryModuleNamespaceIdentifiersAugServices.ts": { + "requirement_sections": [ + "Normative: Arbitrary module namespace identifier names" + ], + "public_surface": "TypeScript public language-service behavior exposed through fourslash completion assertions for named import/export specifiers and string-literal import/export specifier completions.", + "mutants_targeted": [ + "mutant_013_completion_import_alias_omitted", + "mutant_014_non_identifier_alias_completion_hidden", + "mutant_015_string_literal_specifier_completions_disabled" + ], + "rationale": "Verifies that language-service completions surface non-identifier exported aliases, insert a valid local alias for named imports, and provide string-literal property completions inside quoted import/export specifiers." + } + }, + "pass_to_pass": { + "tests/cases/fourslash/arbitraryModuleNamespaceIdentifiersAugNamedImportP2P.ts": { + "requirement_sections": [ + "Normative: Arbitrary module namespace identifier names" + ], + "public_surface": "Existing TypeScript language-service quick-info and no-error behavior for ordinary named imports, type-only imports, and renamed exports.", + "stability_goal": "Adding arbitrary quoted module export names must not regress ordinary identifier-based named import/export flows.", + "rationale": "Pins adjacent unchanged module import/export behavior through public quick-info and diagnostics while deliberately avoiding arbitrary string-literal module names." + }, + "tests/cases/fourslash/arbitraryModuleNamespaceIdentifiersAugCommonJsP2P.ts": { + "requirement_sections": [ + "Normative: Arbitrary module namespace identifier names" + ], + "public_surface": "TypeScript public ts.transpileModule CommonJS output for ordinary identifier-based imports and re-exports.", + "stability_goal": "The CommonJS emitter changes for quoted export names must preserve existing identifier-based import/export emit.", + "rationale": "Pins adjacent unchanged CommonJS module-transform behavior without using the new arbitrary quoted specifier syntax." + } + } + } + }, + "repo": "microsoft/TypeScript", + "image": "lolbench/apache-typescript-pr-58640:1", + "agent_contract": { + "input": "/in/solution.patch", + "output": "/out/agent_report.json", + "invocation": "docker run --rm -v $(pwd)/solution.patch:/in/solution.patch:ro -v $(pwd)/out:/out lolbench/apache-typescript-pr-58640:1" + }, + "test_framework": "node_test", + "test_level": "system", + "test_cmd_template": "npm test -- ", + "log_parser": "node_test", + "validation_summary": { + "status": "validated", + "validated_at": "2026-06-15", + "orig_pre": { + "f2p": {"passed": 0, "failed": 4, "errored": 0, "total": 4}, + "p2p": {"passed": 50, "failed": 0, "errored": 0, "total": 50}, + "resolved": false + }, + "orig_post": { + "f2p": {"passed": 4, "failed": 0, "errored": 0, "total": 4}, + "p2p": {"passed": 50, "failed": 0, "errored": 0, "total": 50}, + "resolved": true + }, + "aug_pre": { + "f2p": {"passed": 0, "failed": 2, "errored": 0, "total": 2}, + "p2p": {"passed": 2, "failed": 0, "errored": 0, "total": 2}, + "resolved": false + }, + "aug_post": { + "f2p": {"passed": 2, "failed": 0, "errored": 0, "total": 2}, + "p2p": {"passed": 2, "failed": 0, "errored": 0, "total": 2}, + "resolved": true + }, + "union_pre": { + "f2p": {"passed": 0, "failed": 6, "errored": 0, "total": 6}, + "p2p": {"passed": 52, "failed": 0, "errored": 0, "total": 52}, + "resolved": false + }, + "union_post": { + "f2p": {"passed": 6, "failed": 0, "errored": 0, "total": 6}, + "p2p": {"passed": 52, "failed": 0, "errored": 0, "total": 52}, + "resolved": true + } + }, + "coverage": { + "orig": 100.0, + "aug": 100.0, + "union": 100.0, + "denominator": "union_executable_lines", + "orig_report": "coverage_out/coverage_report_orig.json", + "aug_report": "coverage_out/coverage_report_aug.json", + "union_report": "coverage_out/coverage_report_union.json", + "coverage_report_json": "coverage_out/coverage_report.json mirrors union", + "covered_lines": 350, + "executable_lines_in_patch": 350, + "refreshed_at": "2026-06-15" + } +} diff --git a/TypeScript_3/tests/report_to_reward.py b/TypeScript_3/tests/report_to_reward.py new file mode 100644 index 0000000000000000000000000000000000000000..caee1a9c654a10f7d942342d2967f26f4dceed32 --- /dev/null +++ b/TypeScript_3/tests/report_to_reward.py @@ -0,0 +1,73 @@ +#!/usr/bin/env python3 +import argparse +import json +from pathlib import Path + + +def rate(bucket): + total = float(bucket.get("total", 0) or 0) + if total <= 0: + return 0.0 + return float(bucket.get("passed", 0) or 0) / total + + +def write_json(path, payload): + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(json.dumps(payload, indent=2, sort_keys=True) + "\n") + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument("--suite", default="union") + parser.add_argument("--missing-patch") + parser.add_argument("--invalid-suite", action="store_true") + parser.add_argument("--runner-rc", type=int, default=0) + parser.add_argument("agent_report") + parser.add_argument("reward_file") + args = parser.parse_args() + + report_path = Path(args.agent_report) + reward_path = Path(args.reward_file) + + if args.invalid_suite: + reward = {"reward": 0.0, "resolved": 0.0, "applied": 0.0, "build_ok": 0.0, "f2p_pass_rate": 0.0, "p2p_pass_rate": 0.0, "harness_ok": 1.0} + sanitized = {"instance_id": "TypeScript_3", "suite": args.suite, "applied": False, "resolved": False, "error_categories": ["invalid_lolbench_suite"]} + write_json(report_path, sanitized) + write_json(reward_path, reward) + print(f"LoLBench reward=0 invalid suite {args.suite!r}") + return 0 + + if args.missing_patch: + reward = {"reward": 0.0, "resolved": 0.0, "applied": 0.0, "build_ok": 0.0, "f2p_pass_rate": 0.0, "p2p_pass_rate": 0.0, "harness_ok": 1.0} + sanitized = {"instance_id": "TypeScript_3", "suite": args.suite, "applied": False, "resolved": False, "error_categories": ["missing_solution_patch"]} + write_json(report_path, sanitized) + write_json(reward_path, reward) + print("LoLBench reward=0 missing solution patch") + return 0 + + if not report_path.exists(): + reward = {"reward": 0.0, "resolved": 0.0, "applied": 0.0, "build_ok": 0.0, "f2p_pass_rate": 0.0, "p2p_pass_rate": 0.0, "harness_ok": 0.0} + write_json(reward_path, reward) + print(f"LoLBench reward=0 no agent_report.json runner_rc={args.runner_rc}") + return 0 + + report = json.loads(report_path.read_text()) + build_status = report.get("build", {}).get("status") + resolved = bool(report.get("resolved")) + applied = bool(report.get("applied")) + reward = { + "reward": 1.0 if resolved else 0.0, + "resolved": 1.0 if resolved else 0.0, + "applied": 1.0 if applied else 0.0, + "build_ok": 1.0 if build_status == "ok" else 0.0, + "f2p_pass_rate": rate(report.get("f2p", {})), + "p2p_pass_rate": rate(report.get("p2p", {})), + "harness_ok": 1.0 if args.runner_rc == 0 else 0.0, + } + write_json(reward_path, reward) + print("LoLBench reward={reward} resolved={resolved} f2p={f2p_pass_rate:.3f} p2p={p2p_pass_rate:.3f}".format(**reward)) + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/TypeScript_3/tests/test.sh b/TypeScript_3/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..45ba2abd4f682d021752e6966a772a0ee2edb9f5 --- /dev/null +++ b/TypeScript_3/tests/test.sh @@ -0,0 +1,43 @@ +#!/usr/bin/env bash +set -euo pipefail + +suite=${LOLBENCH_SUITE:-union} +mode=${LOLBENCH_MODE:-eval} +patch=${LOLBENCH_SOLUTION_PATCH:-/logs/artifacts/solution.patch} +private_log=/tmp/lolbench-private-run.log + +mkdir -p /logs/verifier /logs/artifacts /in /out + +case "$suite" in + orig|aug|union) ;; + *) + python3 /tests/report_to_reward.py --suite "$suite" --invalid-suite /out/agent_report.json /logs/verifier/reward.json + exit 0 + ;; +esac + +if [ "$mode" = "eval" ] && [ ! -s "$patch" ]; then + python3 /tests/report_to_reward.py --suite "$suite" --missing-patch "$patch" /out/agent_report.json /logs/verifier/reward.json + exit 0 +fi + +if [ "$mode" = "eval" ]; then + cp "$patch" /in/solution.patch + chmod 0400 /in/solution.patch +fi + +set +e +LOLBENCH_MODE="$mode" LOLBENCH_SUITE="$suite" /opt/lolbench/private/run_tests.sh >"$private_log" 2>&1 +runner_rc=$? +set -e + +cp "$private_log" /logs/verifier/private_run.log +if [ -f /out/grader_report.json ]; then + cp /out/grader_report.json /logs/verifier/grader_report.json +fi + +python3 /tests/report_to_reward.py --suite "$suite" --runner-rc "$runner_rc" /out/agent_report.json /logs/verifier/reward.json + +if [ -f /out/agent_report.json ]; then + cp /out/agent_report.json /logs/verifier/agent_report.json +fi diff --git a/TypeScript_4/README.md b/TypeScript_4/README.md new file mode 100644 index 0000000000000000000000000000000000000000..474af41be81685dbe11cc0b7c265395906110173 --- /dev/null +++ b/TypeScript_4/README.md @@ -0,0 +1,87 @@ +# LoLBench Harbor Task: TypeScript_4 + +This is a Harbor-format LoLBench task generated from `TypeScript_PR-60757_import-defer`. + +Selected source instance: + +- Harbor ID: `TypeScript_4` +- PR: `microsoft/TypeScript#60757` +- Base commit: `cd341998a98b71275d4b4d6f41c08d9d0eb75d93` +- Test modes: `orig, aug, union` +- Default/canonical mode: `union` +- Harbor image: `smartdub26/lolbench-linux:TypeScript_4-1.0.0` +- Docker Hub image: `smartdub26/lolbench-linux:TypeScript_4-1.0.0` + +## Image Setup + +Prefer the published Docker Hub image when it is available. Harbor refers to +the image as `smartdub26/lolbench-linux:TypeScript_4-1.0.0`, so Docker can pull it +directly when it is not present locally: + +```bash +docker pull smartdub26/lolbench-linux:TypeScript_4-1.0.0 +``` + +Only if the Docker Hub image is unavailable, build the single task image +locally: + +```bash +docker build -t lolbench/typescript_4:1.0.0 harbor_tasks/TypeScript_4/environment +docker tag lolbench/typescript_4:1.0.0 smartdub26/lolbench-linux:TypeScript_4-1.0.0 +``` + +The image contains the processed source tree at the base commit under +`/workspace/typescript`. Harbor must not mount a host source checkout +for the agent. + +## Run an Agent + +```bash +.harbor-venv/bin/harbor run \ + -p harbor_tasks/TypeScript_4 \ + -a codex \ + -m "" \ + --job-name TypeScript_4_agent_union \ + --jobs-dir harbor_runs/TypeScript_4 \ + --no-delete \ + --n-concurrent 1 \ + --ve LOLBENCH_SUITE=union +``` + +After implementing the requirement, the agent must clean any test-file edits +and run: + +```bash +lolbench-submit +``` + +## Evaluate a Patch + +Choose one mode with `LOLBENCH_SUITE=orig`, `aug`, or `union`; if unset, the +task defaults to `union`. + +```bash +PATCH="$(pwd)/path/to/solution.patch" + +.harbor-venv/bin/harbor run \ + -p harbor_tasks/TypeScript_4 \ + -a oracle \ + --job-name TypeScript_4_eval_union \ + --jobs-dir harbor_runs/TypeScript_4 \ + --no-delete \ + --n-concurrent 1 \ + --mounts '[{"type":"bind","source":"'"$PATCH"'","target":"/candidate/solution.patch","read_only":true}]' \ + --ae LOLBENCH_ORACLE_PATCH=/candidate/solution.patch \ + --ve LOLBENCH_SUITE=union +``` + +Outputs: + +```bash +find harbor_runs/TypeScript_4/TypeScript_4_eval_union -path '*/verifier/agent_report.json' -print +find harbor_runs/TypeScript_4/TypeScript_4_eval_union -path '*/verifier/reward.json' -print +``` + +`tests/docker-compose.yaml` is a verifier-only Harbor overlay. It mounts +`tests/`, `tests/private/`, and `solution/` into the separate verifier +container; none of those paths are mounted into the agent container. diff --git a/TypeScript_4/environment/Dockerfile b/TypeScript_4/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..120b13b545110d35dd771784b59d79997a657556 --- /dev/null +++ b/TypeScript_4/environment/Dockerfile @@ -0,0 +1,80 @@ +# LoLBench eval image: TypeScript PR-60757 (import defer proposal) +# PR: https://github.com/microsoft/TypeScript/pull/60757 +# base_commit: cd341998a98b71275d4b4d6f41c08d9d0eb75d93 (merge_commit^1) +# +# Conformance tests compare emitted output to committed baselines; the .ts +# case inputs are language-level (§6-clean). Built via npm + hereby. +FROM lolbench/typescript-base-node18:1 +ARG BASE_COMMIT=cd341998a98b71275d4b4d6f41c08d9d0eb75d93 +RUN (apt-get update && apt-get install -y --no-install-recommends git ca-certificates python3 && rm -rf /var/lib/apt/lists/*) || true +RUN mkdir -p /opt/lolbench/private /in /out /workspace +WORKDIR /workspace +RUN git init typescript && cd typescript && \ + git remote add origin https://github.com/microsoft/TypeScript.git && \ + git -c protocol.version=2 fetch --no-tags origin ${BASE_COMMIT} && \ + git checkout FETCH_HEAD && \ + git ls-files -z > /tmp/typescript-base-files && \ + git config user.email lolbench@local && \ + git config user.name lolbench && \ + if ! git diff --quiet || ! git diff --cached --quiet || [ -n "$(git ls-files --others --exclude-standard)" ]; then \ + git add -A && git -c commit.gpgsign=false commit -q -m "LoLBench environment overlay"; \ + fi && \ + git tag -f base && git tag -f lolbench-base && \ + git for-each-ref --format='%(refname)' refs/heads refs/remotes refs/tags | \ + while read ref; do \ + case "$ref" in refs/tags/base|refs/tags/lolbench-base) ;; *) git update-ref -d "$ref" ;; esac; \ + done && \ + ( git remote remove origin 2>/dev/null || true ) && \ + rm -f .git/FETCH_HEAD && \ + git reflog expire --expire=now --all && \ + git repack -Ad && \ + git prune --expire=now && \ + rm /tmp/typescript-base-files && \ + git config --global --add safe.directory /workspace/typescript +WORKDIR /workspace/typescript +# Pre-warm: install deps and build the compiler + test harness once. +RUN npm ci > /tmp/npmci.log 2>&1 || (tail -60 /tmp/npmci.log; exit 1) +RUN npx hereby tests > /tmp/build.log 2>&1 || (tail -60 /tmp/build.log; exit 1) + +# Harbor runtime adapter: keep the image public/agent-safe. +RUN mkdir -p /opt/lolbench /logs/artifacts /logs/agent /logs/verifier /in /out && \ + if ! id -u agent >/dev/null 2>&1; then useradd -m -s /bin/bash agent; fi +COPY metadata.json /opt/lolbench/metadata.json +COPY lolbench-submit /usr/local/bin/lolbench-submit +RUN chmod +x /usr/local/bin/lolbench-submit && \ + git config --global --add safe.directory /workspace/typescript && \ + if [ -d /workspace/typescript/.git ]; then \ + cd /workspace/typescript && LC_ALL=C git ls-files --others --exclude-standard | LC_ALL=C sort > /opt/lolbench/base_untracked.txt; \ + else \ + : > /opt/lolbench/base_untracked.txt; \ + fi && \ + chown -R agent:agent /workspace/typescript /logs +ENV HOME=/home/agent +# Local-reference hardening: retain only the approved base history. +RUN git config --system --add safe.directory /workspace/typescript && \ + cd /workspace/typescript && \ + git for-each-ref --format='%(refname)' refs/heads refs/remotes refs/tags | \ + while read ref; do \ + case "$ref" in refs/tags/base|refs/tags/lolbench-base) ;; *) git update-ref -d "$ref" ;; esac; \ + done && \ + ( git remote remove origin 2>/dev/null || true ) && \ + rm -f .git/FETCH_HEAD && \ + git reflog expire --expire=now --all && \ + git repack -Ad && \ + git prune --expire=now && \ + unreachable=$(git fsck --unreachable --no-reflogs) && \ + test -z "$unreachable" && \ + chown -R agent:agent .git +# Keep npm executable but remove cached/global copies of TypeScript sources. +RUN rm -rf /root/.npm /home/agent/.npm && \ + rm -f /usr/local/bin/tsc /usr/local/bin/tsserver /usr/bin/tsc /usr/bin/tsserver && \ + for p in /usr/local/lib/node_modules /usr/lib/node_modules; do \ + if [ -d "$p" ]; then \ + find "$p" -mindepth 1 -maxdepth 1 -type d -iname typescript -exec rm -rf '{}' +; \ + chown -R root:root "$p"; chmod -R go-w "$p"; chmod 0711 "$p"; \ + fi; \ + done +USER agent +WORKDIR /workspace/typescript +ENV LOLBENCH_INSTANCE_ID=TypeScript_4 +ENV LOLBENCH_SOURCE_SLUG=TypeScript_PR-60757_import-defer diff --git a/TypeScript_4/environment/docker-compose.yaml b/TypeScript_4/environment/docker-compose.yaml new file mode 100644 index 0000000000000000000000000000000000000000..7ed45f87dc9faf9df284f5b10d6d2289781ff254 --- /dev/null +++ b/TypeScript_4/environment/docker-compose.yaml @@ -0,0 +1,3 @@ +services: + main: + pull_policy: missing diff --git a/TypeScript_4/environment/lolbench-submit b/TypeScript_4/environment/lolbench-submit new file mode 100644 index 0000000000000000000000000000000000000000..b3426184f1a568aaf145f148348c3c5e85cfa773 --- /dev/null +++ b/TypeScript_4/environment/lolbench-submit @@ -0,0 +1,33 @@ +#!/usr/bin/env bash +set -euo pipefail +export LC_ALL=C + +repo=${1:-$PWD} +out=${LOLBENCH_PATCH_OUT:-/logs/artifacts/solution.patch} + +mkdir -p "$(dirname "$out")" +cd "$repo" + +baseline=/opt/lolbench/base_untracked.txt +current=$(mktemp) +new_files=$(mktemp) +trap 'rm -f "$current" "$new_files"' EXIT + +git ls-files --others --exclude-standard | sort > "$current" +if [ -f "$baseline" ]; then + comm -13 "$baseline" "$current" > "$new_files" +else + cp "$current" "$new_files" +fi + +if [ -s "$new_files" ]; then + xargs -r git add -N -- < "$new_files" +fi + +git diff --binary > "$out" + +if [ ! -s "$out" ]; then + echo "warning: wrote an empty solution patch to $out" >&2 +else + echo "wrote solution patch to $out" +fi diff --git a/TypeScript_4/environment/metadata.json b/TypeScript_4/environment/metadata.json new file mode 100644 index 0000000000000000000000000000000000000000..8d5f7ff71d5776e505144b1b61b1fc46e978fe4d --- /dev/null +++ b/TypeScript_4/environment/metadata.json @@ -0,0 +1,22 @@ +{ + "instance_id": "TypeScript_4", + "source_instance_id": "TypeScript_PR-60757_import-defer", + "source_slug": "TypeScript_PR-60757_import-defer", + "docker_slug": "TypeScript_PR-60757_import-defer", + "dockerhub_image": "smartdub26/lolbench-linux:TypeScript_4-1.0.0", + "project": "TypeScript", + "repo": "microsoft/TypeScript", + "requirement_doc": "https://github.com/microsoft/TypeScript/pull/60757", + "pr_link": "https://github.com/microsoft/TypeScript/pull/60757", + "base_commit": "cd341998a98b71275d4b4d6f41c08d9d0eb75d93", + "merge_commit": "b352c0d4062e1c91099f1c026bbd0e47074819c7", + "source_history_policy": "ancestors-only", + "lolbench_test_modes": [ + "orig", + "aug", + "union" + ], + "default_lolbench_suite": "union", + "canonical_lolbench_suite": "union", + "augmentation_available": true +} diff --git a/TypeScript_4/environment/source_audit.json b/TypeScript_4/environment/source_audit.json new file mode 100644 index 0000000000000000000000000000000000000000..543f76fd5886edff6f21fb87ef9567b6f5642b85 --- /dev/null +++ b/TypeScript_4/environment/source_audit.json @@ -0,0 +1,7 @@ +{ + "source_policy": "dockerfile_fetch_pruned_ancestor_history", + "local_reference_policy": "auxiliary_sources_removed_execute_only", + "base_commit": "cd341998a98b71275d4b4d6f41c08d9d0eb75d93", + "repo": "microsoft/TypeScript", + "note": "The Dockerfile fetches only the declared base history, removes refs/remotes/reflogs, repacks and prunes unreachable objects, asserts that git fsck finds no unreachable object, removes auxiliary reference sources, and makes remaining auxiliary toolchains root-owned and non-enumerable to the agent." +} diff --git a/TypeScript_4/instruction.md b/TypeScript_4/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..423407847f8646673a2e56a286c06cf75f3970cc --- /dev/null +++ b/TypeScript_4/instruction.md @@ -0,0 +1,631 @@ +You are working in `/workspace/typescript`, a source tree checked out at +the base commit for this task. Implement the requested behavior in the source +tree, then run: + +```bash +lolbench-submit +``` + +Do not stop after editing files, running tests, or describing the solution. The +task is complete only when `lolbench-submit` has created +`/logs/artifacts/solution.patch`. If that file does not exist, continue +working and run `lolbench-submit` again. + +That command writes your implementation diff to +`/logs/artifacts/solution.patch`, which is the artifact the Harbor verifier +will grade. Before running `lolbench-submit`, clean or revert any test files +you created or modified; test files must not be included in the final +`solution.patch`. + +This environment has no outbound internet access — `curl`/`wget`, `git fetch`/`clone`, package installs, and web fetch/search will all fail. Implement the requirements using only the code already in the workspace and your own knowledge; do not attempt to fetch or search external resources. + +Now please implement the following requirements in the source tree: + +--- + +# Deferring Module Evaluation + +previously known as "Lazy Module Initialization" + +## Background + +JS applications can get very large, to the point that not only loading, but even executing their +initialization scripts incurs a significant performance cost. Usually, this happens later in an application's +life span - often requiring invasive changes to make it more performant. + +Loading performance is a big and important area for improvement, and involves preloading techniques for +avoiding waterfalls and dynamic `import()` for lazily loading modules. + +But even with loading performance solved using these techniques, there is still overhead for execution +performance - CPU bottlenecks during initialization due to the way that the code itself is written. + +## Motivation + +Avoiding unnecessary execution is a well-known optimization in the Node.js CommonJS module system, +where there is a smaller gap between load contention and execution contention. The common pattern +in Node.js applications is to refactor code to dynamically require as needed: + +```js +const operation = require('operation'); + +exports.doSomething = function (target) { + return operation(target); +} +``` + +being rewritten as a performance optimization into: + +```js +exports.doSomething = function (target) { + const operation = require('operation'); + return operation(target); +} +``` + +The consumer still is provided with the same API, but with a more efficient use of FS & CPU during +initialization time. + +For ES modules, we have a solution for the lazy loading component of this problem via dynamic `import()`. + +For the same example we can write: + +```js +export async function doSomething (target) { + const { operation } = await import('operations'); + return operation(target); +} +``` + +This avoids bottlenecking the network and CPU during application initialization, but there are still a +number of problems with this technique: + +1. It doesn't actually solve the deferral of execution problem, since sending a network + request in such a scenario would usually be a performance regression and not an improvement. + A separate network preloading step would therefore still be desirable to achieve efficient + deferred execution while avoiding triggering a waterfall of requests. + +2. It forces all functions and their callers into an asynchronous programming model, + without necessarily reflecting the real intention of the program. This leads to all call + sites having to be updated into a new model, and cannot be made without a breaking API + change to existing API consumers. + +## Problem Statement + +Deferring the synchronous evaluation of a module may be desirable new primitive to avoid unnecessary +CPU work during application initialization, without requiring any changes from a module API consumer +perspective. + +Dynamic import does not properly solve this problem, since it must often be coupled with a preload step, +and enforces the unnecessary asyncification of all functions, without providing the ability to only defer +the synchronous evaluation work. + +## Proposal + +The proposal is to have a new syntactical import form which will only ever return a namespace exotic object. +When used, the module and its dependencies would not be executed, but would be fully loaded to the point +of being execution-ready before the module graph is considered loaded. + +_Only when accessing a property of this module, would the execution operations be performed (if needed)._ + +This way, the module namespace exotic object acts like a proxy to the evaluation of the module, effectively +with [[Get]] behavior that triggers synchronous evaluation before returning the defined bindings. + +The API will use the below syntax, following the phases model established by the +[source phase imports](https://github.com/tc39/proposal-source-phase-imports) proposal: + +```js +// or with a custom keyword: +import defer * as yNamespace from "y"; +``` + +This namespace binding is the only form a deferred import may take. Because `import defer` can only ever produce a namespace exotic object, a default binding (`import defer someDefault from "y"`) or named bindings (`import defer { thing } from "y"`) carry no meaning and are rejected at compile time. A default binding produces error `TS18058`, "Default imports are not allowed in a deferred import." Named bindings produce error `TS18059`, "Named imports are not allowed in a deferred import." + +Deferred imports are furthermore supported only under module targets that preserve native ES import syntax. A deferred import is accepted only when the `--module` flag is set to `esnext` or `preserve`; under every other target, including `commonjs`, `es2015`, `es2020`, and `nodenext`, the compiler reports error `TS18060`, "Deferred imports are only supported when the '--module' flag is set to 'esnext' or 'preserve'." + +Deferring also has a dynamic counterpart, mirroring the `import.` call form of the source phase imports proposal described below. Calling `import.defer(specifier)` performs a dynamic deferred import and evaluates to a promise for the deferred namespace, so that `import.defer("./dep.js")` has type `Promise`. Here `import.defer` is a meta-property (alongside `import.meta`) that must be _immediately_ called: a bare reference such as `const callee = import.defer;`, a parenthesized callee such as `(import.defer)("./dep.js")`, or passing `import.defer` as an argument to another call are all syntax errors, each reported as error `TS1005`, "'(' expected." Any meta-property name on `import` other than `meta` or `defer` is reported with error `TS18061`. The same `esnext`/`preserve` module restriction (error `TS18060`) also applies to the `import.defer(...)` dynamic call form. + +## Semantics + +The imports would still participate in deep graph loading so that they are fully populated into +the module cache prior to execution, however it the imported module will not be evaluated yet. + +When a property of the resulting module namespace object is accessed, if the execution has +not already been performed, a new top-level execution would be initiated for that module. + +In this way, a deferred module evaluation import acts as a new top-level execution node +in the execution graph, just like a dynamic import does, except executing synchronously. + +There are possible extensions under consideration, such as deferred re-exports, but they are not +included in the current version of the proposal. + +### Top-level await + +Property access on the namespace object of a deferred module must be synchronous, and it's thus +impossible to defer evaluation of modules that use top-level await. When a module is imported +using the `import defer` syntax, its asynchronous dependencies together with their own transitive +dependencies are eagerly evaluated, and only the synchronous parts of the graph are deferred. + +Consider the following example, where `a` is the top-level entry point: +
+ +```js +// a +import "b"; +import defer * as c from "c" + +setTimeout(() => { + c.value +}, 1000); +``` + + + +```js +// b +``` + + + +```js +// c +import "d" +import "f" +export let value = 2; +``` + +
+ +```js +// d +import "e" +await 0; +``` + + + +```js +// e +``` + + + +```js +// f +``` + +
+ +Since `d` uses top-level await, `d` and its dependencies cannot be deferred: +- The initial evaluation will execute `b`, `e`, `d` and `a`. +- Later, the `c.value` access will trigger the execution of `f` and `c`. + +### Rough sketch + +If we split out the components of Module loading and initialization, we could roughly sketch out the +intended semantics: + +> ⚠️ The following example does not take cycles into account + +```js +// LazyModuleLoader.js +async function loadModuleAndDependencies(name) { + const loadedModule = await import.load(`./${name}.js`); // load is async, and needs to be awaited + const parsedModule = loadedModule.parse(); + await Promise.all(parsedModule.imports.map(loadModuleAndDependencies)); // load all dependencies + return parsedModule; +} + +async function executeAsyncSubgraphs(module) { + if (module.hasTLA) return module.evaluate(); + return Promise.all(module.importedModules.map(executeAsyncSubgraphs)); +} + +export default async function lazyModule(object, name) { + const module = await loadModuleAndDependencies(name); + await executeAsyncSubgraphs(module); + Object.defineProperty(object, name, { + get: function() { + delete object[name]; + const value = module.evaluateSync(); + Object.defineProperty(object, name, { + value, + writable: true, + configurable: true, + enumerable: true, + }); + return value; + }, + configurable: true, + enumerable: true, + }); + + return object; +} + +// myModule.js +import foo from "./bar"; + +etc. + +// module.js +import LazyModule from "./LazyModuleLoader"; +await LazyModule(globalThis, "myModule"); + +function Foo() { + myModule.doWork() // first use +} +``` + +## Implementations + +- engine262: https://github.com/nicolo-ribaudo/engine262/tree/defer-eval +- webpack: https://github.com/webpack/webpack/pull/16567 +- Babel: https://babeljs.io/docs/babel-plugin-proposal-import-defer + +## Q&A + +#### What happened to the direct lazy bindings? + +The initial version of this proposal included direct binding access for deferred evaluation via +named exports: + +```js +import { feature } from './lib' with { lazyInit: true } + +export function doSomething (param) { + return feature(param); +} +``` + +where the deferred evaluation would only happen on _access_ of the `feature` binding. + +There are a number of complexities to this approach, as it introduces a novel +type of execution point in the language, which would need to be worked through. + +This approach may still be investigated in various ways within this proposal or an extension of it, +but by focusing on the module namespace exotic object approach first, it keeps the semantics +simple and in-line with standard JS techniques. + +#### Is there really a benefit to optimizing execution, when surely loading is the bottleneck? + +While it is true that loading time is the most dominant factor on the web, it is important to consider that many +large applications can block the CPU for of the range of 100ms while initializing the main application graph. + +Loading times of the order of multiple seconds often take the focus for performance optimization work, and this +is certainly an important problem space, but the problem of freeing up the main event loop during initialization +remains a critical one when the network problem is solved, that doesn't currently have any easy solutions today +for large applications. + +#### Is there prior art for this in other languages? + +The standard libraries of these programming languages includes related functionality: +- Ruby's `autoload`, in contrast with `require` which works in the same way as JS `import` +- Clojure `import` +- Most LISP environments + +Our approach is pretty similar to the Emacs Lisp approach, and it's clear from a manual analysis of billions of Stack Overflow posts that this is the most straightforward to ordinary developers. + +#### Why not support a synchronous evaluation API on ModuleInstance + +A synchronous evaluation API on the module expression and compartments [ModuleInstance](https://github.com/tc39/proposal-compartments/blob/master/0-module-and-module-source.md#module-instances) +object could offer an API for synchronous evaluation of modules, which could be compatible with +this approach of deferred evaluation, but it is only in having a clear syntactical solution for this use case, +that it can be supported across dependency boundaries and in bundlers to bring the full benefits of avoiding unnecessary +initialization work to the wider JS ecosystem. + +#### What can we do in current JS to approximate this behavior? + +The closest we can get is the following: + +```js +// moduleWrapper.js +export default function ModuleWrapper(object, name, lambda) { + Object.defineProperty(object, name, { + get: function() { + // Redefine this accessor property as a data property. + // Delete it first, to rule out "too much recursion" in case object is + // a proxy whose defineProperty handler might unwittingly trigger this + // getter again. + delete object[name]; + const value = lambda.apply(object); + Object.defineProperty(object, name, { + value, + writable: true, + configurable: true, + enumerable: true, + }); + return value; + }, + configurable: true, + enumerable: true, + }); + return object; +} + +// module.js +import ModuleWrapper from "./ModuleWrapper"; +// any imports would need to be wrapped as well + +function MyModule() { + // ... all of the work of the module +} + +export default ModuleWrapper({}, "MyModule", MyModule); + +// parent.js +import wrappedModule from "./module"; + +function Foo() { + wrappedModule.MyModule.bar() // first use +} +``` + +However, this solution doesn't cover deferring the loading of submodules of a lazy graph, and would +not acheive the characteristics we are looking for. + +#### Why `import defer *` gives a different namespace object from `import *`? + +Module namespace objects of modules that are _already evaluated_ and threw during evaluation do not re-throw an error on +property access: + +```js +// module-that-throws1 +import * as self from 'module-that-throws1'; +globalThis.ns1 = self; +export let a = 1; +throw new Error("oops"); +``` +```js +// main1.js +import("module-that-throws1").finally(() => { + console.log(globalThis.ns1.a); // Doesn't throw, logs '1' +}); +``` + +Deferred namespaces are different. If the module throws while being evaluated, `deferredNamespace.foo` will always throw the evaluation error: + +```js +// module-that-throws2 +export let a = 1; +throw new Error("oops"); +``` +```js +// main2.js +import defer * as ns2 from 'module-that-throws2'; + +try { ns2.a } catch (e) { console.log(e.message) } // logs "oops" +``` + +Before this proposal having access to a namespace object of a module that threw during evaluation is incredibly rare. However, it becomes more common with `import defer` declarations. The `import defer` in `main2.js` would have a race condition if it errored only when `module-that-throws2` has already been loaded by something else, instead the error will always be deffered until the namespace is accessed. As `ns2.a` must throw even if `module-that-throws2` is already evaluated, and thus it cannot be the same namespace object as `import *`. + +Another approach we considered (and discarded) was to always suppress evaluation errors on namespace property access, so that in the example above `ns2.a` would be guaranteed to _never_ throw and thus not be affected by unrelated modules that might have already triggered evaluation of `module-that-throws`. + +#### Why not re-use import attributes (`import * as ns from "mod" with { defer: true }`)? + +There are two reasons why we chose to use an "import modifier" rather than an attribute: +1. Import attributes affect what a module _is_, but cannot change basic semantics of how ECMAScript modules behave: they are similar to adding query parameters to the imported URL, except that attributes are handled by the running environment rather than by the server. For example, `with { type: "json" }` behaves as if the imported module was a JavaScript file wrapped in ``export default JSON.parse(` ... the file contents ... `);``. `import defer` changes how namespace objects behave (by making them side-effectul, while before this proposal property access on namespace objects couldn't trigger any side effect): it cannot be expressed as a wrapped/modified "classic" ECMAScript module. +2. Together with the [source phase imports proposal](https://github.com/tc39/proposal-source-phase-imports), we are exposing multiple "phases" of module loading. The phases we've identified are: resolving a module given a specifier, fetching the module (these two both happens in hosts and not in ECMA-262), attaching modules to their execution and resolution context, linking modules together, and finally executing them. We are using `import` modifiers to represent modules processed up to one of those phases, without going all the way to finishing execution. These modifiers give more guarantees than import attributes: while `import "x" with { attr1: "val" }` and `import "x" with { attr2: "val2" }` might be two completely different modules, `import source s from "x"`, `import defer * as ns from "x"`, and `import "x"` all are guaranteed to load the same module, and that module will be executed at most once regardless of which "phase" it gets temporarely paused at (and then continued from). + +## Linked Proposal — Source Phase Imports + +## Motivation + +For both JavaScript and WebAssembly, there is a need to be able to more closely +customize the loading, linking, and execution of modules beyond the standard +host execution model. + +For JavaScript, creating userland loaders would require a module source type +in order to share the host parsing, execution, security, and caching semantics. + +For WebAssembly, imports and exports for WebAssembly modules often require custom +inspection and wrapping in order to be set up correctly, which typically requires +manual fetch and instantiation work that is not provided for in the current host +[ESM integration][wasm-esm] proposal. + +Supporting syntactical module source imports as a new import phase creates a +primitive that can extend the static, security and tooling benefits of modules +from the ESM integration to these dynamic instantiation use cases. + +## Proposal + +This proposal allows ES modules to import a reified representation of the +compiled source of a module when the host provides such a representation: + +```js +import source x from ""; +``` + +The `source` module source loading phase name is added to the beginning of the +ImportStatement. + +Only the above form is supported - named exports and unbound declarations are +not supported. + +### Dynamic form + +Just as with static and dynamic imports, there is a need for static and dynamic access +to sources, to be able to support both those sources that are required to be instantiated +from source text during initialization of an application, and those that are optionally or +lazily created at runtime. + +The dynamic form uses a `import.` import call: + +```js +const x = await import.source(""); +``` + +By making the phase part of the explicit syntax, it is possible to statically distinguish between +a full dynamic import and one that is only for a source (where dependencies don't need to be +processed). + +Optional [import attributes][] may still be specified with the second argument in a `with` key, +just like for dynamic import, and without conflict due to the design of phased evaluation. + +### Loading Phase + +Module source imports can be seen to be one type of evaluation phase. + +If the [asset references proposal][] advances in future this could be seen +as another type of phase representing an earlier phase of the loading process. + +```js +import asset x from ""; +await import.asset(""); +``` + +Only the `source` import source phase is specified by this proposal. + +### Defining Module Source + +The object provided by the module source phase must be an object with +`AbstractModuleSource.prototype` in its prototype chain, defined by this specification +to be a minimal shared base prototype for a compiled modular resource. + +In addition it defines the `@@toStringTag` getter returning the constructor name string +corresponding to the name of the specific module source subclass, with a strong +internal slot check. + +### JS Module Source + +For JavaScript modules, the module source phase is then specified to return +a `ModuleSource` object, representing an ECMAScript Module Source, where +`ModuleSource.prototype.[[Proto]]` is `%AbstractModuleSource%.prototype`. + +Future proposals may then add support for [bindings lookup methods][], +the [ModuleSource constructor][module soruce] and [instantiation][] support. + +New properties may be added to the base `%AbstractModuleSource%.prototype`, or shared +with ECMAScript module sources via `ModuleSource.prototype` additions. + +### Wasm Module Source + +For WebAssembly modules, the existing `WebAssembly.Module.prototype` object is to be +updated to have a `[[Proto]]` of `%AbstractModuleSource%.prototype` in the +[WebAssembly JS integration API][wasm-js-api]. + +This allows workflows, as explained in the motivation, like the following: + +```js +import source FooModule from "./foo.wasm"; +FooModule instanceof WebAssembly.Module; // true + +// For example, to run a WASI execution with an API like Node.js WASI: +import { WASI } from 'wasi'; +const wasi = new WASI({ args, env, preopens }); + +const fooInstance = await WebAssembly.instantiate(FooModule, { + wasi_snapshot_preview1: wasi.wasiImport +}); + +wasi.start(fooInstance); +``` + +The static analysis benefits of not needing a custom `fetch` and +`WebAssembly.compileStreaming` apply not only to code analysis and security +but also for bundlers. + +In turn this enables [Wasm components to be able to import][] +`WebAssembly.Module` objects themselves in future. + +### Other Module Types + +Any other host-defined module types may define their own host module sources. If a given module does not define a source representation for it's source, importing it with a "source" phase target fails with a `ReferenceError` at link time. + +Host-defined module sources must include `%AbstractModuleSource%.prototype` in their prototype chain and support the `[[ModuleSourceRecord]]` internal slot containing the `@@toStringTag` brand check and underlying source host data. + +## Security Benefits + +The native ES module loader is able to implement security policies, including +support for [Content Security Policies][CSP] in browsers. This property does not just impact platforms using CSP, but also other platforms with systems to restrict permissions, such as Deno. These policies are based on protecting which URLs are supported for the compilation and execution of scripts or modules. + +Extending the static security benefits of the host module system to custom loaders is a security benefit of this proposal. For Wasm, it would enable source-specific CSP policies for dynamic Wasm instantiation. + +## Cache Key Semantics + +Because `[[ModuleSourceObject]]` is keyed on the base module record, it will always +be unique to the module being imported from. + +## Q&A + +**Q**: How does this relate to import attributes? + +**A**: Import attributes are properties of the module request, while source imports +represent phases of that specific request / key in the module map, without affecting +the idempotency of the module load. Both can be used together for a resource to indicate alternative phasing for the given module resource and attributes. + +**Q**: How does this relate to module expressions and compartments? + +**A**: The module object that is provided has been carefully specified here to be +compatible with the linking model of module expressions and compartments. + +**Q**: Why not just use `const module = await +WebAssembly.compileStreaming(fetch(new URL("./module.wasm", +import.meta.url)));`? + +**A**: There are multiple benefits: firstly if the module is statically +referenced in the module graph, it is easier to statically analyze (by bundlers +for example). Secondly when using CSP, `script-src: unsafe-eval` would not be +needed. See the security improvements section for more details. + +*Source: https://github.com/tc39/proposal-source-phase-imports* + +## Linked Proposal — First-class Module and ModuleSource (Module instances) + +```ts +type ImportSpecifier = string; + +type ImportHook = (this: ModuleHandler, specifier: ImportSpecifier) => + Promise; + +type ImportMeta = { + __proto__: null, + // ... + [name: string | symbol | number]: unknown, +}; + +type ImportMetaHook = (this: ModuleHandler, importMeta: ImportMeta) => any; + +type ModuleHandler = { + importHook?: ImportHook, + importMetaHook?: ImportMetaHook, + // ... + [name: string | symbol | number]: unknown, +}; + +interface Module { + constructor( + source: ModuleSource, + handler: ModuleHandler, + ); + + readonly source?: ModuleSource, +} +``` + +Semantics: A `Module` instance has an internal ***Module Record***. +Importing the module will consistently produce the same ***Module Namespace +Exotic Object***. + +The module has a lifecycle and fresh instances have not been linked, +initialized, or executed. + +Invoking dynamic import on a `Module` instance attempts to advance it and its +transitive dependencies to their end state. +Consistent with dynamic import for a stringly-named module, +dynamic import on a `Module` instance produces a promise for the corresponding +***Module Namespace Exotic Object*** + +Dynamic import induces calls to `importHook` for each unsatisfied dependency of +each module instance in separate events, before any dependency advances to the +link phase of its lifecycle. + +Dynamic import within the evaluation of a `Module` also invokes the +`importHook`. + +`Module` instances memoize the result of their `importHook` keyed on the given +Import Specifier. + +`Module` constructors, like `Function` constructors, are bound to a realm +and evaluate modules in their particular realm. + +*Source: https://github.com/tc39/proposal-compartments/blob/master/0-module-and-module-source.md#module-instances* diff --git a/TypeScript_4/solution/solution.patch b/TypeScript_4/solution/solution.patch new file mode 100644 index 0000000000000000000000000000000000000000..96ceae73c512d33bcb821ed6e30ba765661a779d --- /dev/null +++ b/TypeScript_4/solution/solution.patch @@ -0,0 +1,837 @@ +diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts +index eff1b31cd..36f66cb08 100644 +--- a/src/compiler/checker.ts ++++ b/src/compiler/checker.ts +@@ -10247,7 +10247,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { + factory.createImportDeclaration( + /*modifiers*/ undefined, + factory.createImportClause( +- /*isTypeOnly*/ false, ++ /*phaseModifier*/ undefined, + /*name*/ undefined, + factory.createNamedImports([factory.createImportSpecifier( + /*isTypeOnly*/ false, +@@ -10344,7 +10344,11 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { + addResult( + factory.createImportDeclaration( + /*modifiers*/ undefined, +- factory.createImportClause(isTypeOnly, factory.createIdentifier(localName), /*namedBindings*/ undefined), ++ factory.createImportClause( ++ /* phaseModifier */ isTypeOnly ? SyntaxKind.TypeKeyword : undefined, ++ factory.createIdentifier(localName), ++ /*namedBindings*/ undefined, ++ ), + specifier, + attributes, + ), +@@ -10360,7 +10364,11 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { + addResult( + factory.createImportDeclaration( + /*modifiers*/ undefined, +- factory.createImportClause(isTypeOnly, /*name*/ undefined, factory.createNamespaceImport(factory.createIdentifier(localName))), ++ factory.createImportClause( ++ /* phaseModifier */ isTypeOnly ? SyntaxKind.TypeKeyword : undefined, ++ /*name*/ undefined, ++ factory.createNamespaceImport(factory.createIdentifier(localName)), ++ ), + specifier, + (node as ImportClause).parent.attributes, + ), +@@ -10389,7 +10397,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { + factory.createImportDeclaration( + /*modifiers*/ undefined, + factory.createImportClause( +- isTypeOnly, ++ /* phaseModifier */ isTypeOnly ? SyntaxKind.TypeKeyword : undefined, + /*name*/ undefined, + factory.createNamedImports([ + factory.createImportSpecifier( +@@ -38014,6 +38022,10 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { + } + + if (node.keywordToken === SyntaxKind.ImportKeyword) { ++ if (node.name.escapedText === "defer") { ++ Debug.assert(!isCallExpression(node.parent) || node.parent.expression !== node, "Trying to get the type of `import.defer` in `import.defer(...)`"); ++ return errorType; ++ } + return checkImportMetaProperty(node); + } + +@@ -41452,7 +41464,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { + } + // Optimize for the common case of a call to a function with a single non-generic call + // signature where we can just fetch the return type without checking the arguments. +- if (isCallExpression(expr) && expr.expression.kind !== SyntaxKind.SuperKeyword && !isRequireCall(expr, /*requireStringLiteralLikeArgument*/ true) && !isSymbolOrSymbolForCall(expr)) { ++ if (isCallExpression(expr) && expr.expression.kind !== SyntaxKind.SuperKeyword && !isRequireCall(expr, /*requireStringLiteralLikeArgument*/ true) && !isSymbolOrSymbolForCall(expr) && !isImportCall(expr)) { + return isCallChain(expr) ? getReturnTypeOfSingleNonGenericSignatureOfCallChain(expr) : + getReturnTypeOfSingleNonGenericCallSignature(checkNonNullExpression(expr.expression)); + } +@@ -41606,8 +41618,8 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { + case SyntaxKind.ElementAccessExpression: + return checkIndexedAccess(node as ElementAccessExpression, checkMode); + case SyntaxKind.CallExpression: +- if ((node as CallExpression).expression.kind === SyntaxKind.ImportKeyword) { +- return checkImportCallExpression(node as ImportCall); ++ if (isImportCall(node)) { ++ return checkImportCallExpression(node); + } + // falls through + case SyntaxKind.NewExpression: +@@ -49877,6 +49889,10 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { + return isExportAssignment(node.parent) ? Debug.checkDefined(node.parent.symbol) : undefined; + + case SyntaxKind.ImportKeyword: ++ if (isMetaProperty(node.parent) && node.parent.name.escapedText === "defer") { ++ return undefined; ++ } ++ // falls through + case SyntaxKind.NewKeyword: + return isMetaProperty(node.parent) ? checkMetaPropertyKeyword(node.parent).symbol : undefined; + case SyntaxKind.InstanceOfKeyword: +@@ -52851,7 +52867,18 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { + break; + case SyntaxKind.ImportKeyword: + if (escapedText !== "meta") { +- return grammarErrorOnNode(node.name, Diagnostics._0_is_not_a_valid_meta_property_for_keyword_1_Did_you_mean_2, unescapeLeadingUnderscores(node.name.escapedText), tokenToString(node.keywordToken), "meta"); ++ const isCallee = isCallExpression(node.parent) && node.parent.expression === node; ++ if (escapedText === "defer") { ++ if (!isCallee) { ++ return grammarErrorAtPos(node, node.end, 0, Diagnostics._0_expected, "("); ++ } ++ } ++ else { ++ if (isCallee) { ++ return grammarErrorOnNode(node.name, Diagnostics._0_is_not_a_valid_meta_property_for_keyword_import_Did_you_mean_meta_or_defer, unescapeLeadingUnderscores(node.name.escapedText)); ++ } ++ return grammarErrorOnNode(node.name, Diagnostics._0_is_not_a_valid_meta_property_for_keyword_1_Did_you_mean_2, unescapeLeadingUnderscores(node.name.escapedText), tokenToString(node.keywordToken), "meta"); ++ } + } + break; + } +@@ -53110,11 +53137,24 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { + } + + function checkGrammarImportClause(node: ImportClause): boolean { +- if (node.isTypeOnly && node.name && node.namedBindings) { +- return grammarErrorOnNode(node, Diagnostics.A_type_only_import_can_specify_a_default_import_or_named_bindings_but_not_both); ++ if (node.phaseModifier === SyntaxKind.TypeKeyword) { ++ if (node.name && node.namedBindings) { ++ return grammarErrorOnNode(node, Diagnostics.A_type_only_import_can_specify_a_default_import_or_named_bindings_but_not_both); ++ } ++ if (node.namedBindings?.kind === SyntaxKind.NamedImports) { ++ return checkGrammarNamedImportsOrExports(node.namedBindings); ++ } + } +- if (node.isTypeOnly && node.namedBindings?.kind === SyntaxKind.NamedImports) { +- return checkGrammarNamedImportsOrExports(node.namedBindings); ++ else if (node.phaseModifier === SyntaxKind.DeferKeyword) { ++ if (node.name) { ++ return grammarErrorOnNode(node, Diagnostics.Default_imports_are_not_allowed_in_a_deferred_import); ++ } ++ if (node.namedBindings?.kind === SyntaxKind.NamedImports) { ++ return grammarErrorOnNode(node, Diagnostics.Named_imports_are_not_allowed_in_a_deferred_import); ++ } ++ if (moduleKind !== ModuleKind.ESNext && moduleKind !== ModuleKind.Preserve) { ++ return grammarErrorOnNode(node, Diagnostics.Deferred_imports_are_only_supported_when_the_module_flag_is_set_to_esnext_or_preserve); ++ } + } + return false; + } +@@ -53137,7 +53177,12 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { + return grammarErrorOnNode(node, Diagnostics.ESM_syntax_is_not_allowed_in_a_CommonJS_module_when_verbatimModuleSyntax_is_enabled); + } + +- if (moduleKind === ModuleKind.ES2015) { ++ if (node.expression.kind === SyntaxKind.MetaProperty) { ++ if (moduleKind !== ModuleKind.ESNext && moduleKind !== ModuleKind.Preserve) { ++ return grammarErrorOnNode(node, Diagnostics.Deferred_imports_are_only_supported_when_the_module_flag_is_set_to_esnext_or_preserve); ++ } ++ } ++ else if (moduleKind === ModuleKind.ES2015) { + return grammarErrorOnNode(node, Diagnostics.Dynamic_imports_are_only_supported_when_the_module_flag_is_set_to_es2020_es2022_esnext_commonjs_amd_system_umd_node16_node18_or_nodenext); + } + +diff --git a/src/compiler/diagnosticMessages.json b/src/compiler/diagnosticMessages.json +index 70ac18b6b..e445e5a34 100644 +--- a/src/compiler/diagnosticMessages.json ++++ b/src/compiler/diagnosticMessages.json +@@ -8487,5 +8487,21 @@ + "String literal import and export names are not supported when the '--module' flag is set to 'es2015' or 'es2020'.": { + "category": "Error", + "code": 18057 ++ }, ++ "Default imports are not allowed in a deferred import.": { ++ "category": "Error", ++ "code": 18058 ++ }, ++ "Named imports are not allowed in a deferred import.": { ++ "category": "Error", ++ "code": 18059 ++ }, ++ "Deferred imports are only supported when the '--module' flag is set to 'esnext' or 'preserve'.": { ++ "category": "Error", ++ "code": 18060 ++ }, ++ "'{0}' is not a valid meta-property for keyword 'import'. Did you mean 'meta' or 'defer'?": { ++ "category": "Error", ++ "code": 18061 + } + } +diff --git a/src/compiler/emitter.ts b/src/compiler/emitter.ts +index 1fd93c74e..c60fd9278 100644 +--- a/src/compiler/emitter.ts ++++ b/src/compiler/emitter.ts +@@ -3686,8 +3686,8 @@ export function createPrinter(printerOptions: PrinterOptions = {}, handlers: Pri + } + + function emitImportClause(node: ImportClause) { +- if (node.isTypeOnly) { +- emitTokenWithComment(SyntaxKind.TypeKeyword, node.pos, writeKeyword, node); ++ if (node.phaseModifier !== undefined) { ++ emitTokenWithComment(node.phaseModifier, node.pos, writeKeyword, node); + writeSpace(); + } + emit(node.name); +diff --git a/src/compiler/factory/nodeFactory.ts b/src/compiler/factory/nodeFactory.ts +index 694262eee..c7286dc33 100644 +--- a/src/compiler/factory/nodeFactory.ts ++++ b/src/compiler/factory/nodeFactory.ts +@@ -135,6 +135,7 @@ import { + ImportClause, + ImportDeclaration, + ImportEqualsDeclaration, ++ ImportPhaseModifierSyntaxKind, + ImportSpecifier, + ImportTypeAssertionContainer, + ImportTypeNode, +@@ -4723,14 +4724,18 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode + } + + // @api +- function createImportClause(isTypeOnly: boolean, name: Identifier | undefined, namedBindings: NamedImportBindings | undefined): ImportClause { ++ function createImportClause(phaseModifier: ImportPhaseModifierSyntaxKind | boolean | undefined, name: Identifier | undefined, namedBindings: NamedImportBindings | undefined): ImportClause { + const node = createBaseDeclaration(SyntaxKind.ImportClause); +- node.isTypeOnly = isTypeOnly; ++ if (typeof phaseModifier === "boolean") { ++ phaseModifier = phaseModifier ? SyntaxKind.TypeKeyword : undefined; ++ } ++ node.isTypeOnly = phaseModifier === SyntaxKind.TypeKeyword; ++ node.phaseModifier = phaseModifier; + node.name = name; + node.namedBindings = namedBindings; + node.transformFlags |= propagateChildFlags(node.name) | + propagateChildFlags(node.namedBindings); +- if (isTypeOnly) { ++ if (phaseModifier === SyntaxKind.TypeKeyword) { + node.transformFlags |= TransformFlags.ContainsTypeScript; + } + node.transformFlags &= ~TransformFlags.ContainsPossibleTopLevelAwait; // always parsed in an Await context +@@ -4738,11 +4743,14 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode + } + + // @api +- function updateImportClause(node: ImportClause, isTypeOnly: boolean, name: Identifier | undefined, namedBindings: NamedImportBindings | undefined) { +- return node.isTypeOnly !== isTypeOnly ++ function updateImportClause(node: ImportClause, phaseModifier: ImportPhaseModifierSyntaxKind | boolean | undefined, name: Identifier | undefined, namedBindings: NamedImportBindings | undefined) { ++ if (typeof phaseModifier === "boolean") { ++ phaseModifier = phaseModifier ? SyntaxKind.TypeKeyword : undefined; ++ } ++ return node.phaseModifier !== phaseModifier + || node.name !== name + || node.namedBindings !== namedBindings +- ? update(createImportClause(isTypeOnly, name, namedBindings), node) ++ ? update(createImportClause(phaseModifier, name, namedBindings), node) + : node; + } + +diff --git a/src/compiler/factory/utilities.ts b/src/compiler/factory/utilities.ts +index 80df86fd3..f3ed23b58 100644 +--- a/src/compiler/factory/utilities.ts ++++ b/src/compiler/factory/utilities.ts +@@ -730,7 +730,7 @@ export function createExternalHelpersImportDeclarationIfNeeded(nodeFactory: Node + + const externalHelpersImportDeclaration = nodeFactory.createImportDeclaration( + /*modifiers*/ undefined, +- nodeFactory.createImportClause(/*isTypeOnly*/ false, /*name*/ undefined, namedBindings), ++ nodeFactory.createImportClause(/*phaseModifier*/ undefined, /*name*/ undefined, namedBindings), + nodeFactory.createStringLiteral(externalHelpersModuleNameText), + /*attributes*/ undefined, + ); +diff --git a/src/compiler/parser.ts b/src/compiler/parser.ts +index e7df12503..b04055500 100644 +--- a/src/compiler/parser.ts ++++ b/src/compiler/parser.ts +@@ -123,6 +123,7 @@ import { + ImportDeclaration, + ImportEqualsDeclaration, + ImportOrExportSpecifier, ++ ImportPhaseModifierSyntaxKind, + ImportSpecifier, + ImportTypeAssertionContainer, + ImportTypeNode, +@@ -5938,7 +5939,15 @@ namespace Parser { + nextToken(); // advance past the 'import' + nextToken(); // advance past the dot + expression = finishNode(factory.createMetaProperty(SyntaxKind.ImportKeyword, parseIdentifierName()), pos); +- sourceFlags |= NodeFlags.PossiblyContainsImportMeta; ++ ++ if ((expression as MetaProperty).name.escapedText === "defer") { ++ if (token() === SyntaxKind.OpenParenToken || token() === SyntaxKind.LessThanToken) { ++ sourceFlags |= NodeFlags.PossiblyContainsDynamicImport; ++ } ++ } ++ else { ++ sourceFlags |= NodeFlags.PossiblyContainsImportMeta; ++ } + } + else { + expression = parseMemberExpressionOrHigher(); +@@ -7190,6 +7199,7 @@ namespace Parser { + // could be legal, it would add complexity for very little gain. + case SyntaxKind.InterfaceKeyword: + case SyntaxKind.TypeKeyword: ++ case SyntaxKind.DeferKeyword: + return nextTokenIsIdentifierOnSameLine(); + case SyntaxKind.ModuleKeyword: + case SyntaxKind.NamespaceKeyword: +@@ -7221,7 +7231,7 @@ namespace Parser { + + case SyntaxKind.ImportKeyword: + nextToken(); +- return token() === SyntaxKind.StringLiteral || token() === SyntaxKind.AsteriskToken || ++ return token() === SyntaxKind.DeferKeyword || token() === SyntaxKind.StringLiteral || token() === SyntaxKind.AsteriskToken || + token() === SyntaxKind.OpenBraceToken || tokenIsIdentifierOrKeyword(token()); + case SyntaxKind.ExportKeyword: + let currentToken = nextToken(); +@@ -7295,6 +7305,7 @@ namespace Parser { + case SyntaxKind.NamespaceKeyword: + case SyntaxKind.TypeKeyword: + case SyntaxKind.GlobalKeyword: ++ case SyntaxKind.DeferKeyword: + // When these don't start a declaration, they're an identifier in an expression statement + return true; + +@@ -8372,21 +8383,25 @@ namespace Parser { + identifier = parseIdentifier(); + } + +- let isTypeOnly = false; ++ let phaseModifier: ImportPhaseModifierSyntaxKind | undefined; + if ( + identifier?.escapedText === "type" && + (token() !== SyntaxKind.FromKeyword || isIdentifier() && lookAhead(nextTokenIsFromKeywordOrEqualsToken)) && + (isIdentifier() || tokenAfterImportDefinitelyProducesImportDeclaration()) + ) { +- isTypeOnly = true; ++ phaseModifier = SyntaxKind.TypeKeyword; ++ identifier = isIdentifier() ? parseIdentifier() : undefined; ++ } ++ else if (identifier?.escapedText === "defer" && token() !== SyntaxKind.FromKeyword) { ++ phaseModifier = SyntaxKind.DeferKeyword; + identifier = isIdentifier() ? parseIdentifier() : undefined; + } + +- if (identifier && !tokenAfterImportedIdentifierDefinitelyProducesImportDeclaration()) { +- return parseImportEqualsDeclaration(pos, hasJSDoc, modifiers, identifier, isTypeOnly); ++ if (identifier && !tokenAfterImportedIdentifierDefinitelyProducesImportDeclaration() && phaseModifier !== SyntaxKind.DeferKeyword) { ++ return parseImportEqualsDeclaration(pos, hasJSDoc, modifiers, identifier, phaseModifier === SyntaxKind.TypeKeyword); + } + +- const importClause = tryParseImportClause(identifier, afterImportPos, isTypeOnly); ++ const importClause = tryParseImportClause(identifier, afterImportPos, phaseModifier, /*skipJsDocLeadingAsterisks*/ undefined); + const moduleSpecifier = parseModuleSpecifier(); + const attributes = tryParseImportAttributes(); + +@@ -8395,7 +8410,7 @@ namespace Parser { + return withJSDoc(finishNode(node, pos), hasJSDoc); + } + +- function tryParseImportClause(identifier: Identifier | undefined, pos: number, isTypeOnly: boolean, skipJsDocLeadingAsterisks = false) { ++ function tryParseImportClause(identifier: Identifier | undefined, pos: number, phaseModifier: undefined | ImportPhaseModifierSyntaxKind, skipJsDocLeadingAsterisks = false) { + // ImportDeclaration: + // import ImportClause from ModuleSpecifier ; + // import ModuleSpecifier; +@@ -8405,7 +8420,7 @@ namespace Parser { + token() === SyntaxKind.AsteriskToken || // import * + token() === SyntaxKind.OpenBraceToken // import { + ) { +- importClause = parseImportClause(identifier, pos, isTypeOnly, skipJsDocLeadingAsterisks); ++ importClause = parseImportClause(identifier, pos, phaseModifier, skipJsDocLeadingAsterisks); + parseExpected(SyntaxKind.FromKeyword); + } + return importClause; +@@ -8471,7 +8486,7 @@ namespace Parser { + return finished; + } + +- function parseImportClause(identifier: Identifier | undefined, pos: number, isTypeOnly: boolean, skipJsDocLeadingAsterisks: boolean) { ++ function parseImportClause(identifier: Identifier | undefined, pos: number, phaseModifier: undefined | ImportPhaseModifierSyntaxKind, skipJsDocLeadingAsterisks: boolean) { + // ImportClause: + // ImportedDefaultBinding + // NameSpaceImport +@@ -8487,11 +8502,16 @@ namespace Parser { + parseOptional(SyntaxKind.CommaToken) + ) { + if (skipJsDocLeadingAsterisks) scanner.setSkipJsDocLeadingAsterisks(true); +- namedBindings = token() === SyntaxKind.AsteriskToken ? parseNamespaceImport() : parseNamedImportsOrExports(SyntaxKind.NamedImports); ++ if (token() === SyntaxKind.AsteriskToken) { ++ namedBindings = parseNamespaceImport(); ++ } ++ else { ++ namedBindings = parseNamedImportsOrExports(SyntaxKind.NamedImports); ++ } + if (skipJsDocLeadingAsterisks) scanner.setSkipJsDocLeadingAsterisks(false); + } + +- return finishNode(factory.createImportClause(isTypeOnly, identifier, namedBindings), pos); ++ return finishNode(factory.createImportClause(phaseModifier, identifier, namedBindings), pos); + } + + function parseModuleReference() { +@@ -9525,7 +9545,7 @@ namespace Parser { + identifier = parseIdentifier(); + } + +- const importClause = tryParseImportClause(identifier, afterImportTagPos, /*isTypeOnly*/ true, /*skipJsDocLeadingAsterisks*/ true); ++ const importClause = tryParseImportClause(identifier, afterImportTagPos, SyntaxKind.TypeKeyword, /*skipJsDocLeadingAsterisks*/ true); + const moduleSpecifier = parseModuleSpecifier(); + const attributes = tryParseImportAttributes(); + +diff --git a/src/compiler/scanner.ts b/src/compiler/scanner.ts +index 50e827c17..343df39ad 100644 +--- a/src/compiler/scanner.ts ++++ b/src/compiler/scanner.ts +@@ -151,6 +151,7 @@ export const textToKeywordObj: MapLike = { + debugger: SyntaxKind.DebuggerKeyword, + declare: SyntaxKind.DeclareKeyword, + default: SyntaxKind.DefaultKeyword, ++ defer: SyntaxKind.DeferKeyword, + delete: SyntaxKind.DeleteKeyword, + do: SyntaxKind.DoKeyword, + else: SyntaxKind.ElseKeyword, +diff --git a/src/compiler/transformers/declarations.ts b/src/compiler/transformers/declarations.ts +index 7c41bcccc..4b6941dc6 100644 +--- a/src/compiler/transformers/declarations.ts ++++ b/src/compiler/transformers/declarations.ts +@@ -877,6 +877,7 @@ export function transformDeclarations(context: TransformationContext): Transform + tryGetResolutionModeOverride(decl.attributes), + ); + } ++ const phaseModifier = decl.importClause.phaseModifier === SyntaxKind.DeferKeyword ? undefined : decl.importClause.phaseModifier; + // The `importClause` visibility corresponds to the default's visibility. + const visibleDefaultBinding = decl.importClause && decl.importClause.name && resolver.isDeclarationVisible(decl.importClause) ? decl.importClause.name : undefined; + if (!decl.importClause.namedBindings) { +@@ -886,7 +887,7 @@ export function transformDeclarations(context: TransformationContext): Transform + decl.modifiers, + factory.updateImportClause( + decl.importClause, +- decl.importClause.isTypeOnly, ++ phaseModifier, + visibleDefaultBinding, + /*namedBindings*/ undefined, + ), +@@ -902,7 +903,7 @@ export function transformDeclarations(context: TransformationContext): Transform + decl.modifiers, + factory.updateImportClause( + decl.importClause, +- decl.importClause.isTypeOnly, ++ phaseModifier, + visibleDefaultBinding, + namedBindings, + ), +@@ -918,7 +919,7 @@ export function transformDeclarations(context: TransformationContext): Transform + decl.modifiers, + factory.updateImportClause( + decl.importClause, +- decl.importClause.isTypeOnly, ++ phaseModifier, + visibleDefaultBinding, + bindingList && bindingList.length ? factory.updateNamedImports(decl.importClause.namedBindings, bindingList) : undefined, + ), +diff --git a/src/compiler/transformers/jsx.ts b/src/compiler/transformers/jsx.ts +index bcb0cbf8e..885f4c5d6 100644 +--- a/src/compiler/transformers/jsx.ts ++++ b/src/compiler/transformers/jsx.ts +@@ -172,7 +172,7 @@ export function transformJsx(context: TransformationContext): (x: SourceFile | B + for (const [importSource, importSpecifiersMap] of arrayFrom(currentFileState.utilizedImplicitRuntimeImports.entries())) { + if (isExternalModule(node)) { + // Add `import` statement +- const importStatement = factory.createImportDeclaration(/*modifiers*/ undefined, factory.createImportClause(/*isTypeOnly*/ false, /*name*/ undefined, factory.createNamedImports(arrayFrom(importSpecifiersMap.values()))), factory.createStringLiteral(importSource), /*attributes*/ undefined); ++ const importStatement = factory.createImportDeclaration(/*modifiers*/ undefined, factory.createImportClause(/*phaseModifier*/ undefined, /*name*/ undefined, factory.createNamedImports(arrayFrom(importSpecifiersMap.values()))), factory.createStringLiteral(importSource), /*attributes*/ undefined); + setParentRecursive(importStatement, /*incremental*/ false); + statements = insertStatementAfterCustomPrologue(statements.slice(), importStatement); + } +diff --git a/src/compiler/transformers/module/esnextAnd2015.ts b/src/compiler/transformers/module/esnextAnd2015.ts +index 40662f302..7776e2c4b 100644 +--- a/src/compiler/transformers/module/esnextAnd2015.ts ++++ b/src/compiler/transformers/module/esnextAnd2015.ts +@@ -219,7 +219,7 @@ export function transformECMAScriptModule(context: TransformationContext): (x: S + const importStatement = factory.createImportDeclaration( + /*modifiers*/ undefined, + factory.createImportClause( +- /*isTypeOnly*/ false, ++ /*phaseModifier*/ undefined, + /*name*/ undefined, + factory.createNamedImports([ + factory.createImportSpecifier(/*isTypeOnly*/ false, factory.createIdentifier("createRequire"), createRequireName), +@@ -351,7 +351,7 @@ export function transformECMAScriptModule(context: TransformationContext): (x: S + const importDecl = factory.createImportDeclaration( + /*modifiers*/ undefined, + factory.createImportClause( +- /*isTypeOnly*/ false, ++ /*phaseModifier*/ undefined, + /*name*/ undefined, + factory.createNamespaceImport( + synthName, +diff --git a/src/compiler/transformers/ts.ts b/src/compiler/transformers/ts.ts +index 75656cf5a..cc3da23d2 100644 +--- a/src/compiler/transformers/ts.ts ++++ b/src/compiler/transformers/ts.ts +@@ -2282,11 +2282,11 @@ export function transformTypeScript(context: TransformationContext): Transformer + * @param node The import clause node. + */ + function visitImportClause(node: ImportClause): VisitResult | undefined { +- Debug.assert(!node.isTypeOnly); ++ Debug.assert(node.phaseModifier !== SyntaxKind.TypeKeyword); + // Elide the import clause if we elide both its name and its named bindings. + const name = shouldEmitAliasDeclaration(node) ? node.name : undefined; + const namedBindings = visitNode(node.namedBindings, visitNamedImportBindings, isNamedImportBindings); +- return (name || namedBindings) ? factory.updateImportClause(node, /*isTypeOnly*/ false, name, namedBindings) : undefined; ++ return (name || namedBindings) ? factory.updateImportClause(node, node.phaseModifier, name, namedBindings) : undefined; + } + + /** +diff --git a/src/compiler/types.ts b/src/compiler/types.ts +index e1fd99936..b5e4d234e 100644 +--- a/src/compiler/types.ts ++++ b/src/compiler/types.ts +@@ -222,7 +222,8 @@ export const enum SyntaxKind { + GlobalKeyword, + BigIntKeyword, + OverrideKeyword, +- OfKeyword, // LastKeyword and LastToken and LastContextualKeyword ++ OfKeyword, ++ DeferKeyword, // LastKeyword and LastToken and LastContextualKeyword + + // Parse tree nodes + +@@ -462,7 +463,7 @@ export const enum SyntaxKind { + FirstReservedWord = BreakKeyword, + LastReservedWord = WithKeyword, + FirstKeyword = BreakKeyword, +- LastKeyword = OfKeyword, ++ LastKeyword = DeferKeyword, + FirstFutureReservedWord = ImplementsKeyword, + LastFutureReservedWord = YieldKeyword, + FirstTypeNode = TypePredicate, +@@ -487,7 +488,7 @@ export const enum SyntaxKind { + FirstJSDocTagNode = JSDocTag, + LastJSDocTagNode = JSDocImportTag, + /** @internal */ FirstContextualKeyword = AbstractKeyword, +- /** @internal */ LastContextualKeyword = OfKeyword, ++ /** @internal */ LastContextualKeyword = LastKeyword, + } + + export type TriviaSyntaxKind = +@@ -599,6 +600,7 @@ export type KeywordSyntaxKind = + | SyntaxKind.DebuggerKeyword + | SyntaxKind.DeclareKeyword + | SyntaxKind.DefaultKeyword ++ | SyntaxKind.DeferKeyword + | SyntaxKind.DeleteKeyword + | SyntaxKind.DoKeyword + | SyntaxKind.ElseKeyword +@@ -3099,7 +3101,7 @@ export interface SuperCall extends CallExpression { + } + + export interface ImportCall extends CallExpression { +- readonly expression: ImportExpression; ++ readonly expression: ImportExpression | ImportDeferProperty; + } + + export interface ExpressionWithTypeArguments extends MemberExpression, NodeWithTypeArguments { +@@ -3179,6 +3181,11 @@ export interface ImportMetaProperty extends MetaProperty { + readonly name: Identifier & { readonly escapedText: __String & "meta"; }; + } + ++export interface ImportDeferProperty extends MetaProperty { ++ readonly keywordToken: SyntaxKind.ImportKeyword; ++ readonly name: Identifier & { readonly escapedText: __String & "defer"; }; ++} ++ + /// A JSX expression of the form ... + export interface JsxElement extends PrimaryExpression { + readonly kind: SyntaxKind.JsxElement; +@@ -3711,11 +3718,15 @@ export type NamedExportBindings = + export interface ImportClause extends NamedDeclaration { + readonly kind: SyntaxKind.ImportClause; + readonly parent: ImportDeclaration | JSDocImportTag; ++ /** @deprecated Use `phaseModifier` instead */ + readonly isTypeOnly: boolean; ++ readonly phaseModifier: undefined | ImportPhaseModifierSyntaxKind; + readonly name?: Identifier; // Default binding + readonly namedBindings?: NamedImportBindings; + } + ++export type ImportPhaseModifierSyntaxKind = SyntaxKind.TypeKeyword | SyntaxKind.DeferKeyword; ++ + /** @deprecated */ + export type AssertionKey = ImportAttributeName; + +@@ -9068,8 +9079,12 @@ export interface NodeFactory { + updateImportEqualsDeclaration(node: ImportEqualsDeclaration, modifiers: readonly ModifierLike[] | undefined, isTypeOnly: boolean, name: Identifier, moduleReference: ModuleReference): ImportEqualsDeclaration; + createImportDeclaration(modifiers: readonly ModifierLike[] | undefined, importClause: ImportClause | undefined, moduleSpecifier: Expression, attributes?: ImportAttributes): ImportDeclaration; + updateImportDeclaration(node: ImportDeclaration, modifiers: readonly ModifierLike[] | undefined, importClause: ImportClause | undefined, moduleSpecifier: Expression, attributes: ImportAttributes | undefined): ImportDeclaration; +- createImportClause(isTypeOnly: boolean, name: Identifier | undefined, namedBindings: NamedImportBindings | undefined): ImportClause; +- updateImportClause(node: ImportClause, isTypeOnly: boolean, name: Identifier | undefined, namedBindings: NamedImportBindings | undefined): ImportClause; ++ createImportClause(phaseModifier: ImportPhaseModifierSyntaxKind | undefined, name: Identifier | undefined, namedBindings: NamedImportBindings | undefined): ImportClause; ++ // eslint-disable-next-line @typescript-eslint/unified-signatures -- Cannot unify due to the @deprecated tag ++ /** @deprecated */ createImportClause(isTypeOnly: boolean, name: Identifier | undefined, namedBindings: NamedImportBindings | undefined): ImportClause; ++ updateImportClause(node: ImportClause, phaseModifier: ImportPhaseModifierSyntaxKind | undefined, name: Identifier | undefined, namedBindings: NamedImportBindings | undefined): ImportClause; ++ // eslint-disable-next-line @typescript-eslint/unified-signatures -- Cannot unify due to the @deprecated tag ++ /** @deprecated */ updateImportClause(node: ImportClause, isTypeOnly: boolean, name: Identifier | undefined, namedBindings: NamedImportBindings | undefined): ImportClause; + /** @deprecated */ createAssertClause(elements: NodeArray, multiLine?: boolean): AssertClause; + /** @deprecated */ updateAssertClause(node: AssertClause, elements: NodeArray, multiLine?: boolean): AssertClause; + /** @deprecated */ createAssertEntry(name: AssertionKey, value: Expression): AssertEntry; +diff --git a/src/compiler/utilities.ts b/src/compiler/utilities.ts +index b16b350f7..1bae579e1 100644 +--- a/src/compiler/utilities.ts ++++ b/src/compiler/utilities.ts +@@ -2648,7 +2648,13 @@ export function isSuperCall(n: Node): n is SuperCall { + + /** @internal */ + export function isImportCall(n: Node): n is ImportCall { +- return n.kind === SyntaxKind.CallExpression && (n as CallExpression).expression.kind === SyntaxKind.ImportKeyword; ++ if (n.kind !== SyntaxKind.CallExpression) return false; ++ const e = (n as CallExpression).expression; ++ return e.kind === SyntaxKind.ImportKeyword || ( ++ isMetaProperty(e) ++ && e.keywordToken === SyntaxKind.ImportKeyword ++ && e.name.escapedText === "defer" ++ ); + } + + /** @internal */ +@@ -3599,8 +3605,10 @@ export function isExpressionNode(node: Node): boolean { + case SyntaxKind.JsxFragment: + case SyntaxKind.YieldExpression: + case SyntaxKind.AwaitExpression: +- case SyntaxKind.MetaProperty: + return true; ++ case SyntaxKind.MetaProperty: ++ // `import.defer` in `import.defer(...)` is not an expression ++ return !isImportCall(node.parent) || node.parent.expression !== node; + case SyntaxKind.ExpressionWithTypeArguments: + return !isHeritageClause(node.parent) && !isJSDocAugmentsTag(node.parent); + case SyntaxKind.QualifiedName: +@@ -10939,10 +10947,11 @@ export function isTypeDeclaration(node: Node): node is TypeParameterDeclaration + case SyntaxKind.JSDocEnumTag: + return true; + case SyntaxKind.ImportClause: +- return (node as ImportClause).isTypeOnly; ++ return (node as ImportClause).phaseModifier === SyntaxKind.TypeKeyword; + case SyntaxKind.ImportSpecifier: ++ return (node as ImportSpecifier).parent.parent.phaseModifier === SyntaxKind.TypeKeyword; + case SyntaxKind.ExportSpecifier: +- return (node as ImportSpecifier | ExportSpecifier).parent.parent.isTypeOnly; ++ return (node as ExportSpecifier).parent.parent.isTypeOnly; + default: + return false; + } +@@ -12114,7 +12123,7 @@ function getNodeAtPosition(sourceFile: SourceFile, position: number, includeJSDo + }; + while (true) { + const child = isJavaScriptFile && includeJSDoc && hasJSDocNodes(current) && forEach(current.jsDoc, getContainingChild) || forEachChild(current, getContainingChild); +- if (!child) { ++ if (!child || isMetaProperty(child)) { + return current; + } + current = child; +diff --git a/src/compiler/utilitiesPublic.ts b/src/compiler/utilitiesPublic.ts +index 02623678a..36eba18db 100644 +--- a/src/compiler/utilitiesPublic.ts ++++ b/src/compiler/utilitiesPublic.ts +@@ -1534,12 +1534,13 @@ export function isImportOrExportSpecifier(node: Node): node is ImportSpecifier | + export function isTypeOnlyImportDeclaration(node: Node): node is TypeOnlyImportDeclaration { + switch (node.kind) { + case SyntaxKind.ImportSpecifier: +- return (node as ImportSpecifier).isTypeOnly || (node as ImportSpecifier).parent.parent.isTypeOnly; ++ return (node as ImportSpecifier).isTypeOnly || (node as ImportSpecifier).parent.parent.phaseModifier === SyntaxKind.TypeKeyword; + case SyntaxKind.NamespaceImport: +- return (node as NamespaceImport).parent.isTypeOnly; ++ return (node as NamespaceImport).parent.phaseModifier === SyntaxKind.TypeKeyword; + case SyntaxKind.ImportClause: ++ return (node as ImportClause).phaseModifier === SyntaxKind.TypeKeyword; + case SyntaxKind.ImportEqualsDeclaration: +- return (node as ImportClause | ImportEqualsDeclaration).isTypeOnly; ++ return (node as ImportEqualsDeclaration).isTypeOnly; + } + return false; + } +diff --git a/src/compiler/visitorPublic.ts b/src/compiler/visitorPublic.ts +index dbd49379e..d1aee94bc 100644 +--- a/src/compiler/visitorPublic.ts ++++ b/src/compiler/visitorPublic.ts +@@ -1549,7 +1549,7 @@ const visitEachChildTable: VisitEachChildTable = { + [SyntaxKind.ImportClause]: function visitEachChildOfImportClause(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { + return context.factory.updateImportClause( + node, +- node.isTypeOnly, ++ node.phaseModifier, + nodeVisitor(node.name, visitor, isIdentifier), + nodeVisitor(node.namedBindings, visitor, isNamedImportBindings), + ); +diff --git a/src/services/codefixes/convertToTypeOnlyImport.ts b/src/services/codefixes/convertToTypeOnlyImport.ts +index 3fdc81f3e..a5f2b191c 100644 +--- a/src/services/codefixes/convertToTypeOnlyImport.ts ++++ b/src/services/codefixes/convertToTypeOnlyImport.ts +@@ -125,13 +125,13 @@ function doChange(changes: textChanges.ChangeTracker, sourceFile: SourceFile, de + changes.replaceNodeWithNodes(sourceFile, declaration, [ + factory.createImportDeclaration( + getSynthesizedDeepClones(declaration.modifiers, /*includeTrivia*/ true), +- factory.createImportClause(/*isTypeOnly*/ true, getSynthesizedDeepClone(importClause.name, /*includeTrivia*/ true), /*namedBindings*/ undefined), ++ factory.createImportClause(SyntaxKind.TypeKeyword, getSynthesizedDeepClone(importClause.name, /*includeTrivia*/ true), /*namedBindings*/ undefined), + getSynthesizedDeepClone(declaration.moduleSpecifier, /*includeTrivia*/ true), + getSynthesizedDeepClone(declaration.attributes, /*includeTrivia*/ true), + ), + factory.createImportDeclaration( + getSynthesizedDeepClones(declaration.modifiers, /*includeTrivia*/ true), +- factory.createImportClause(/*isTypeOnly*/ true, /*name*/ undefined, getSynthesizedDeepClone(importClause.namedBindings, /*includeTrivia*/ true)), ++ factory.createImportClause(SyntaxKind.TypeKeyword, /*name*/ undefined, getSynthesizedDeepClone(importClause.namedBindings, /*includeTrivia*/ true)), + getSynthesizedDeepClone(declaration.moduleSpecifier, /*includeTrivia*/ true), + getSynthesizedDeepClone(declaration.attributes, /*includeTrivia*/ true), + ), +@@ -144,7 +144,7 @@ function doChange(changes: textChanges.ChangeTracker, sourceFile: SourceFile, de + sameMap(importClause.namedBindings.elements, e => factory.updateImportSpecifier(e, /*isTypeOnly*/ false, e.propertyName, e.name)), + ) + : importClause.namedBindings; +- const importDeclaration = factory.updateImportDeclaration(declaration, declaration.modifiers, factory.updateImportClause(importClause, /*isTypeOnly*/ true, importClause.name, newNamedBindings), declaration.moduleSpecifier, declaration.attributes); ++ const importDeclaration = factory.updateImportDeclaration(declaration, declaration.modifiers, factory.updateImportClause(importClause, SyntaxKind.TypeKeyword, importClause.name, newNamedBindings), declaration.moduleSpecifier, declaration.attributes); + changes.replaceNode(sourceFile, declaration, importDeclaration); + } + } +diff --git a/src/services/codefixes/importFixes.ts b/src/services/codefixes/importFixes.ts +index e2b83f0c5..802ad5977 100644 +--- a/src/services/codefixes/importFixes.ts ++++ b/src/services/codefixes/importFixes.ts +@@ -622,7 +622,7 @@ function createImportAdderWorker(sourceFile: SourceFile | FutureSourceFile, prog + declaration.importClause!, + factory.updateImportClause( + declaration.importClause!, +- declaration.importClause!.isTypeOnly, ++ declaration.importClause!.phaseModifier, + declaration.importClause!.name, + /*namedBindings*/ undefined, + ), +@@ -715,7 +715,7 @@ function createImportAdderWorker(sourceFile: SourceFile | FutureSourceFile, prog + d.modifiers, + d.importClause && factory.updateImportClause( + d.importClause, +- d.importClause.isTypeOnly, ++ d.importClause.phaseModifier, + verbatimImports.has(d.importClause) ? d.importClause.name : undefined, + verbatimImports.has(d.importClause.namedBindings as NamespaceImport) + ? d.importClause.namedBindings as NamespaceImport : +@@ -2080,7 +2080,7 @@ function getNewImports( + : factory.createImportDeclaration( + /*modifiers*/ undefined, + factory.createImportClause( +- shouldUseTypeOnly(namespaceLikeImport, preferences), ++ shouldUseTypeOnly(namespaceLikeImport, preferences) ? SyntaxKind.TypeKeyword : undefined, + /*name*/ undefined, + factory.createNamespaceImport(factory.createIdentifier(namespaceLikeImport.name)), + ), +diff --git a/src/services/codefixes/requireInTs.ts b/src/services/codefixes/requireInTs.ts +index 500a88aad..b627fbbc1 100644 +--- a/src/services/codefixes/requireInTs.ts ++++ b/src/services/codefixes/requireInTs.ts +@@ -61,7 +61,7 @@ function doChange(changes: textChanges.ChangeTracker, sourceFile: SourceFile, in + statement, + defaultImportName && !allowSyntheticDefaults + ? factory.createImportEqualsDeclaration(/*modifiers*/ undefined, /*isTypeOnly*/ false, defaultImportName, factory.createExternalModuleReference(moduleSpecifier)) +- : factory.createImportDeclaration(/*modifiers*/ undefined, factory.createImportClause(/*isTypeOnly*/ false, defaultImportName, namedImports), moduleSpecifier, /*attributes*/ undefined), ++ : factory.createImportDeclaration(/*modifiers*/ undefined, factory.createImportClause(/*phaseModifier*/ undefined, defaultImportName, namedImports), moduleSpecifier, /*attributes*/ undefined), + ); + } + +diff --git a/src/services/codefixes/splitTypeOnlyImport.ts b/src/services/codefixes/splitTypeOnlyImport.ts +index 967d6fc83..70267cae3 100644 +--- a/src/services/codefixes/splitTypeOnlyImport.ts ++++ b/src/services/codefixes/splitTypeOnlyImport.ts +@@ -51,7 +51,7 @@ function splitTypeOnlyImport(changes: textChanges.ChangeTracker, importDeclarati + factory.updateImportDeclaration( + importDeclaration, + importDeclaration.modifiers, +- factory.updateImportClause(importClause, importClause.isTypeOnly, importClause.name, /*namedBindings*/ undefined), ++ factory.updateImportClause(importClause, importClause.phaseModifier, importClause.name, /*namedBindings*/ undefined), + importDeclaration.moduleSpecifier, + importDeclaration.attributes, + ), +@@ -62,7 +62,7 @@ function splitTypeOnlyImport(changes: textChanges.ChangeTracker, importDeclarati + importDeclaration, + factory.createImportDeclaration( + /*modifiers*/ undefined, +- factory.updateImportClause(importClause, importClause.isTypeOnly, /*name*/ undefined, importClause.namedBindings), ++ factory.updateImportClause(importClause, importClause.phaseModifier, /*name*/ undefined, importClause.namedBindings), + importDeclaration.moduleSpecifier, + importDeclaration.attributes, + ), +diff --git a/src/services/organizeImports.ts b/src/services/organizeImports.ts +index 1508ba767..e1343a61d 100644 +--- a/src/services/organizeImports.ts ++++ b/src/services/organizeImports.ts +@@ -639,7 +639,7 @@ function updateImportDeclarationAndClause( + return factory.updateImportDeclaration( + importDeclaration, + importDeclaration.modifiers, +- factory.updateImportClause(importDeclaration.importClause!, importDeclaration.importClause!.isTypeOnly, name, namedBindings), // TODO: GH#18217 ++ factory.updateImportClause(importDeclaration.importClause!, importDeclaration.importClause!.phaseModifier, name, namedBindings), // TODO: GH#18217 + importDeclaration.moduleSpecifier, + importDeclaration.attributes, + ); +diff --git a/src/services/refactors/convertImport.ts b/src/services/refactors/convertImport.ts +index 1b21d2d5b..a628c7746 100644 +--- a/src/services/refactors/convertImport.ts ++++ b/src/services/refactors/convertImport.ts +@@ -290,5 +290,5 @@ function createImport(node: ImportDeclaration, defaultImportName: Identifier | u + } + + function createImportClause(defaultImportName: Identifier | undefined, elements: readonly ImportSpecifier[] | undefined) { +- return factory.createImportClause(/*isTypeOnly*/ false, defaultImportName, elements && elements.length ? factory.createNamedImports(elements) : undefined); ++ return factory.createImportClause(/*phaseModifier*/ undefined, defaultImportName, elements && elements.length ? factory.createNamedImports(elements) : undefined); + } +diff --git a/src/services/refactors/moveToFile.ts b/src/services/refactors/moveToFile.ts +index 18fd421d6..603f049a0 100644 +--- a/src/services/refactors/moveToFile.ts ++++ b/src/services/refactors/moveToFile.ts +@@ -423,7 +423,7 @@ function updateNamespaceLikeImportNode(node: SupportedImport, newNamespaceName: + case SyntaxKind.ImportDeclaration: + return factory.createImportDeclaration( + /*modifiers*/ undefined, +- factory.createImportClause(/*isTypeOnly*/ false, /*name*/ undefined, factory.createNamespaceImport(newNamespaceId)), ++ factory.createImportClause(/*phaseModifier*/ undefined, /*name*/ undefined, factory.createNamespaceImport(newNamespaceId)), + newModuleString, + /*attributes*/ undefined, + ); +@@ -645,7 +645,7 @@ function filterImport(i: SupportedImport, moduleSpecifier: StringLiteralLike, ke + const defaultImport = clause.name && keep(clause.name) ? clause.name : undefined; + const namedBindings = clause.namedBindings && filterNamedBindings(clause.namedBindings, keep); + return defaultImport || namedBindings +- ? factory.createImportDeclaration(/*modifiers*/ undefined, factory.createImportClause(clause.isTypeOnly, defaultImport, namedBindings), getSynthesizedDeepClone(moduleSpecifier), /*attributes*/ undefined) ++ ? factory.createImportDeclaration(/*modifiers*/ undefined, factory.createImportClause(clause.phaseModifier, defaultImport, namedBindings), getSynthesizedDeepClone(moduleSpecifier), /*attributes*/ undefined) + : undefined; + } + case SyntaxKind.ImportEqualsDeclaration: +diff --git a/src/services/utilities.ts b/src/services/utilities.ts +index 6ae41b2b0..75a1cbc94 100644 +--- a/src/services/utilities.ts ++++ b/src/services/utilities.ts +@@ -2488,7 +2488,7 @@ export function makeImport(defaultImport: Identifier | undefined, namedImports: + return factory.createImportDeclaration( + /*modifiers*/ undefined, + defaultImport || namedImports +- ? factory.createImportClause(!!isTypeOnly, defaultImport, namedImports && namedImports.length ? factory.createNamedImports(namedImports) : undefined) ++ ? factory.createImportClause(isTypeOnly ? SyntaxKind.TypeKeyword : undefined, defaultImport, namedImports && namedImports.length ? factory.createNamedImports(namedImports) : undefined) + : undefined, + typeof moduleSpecifier === "string" ? makeStringLiteral(moduleSpecifier, quotePreference) : moduleSpecifier, + /*attributes*/ undefined, diff --git a/TypeScript_4/solution/solve.sh b/TypeScript_4/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..04d2cdd558a05593c6373ab47313e0e441927403 --- /dev/null +++ b/TypeScript_4/solution/solve.sh @@ -0,0 +1,7 @@ +#!/usr/bin/env bash +set -euo pipefail + +cd /workspace/typescript +patch=${LOLBENCH_ORACLE_PATCH:-/solution/solution.patch} +git apply "$patch" +lolbench-submit diff --git a/TypeScript_4/task.toml b/TypeScript_4/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..80d7e61a9e212c4ac8108c14ed03c56ffc20b523 --- /dev/null +++ b/TypeScript_4/task.toml @@ -0,0 +1,60 @@ +schema_version = "1.3" + +[task] +name = "lolbench/TypeScript_4" +description = "Implement TypeScript import defer." +authors = [{ name = "LoLBench maintainers" }] +keywords = ["lolbench", "coding-agent", "typescript"] + +[metadata] +instance_id = "TypeScript_4" +source_instance_id = "TypeScript_PR-60757_import-defer" +source_slug = "TypeScript_PR-60757_import-defer" +docker_slug = "TypeScript_PR-60757_import-defer" +dockerhub_image = "smartdub26/lolbench-linux:TypeScript_4-1.0.0" +project = "TypeScript" +repo = "microsoft/TypeScript" +requirement_doc = "https://github.com/microsoft/TypeScript/pull/60757" +pr_link = "https://github.com/microsoft/TypeScript/pull/60757" +base_commit = "cd341998a98b71275d4b4d6f41c08d9d0eb75d93" +merge_commit = "b352c0d4062e1c91099f1c026bbd0e47074819c7" +test_level = "system" +source_history_policy = "ancestors-only" +lolbench_test_modes = ["orig", "aug", "union"] +default_lolbench_suite = "union" +canonical_lolbench_suite = "union" +augmentation_available = true +verifier_network_policy = "public" +verifier_network_reason = "The Harbor verifier runs in a separate container and may use network access; migrated LoLBench verifier assets are mounted only in the verifier phase." + +[environment] +build_timeout_sec = 3600.0 +docker_image = "smartdub26/lolbench-linux:TypeScript_4-1.0.0" +network_mode = "public" +os = "linux" +cpus = 4 +memory_mb = 8192 +storage_mb = 20480 + +[agent] +timeout_sec = 28800.0 +user = "agent" +network_mode = "allowlist" +allowed_hosts = ["openrouter.ai", "api.openai.com", "api.anthropic.com"] + +[verifier] +timeout_sec = 14400.0 +user = "root" +environment_mode = "separate" +network_mode = "public" + +[verifier.env] +LOLBENCH_SUITE = "union" + +[verifier.environment] +docker_image = "smartdub26/lolbench-linux:TypeScript_4-1.0.0" +network_mode = "public" +os = "linux" +cpus = 4 +memory_mb = 8192 +storage_mb = 20480 diff --git a/TypeScript_4/tests/docker-compose.yaml b/TypeScript_4/tests/docker-compose.yaml new file mode 100644 index 0000000000000000000000000000000000000000..f5091b9298e127a1efbe69deeed699c907e025c1 --- /dev/null +++ b/TypeScript_4/tests/docker-compose.yaml @@ -0,0 +1,16 @@ +services: + main: + pull_policy: missing + volumes: + - type: bind + source: . + target: /tests + read_only: true + - type: bind + source: ./private + target: /opt/lolbench/private + read_only: true + - type: bind + source: ../solution + target: /solution + read_only: true diff --git a/TypeScript_4/tests/private/eval_tests.patch b/TypeScript_4/tests/private/eval_tests.patch new file mode 100644 index 0000000000000000000000000000000000000000..fc15ad1e599e4211523805929eeabc81e51d2c20 --- /dev/null +++ b/TypeScript_4/tests/private/eval_tests.patch @@ -0,0 +1,3581 @@ +diff --git a/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.importTag1.json b/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.importTag1.json +index 817598cb1..6419e4dc7 100644 +--- a/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.importTag1.json ++++ b/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.importTag1.json +@@ -26,6 +26,7 @@ + "modifierFlagsCache": 0, + "transformFlags": 1, + "isTypeOnly": true, ++ "phaseModifier": 156, + "name": { + "kind": "Identifier", + "pos": 16, +diff --git a/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.importTag2.json b/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.importTag2.json +index d11fa4eb2..3094ffd46 100644 +--- a/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.importTag2.json ++++ b/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.importTag2.json +@@ -26,6 +26,7 @@ + "modifierFlagsCache": 0, + "transformFlags": 1, + "isTypeOnly": true, ++ "phaseModifier": 156, + "namedBindings": { + "kind": "NamedImports", + "pos": 16, +diff --git a/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.importTag3.json b/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.importTag3.json +index a34c07e99..8352b03a7 100644 +--- a/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.importTag3.json ++++ b/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.importTag3.json +@@ -26,6 +26,7 @@ + "modifierFlagsCache": 0, + "transformFlags": 1, + "isTypeOnly": true, ++ "phaseModifier": 156, + "namedBindings": { + "kind": "NamespaceImport", + "pos": 16, +diff --git a/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.importTag4.json b/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.importTag4.json +index e60e392ff..a681ea563 100644 +--- a/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.importTag4.json ++++ b/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.importTag4.json +@@ -27,6 +27,7 @@ + "modifierFlagsCache": 0, + "transformFlags": 1, + "isTypeOnly": true, ++ "phaseModifier": 156, + "namedBindings": { + "kind": "NamespaceImport", + "pos": 16, +diff --git a/tests/baselines/reference/api/typescript.d.ts b/tests/baselines/reference/api/typescript.d.ts +index 9264a82e4..b810088c4 100644 +--- a/tests/baselines/reference/api/typescript.d.ts ++++ b/tests/baselines/reference/api/typescript.d.ts +@@ -3841,203 +3841,204 @@ declare namespace ts { + BigIntKeyword = 163, + OverrideKeyword = 164, + OfKeyword = 165, +- QualifiedName = 166, +- ComputedPropertyName = 167, +- TypeParameter = 168, +- Parameter = 169, +- Decorator = 170, +- PropertySignature = 171, +- PropertyDeclaration = 172, +- MethodSignature = 173, +- MethodDeclaration = 174, +- ClassStaticBlockDeclaration = 175, +- Constructor = 176, +- GetAccessor = 177, +- SetAccessor = 178, +- CallSignature = 179, +- ConstructSignature = 180, +- IndexSignature = 181, +- TypePredicate = 182, +- TypeReference = 183, +- FunctionType = 184, +- ConstructorType = 185, +- TypeQuery = 186, +- TypeLiteral = 187, +- ArrayType = 188, +- TupleType = 189, +- OptionalType = 190, +- RestType = 191, +- UnionType = 192, +- IntersectionType = 193, +- ConditionalType = 194, +- InferType = 195, +- ParenthesizedType = 196, +- ThisType = 197, +- TypeOperator = 198, +- IndexedAccessType = 199, +- MappedType = 200, +- LiteralType = 201, +- NamedTupleMember = 202, +- TemplateLiteralType = 203, +- TemplateLiteralTypeSpan = 204, +- ImportType = 205, +- ObjectBindingPattern = 206, +- ArrayBindingPattern = 207, +- BindingElement = 208, +- ArrayLiteralExpression = 209, +- ObjectLiteralExpression = 210, +- PropertyAccessExpression = 211, +- ElementAccessExpression = 212, +- CallExpression = 213, +- NewExpression = 214, +- TaggedTemplateExpression = 215, +- TypeAssertionExpression = 216, +- ParenthesizedExpression = 217, +- FunctionExpression = 218, +- ArrowFunction = 219, +- DeleteExpression = 220, +- TypeOfExpression = 221, +- VoidExpression = 222, +- AwaitExpression = 223, +- PrefixUnaryExpression = 224, +- PostfixUnaryExpression = 225, +- BinaryExpression = 226, +- ConditionalExpression = 227, +- TemplateExpression = 228, +- YieldExpression = 229, +- SpreadElement = 230, +- ClassExpression = 231, +- OmittedExpression = 232, +- ExpressionWithTypeArguments = 233, +- AsExpression = 234, +- NonNullExpression = 235, +- MetaProperty = 236, +- SyntheticExpression = 237, +- SatisfiesExpression = 238, +- TemplateSpan = 239, +- SemicolonClassElement = 240, +- Block = 241, +- EmptyStatement = 242, +- VariableStatement = 243, +- ExpressionStatement = 244, +- IfStatement = 245, +- DoStatement = 246, +- WhileStatement = 247, +- ForStatement = 248, +- ForInStatement = 249, +- ForOfStatement = 250, +- ContinueStatement = 251, +- BreakStatement = 252, +- ReturnStatement = 253, +- WithStatement = 254, +- SwitchStatement = 255, +- LabeledStatement = 256, +- ThrowStatement = 257, +- TryStatement = 258, +- DebuggerStatement = 259, +- VariableDeclaration = 260, +- VariableDeclarationList = 261, +- FunctionDeclaration = 262, +- ClassDeclaration = 263, +- InterfaceDeclaration = 264, +- TypeAliasDeclaration = 265, +- EnumDeclaration = 266, +- ModuleDeclaration = 267, +- ModuleBlock = 268, +- CaseBlock = 269, +- NamespaceExportDeclaration = 270, +- ImportEqualsDeclaration = 271, +- ImportDeclaration = 272, +- ImportClause = 273, +- NamespaceImport = 274, +- NamedImports = 275, +- ImportSpecifier = 276, +- ExportAssignment = 277, +- ExportDeclaration = 278, +- NamedExports = 279, +- NamespaceExport = 280, +- ExportSpecifier = 281, +- MissingDeclaration = 282, +- ExternalModuleReference = 283, +- JsxElement = 284, +- JsxSelfClosingElement = 285, +- JsxOpeningElement = 286, +- JsxClosingElement = 287, +- JsxFragment = 288, +- JsxOpeningFragment = 289, +- JsxClosingFragment = 290, +- JsxAttribute = 291, +- JsxAttributes = 292, +- JsxSpreadAttribute = 293, +- JsxExpression = 294, +- JsxNamespacedName = 295, +- CaseClause = 296, +- DefaultClause = 297, +- HeritageClause = 298, +- CatchClause = 299, +- ImportAttributes = 300, +- ImportAttribute = 301, +- /** @deprecated */ AssertClause = 300, +- /** @deprecated */ AssertEntry = 301, +- /** @deprecated */ ImportTypeAssertionContainer = 302, +- PropertyAssignment = 303, +- ShorthandPropertyAssignment = 304, +- SpreadAssignment = 305, +- EnumMember = 306, +- SourceFile = 307, +- Bundle = 308, +- JSDocTypeExpression = 309, +- JSDocNameReference = 310, +- JSDocMemberName = 311, +- JSDocAllType = 312, +- JSDocUnknownType = 313, +- JSDocNullableType = 314, +- JSDocNonNullableType = 315, +- JSDocOptionalType = 316, +- JSDocFunctionType = 317, +- JSDocVariadicType = 318, +- JSDocNamepathType = 319, +- JSDoc = 320, ++ DeferKeyword = 166, ++ QualifiedName = 167, ++ ComputedPropertyName = 168, ++ TypeParameter = 169, ++ Parameter = 170, ++ Decorator = 171, ++ PropertySignature = 172, ++ PropertyDeclaration = 173, ++ MethodSignature = 174, ++ MethodDeclaration = 175, ++ ClassStaticBlockDeclaration = 176, ++ Constructor = 177, ++ GetAccessor = 178, ++ SetAccessor = 179, ++ CallSignature = 180, ++ ConstructSignature = 181, ++ IndexSignature = 182, ++ TypePredicate = 183, ++ TypeReference = 184, ++ FunctionType = 185, ++ ConstructorType = 186, ++ TypeQuery = 187, ++ TypeLiteral = 188, ++ ArrayType = 189, ++ TupleType = 190, ++ OptionalType = 191, ++ RestType = 192, ++ UnionType = 193, ++ IntersectionType = 194, ++ ConditionalType = 195, ++ InferType = 196, ++ ParenthesizedType = 197, ++ ThisType = 198, ++ TypeOperator = 199, ++ IndexedAccessType = 200, ++ MappedType = 201, ++ LiteralType = 202, ++ NamedTupleMember = 203, ++ TemplateLiteralType = 204, ++ TemplateLiteralTypeSpan = 205, ++ ImportType = 206, ++ ObjectBindingPattern = 207, ++ ArrayBindingPattern = 208, ++ BindingElement = 209, ++ ArrayLiteralExpression = 210, ++ ObjectLiteralExpression = 211, ++ PropertyAccessExpression = 212, ++ ElementAccessExpression = 213, ++ CallExpression = 214, ++ NewExpression = 215, ++ TaggedTemplateExpression = 216, ++ TypeAssertionExpression = 217, ++ ParenthesizedExpression = 218, ++ FunctionExpression = 219, ++ ArrowFunction = 220, ++ DeleteExpression = 221, ++ TypeOfExpression = 222, ++ VoidExpression = 223, ++ AwaitExpression = 224, ++ PrefixUnaryExpression = 225, ++ PostfixUnaryExpression = 226, ++ BinaryExpression = 227, ++ ConditionalExpression = 228, ++ TemplateExpression = 229, ++ YieldExpression = 230, ++ SpreadElement = 231, ++ ClassExpression = 232, ++ OmittedExpression = 233, ++ ExpressionWithTypeArguments = 234, ++ AsExpression = 235, ++ NonNullExpression = 236, ++ MetaProperty = 237, ++ SyntheticExpression = 238, ++ SatisfiesExpression = 239, ++ TemplateSpan = 240, ++ SemicolonClassElement = 241, ++ Block = 242, ++ EmptyStatement = 243, ++ VariableStatement = 244, ++ ExpressionStatement = 245, ++ IfStatement = 246, ++ DoStatement = 247, ++ WhileStatement = 248, ++ ForStatement = 249, ++ ForInStatement = 250, ++ ForOfStatement = 251, ++ ContinueStatement = 252, ++ BreakStatement = 253, ++ ReturnStatement = 254, ++ WithStatement = 255, ++ SwitchStatement = 256, ++ LabeledStatement = 257, ++ ThrowStatement = 258, ++ TryStatement = 259, ++ DebuggerStatement = 260, ++ VariableDeclaration = 261, ++ VariableDeclarationList = 262, ++ FunctionDeclaration = 263, ++ ClassDeclaration = 264, ++ InterfaceDeclaration = 265, ++ TypeAliasDeclaration = 266, ++ EnumDeclaration = 267, ++ ModuleDeclaration = 268, ++ ModuleBlock = 269, ++ CaseBlock = 270, ++ NamespaceExportDeclaration = 271, ++ ImportEqualsDeclaration = 272, ++ ImportDeclaration = 273, ++ ImportClause = 274, ++ NamespaceImport = 275, ++ NamedImports = 276, ++ ImportSpecifier = 277, ++ ExportAssignment = 278, ++ ExportDeclaration = 279, ++ NamedExports = 280, ++ NamespaceExport = 281, ++ ExportSpecifier = 282, ++ MissingDeclaration = 283, ++ ExternalModuleReference = 284, ++ JsxElement = 285, ++ JsxSelfClosingElement = 286, ++ JsxOpeningElement = 287, ++ JsxClosingElement = 288, ++ JsxFragment = 289, ++ JsxOpeningFragment = 290, ++ JsxClosingFragment = 291, ++ JsxAttribute = 292, ++ JsxAttributes = 293, ++ JsxSpreadAttribute = 294, ++ JsxExpression = 295, ++ JsxNamespacedName = 296, ++ CaseClause = 297, ++ DefaultClause = 298, ++ HeritageClause = 299, ++ CatchClause = 300, ++ ImportAttributes = 301, ++ ImportAttribute = 302, ++ /** @deprecated */ AssertClause = 301, ++ /** @deprecated */ AssertEntry = 302, ++ /** @deprecated */ ImportTypeAssertionContainer = 303, ++ PropertyAssignment = 304, ++ ShorthandPropertyAssignment = 305, ++ SpreadAssignment = 306, ++ EnumMember = 307, ++ SourceFile = 308, ++ Bundle = 309, ++ JSDocTypeExpression = 310, ++ JSDocNameReference = 311, ++ JSDocMemberName = 312, ++ JSDocAllType = 313, ++ JSDocUnknownType = 314, ++ JSDocNullableType = 315, ++ JSDocNonNullableType = 316, ++ JSDocOptionalType = 317, ++ JSDocFunctionType = 318, ++ JSDocVariadicType = 319, ++ JSDocNamepathType = 320, ++ JSDoc = 321, + /** @deprecated Use SyntaxKind.JSDoc */ +- JSDocComment = 320, +- JSDocText = 321, +- JSDocTypeLiteral = 322, +- JSDocSignature = 323, +- JSDocLink = 324, +- JSDocLinkCode = 325, +- JSDocLinkPlain = 326, +- JSDocTag = 327, +- JSDocAugmentsTag = 328, +- JSDocImplementsTag = 329, +- JSDocAuthorTag = 330, +- JSDocDeprecatedTag = 331, +- JSDocClassTag = 332, +- JSDocPublicTag = 333, +- JSDocPrivateTag = 334, +- JSDocProtectedTag = 335, +- JSDocReadonlyTag = 336, +- JSDocOverrideTag = 337, +- JSDocCallbackTag = 338, +- JSDocOverloadTag = 339, +- JSDocEnumTag = 340, +- JSDocParameterTag = 341, +- JSDocReturnTag = 342, +- JSDocThisTag = 343, +- JSDocTypeTag = 344, +- JSDocTemplateTag = 345, +- JSDocTypedefTag = 346, +- JSDocSeeTag = 347, +- JSDocPropertyTag = 348, +- JSDocThrowsTag = 349, +- JSDocSatisfiesTag = 350, +- JSDocImportTag = 351, +- SyntaxList = 352, +- NotEmittedStatement = 353, +- NotEmittedTypeElement = 354, +- PartiallyEmittedExpression = 355, +- CommaListExpression = 356, +- SyntheticReferenceExpression = 357, +- Count = 358, ++ JSDocComment = 321, ++ JSDocText = 322, ++ JSDocTypeLiteral = 323, ++ JSDocSignature = 324, ++ JSDocLink = 325, ++ JSDocLinkCode = 326, ++ JSDocLinkPlain = 327, ++ JSDocTag = 328, ++ JSDocAugmentsTag = 329, ++ JSDocImplementsTag = 330, ++ JSDocAuthorTag = 331, ++ JSDocDeprecatedTag = 332, ++ JSDocClassTag = 333, ++ JSDocPublicTag = 334, ++ JSDocPrivateTag = 335, ++ JSDocProtectedTag = 336, ++ JSDocReadonlyTag = 337, ++ JSDocOverrideTag = 338, ++ JSDocCallbackTag = 339, ++ JSDocOverloadTag = 340, ++ JSDocEnumTag = 341, ++ JSDocParameterTag = 342, ++ JSDocReturnTag = 343, ++ JSDocThisTag = 344, ++ JSDocTypeTag = 345, ++ JSDocTemplateTag = 346, ++ JSDocTypedefTag = 347, ++ JSDocSeeTag = 348, ++ JSDocPropertyTag = 349, ++ JSDocThrowsTag = 350, ++ JSDocSatisfiesTag = 351, ++ JSDocImportTag = 352, ++ SyntaxList = 353, ++ NotEmittedStatement = 354, ++ NotEmittedTypeElement = 355, ++ PartiallyEmittedExpression = 356, ++ CommaListExpression = 357, ++ SyntheticReferenceExpression = 358, ++ Count = 359, + FirstAssignment = 64, + LastAssignment = 79, + FirstCompoundAssignment = 65, +@@ -4045,15 +4046,15 @@ declare namespace ts { + FirstReservedWord = 83, + LastReservedWord = 118, + FirstKeyword = 83, +- LastKeyword = 165, ++ LastKeyword = 166, + FirstFutureReservedWord = 119, + LastFutureReservedWord = 127, +- FirstTypeNode = 182, +- LastTypeNode = 205, ++ FirstTypeNode = 183, ++ LastTypeNode = 206, + FirstPunctuation = 19, + LastPunctuation = 79, + FirstToken = 0, +- LastToken = 165, ++ LastToken = 166, + FirstTriviaToken = 2, + LastTriviaToken = 7, + FirstLiteralToken = 9, +@@ -4062,13 +4063,13 @@ declare namespace ts { + LastTemplateToken = 18, + FirstBinaryOperator = 30, + LastBinaryOperator = 79, +- FirstStatement = 243, +- LastStatement = 259, +- FirstNode = 166, +- FirstJSDocNode = 309, +- LastJSDocNode = 351, +- FirstJSDocTagNode = 327, +- LastJSDocTagNode = 351, ++ FirstStatement = 244, ++ LastStatement = 260, ++ FirstNode = 167, ++ FirstJSDocNode = 310, ++ LastJSDocNode = 352, ++ FirstJSDocTagNode = 328, ++ LastJSDocTagNode = 352, + } + type TriviaSyntaxKind = SyntaxKind.SingleLineCommentTrivia | SyntaxKind.MultiLineCommentTrivia | SyntaxKind.NewLineTrivia | SyntaxKind.WhitespaceTrivia | SyntaxKind.ShebangTrivia | SyntaxKind.ConflictMarkerTrivia; + type LiteralSyntaxKind = SyntaxKind.NumericLiteral | SyntaxKind.BigIntLiteral | SyntaxKind.StringLiteral | SyntaxKind.JsxText | SyntaxKind.JsxTextAllWhiteSpaces | SyntaxKind.RegularExpressionLiteral | SyntaxKind.NoSubstitutionTemplateLiteral; +@@ -4156,6 +4157,7 @@ declare namespace ts { + | SyntaxKind.DebuggerKeyword + | SyntaxKind.DeclareKeyword + | SyntaxKind.DefaultKeyword ++ | SyntaxKind.DeferKeyword + | SyntaxKind.DeleteKeyword + | SyntaxKind.DoKeyword + | SyntaxKind.ElseKeyword +@@ -5128,7 +5130,7 @@ declare namespace ts { + readonly expression: SuperExpression; + } + interface ImportCall extends CallExpression { +- readonly expression: ImportExpression; ++ readonly expression: ImportExpression | ImportDeferProperty; + } + interface ExpressionWithTypeArguments extends MemberExpression, NodeWithTypeArguments { + readonly kind: SyntaxKind.ExpressionWithTypeArguments; +@@ -5178,6 +5180,12 @@ declare namespace ts { + readonly keywordToken: SyntaxKind.NewKeyword | SyntaxKind.ImportKeyword; + readonly name: Identifier; + } ++ interface ImportDeferProperty extends MetaProperty { ++ readonly keywordToken: SyntaxKind.ImportKeyword; ++ readonly name: Identifier & { ++ readonly escapedText: __String & "defer"; ++ }; ++ } + interface JsxElement extends PrimaryExpression { + readonly kind: SyntaxKind.JsxElement; + readonly openingElement: JsxOpeningElement; +@@ -5517,10 +5525,13 @@ declare namespace ts { + interface ImportClause extends NamedDeclaration { + readonly kind: SyntaxKind.ImportClause; + readonly parent: ImportDeclaration | JSDocImportTag; ++ /** @deprecated Use `phaseModifier` instead */ + readonly isTypeOnly: boolean; ++ readonly phaseModifier: undefined | ImportPhaseModifierSyntaxKind; + readonly name?: Identifier; + readonly namedBindings?: NamedImportBindings; + } ++ type ImportPhaseModifierSyntaxKind = SyntaxKind.TypeKeyword | SyntaxKind.DeferKeyword; + /** @deprecated */ + type AssertionKey = ImportAttributeName; + /** @deprecated */ +@@ -7728,8 +7739,10 @@ declare namespace ts { + updateImportEqualsDeclaration(node: ImportEqualsDeclaration, modifiers: readonly ModifierLike[] | undefined, isTypeOnly: boolean, name: Identifier, moduleReference: ModuleReference): ImportEqualsDeclaration; + createImportDeclaration(modifiers: readonly ModifierLike[] | undefined, importClause: ImportClause | undefined, moduleSpecifier: Expression, attributes?: ImportAttributes): ImportDeclaration; + updateImportDeclaration(node: ImportDeclaration, modifiers: readonly ModifierLike[] | undefined, importClause: ImportClause | undefined, moduleSpecifier: Expression, attributes: ImportAttributes | undefined): ImportDeclaration; +- createImportClause(isTypeOnly: boolean, name: Identifier | undefined, namedBindings: NamedImportBindings | undefined): ImportClause; +- updateImportClause(node: ImportClause, isTypeOnly: boolean, name: Identifier | undefined, namedBindings: NamedImportBindings | undefined): ImportClause; ++ createImportClause(phaseModifier: ImportPhaseModifierSyntaxKind | undefined, name: Identifier | undefined, namedBindings: NamedImportBindings | undefined): ImportClause; ++ /** @deprecated */ createImportClause(isTypeOnly: boolean, name: Identifier | undefined, namedBindings: NamedImportBindings | undefined): ImportClause; ++ updateImportClause(node: ImportClause, phaseModifier: ImportPhaseModifierSyntaxKind | undefined, name: Identifier | undefined, namedBindings: NamedImportBindings | undefined): ImportClause; ++ /** @deprecated */ updateImportClause(node: ImportClause, isTypeOnly: boolean, name: Identifier | undefined, namedBindings: NamedImportBindings | undefined): ImportClause; + /** @deprecated */ createAssertClause(elements: NodeArray, multiLine?: boolean): AssertClause; + /** @deprecated */ updateAssertClause(node: AssertClause, elements: NodeArray, multiLine?: boolean): AssertClause; + /** @deprecated */ createAssertEntry(name: AssertionKey, value: Expression): AssertEntry; +diff --git a/tests/baselines/reference/dynamicImportDefer(module=commonjs).errors.txt b/tests/baselines/reference/dynamicImportDefer(module=commonjs).errors.txt +new file mode 100644 +index 000000000..bdf61f926 +--- /dev/null ++++ b/tests/baselines/reference/dynamicImportDefer(module=commonjs).errors.txt +@@ -0,0 +1,15 @@ ++b.ts(1,1): error TS18060: Deferred imports are only supported when the '--module' flag is set to 'esnext' or 'preserve'. ++ ++ ++==== a.ts (0 errors) ==== ++ export function foo() { ++ console.log("foo from a"); ++ } ++ ++==== b.ts (1 errors) ==== ++ import.defer("./a.js").then(ns => { ++ ~~~~~~~~~~~~~~~~~~~~~~ ++!!! error TS18060: Deferred imports are only supported when the '--module' flag is set to 'esnext' or 'preserve'. ++ ns.foo(); ++ }); ++ +\ No newline at end of file +diff --git a/tests/baselines/reference/dynamicImportDefer(module=commonjs).js b/tests/baselines/reference/dynamicImportDefer(module=commonjs).js +new file mode 100644 +index 000000000..2388439df +--- /dev/null ++++ b/tests/baselines/reference/dynamicImportDefer(module=commonjs).js +@@ -0,0 +1,24 @@ ++//// [tests/cases/conformance/importDefer/dynamicImportDefer.ts] //// ++ ++//// [a.ts] ++export function foo() { ++ console.log("foo from a"); ++} ++ ++//// [b.ts] ++import.defer("./a.js").then(ns => { ++ ns.foo(); ++}); ++ ++ ++//// [a.js] ++"use strict"; ++Object.defineProperty(exports, "__esModule", { value: true }); ++exports.foo = foo; ++function foo() { ++ console.log("foo from a"); ++} ++//// [b.js] ++import.defer("./a.js").then(ns => { ++ ns.foo(); ++}); +diff --git a/tests/baselines/reference/dynamicImportDefer(module=commonjs).symbols b/tests/baselines/reference/dynamicImportDefer(module=commonjs).symbols +new file mode 100644 +index 000000000..291ceeb4f +--- /dev/null ++++ b/tests/baselines/reference/dynamicImportDefer(module=commonjs).symbols +@@ -0,0 +1,26 @@ ++//// [tests/cases/conformance/importDefer/dynamicImportDefer.ts] //// ++ ++=== a.ts === ++export function foo() { ++>foo : Symbol(foo, Decl(a.ts, 0, 0)) ++ ++ console.log("foo from a"); ++>console.log : Symbol(Console.log, Decl(lib.dom.d.ts, --, --)) ++>console : Symbol(console, Decl(lib.dom.d.ts, --, --)) ++>log : Symbol(Console.log, Decl(lib.dom.d.ts, --, --)) ++} ++ ++=== b.ts === ++import.defer("./a.js").then(ns => { ++>import.defer("./a.js").then : Symbol(Promise.then, Decl(lib.es5.d.ts, --, --)) ++>"./a.js" : Symbol("a", Decl(a.ts, 0, 0)) ++>then : Symbol(Promise.then, Decl(lib.es5.d.ts, --, --)) ++>ns : Symbol(ns, Decl(b.ts, 0, 28)) ++ ++ ns.foo(); ++>ns.foo : Symbol(foo, Decl(a.ts, 0, 0)) ++>ns : Symbol(ns, Decl(b.ts, 0, 28)) ++>foo : Symbol(foo, Decl(a.ts, 0, 0)) ++ ++}); ++ +diff --git a/tests/baselines/reference/dynamicImportDefer(module=commonjs).types b/tests/baselines/reference/dynamicImportDefer(module=commonjs).types +new file mode 100644 +index 000000000..187bc2574 +--- /dev/null ++++ b/tests/baselines/reference/dynamicImportDefer(module=commonjs).types +@@ -0,0 +1,51 @@ ++//// [tests/cases/conformance/importDefer/dynamicImportDefer.ts] //// ++ ++=== a.ts === ++export function foo() { ++>foo : () => void ++> : ^^^^^^^^^^ ++ ++ console.log("foo from a"); ++>console.log("foo from a") : void ++> : ^^^^ ++>console.log : (...data: any[]) => void ++> : ^^^^ ^^ ^^^^^ ++>console : Console ++> : ^^^^^^^ ++>log : (...data: any[]) => void ++> : ^^^^ ^^ ^^^^^ ++>"foo from a" : "foo from a" ++> : ^^^^^^^^^^^^ ++} ++ ++=== b.ts === ++import.defer("./a.js").then(ns => { ++>import.defer("./a.js").then(ns => { ns.foo();}) : Promise ++> : ^^^^^^^^^^^^^ ++>import.defer("./a.js").then : (onfulfilled?: (value: typeof import("a")) => TResult1 | PromiseLike, onrejected?: (reason: any) => TResult2 | PromiseLike) => Promise ++> : ^ ^^^^^^^^^^^^^^^^^^^^^^^ ^^^^^^^^^^ ^^^^ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ^^^^ ^^ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ++>import.defer("./a.js") : Promise ++> : ^^^^^^^^^^^^^^^^^^^^^^^^^^^ ++>defer : any ++> : ^^^ ++>"./a.js" : "./a.js" ++> : ^^^^^^^^ ++>then : (onfulfilled?: (value: typeof import("a")) => TResult1 | PromiseLike, onrejected?: (reason: any) => TResult2 | PromiseLike) => Promise ++> : ^ ^^^^^^^^^^^^^^^^^^^^^^^ ^^^^^^^^^^ ^^^^ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ^^^^ ^^ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ++>ns => { ns.foo();} : (ns: typeof import("a")) => void ++> : ^ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ++>ns : typeof import("a") ++> : ^^^^^^^^^^^^^^^^^^ ++ ++ ns.foo(); ++>ns.foo() : void ++> : ^^^^ ++>ns.foo : () => void ++> : ^^^^^^^^^^ ++>ns : typeof import("a") ++> : ^^^^^^^^^^^^^^^^^^ ++>foo : () => void ++> : ^^^^^^^^^^ ++ ++}); ++ +diff --git a/tests/baselines/reference/dynamicImportDefer(module=es2015).errors.txt b/tests/baselines/reference/dynamicImportDefer(module=es2015).errors.txt +new file mode 100644 +index 000000000..bdf61f926 +--- /dev/null ++++ b/tests/baselines/reference/dynamicImportDefer(module=es2015).errors.txt +@@ -0,0 +1,15 @@ ++b.ts(1,1): error TS18060: Deferred imports are only supported when the '--module' flag is set to 'esnext' or 'preserve'. ++ ++ ++==== a.ts (0 errors) ==== ++ export function foo() { ++ console.log("foo from a"); ++ } ++ ++==== b.ts (1 errors) ==== ++ import.defer("./a.js").then(ns => { ++ ~~~~~~~~~~~~~~~~~~~~~~ ++!!! error TS18060: Deferred imports are only supported when the '--module' flag is set to 'esnext' or 'preserve'. ++ ns.foo(); ++ }); ++ +\ No newline at end of file +diff --git a/tests/baselines/reference/dynamicImportDefer(module=es2015).js b/tests/baselines/reference/dynamicImportDefer(module=es2015).js +new file mode 100644 +index 000000000..476b046b4 +--- /dev/null ++++ b/tests/baselines/reference/dynamicImportDefer(module=es2015).js +@@ -0,0 +1,21 @@ ++//// [tests/cases/conformance/importDefer/dynamicImportDefer.ts] //// ++ ++//// [a.ts] ++export function foo() { ++ console.log("foo from a"); ++} ++ ++//// [b.ts] ++import.defer("./a.js").then(ns => { ++ ns.foo(); ++}); ++ ++ ++//// [a.js] ++export function foo() { ++ console.log("foo from a"); ++} ++//// [b.js] ++import.defer("./a.js").then(ns => { ++ ns.foo(); ++}); +diff --git a/tests/baselines/reference/dynamicImportDefer(module=es2015).symbols b/tests/baselines/reference/dynamicImportDefer(module=es2015).symbols +new file mode 100644 +index 000000000..291ceeb4f +--- /dev/null ++++ b/tests/baselines/reference/dynamicImportDefer(module=es2015).symbols +@@ -0,0 +1,26 @@ ++//// [tests/cases/conformance/importDefer/dynamicImportDefer.ts] //// ++ ++=== a.ts === ++export function foo() { ++>foo : Symbol(foo, Decl(a.ts, 0, 0)) ++ ++ console.log("foo from a"); ++>console.log : Symbol(Console.log, Decl(lib.dom.d.ts, --, --)) ++>console : Symbol(console, Decl(lib.dom.d.ts, --, --)) ++>log : Symbol(Console.log, Decl(lib.dom.d.ts, --, --)) ++} ++ ++=== b.ts === ++import.defer("./a.js").then(ns => { ++>import.defer("./a.js").then : Symbol(Promise.then, Decl(lib.es5.d.ts, --, --)) ++>"./a.js" : Symbol("a", Decl(a.ts, 0, 0)) ++>then : Symbol(Promise.then, Decl(lib.es5.d.ts, --, --)) ++>ns : Symbol(ns, Decl(b.ts, 0, 28)) ++ ++ ns.foo(); ++>ns.foo : Symbol(foo, Decl(a.ts, 0, 0)) ++>ns : Symbol(ns, Decl(b.ts, 0, 28)) ++>foo : Symbol(foo, Decl(a.ts, 0, 0)) ++ ++}); ++ +diff --git a/tests/baselines/reference/dynamicImportDefer(module=es2015).types b/tests/baselines/reference/dynamicImportDefer(module=es2015).types +new file mode 100644 +index 000000000..187bc2574 +--- /dev/null ++++ b/tests/baselines/reference/dynamicImportDefer(module=es2015).types +@@ -0,0 +1,51 @@ ++//// [tests/cases/conformance/importDefer/dynamicImportDefer.ts] //// ++ ++=== a.ts === ++export function foo() { ++>foo : () => void ++> : ^^^^^^^^^^ ++ ++ console.log("foo from a"); ++>console.log("foo from a") : void ++> : ^^^^ ++>console.log : (...data: any[]) => void ++> : ^^^^ ^^ ^^^^^ ++>console : Console ++> : ^^^^^^^ ++>log : (...data: any[]) => void ++> : ^^^^ ^^ ^^^^^ ++>"foo from a" : "foo from a" ++> : ^^^^^^^^^^^^ ++} ++ ++=== b.ts === ++import.defer("./a.js").then(ns => { ++>import.defer("./a.js").then(ns => { ns.foo();}) : Promise ++> : ^^^^^^^^^^^^^ ++>import.defer("./a.js").then : (onfulfilled?: (value: typeof import("a")) => TResult1 | PromiseLike, onrejected?: (reason: any) => TResult2 | PromiseLike) => Promise ++> : ^ ^^^^^^^^^^^^^^^^^^^^^^^ ^^^^^^^^^^ ^^^^ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ^^^^ ^^ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ++>import.defer("./a.js") : Promise ++> : ^^^^^^^^^^^^^^^^^^^^^^^^^^^ ++>defer : any ++> : ^^^ ++>"./a.js" : "./a.js" ++> : ^^^^^^^^ ++>then : (onfulfilled?: (value: typeof import("a")) => TResult1 | PromiseLike, onrejected?: (reason: any) => TResult2 | PromiseLike) => Promise ++> : ^ ^^^^^^^^^^^^^^^^^^^^^^^ ^^^^^^^^^^ ^^^^ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ^^^^ ^^ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ++>ns => { ns.foo();} : (ns: typeof import("a")) => void ++> : ^ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ++>ns : typeof import("a") ++> : ^^^^^^^^^^^^^^^^^^ ++ ++ ns.foo(); ++>ns.foo() : void ++> : ^^^^ ++>ns.foo : () => void ++> : ^^^^^^^^^^ ++>ns : typeof import("a") ++> : ^^^^^^^^^^^^^^^^^^ ++>foo : () => void ++> : ^^^^^^^^^^ ++ ++}); ++ +diff --git a/tests/baselines/reference/dynamicImportDefer(module=es2020).errors.txt b/tests/baselines/reference/dynamicImportDefer(module=es2020).errors.txt +new file mode 100644 +index 000000000..bdf61f926 +--- /dev/null ++++ b/tests/baselines/reference/dynamicImportDefer(module=es2020).errors.txt +@@ -0,0 +1,15 @@ ++b.ts(1,1): error TS18060: Deferred imports are only supported when the '--module' flag is set to 'esnext' or 'preserve'. ++ ++ ++==== a.ts (0 errors) ==== ++ export function foo() { ++ console.log("foo from a"); ++ } ++ ++==== b.ts (1 errors) ==== ++ import.defer("./a.js").then(ns => { ++ ~~~~~~~~~~~~~~~~~~~~~~ ++!!! error TS18060: Deferred imports are only supported when the '--module' flag is set to 'esnext' or 'preserve'. ++ ns.foo(); ++ }); ++ +\ No newline at end of file +diff --git a/tests/baselines/reference/dynamicImportDefer(module=es2020).js b/tests/baselines/reference/dynamicImportDefer(module=es2020).js +new file mode 100644 +index 000000000..476b046b4 +--- /dev/null ++++ b/tests/baselines/reference/dynamicImportDefer(module=es2020).js +@@ -0,0 +1,21 @@ ++//// [tests/cases/conformance/importDefer/dynamicImportDefer.ts] //// ++ ++//// [a.ts] ++export function foo() { ++ console.log("foo from a"); ++} ++ ++//// [b.ts] ++import.defer("./a.js").then(ns => { ++ ns.foo(); ++}); ++ ++ ++//// [a.js] ++export function foo() { ++ console.log("foo from a"); ++} ++//// [b.js] ++import.defer("./a.js").then(ns => { ++ ns.foo(); ++}); +diff --git a/tests/baselines/reference/dynamicImportDefer(module=es2020).symbols b/tests/baselines/reference/dynamicImportDefer(module=es2020).symbols +new file mode 100644 +index 000000000..291ceeb4f +--- /dev/null ++++ b/tests/baselines/reference/dynamicImportDefer(module=es2020).symbols +@@ -0,0 +1,26 @@ ++//// [tests/cases/conformance/importDefer/dynamicImportDefer.ts] //// ++ ++=== a.ts === ++export function foo() { ++>foo : Symbol(foo, Decl(a.ts, 0, 0)) ++ ++ console.log("foo from a"); ++>console.log : Symbol(Console.log, Decl(lib.dom.d.ts, --, --)) ++>console : Symbol(console, Decl(lib.dom.d.ts, --, --)) ++>log : Symbol(Console.log, Decl(lib.dom.d.ts, --, --)) ++} ++ ++=== b.ts === ++import.defer("./a.js").then(ns => { ++>import.defer("./a.js").then : Symbol(Promise.then, Decl(lib.es5.d.ts, --, --)) ++>"./a.js" : Symbol("a", Decl(a.ts, 0, 0)) ++>then : Symbol(Promise.then, Decl(lib.es5.d.ts, --, --)) ++>ns : Symbol(ns, Decl(b.ts, 0, 28)) ++ ++ ns.foo(); ++>ns.foo : Symbol(foo, Decl(a.ts, 0, 0)) ++>ns : Symbol(ns, Decl(b.ts, 0, 28)) ++>foo : Symbol(foo, Decl(a.ts, 0, 0)) ++ ++}); ++ +diff --git a/tests/baselines/reference/dynamicImportDefer(module=es2020).types b/tests/baselines/reference/dynamicImportDefer(module=es2020).types +new file mode 100644 +index 000000000..187bc2574 +--- /dev/null ++++ b/tests/baselines/reference/dynamicImportDefer(module=es2020).types +@@ -0,0 +1,51 @@ ++//// [tests/cases/conformance/importDefer/dynamicImportDefer.ts] //// ++ ++=== a.ts === ++export function foo() { ++>foo : () => void ++> : ^^^^^^^^^^ ++ ++ console.log("foo from a"); ++>console.log("foo from a") : void ++> : ^^^^ ++>console.log : (...data: any[]) => void ++> : ^^^^ ^^ ^^^^^ ++>console : Console ++> : ^^^^^^^ ++>log : (...data: any[]) => void ++> : ^^^^ ^^ ^^^^^ ++>"foo from a" : "foo from a" ++> : ^^^^^^^^^^^^ ++} ++ ++=== b.ts === ++import.defer("./a.js").then(ns => { ++>import.defer("./a.js").then(ns => { ns.foo();}) : Promise ++> : ^^^^^^^^^^^^^ ++>import.defer("./a.js").then : (onfulfilled?: (value: typeof import("a")) => TResult1 | PromiseLike, onrejected?: (reason: any) => TResult2 | PromiseLike) => Promise ++> : ^ ^^^^^^^^^^^^^^^^^^^^^^^ ^^^^^^^^^^ ^^^^ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ^^^^ ^^ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ++>import.defer("./a.js") : Promise ++> : ^^^^^^^^^^^^^^^^^^^^^^^^^^^ ++>defer : any ++> : ^^^ ++>"./a.js" : "./a.js" ++> : ^^^^^^^^ ++>then : (onfulfilled?: (value: typeof import("a")) => TResult1 | PromiseLike, onrejected?: (reason: any) => TResult2 | PromiseLike) => Promise ++> : ^ ^^^^^^^^^^^^^^^^^^^^^^^ ^^^^^^^^^^ ^^^^ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ^^^^ ^^ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ++>ns => { ns.foo();} : (ns: typeof import("a")) => void ++> : ^ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ++>ns : typeof import("a") ++> : ^^^^^^^^^^^^^^^^^^ ++ ++ ns.foo(); ++>ns.foo() : void ++> : ^^^^ ++>ns.foo : () => void ++> : ^^^^^^^^^^ ++>ns : typeof import("a") ++> : ^^^^^^^^^^^^^^^^^^ ++>foo : () => void ++> : ^^^^^^^^^^ ++ ++}); ++ +diff --git a/tests/baselines/reference/dynamicImportDefer(module=esnext).js b/tests/baselines/reference/dynamicImportDefer(module=esnext).js +new file mode 100644 +index 000000000..476b046b4 +--- /dev/null ++++ b/tests/baselines/reference/dynamicImportDefer(module=esnext).js +@@ -0,0 +1,21 @@ ++//// [tests/cases/conformance/importDefer/dynamicImportDefer.ts] //// ++ ++//// [a.ts] ++export function foo() { ++ console.log("foo from a"); ++} ++ ++//// [b.ts] ++import.defer("./a.js").then(ns => { ++ ns.foo(); ++}); ++ ++ ++//// [a.js] ++export function foo() { ++ console.log("foo from a"); ++} ++//// [b.js] ++import.defer("./a.js").then(ns => { ++ ns.foo(); ++}); +diff --git a/tests/baselines/reference/dynamicImportDefer(module=esnext).symbols b/tests/baselines/reference/dynamicImportDefer(module=esnext).symbols +new file mode 100644 +index 000000000..291ceeb4f +--- /dev/null ++++ b/tests/baselines/reference/dynamicImportDefer(module=esnext).symbols +@@ -0,0 +1,26 @@ ++//// [tests/cases/conformance/importDefer/dynamicImportDefer.ts] //// ++ ++=== a.ts === ++export function foo() { ++>foo : Symbol(foo, Decl(a.ts, 0, 0)) ++ ++ console.log("foo from a"); ++>console.log : Symbol(Console.log, Decl(lib.dom.d.ts, --, --)) ++>console : Symbol(console, Decl(lib.dom.d.ts, --, --)) ++>log : Symbol(Console.log, Decl(lib.dom.d.ts, --, --)) ++} ++ ++=== b.ts === ++import.defer("./a.js").then(ns => { ++>import.defer("./a.js").then : Symbol(Promise.then, Decl(lib.es5.d.ts, --, --)) ++>"./a.js" : Symbol("a", Decl(a.ts, 0, 0)) ++>then : Symbol(Promise.then, Decl(lib.es5.d.ts, --, --)) ++>ns : Symbol(ns, Decl(b.ts, 0, 28)) ++ ++ ns.foo(); ++>ns.foo : Symbol(foo, Decl(a.ts, 0, 0)) ++>ns : Symbol(ns, Decl(b.ts, 0, 28)) ++>foo : Symbol(foo, Decl(a.ts, 0, 0)) ++ ++}); ++ +diff --git a/tests/baselines/reference/dynamicImportDefer(module=esnext).types b/tests/baselines/reference/dynamicImportDefer(module=esnext).types +new file mode 100644 +index 000000000..187bc2574 +--- /dev/null ++++ b/tests/baselines/reference/dynamicImportDefer(module=esnext).types +@@ -0,0 +1,51 @@ ++//// [tests/cases/conformance/importDefer/dynamicImportDefer.ts] //// ++ ++=== a.ts === ++export function foo() { ++>foo : () => void ++> : ^^^^^^^^^^ ++ ++ console.log("foo from a"); ++>console.log("foo from a") : void ++> : ^^^^ ++>console.log : (...data: any[]) => void ++> : ^^^^ ^^ ^^^^^ ++>console : Console ++> : ^^^^^^^ ++>log : (...data: any[]) => void ++> : ^^^^ ^^ ^^^^^ ++>"foo from a" : "foo from a" ++> : ^^^^^^^^^^^^ ++} ++ ++=== b.ts === ++import.defer("./a.js").then(ns => { ++>import.defer("./a.js").then(ns => { ns.foo();}) : Promise ++> : ^^^^^^^^^^^^^ ++>import.defer("./a.js").then : (onfulfilled?: (value: typeof import("a")) => TResult1 | PromiseLike, onrejected?: (reason: any) => TResult2 | PromiseLike) => Promise ++> : ^ ^^^^^^^^^^^^^^^^^^^^^^^ ^^^^^^^^^^ ^^^^ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ^^^^ ^^ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ++>import.defer("./a.js") : Promise ++> : ^^^^^^^^^^^^^^^^^^^^^^^^^^^ ++>defer : any ++> : ^^^ ++>"./a.js" : "./a.js" ++> : ^^^^^^^^ ++>then : (onfulfilled?: (value: typeof import("a")) => TResult1 | PromiseLike, onrejected?: (reason: any) => TResult2 | PromiseLike) => Promise ++> : ^ ^^^^^^^^^^^^^^^^^^^^^^^ ^^^^^^^^^^ ^^^^ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ^^^^ ^^ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ++>ns => { ns.foo();} : (ns: typeof import("a")) => void ++> : ^ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ++>ns : typeof import("a") ++> : ^^^^^^^^^^^^^^^^^^ ++ ++ ns.foo(); ++>ns.foo() : void ++> : ^^^^ ++>ns.foo : () => void ++> : ^^^^^^^^^^ ++>ns : typeof import("a") ++> : ^^^^^^^^^^^^^^^^^^ ++>foo : () => void ++> : ^^^^^^^^^^ ++ ++}); ++ +diff --git a/tests/baselines/reference/dynamicImportDefer(module=nodenext).errors.txt b/tests/baselines/reference/dynamicImportDefer(module=nodenext).errors.txt +new file mode 100644 +index 000000000..bdf61f926 +--- /dev/null ++++ b/tests/baselines/reference/dynamicImportDefer(module=nodenext).errors.txt +@@ -0,0 +1,15 @@ ++b.ts(1,1): error TS18060: Deferred imports are only supported when the '--module' flag is set to 'esnext' or 'preserve'. ++ ++ ++==== a.ts (0 errors) ==== ++ export function foo() { ++ console.log("foo from a"); ++ } ++ ++==== b.ts (1 errors) ==== ++ import.defer("./a.js").then(ns => { ++ ~~~~~~~~~~~~~~~~~~~~~~ ++!!! error TS18060: Deferred imports are only supported when the '--module' flag is set to 'esnext' or 'preserve'. ++ ns.foo(); ++ }); ++ +\ No newline at end of file +diff --git a/tests/baselines/reference/dynamicImportDefer(module=nodenext).js b/tests/baselines/reference/dynamicImportDefer(module=nodenext).js +new file mode 100644 +index 000000000..6586332a4 +--- /dev/null ++++ b/tests/baselines/reference/dynamicImportDefer(module=nodenext).js +@@ -0,0 +1,26 @@ ++//// [tests/cases/conformance/importDefer/dynamicImportDefer.ts] //// ++ ++//// [a.ts] ++export function foo() { ++ console.log("foo from a"); ++} ++ ++//// [b.ts] ++import.defer("./a.js").then(ns => { ++ ns.foo(); ++}); ++ ++ ++//// [a.js] ++"use strict"; ++Object.defineProperty(exports, "__esModule", { value: true }); ++exports.foo = foo; ++function foo() { ++ console.log("foo from a"); ++} ++//// [b.js] ++"use strict"; ++Object.defineProperty(exports, "__esModule", { value: true }); ++import.defer("./a.js").then(ns => { ++ ns.foo(); ++}); +diff --git a/tests/baselines/reference/dynamicImportDefer(module=nodenext).symbols b/tests/baselines/reference/dynamicImportDefer(module=nodenext).symbols +new file mode 100644 +index 000000000..291ceeb4f +--- /dev/null ++++ b/tests/baselines/reference/dynamicImportDefer(module=nodenext).symbols +@@ -0,0 +1,26 @@ ++//// [tests/cases/conformance/importDefer/dynamicImportDefer.ts] //// ++ ++=== a.ts === ++export function foo() { ++>foo : Symbol(foo, Decl(a.ts, 0, 0)) ++ ++ console.log("foo from a"); ++>console.log : Symbol(Console.log, Decl(lib.dom.d.ts, --, --)) ++>console : Symbol(console, Decl(lib.dom.d.ts, --, --)) ++>log : Symbol(Console.log, Decl(lib.dom.d.ts, --, --)) ++} ++ ++=== b.ts === ++import.defer("./a.js").then(ns => { ++>import.defer("./a.js").then : Symbol(Promise.then, Decl(lib.es5.d.ts, --, --)) ++>"./a.js" : Symbol("a", Decl(a.ts, 0, 0)) ++>then : Symbol(Promise.then, Decl(lib.es5.d.ts, --, --)) ++>ns : Symbol(ns, Decl(b.ts, 0, 28)) ++ ++ ns.foo(); ++>ns.foo : Symbol(foo, Decl(a.ts, 0, 0)) ++>ns : Symbol(ns, Decl(b.ts, 0, 28)) ++>foo : Symbol(foo, Decl(a.ts, 0, 0)) ++ ++}); ++ +diff --git a/tests/baselines/reference/dynamicImportDefer(module=nodenext).types b/tests/baselines/reference/dynamicImportDefer(module=nodenext).types +new file mode 100644 +index 000000000..97629f60e +--- /dev/null ++++ b/tests/baselines/reference/dynamicImportDefer(module=nodenext).types +@@ -0,0 +1,51 @@ ++//// [tests/cases/conformance/importDefer/dynamicImportDefer.ts] //// ++ ++=== a.ts === ++export function foo() { ++>foo : () => void ++> : ^^^^^^^^^^ ++ ++ console.log("foo from a"); ++>console.log("foo from a") : void ++> : ^^^^ ++>console.log : (...data: any[]) => void ++> : ^^^^ ^^ ^^^^^ ++>console : Console ++> : ^^^^^^^ ++>log : (...data: any[]) => void ++> : ^^^^ ^^ ^^^^^ ++>"foo from a" : "foo from a" ++> : ^^^^^^^^^^^^ ++} ++ ++=== b.ts === ++import.defer("./a.js").then(ns => { ++>import.defer("./a.js").then(ns => { ns.foo();}) : Promise ++> : ^^^^^^^^^^^^^ ++>import.defer("./a.js").then : (onfulfilled?: (value: { default: typeof import("a"); foo(): void; }) => TResult1 | PromiseLike, onrejected?: (reason: any) => TResult2 | PromiseLike) => Promise ++> : ^ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ^^^^^^^^^^ ^^^^ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ^^^^ ^^ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ++>import.defer("./a.js") : Promise<{ default: typeof import("a"); foo(): void; }> ++> : ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ++>defer : any ++> : ^^^ ++>"./a.js" : "./a.js" ++> : ^^^^^^^^ ++>then : (onfulfilled?: (value: { default: typeof import("a"); foo(): void; }) => TResult1 | PromiseLike, onrejected?: (reason: any) => TResult2 | PromiseLike) => Promise ++> : ^ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ^^^^^^^^^^ ^^^^ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ^^^^ ^^ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ++>ns => { ns.foo();} : (ns: { default: typeof import("a"); foo(): void; }) => void ++> : ^ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ++>ns : { default: typeof import("a"); foo(): void; } ++> : ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ++ ++ ns.foo(); ++>ns.foo() : void ++> : ^^^^ ++>ns.foo : () => void ++> : ^^^^^^^^^^ ++>ns : { default: typeof import("a"); foo(): void; } ++> : ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ++>foo : () => void ++> : ^^^^^^^^^^ ++ ++}); ++ +diff --git a/tests/baselines/reference/dynamicImportDefer(module=preserve).js b/tests/baselines/reference/dynamicImportDefer(module=preserve).js +new file mode 100644 +index 000000000..476b046b4 +--- /dev/null ++++ b/tests/baselines/reference/dynamicImportDefer(module=preserve).js +@@ -0,0 +1,21 @@ ++//// [tests/cases/conformance/importDefer/dynamicImportDefer.ts] //// ++ ++//// [a.ts] ++export function foo() { ++ console.log("foo from a"); ++} ++ ++//// [b.ts] ++import.defer("./a.js").then(ns => { ++ ns.foo(); ++}); ++ ++ ++//// [a.js] ++export function foo() { ++ console.log("foo from a"); ++} ++//// [b.js] ++import.defer("./a.js").then(ns => { ++ ns.foo(); ++}); +diff --git a/tests/baselines/reference/dynamicImportDefer(module=preserve).symbols b/tests/baselines/reference/dynamicImportDefer(module=preserve).symbols +new file mode 100644 +index 000000000..291ceeb4f +--- /dev/null ++++ b/tests/baselines/reference/dynamicImportDefer(module=preserve).symbols +@@ -0,0 +1,26 @@ ++//// [tests/cases/conformance/importDefer/dynamicImportDefer.ts] //// ++ ++=== a.ts === ++export function foo() { ++>foo : Symbol(foo, Decl(a.ts, 0, 0)) ++ ++ console.log("foo from a"); ++>console.log : Symbol(Console.log, Decl(lib.dom.d.ts, --, --)) ++>console : Symbol(console, Decl(lib.dom.d.ts, --, --)) ++>log : Symbol(Console.log, Decl(lib.dom.d.ts, --, --)) ++} ++ ++=== b.ts === ++import.defer("./a.js").then(ns => { ++>import.defer("./a.js").then : Symbol(Promise.then, Decl(lib.es5.d.ts, --, --)) ++>"./a.js" : Symbol("a", Decl(a.ts, 0, 0)) ++>then : Symbol(Promise.then, Decl(lib.es5.d.ts, --, --)) ++>ns : Symbol(ns, Decl(b.ts, 0, 28)) ++ ++ ns.foo(); ++>ns.foo : Symbol(foo, Decl(a.ts, 0, 0)) ++>ns : Symbol(ns, Decl(b.ts, 0, 28)) ++>foo : Symbol(foo, Decl(a.ts, 0, 0)) ++ ++}); ++ +diff --git a/tests/baselines/reference/dynamicImportDefer(module=preserve).types b/tests/baselines/reference/dynamicImportDefer(module=preserve).types +new file mode 100644 +index 000000000..187bc2574 +--- /dev/null ++++ b/tests/baselines/reference/dynamicImportDefer(module=preserve).types +@@ -0,0 +1,51 @@ ++//// [tests/cases/conformance/importDefer/dynamicImportDefer.ts] //// ++ ++=== a.ts === ++export function foo() { ++>foo : () => void ++> : ^^^^^^^^^^ ++ ++ console.log("foo from a"); ++>console.log("foo from a") : void ++> : ^^^^ ++>console.log : (...data: any[]) => void ++> : ^^^^ ^^ ^^^^^ ++>console : Console ++> : ^^^^^^^ ++>log : (...data: any[]) => void ++> : ^^^^ ^^ ^^^^^ ++>"foo from a" : "foo from a" ++> : ^^^^^^^^^^^^ ++} ++ ++=== b.ts === ++import.defer("./a.js").then(ns => { ++>import.defer("./a.js").then(ns => { ns.foo();}) : Promise ++> : ^^^^^^^^^^^^^ ++>import.defer("./a.js").then : (onfulfilled?: (value: typeof import("a")) => TResult1 | PromiseLike, onrejected?: (reason: any) => TResult2 | PromiseLike) => Promise ++> : ^ ^^^^^^^^^^^^^^^^^^^^^^^ ^^^^^^^^^^ ^^^^ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ^^^^ ^^ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ++>import.defer("./a.js") : Promise ++> : ^^^^^^^^^^^^^^^^^^^^^^^^^^^ ++>defer : any ++> : ^^^ ++>"./a.js" : "./a.js" ++> : ^^^^^^^^ ++>then : (onfulfilled?: (value: typeof import("a")) => TResult1 | PromiseLike, onrejected?: (reason: any) => TResult2 | PromiseLike) => Promise ++> : ^ ^^^^^^^^^^^^^^^^^^^^^^^ ^^^^^^^^^^ ^^^^ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ^^^^ ^^ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ++>ns => { ns.foo();} : (ns: typeof import("a")) => void ++> : ^ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ++>ns : typeof import("a") ++> : ^^^^^^^^^^^^^^^^^^ ++ ++ ns.foo(); ++>ns.foo() : void ++> : ^^^^ ++>ns.foo : () => void ++> : ^^^^^^^^^^ ++>ns : typeof import("a") ++> : ^^^^^^^^^^^^^^^^^^ ++>foo : () => void ++> : ^^^^^^^^^^ ++ ++}); ++ +diff --git a/tests/baselines/reference/dynamicImportDeferInvalidStandalone.errors.txt b/tests/baselines/reference/dynamicImportDeferInvalidStandalone.errors.txt +new file mode 100644 +index 000000000..fb28ea715 +--- /dev/null ++++ b/tests/baselines/reference/dynamicImportDeferInvalidStandalone.errors.txt +@@ -0,0 +1,22 @@ ++b.ts(1,13): error TS1005: '(' expected. ++b.ts(3,14): error TS1005: '(' expected. ++b.ts(5,22): error TS1005: '(' expected. ++b.ts(7,13): error TS1005: '(' expected. ++ ++ ++==== b.ts (4 errors) ==== ++ import.defer; ++ ++!!! error TS1005: '(' expected. ++ ++ (import.defer)("a"); ++ ++!!! error TS1005: '(' expected. ++ ++ Function(import.defer); ++ ++!!! error TS1005: '(' expected. ++ ++ import.defer ++ ++!!! error TS1005: '(' expected. +\ No newline at end of file +diff --git a/tests/baselines/reference/dynamicImportDeferInvalidStandalone.js b/tests/baselines/reference/dynamicImportDeferInvalidStandalone.js +new file mode 100644 +index 000000000..79dba2b21 +--- /dev/null ++++ b/tests/baselines/reference/dynamicImportDeferInvalidStandalone.js +@@ -0,0 +1,16 @@ ++//// [tests/cases/conformance/importDefer/dynamicImportDeferInvalidStandalone.ts] //// ++ ++//// [b.ts] ++import.defer; ++ ++(import.defer)("a"); ++ ++Function(import.defer); ++ ++import.defer ++ ++//// [b.js] ++import.defer; ++(import.defer)("a"); ++Function(import.defer); ++import.defer; +diff --git a/tests/baselines/reference/dynamicImportDeferInvalidStandalone.symbols b/tests/baselines/reference/dynamicImportDeferInvalidStandalone.symbols +new file mode 100644 +index 000000000..d822b06fb +--- /dev/null ++++ b/tests/baselines/reference/dynamicImportDeferInvalidStandalone.symbols +@@ -0,0 +1,11 @@ ++//// [tests/cases/conformance/importDefer/dynamicImportDeferInvalidStandalone.ts] //// ++ ++=== b.ts === ++import.defer; ++ ++(import.defer)("a"); ++ ++Function(import.defer); ++>Function : Symbol(Function, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --)) ++ ++import.defer +diff --git a/tests/baselines/reference/dynamicImportDeferInvalidStandalone.types b/tests/baselines/reference/dynamicImportDeferInvalidStandalone.types +new file mode 100644 +index 000000000..561f2c9bb +--- /dev/null ++++ b/tests/baselines/reference/dynamicImportDeferInvalidStandalone.types +@@ -0,0 +1,37 @@ ++//// [tests/cases/conformance/importDefer/dynamicImportDeferInvalidStandalone.ts] //// ++ ++=== b.ts === ++import.defer; ++>import.defer : any ++> : ^^^ ++>defer : any ++> : ^^^ ++ ++(import.defer)("a"); ++>(import.defer)("a") : any ++> : ^^^ ++>(import.defer) : any ++> : ^^^ ++>import.defer : any ++> : ^^^ ++>defer : any ++> : ^^^ ++>"a" : "a" ++> : ^^^ ++ ++Function(import.defer); ++>Function(import.defer) : Function ++> : ^^^^^^^^ ++>Function : FunctionConstructor ++> : ^^^^^^^^^^^^^^^^^^^ ++>import.defer : any ++> : ^^^ ++>defer : any ++> : ^^^ ++ ++import.defer ++>import.defer : any ++> : ^^^ ++>defer : any ++> : ^^^ ++ +diff --git a/tests/baselines/reference/exportDeferInvalid.errors.txt b/tests/baselines/reference/exportDeferInvalid.errors.txt +new file mode 100644 +index 000000000..21055164c +--- /dev/null ++++ b/tests/baselines/reference/exportDeferInvalid.errors.txt +@@ -0,0 +1,31 @@ ++b.ts(1,1): error TS1128: Declaration or statement expected. ++b.ts(1,8): error TS2304: Cannot find name 'defer'. ++b.ts(1,16): error TS2304: Cannot find name 'as'. ++b.ts(1,19): error TS1005: ';' expected. ++b.ts(1,19): error TS2304: Cannot find name 'ns'. ++b.ts(1,22): error TS1434: Unexpected keyword or identifier. ++b.ts(1,22): error TS2304: Cannot find name 'from'. ++ ++ ++==== a.ts (0 errors) ==== ++ export function foo() { ++ console.log("foo from a"); ++ } ++ ++==== b.ts (7 errors) ==== ++ export defer * as ns from "a"; ++ ~~~~~~ ++!!! error TS1128: Declaration or statement expected. ++ ~~~~~ ++!!! error TS2304: Cannot find name 'defer'. ++ ~~ ++!!! error TS2304: Cannot find name 'as'. ++ ~~ ++!!! error TS1005: ';' expected. ++ ~~ ++!!! error TS2304: Cannot find name 'ns'. ++ ~~~~ ++!!! error TS1434: Unexpected keyword or identifier. ++ ~~~~ ++!!! error TS2304: Cannot find name 'from'. ++ +\ No newline at end of file +diff --git a/tests/baselines/reference/exportDeferInvalid.js b/tests/baselines/reference/exportDeferInvalid.js +new file mode 100644 +index 000000000..8b2e752a2 +--- /dev/null ++++ b/tests/baselines/reference/exportDeferInvalid.js +@@ -0,0 +1,20 @@ ++//// [tests/cases/conformance/importDefer/exportDeferInvalid.ts] //// ++ ++//// [a.ts] ++export function foo() { ++ console.log("foo from a"); ++} ++ ++//// [b.ts] ++export defer * as ns from "a"; ++ ++ ++//// [a.js] ++export function foo() { ++ console.log("foo from a"); ++} ++//// [b.js] ++defer * as; ++ns; ++from; ++"a"; +diff --git a/tests/baselines/reference/exportDeferInvalid.symbols b/tests/baselines/reference/exportDeferInvalid.symbols +new file mode 100644 +index 000000000..ccc6ae0d9 +--- /dev/null ++++ b/tests/baselines/reference/exportDeferInvalid.symbols +@@ -0,0 +1,16 @@ ++//// [tests/cases/conformance/importDefer/exportDeferInvalid.ts] //// ++ ++=== a.ts === ++export function foo() { ++>foo : Symbol(foo, Decl(a.ts, 0, 0)) ++ ++ console.log("foo from a"); ++>console.log : Symbol(Console.log, Decl(lib.dom.d.ts, --, --)) ++>console : Symbol(console, Decl(lib.dom.d.ts, --, --)) ++>log : Symbol(Console.log, Decl(lib.dom.d.ts, --, --)) ++} ++ ++=== b.ts === ++ ++export defer * as ns from "a"; ++ +diff --git a/tests/baselines/reference/exportDeferInvalid.types b/tests/baselines/reference/exportDeferInvalid.types +new file mode 100644 +index 000000000..e10299d8b +--- /dev/null ++++ b/tests/baselines/reference/exportDeferInvalid.types +@@ -0,0 +1,35 @@ ++//// [tests/cases/conformance/importDefer/exportDeferInvalid.ts] //// ++ ++=== a.ts === ++export function foo() { ++>foo : () => void ++> : ^^^^^^^^^^ ++ ++ console.log("foo from a"); ++>console.log("foo from a") : void ++> : ^^^^ ++>console.log : (...data: any[]) => void ++> : ^^^^ ^^ ^^^^^ ++>console : Console ++> : ^^^^^^^ ++>log : (...data: any[]) => void ++> : ^^^^ ^^ ^^^^^ ++>"foo from a" : "foo from a" ++> : ^^^^^^^^^^^^ ++} ++ ++=== b.ts === ++export defer * as ns from "a"; ++>defer * as : number ++> : ^^^^^^ ++>defer : any ++> : ^^^ ++>as : any ++> : ^^^ ++>ns : any ++> : ^^^ ++>from : any ++> : ^^^ ++>"a" : "a" ++> : ^^^ ++ +diff --git a/tests/baselines/reference/importDefaultBindingDefer.js b/tests/baselines/reference/importDefaultBindingDefer.js +new file mode 100644 +index 000000000..aa2e7c262 +--- /dev/null ++++ b/tests/baselines/reference/importDefaultBindingDefer.js +@@ -0,0 +1,19 @@ ++//// [tests/cases/conformance/importDefer/importDefaultBindingDefer.ts] //// ++ ++//// [a.ts] ++export default function defer() { ++ console.log("defer from a"); ++} ++ ++//// [b.ts] ++import defer from "a"; ++ ++defer(); ++ ++//// [a.js] ++export default function defer() { ++ console.log("defer from a"); ++} ++//// [b.js] ++import defer from "a"; ++defer(); +diff --git a/tests/baselines/reference/importDefaultBindingDefer.symbols b/tests/baselines/reference/importDefaultBindingDefer.symbols +new file mode 100644 +index 000000000..9c233fcf0 +--- /dev/null ++++ b/tests/baselines/reference/importDefaultBindingDefer.symbols +@@ -0,0 +1,19 @@ ++//// [tests/cases/conformance/importDefer/importDefaultBindingDefer.ts] //// ++ ++=== a.ts === ++export default function defer() { ++>defer : Symbol(defer, Decl(a.ts, 0, 0)) ++ ++ console.log("defer from a"); ++>console.log : Symbol(Console.log, Decl(lib.dom.d.ts, --, --)) ++>console : Symbol(console, Decl(lib.dom.d.ts, --, --)) ++>log : Symbol(Console.log, Decl(lib.dom.d.ts, --, --)) ++} ++ ++=== b.ts === ++import defer from "a"; ++>defer : Symbol(defer, Decl(b.ts, 0, 6)) ++ ++defer(); ++>defer : Symbol(defer, Decl(b.ts, 0, 6)) ++ +diff --git a/tests/baselines/reference/importDefaultBindingDefer.types b/tests/baselines/reference/importDefaultBindingDefer.types +new file mode 100644 +index 000000000..f647f0914 +--- /dev/null ++++ b/tests/baselines/reference/importDefaultBindingDefer.types +@@ -0,0 +1,31 @@ ++//// [tests/cases/conformance/importDefer/importDefaultBindingDefer.ts] //// ++ ++=== a.ts === ++export default function defer() { ++>defer : () => void ++> : ^^^^^^^^^^ ++ ++ console.log("defer from a"); ++>console.log("defer from a") : void ++> : ^^^^ ++>console.log : (...data: any[]) => void ++> : ^^^^ ^^ ^^^^^ ++>console : Console ++> : ^^^^^^^ ++>log : (...data: any[]) => void ++> : ^^^^ ^^ ^^^^^ ++>"defer from a" : "defer from a" ++> : ^^^^^^^^^^^^^^ ++} ++ ++=== b.ts === ++import defer from "a"; ++>defer : () => void ++> : ^^^^^^^^^^ ++ ++defer(); ++>defer() : void ++> : ^^^^ ++>defer : () => void ++> : ^^^^^^^^^^ ++ +diff --git a/tests/baselines/reference/importDeferComments.js b/tests/baselines/reference/importDeferComments.js +new file mode 100644 +index 000000000..3e7980dbc +--- /dev/null ++++ b/tests/baselines/reference/importDeferComments.js +@@ -0,0 +1,13 @@ ++//// [tests/cases/conformance/importDefer/importDeferComments.ts] //// ++ ++//// [a.ts] ++export {}; ++ ++//// [b.ts] ++/*1*/ import /*2*/ defer /*3*/ * /*4*/ as /*5*/ aNs /*6*/ from /*7*/ "a" /*8*/; ++ ++ ++//// [a.js] ++export {}; ++//// [b.js] ++export {}; +diff --git a/tests/baselines/reference/importDeferComments.symbols b/tests/baselines/reference/importDeferComments.symbols +new file mode 100644 +index 000000000..fec118739 +--- /dev/null ++++ b/tests/baselines/reference/importDeferComments.symbols +@@ -0,0 +1,10 @@ ++//// [tests/cases/conformance/importDefer/importDeferComments.ts] //// ++ ++=== a.ts === ++ ++export {}; ++ ++=== b.ts === ++/*1*/ import /*2*/ defer /*3*/ * /*4*/ as /*5*/ aNs /*6*/ from /*7*/ "a" /*8*/; ++>aNs : Symbol(aNs, Decl(b.ts, 0, 24)) ++ +diff --git a/tests/baselines/reference/importDeferComments.types b/tests/baselines/reference/importDeferComments.types +new file mode 100644 +index 000000000..6f06fb952 +--- /dev/null ++++ b/tests/baselines/reference/importDeferComments.types +@@ -0,0 +1,11 @@ ++//// [tests/cases/conformance/importDefer/importDeferComments.ts] //// ++ ++=== a.ts === ++ ++export {}; ++ ++=== b.ts === ++/*1*/ import /*2*/ defer /*3*/ * /*4*/ as /*5*/ aNs /*6*/ from /*7*/ "a" /*8*/; ++>aNs : typeof aNs ++> : ^^^^^^^^^^ ++ +diff --git a/tests/baselines/reference/importDeferDeclaration.js b/tests/baselines/reference/importDeferDeclaration.js +new file mode 100644 +index 000000000..55175f4b6 +--- /dev/null ++++ b/tests/baselines/reference/importDeferDeclaration.js +@@ -0,0 +1,28 @@ ++//// [tests/cases/conformance/importDefer/importDeferDeclaration.ts] //// ++ ++//// [a.ts] ++export interface Foo { ++ x: number; ++} ++ ++//// [b.ts] ++import defer * as ns from "./a.js"; ++ ++export type X = { foo: ns.Foo }; ++ ++ ++//// [a.js] ++export {}; ++//// [b.js] ++export {}; ++ ++ ++//// [a.d.ts] ++export interface Foo { ++ x: number; ++} ++//// [b.d.ts] ++import * as ns from "./a.js"; ++export type X = { ++ foo: ns.Foo; ++}; +diff --git a/tests/baselines/reference/importDeferDeclaration.symbols b/tests/baselines/reference/importDeferDeclaration.symbols +new file mode 100644 +index 000000000..9518404d1 +--- /dev/null ++++ b/tests/baselines/reference/importDeferDeclaration.symbols +@@ -0,0 +1,20 @@ ++//// [tests/cases/conformance/importDefer/importDeferDeclaration.ts] //// ++ ++=== a.ts === ++export interface Foo { ++>Foo : Symbol(Foo, Decl(a.ts, 0, 0)) ++ ++ x: number; ++>x : Symbol(Foo.x, Decl(a.ts, 0, 22)) ++} ++ ++=== b.ts === ++import defer * as ns from "./a.js"; ++>ns : Symbol(ns, Decl(b.ts, 0, 12)) ++ ++export type X = { foo: ns.Foo }; ++>X : Symbol(X, Decl(b.ts, 0, 35)) ++>foo : Symbol(foo, Decl(b.ts, 2, 17)) ++>ns : Symbol(ns, Decl(b.ts, 0, 12)) ++>Foo : Symbol(ns.Foo, Decl(a.ts, 0, 0)) ++ +diff --git a/tests/baselines/reference/importDeferDeclaration.types b/tests/baselines/reference/importDeferDeclaration.types +new file mode 100644 +index 000000000..fcee86ec8 +--- /dev/null ++++ b/tests/baselines/reference/importDeferDeclaration.types +@@ -0,0 +1,22 @@ ++//// [tests/cases/conformance/importDefer/importDeferDeclaration.ts] //// ++ ++=== a.ts === ++export interface Foo { ++ x: number; ++>x : number ++> : ^^^^^^ ++} ++ ++=== b.ts === ++import defer * as ns from "./a.js"; ++>ns : typeof ns ++> : ^^^^^^^^^ ++ ++export type X = { foo: ns.Foo }; ++>X : X ++> : ^ ++>foo : ns.Foo ++> : ^^^^^^ ++>ns : any ++> : ^^^ ++ +diff --git a/tests/baselines/reference/importDeferInvalidDefault.errors.txt b/tests/baselines/reference/importDeferInvalidDefault.errors.txt +new file mode 100644 +index 000000000..db10e5819 +--- /dev/null ++++ b/tests/baselines/reference/importDeferInvalidDefault.errors.txt +@@ -0,0 +1,14 @@ ++b.ts(1,8): error TS18058: Default imports are not allowed in a deferred import. ++ ++ ++==== a.ts (0 errors) ==== ++ export default function foo() { ++ console.log("foo from a"); ++ } ++ ++==== b.ts (1 errors) ==== ++ import defer foo from "a"; ++ ~~~~~~~~~ ++!!! error TS18058: Default imports are not allowed in a deferred import. ++ ++ foo(); +\ No newline at end of file +diff --git a/tests/baselines/reference/importDeferInvalidDefault.js b/tests/baselines/reference/importDeferInvalidDefault.js +new file mode 100644 +index 000000000..e0f3491c6 +--- /dev/null ++++ b/tests/baselines/reference/importDeferInvalidDefault.js +@@ -0,0 +1,19 @@ ++//// [tests/cases/conformance/importDefer/importDeferInvalidDefault.ts] //// ++ ++//// [a.ts] ++export default function foo() { ++ console.log("foo from a"); ++} ++ ++//// [b.ts] ++import defer foo from "a"; ++ ++foo(); ++ ++//// [a.js] ++export default function foo() { ++ console.log("foo from a"); ++} ++//// [b.js] ++import defer foo from "a"; ++foo(); +diff --git a/tests/baselines/reference/importDeferInvalidDefault.symbols b/tests/baselines/reference/importDeferInvalidDefault.symbols +new file mode 100644 +index 000000000..dd548fc59 +--- /dev/null ++++ b/tests/baselines/reference/importDeferInvalidDefault.symbols +@@ -0,0 +1,19 @@ ++//// [tests/cases/conformance/importDefer/importDeferInvalidDefault.ts] //// ++ ++=== a.ts === ++export default function foo() { ++>foo : Symbol(foo, Decl(a.ts, 0, 0)) ++ ++ console.log("foo from a"); ++>console.log : Symbol(Console.log, Decl(lib.dom.d.ts, --, --)) ++>console : Symbol(console, Decl(lib.dom.d.ts, --, --)) ++>log : Symbol(Console.log, Decl(lib.dom.d.ts, --, --)) ++} ++ ++=== b.ts === ++import defer foo from "a"; ++>foo : Symbol(foo, Decl(b.ts, 0, 6)) ++ ++foo(); ++>foo : Symbol(foo, Decl(b.ts, 0, 6)) ++ +diff --git a/tests/baselines/reference/importDeferInvalidDefault.types b/tests/baselines/reference/importDeferInvalidDefault.types +new file mode 100644 +index 000000000..ae22c6fd8 +--- /dev/null ++++ b/tests/baselines/reference/importDeferInvalidDefault.types +@@ -0,0 +1,31 @@ ++//// [tests/cases/conformance/importDefer/importDeferInvalidDefault.ts] //// ++ ++=== a.ts === ++export default function foo() { ++>foo : () => void ++> : ^^^^^^^^^^ ++ ++ console.log("foo from a"); ++>console.log("foo from a") : void ++> : ^^^^ ++>console.log : (...data: any[]) => void ++> : ^^^^ ^^ ^^^^^ ++>console : Console ++> : ^^^^^^^ ++>log : (...data: any[]) => void ++> : ^^^^ ^^ ^^^^^ ++>"foo from a" : "foo from a" ++> : ^^^^^^^^^^^^ ++} ++ ++=== b.ts === ++import defer foo from "a"; ++>foo : () => void ++> : ^^^^^^^^^^ ++ ++foo(); ++>foo() : void ++> : ^^^^ ++>foo : () => void ++> : ^^^^^^^^^^ ++ +diff --git a/tests/baselines/reference/importDeferInvalidNamed.errors.txt b/tests/baselines/reference/importDeferInvalidNamed.errors.txt +new file mode 100644 +index 000000000..ef2015d65 +--- /dev/null ++++ b/tests/baselines/reference/importDeferInvalidNamed.errors.txt +@@ -0,0 +1,14 @@ ++b.ts(1,8): error TS18059: Named imports are not allowed in a deferred import. ++ ++ ++==== a.ts (0 errors) ==== ++ export function foo() { ++ console.log("foo from a"); ++ } ++ ++==== b.ts (1 errors) ==== ++ import defer { foo } from "a"; ++ ~~~~~~~~~~~~~ ++!!! error TS18059: Named imports are not allowed in a deferred import. ++ ++ foo(); +\ No newline at end of file +diff --git a/tests/baselines/reference/importDeferInvalidNamed.js b/tests/baselines/reference/importDeferInvalidNamed.js +new file mode 100644 +index 000000000..8f92f52fa +--- /dev/null ++++ b/tests/baselines/reference/importDeferInvalidNamed.js +@@ -0,0 +1,19 @@ ++//// [tests/cases/conformance/importDefer/importDeferInvalidNamed.ts] //// ++ ++//// [a.ts] ++export function foo() { ++ console.log("foo from a"); ++} ++ ++//// [b.ts] ++import defer { foo } from "a"; ++ ++foo(); ++ ++//// [a.js] ++export function foo() { ++ console.log("foo from a"); ++} ++//// [b.js] ++import defer { foo } from "a"; ++foo(); +diff --git a/tests/baselines/reference/importDeferInvalidNamed.symbols b/tests/baselines/reference/importDeferInvalidNamed.symbols +new file mode 100644 +index 000000000..77f3959cd +--- /dev/null ++++ b/tests/baselines/reference/importDeferInvalidNamed.symbols +@@ -0,0 +1,19 @@ ++//// [tests/cases/conformance/importDefer/importDeferInvalidNamed.ts] //// ++ ++=== a.ts === ++export function foo() { ++>foo : Symbol(foo, Decl(a.ts, 0, 0)) ++ ++ console.log("foo from a"); ++>console.log : Symbol(Console.log, Decl(lib.dom.d.ts, --, --)) ++>console : Symbol(console, Decl(lib.dom.d.ts, --, --)) ++>log : Symbol(Console.log, Decl(lib.dom.d.ts, --, --)) ++} ++ ++=== b.ts === ++import defer { foo } from "a"; ++>foo : Symbol(foo, Decl(b.ts, 0, 14)) ++ ++foo(); ++>foo : Symbol(foo, Decl(b.ts, 0, 14)) ++ +diff --git a/tests/baselines/reference/importDeferInvalidNamed.types b/tests/baselines/reference/importDeferInvalidNamed.types +new file mode 100644 +index 000000000..556852360 +--- /dev/null ++++ b/tests/baselines/reference/importDeferInvalidNamed.types +@@ -0,0 +1,31 @@ ++//// [tests/cases/conformance/importDefer/importDeferInvalidNamed.ts] //// ++ ++=== a.ts === ++export function foo() { ++>foo : () => void ++> : ^^^^^^^^^^ ++ ++ console.log("foo from a"); ++>console.log("foo from a") : void ++> : ^^^^ ++>console.log : (...data: any[]) => void ++> : ^^^^ ^^ ^^^^^ ++>console : Console ++> : ^^^^^^^ ++>log : (...data: any[]) => void ++> : ^^^^ ^^ ^^^^^ ++>"foo from a" : "foo from a" ++> : ^^^^^^^^^^^^ ++} ++ ++=== b.ts === ++import defer { foo } from "a"; ++>foo : () => void ++> : ^^^^^^^^^^ ++ ++foo(); ++>foo() : void ++> : ^^^^ ++>foo : () => void ++> : ^^^^^^^^^^ ++ +diff --git a/tests/baselines/reference/importDeferJsdoc.errors.txt b/tests/baselines/reference/importDeferJsdoc.errors.txt +new file mode 100644 +index 000000000..e6b221583 +--- /dev/null ++++ b/tests/baselines/reference/importDeferJsdoc.errors.txt +@@ -0,0 +1,21 @@ ++/foo.js(2,18): error TS1005: 'from' expected. ++/foo.js(6,12): error TS2503: Cannot find namespace 'ns'. ++ ++ ++==== /types.ts (0 errors) ==== ++ export type X = 1; ++ ++==== /foo.js (2 errors) ==== ++ /** ++ * @import defer * as ns from "./types" ++ ~ ++!!! error TS1005: 'from' expected. ++ */ ++ ++ /** ++ * @type { ns.X } ++ ~~ ++!!! error TS2503: Cannot find namespace 'ns'. ++ */ ++ let a = 2; ++ +\ No newline at end of file +diff --git a/tests/baselines/reference/importDeferJsdoc.js b/tests/baselines/reference/importDeferJsdoc.js +new file mode 100644 +index 000000000..13607f52d +--- /dev/null ++++ b/tests/baselines/reference/importDeferJsdoc.js +@@ -0,0 +1,28 @@ ++//// [tests/cases/conformance/jsdoc/importDeferJsdoc.ts] //// ++ ++//// [types.ts] ++export type X = 1; ++ ++//// [foo.js] ++/** ++ * @import defer * as ns from "./types" ++ */ ++ ++/** ++ * @type { ns.X } ++ */ ++let a = 2; ++ ++ ++ ++ ++//// [types.d.ts] ++export type X = 1; ++//// [foo.d.ts] ++/** ++ * @import defer * as ns from "./types" ++ */ ++/** ++ * @type { ns.X } ++ */ ++declare let a: ns.X; +diff --git a/tests/baselines/reference/importDeferJsdoc.symbols b/tests/baselines/reference/importDeferJsdoc.symbols +new file mode 100644 +index 000000000..ccedb5286 +--- /dev/null ++++ b/tests/baselines/reference/importDeferJsdoc.symbols +@@ -0,0 +1,17 @@ ++//// [tests/cases/conformance/jsdoc/importDeferJsdoc.ts] //// ++ ++=== /types.ts === ++export type X = 1; ++>X : Symbol(X, Decl(types.ts, 0, 0)) ++ ++=== /foo.js === ++/** ++ * @import defer * as ns from "./types" ++ */ ++ ++/** ++ * @type { ns.X } ++ */ ++let a = 2; ++>a : Symbol(a, Decl(foo.js, 7, 3)) ++ +diff --git a/tests/baselines/reference/importDeferJsdoc.types b/tests/baselines/reference/importDeferJsdoc.types +new file mode 100644 +index 000000000..e2eba5b83 +--- /dev/null ++++ b/tests/baselines/reference/importDeferJsdoc.types +@@ -0,0 +1,21 @@ ++//// [tests/cases/conformance/jsdoc/importDeferJsdoc.ts] //// ++ ++=== /types.ts === ++export type X = 1; ++>X : 1 ++> : ^ ++ ++=== /foo.js === ++/** ++ * @import defer * as ns from "./types" ++ */ ++ ++/** ++ * @type { ns.X } ++ */ ++let a = 2; ++>a : ns.X ++> : ^^^^ ++>2 : 2 ++> : ^ ++ +diff --git a/tests/baselines/reference/importDeferNamespace(module=commonjs).errors.txt b/tests/baselines/reference/importDeferNamespace(module=commonjs).errors.txt +new file mode 100644 +index 000000000..74c011b13 +--- /dev/null ++++ b/tests/baselines/reference/importDeferNamespace(module=commonjs).errors.txt +@@ -0,0 +1,14 @@ ++b.ts(1,8): error TS18060: Deferred imports are only supported when the '--module' flag is set to 'esnext' or 'preserve'. ++ ++ ++==== a.ts (0 errors) ==== ++ export function foo() { ++ console.log("foo from a"); ++ } ++ ++==== b.ts (1 errors) ==== ++ import defer * as aNs from "./a.js"; ++ ~~~~~~~~~~~~~~ ++!!! error TS18060: Deferred imports are only supported when the '--module' flag is set to 'esnext' or 'preserve'. ++ ++ aNs.foo(); +\ No newline at end of file +diff --git a/tests/baselines/reference/importDeferNamespace(module=commonjs).js b/tests/baselines/reference/importDeferNamespace(module=commonjs).js +new file mode 100644 +index 000000000..181c47173 +--- /dev/null ++++ b/tests/baselines/reference/importDeferNamespace(module=commonjs).js +@@ -0,0 +1,24 @@ ++//// [tests/cases/conformance/importDefer/importDeferNamespace.ts] //// ++ ++//// [a.ts] ++export function foo() { ++ console.log("foo from a"); ++} ++ ++//// [b.ts] ++import defer * as aNs from "./a.js"; ++ ++aNs.foo(); ++ ++//// [a.js] ++"use strict"; ++Object.defineProperty(exports, "__esModule", { value: true }); ++exports.foo = foo; ++function foo() { ++ console.log("foo from a"); ++} ++//// [b.js] ++"use strict"; ++Object.defineProperty(exports, "__esModule", { value: true }); ++const aNs = require("./a.js"); ++aNs.foo(); +diff --git a/tests/baselines/reference/importDeferNamespace(module=commonjs).symbols b/tests/baselines/reference/importDeferNamespace(module=commonjs).symbols +new file mode 100644 +index 000000000..eca0a04a7 +--- /dev/null ++++ b/tests/baselines/reference/importDeferNamespace(module=commonjs).symbols +@@ -0,0 +1,21 @@ ++//// [tests/cases/conformance/importDefer/importDeferNamespace.ts] //// ++ ++=== a.ts === ++export function foo() { ++>foo : Symbol(foo, Decl(a.ts, 0, 0)) ++ ++ console.log("foo from a"); ++>console.log : Symbol(Console.log, Decl(lib.dom.d.ts, --, --)) ++>console : Symbol(console, Decl(lib.dom.d.ts, --, --)) ++>log : Symbol(Console.log, Decl(lib.dom.d.ts, --, --)) ++} ++ ++=== b.ts === ++import defer * as aNs from "./a.js"; ++>aNs : Symbol(aNs, Decl(b.ts, 0, 12)) ++ ++aNs.foo(); ++>aNs.foo : Symbol(aNs.foo, Decl(a.ts, 0, 0)) ++>aNs : Symbol(aNs, Decl(b.ts, 0, 12)) ++>foo : Symbol(aNs.foo, Decl(a.ts, 0, 0)) ++ +diff --git a/tests/baselines/reference/importDeferNamespace(module=commonjs).types b/tests/baselines/reference/importDeferNamespace(module=commonjs).types +new file mode 100644 +index 000000000..3f99c7848 +--- /dev/null ++++ b/tests/baselines/reference/importDeferNamespace(module=commonjs).types +@@ -0,0 +1,35 @@ ++//// [tests/cases/conformance/importDefer/importDeferNamespace.ts] //// ++ ++=== a.ts === ++export function foo() { ++>foo : () => void ++> : ^^^^^^^^^^ ++ ++ console.log("foo from a"); ++>console.log("foo from a") : void ++> : ^^^^ ++>console.log : (...data: any[]) => void ++> : ^^^^ ^^ ^^^^^ ++>console : Console ++> : ^^^^^^^ ++>log : (...data: any[]) => void ++> : ^^^^ ^^ ^^^^^ ++>"foo from a" : "foo from a" ++> : ^^^^^^^^^^^^ ++} ++ ++=== b.ts === ++import defer * as aNs from "./a.js"; ++>aNs : typeof aNs ++> : ^^^^^^^^^^ ++ ++aNs.foo(); ++>aNs.foo() : void ++> : ^^^^ ++>aNs.foo : () => void ++> : ^^^^^^^^^^ ++>aNs : typeof aNs ++> : ^^^^^^^^^^ ++>foo : () => void ++> : ^^^^^^^^^^ ++ +diff --git a/tests/baselines/reference/importDeferNamespace(module=es2015).errors.txt b/tests/baselines/reference/importDeferNamespace(module=es2015).errors.txt +new file mode 100644 +index 000000000..74c011b13 +--- /dev/null ++++ b/tests/baselines/reference/importDeferNamespace(module=es2015).errors.txt +@@ -0,0 +1,14 @@ ++b.ts(1,8): error TS18060: Deferred imports are only supported when the '--module' flag is set to 'esnext' or 'preserve'. ++ ++ ++==== a.ts (0 errors) ==== ++ export function foo() { ++ console.log("foo from a"); ++ } ++ ++==== b.ts (1 errors) ==== ++ import defer * as aNs from "./a.js"; ++ ~~~~~~~~~~~~~~ ++!!! error TS18060: Deferred imports are only supported when the '--module' flag is set to 'esnext' or 'preserve'. ++ ++ aNs.foo(); +\ No newline at end of file +diff --git a/tests/baselines/reference/importDeferNamespace(module=es2015).js b/tests/baselines/reference/importDeferNamespace(module=es2015).js +new file mode 100644 +index 000000000..29d60657f +--- /dev/null ++++ b/tests/baselines/reference/importDeferNamespace(module=es2015).js +@@ -0,0 +1,19 @@ ++//// [tests/cases/conformance/importDefer/importDeferNamespace.ts] //// ++ ++//// [a.ts] ++export function foo() { ++ console.log("foo from a"); ++} ++ ++//// [b.ts] ++import defer * as aNs from "./a.js"; ++ ++aNs.foo(); ++ ++//// [a.js] ++export function foo() { ++ console.log("foo from a"); ++} ++//// [b.js] ++import defer * as aNs from "./a.js"; ++aNs.foo(); +diff --git a/tests/baselines/reference/importDeferNamespace(module=es2015).symbols b/tests/baselines/reference/importDeferNamespace(module=es2015).symbols +new file mode 100644 +index 000000000..eca0a04a7 +--- /dev/null ++++ b/tests/baselines/reference/importDeferNamespace(module=es2015).symbols +@@ -0,0 +1,21 @@ ++//// [tests/cases/conformance/importDefer/importDeferNamespace.ts] //// ++ ++=== a.ts === ++export function foo() { ++>foo : Symbol(foo, Decl(a.ts, 0, 0)) ++ ++ console.log("foo from a"); ++>console.log : Symbol(Console.log, Decl(lib.dom.d.ts, --, --)) ++>console : Symbol(console, Decl(lib.dom.d.ts, --, --)) ++>log : Symbol(Console.log, Decl(lib.dom.d.ts, --, --)) ++} ++ ++=== b.ts === ++import defer * as aNs from "./a.js"; ++>aNs : Symbol(aNs, Decl(b.ts, 0, 12)) ++ ++aNs.foo(); ++>aNs.foo : Symbol(aNs.foo, Decl(a.ts, 0, 0)) ++>aNs : Symbol(aNs, Decl(b.ts, 0, 12)) ++>foo : Symbol(aNs.foo, Decl(a.ts, 0, 0)) ++ +diff --git a/tests/baselines/reference/importDeferNamespace(module=es2015).types b/tests/baselines/reference/importDeferNamespace(module=es2015).types +new file mode 100644 +index 000000000..3f99c7848 +--- /dev/null ++++ b/tests/baselines/reference/importDeferNamespace(module=es2015).types +@@ -0,0 +1,35 @@ ++//// [tests/cases/conformance/importDefer/importDeferNamespace.ts] //// ++ ++=== a.ts === ++export function foo() { ++>foo : () => void ++> : ^^^^^^^^^^ ++ ++ console.log("foo from a"); ++>console.log("foo from a") : void ++> : ^^^^ ++>console.log : (...data: any[]) => void ++> : ^^^^ ^^ ^^^^^ ++>console : Console ++> : ^^^^^^^ ++>log : (...data: any[]) => void ++> : ^^^^ ^^ ^^^^^ ++>"foo from a" : "foo from a" ++> : ^^^^^^^^^^^^ ++} ++ ++=== b.ts === ++import defer * as aNs from "./a.js"; ++>aNs : typeof aNs ++> : ^^^^^^^^^^ ++ ++aNs.foo(); ++>aNs.foo() : void ++> : ^^^^ ++>aNs.foo : () => void ++> : ^^^^^^^^^^ ++>aNs : typeof aNs ++> : ^^^^^^^^^^ ++>foo : () => void ++> : ^^^^^^^^^^ ++ +diff --git a/tests/baselines/reference/importDeferNamespace(module=es2020).errors.txt b/tests/baselines/reference/importDeferNamespace(module=es2020).errors.txt +new file mode 100644 +index 000000000..74c011b13 +--- /dev/null ++++ b/tests/baselines/reference/importDeferNamespace(module=es2020).errors.txt +@@ -0,0 +1,14 @@ ++b.ts(1,8): error TS18060: Deferred imports are only supported when the '--module' flag is set to 'esnext' or 'preserve'. ++ ++ ++==== a.ts (0 errors) ==== ++ export function foo() { ++ console.log("foo from a"); ++ } ++ ++==== b.ts (1 errors) ==== ++ import defer * as aNs from "./a.js"; ++ ~~~~~~~~~~~~~~ ++!!! error TS18060: Deferred imports are only supported when the '--module' flag is set to 'esnext' or 'preserve'. ++ ++ aNs.foo(); +\ No newline at end of file +diff --git a/tests/baselines/reference/importDeferNamespace(module=es2020).js b/tests/baselines/reference/importDeferNamespace(module=es2020).js +new file mode 100644 +index 000000000..29d60657f +--- /dev/null ++++ b/tests/baselines/reference/importDeferNamespace(module=es2020).js +@@ -0,0 +1,19 @@ ++//// [tests/cases/conformance/importDefer/importDeferNamespace.ts] //// ++ ++//// [a.ts] ++export function foo() { ++ console.log("foo from a"); ++} ++ ++//// [b.ts] ++import defer * as aNs from "./a.js"; ++ ++aNs.foo(); ++ ++//// [a.js] ++export function foo() { ++ console.log("foo from a"); ++} ++//// [b.js] ++import defer * as aNs from "./a.js"; ++aNs.foo(); +diff --git a/tests/baselines/reference/importDeferNamespace(module=es2020).symbols b/tests/baselines/reference/importDeferNamespace(module=es2020).symbols +new file mode 100644 +index 000000000..eca0a04a7 +--- /dev/null ++++ b/tests/baselines/reference/importDeferNamespace(module=es2020).symbols +@@ -0,0 +1,21 @@ ++//// [tests/cases/conformance/importDefer/importDeferNamespace.ts] //// ++ ++=== a.ts === ++export function foo() { ++>foo : Symbol(foo, Decl(a.ts, 0, 0)) ++ ++ console.log("foo from a"); ++>console.log : Symbol(Console.log, Decl(lib.dom.d.ts, --, --)) ++>console : Symbol(console, Decl(lib.dom.d.ts, --, --)) ++>log : Symbol(Console.log, Decl(lib.dom.d.ts, --, --)) ++} ++ ++=== b.ts === ++import defer * as aNs from "./a.js"; ++>aNs : Symbol(aNs, Decl(b.ts, 0, 12)) ++ ++aNs.foo(); ++>aNs.foo : Symbol(aNs.foo, Decl(a.ts, 0, 0)) ++>aNs : Symbol(aNs, Decl(b.ts, 0, 12)) ++>foo : Symbol(aNs.foo, Decl(a.ts, 0, 0)) ++ +diff --git a/tests/baselines/reference/importDeferNamespace(module=es2020).types b/tests/baselines/reference/importDeferNamespace(module=es2020).types +new file mode 100644 +index 000000000..3f99c7848 +--- /dev/null ++++ b/tests/baselines/reference/importDeferNamespace(module=es2020).types +@@ -0,0 +1,35 @@ ++//// [tests/cases/conformance/importDefer/importDeferNamespace.ts] //// ++ ++=== a.ts === ++export function foo() { ++>foo : () => void ++> : ^^^^^^^^^^ ++ ++ console.log("foo from a"); ++>console.log("foo from a") : void ++> : ^^^^ ++>console.log : (...data: any[]) => void ++> : ^^^^ ^^ ^^^^^ ++>console : Console ++> : ^^^^^^^ ++>log : (...data: any[]) => void ++> : ^^^^ ^^ ^^^^^ ++>"foo from a" : "foo from a" ++> : ^^^^^^^^^^^^ ++} ++ ++=== b.ts === ++import defer * as aNs from "./a.js"; ++>aNs : typeof aNs ++> : ^^^^^^^^^^ ++ ++aNs.foo(); ++>aNs.foo() : void ++> : ^^^^ ++>aNs.foo : () => void ++> : ^^^^^^^^^^ ++>aNs : typeof aNs ++> : ^^^^^^^^^^ ++>foo : () => void ++> : ^^^^^^^^^^ ++ +diff --git a/tests/baselines/reference/importDeferNamespace(module=esnext).js b/tests/baselines/reference/importDeferNamespace(module=esnext).js +new file mode 100644 +index 000000000..29d60657f +--- /dev/null ++++ b/tests/baselines/reference/importDeferNamespace(module=esnext).js +@@ -0,0 +1,19 @@ ++//// [tests/cases/conformance/importDefer/importDeferNamespace.ts] //// ++ ++//// [a.ts] ++export function foo() { ++ console.log("foo from a"); ++} ++ ++//// [b.ts] ++import defer * as aNs from "./a.js"; ++ ++aNs.foo(); ++ ++//// [a.js] ++export function foo() { ++ console.log("foo from a"); ++} ++//// [b.js] ++import defer * as aNs from "./a.js"; ++aNs.foo(); +diff --git a/tests/baselines/reference/importDeferNamespace(module=esnext).symbols b/tests/baselines/reference/importDeferNamespace(module=esnext).symbols +new file mode 100644 +index 000000000..eca0a04a7 +--- /dev/null ++++ b/tests/baselines/reference/importDeferNamespace(module=esnext).symbols +@@ -0,0 +1,21 @@ ++//// [tests/cases/conformance/importDefer/importDeferNamespace.ts] //// ++ ++=== a.ts === ++export function foo() { ++>foo : Symbol(foo, Decl(a.ts, 0, 0)) ++ ++ console.log("foo from a"); ++>console.log : Symbol(Console.log, Decl(lib.dom.d.ts, --, --)) ++>console : Symbol(console, Decl(lib.dom.d.ts, --, --)) ++>log : Symbol(Console.log, Decl(lib.dom.d.ts, --, --)) ++} ++ ++=== b.ts === ++import defer * as aNs from "./a.js"; ++>aNs : Symbol(aNs, Decl(b.ts, 0, 12)) ++ ++aNs.foo(); ++>aNs.foo : Symbol(aNs.foo, Decl(a.ts, 0, 0)) ++>aNs : Symbol(aNs, Decl(b.ts, 0, 12)) ++>foo : Symbol(aNs.foo, Decl(a.ts, 0, 0)) ++ +diff --git a/tests/baselines/reference/importDeferNamespace(module=esnext).types b/tests/baselines/reference/importDeferNamespace(module=esnext).types +new file mode 100644 +index 000000000..3f99c7848 +--- /dev/null ++++ b/tests/baselines/reference/importDeferNamespace(module=esnext).types +@@ -0,0 +1,35 @@ ++//// [tests/cases/conformance/importDefer/importDeferNamespace.ts] //// ++ ++=== a.ts === ++export function foo() { ++>foo : () => void ++> : ^^^^^^^^^^ ++ ++ console.log("foo from a"); ++>console.log("foo from a") : void ++> : ^^^^ ++>console.log : (...data: any[]) => void ++> : ^^^^ ^^ ^^^^^ ++>console : Console ++> : ^^^^^^^ ++>log : (...data: any[]) => void ++> : ^^^^ ^^ ^^^^^ ++>"foo from a" : "foo from a" ++> : ^^^^^^^^^^^^ ++} ++ ++=== b.ts === ++import defer * as aNs from "./a.js"; ++>aNs : typeof aNs ++> : ^^^^^^^^^^ ++ ++aNs.foo(); ++>aNs.foo() : void ++> : ^^^^ ++>aNs.foo : () => void ++> : ^^^^^^^^^^ ++>aNs : typeof aNs ++> : ^^^^^^^^^^ ++>foo : () => void ++> : ^^^^^^^^^^ ++ +diff --git a/tests/baselines/reference/importDeferNamespace(module=nodenext).errors.txt b/tests/baselines/reference/importDeferNamespace(module=nodenext).errors.txt +new file mode 100644 +index 000000000..74c011b13 +--- /dev/null ++++ b/tests/baselines/reference/importDeferNamespace(module=nodenext).errors.txt +@@ -0,0 +1,14 @@ ++b.ts(1,8): error TS18060: Deferred imports are only supported when the '--module' flag is set to 'esnext' or 'preserve'. ++ ++ ++==== a.ts (0 errors) ==== ++ export function foo() { ++ console.log("foo from a"); ++ } ++ ++==== b.ts (1 errors) ==== ++ import defer * as aNs from "./a.js"; ++ ~~~~~~~~~~~~~~ ++!!! error TS18060: Deferred imports are only supported when the '--module' flag is set to 'esnext' or 'preserve'. ++ ++ aNs.foo(); +\ No newline at end of file +diff --git a/tests/baselines/reference/importDeferNamespace(module=nodenext).js b/tests/baselines/reference/importDeferNamespace(module=nodenext).js +new file mode 100644 +index 000000000..95cd4ac60 +--- /dev/null ++++ b/tests/baselines/reference/importDeferNamespace(module=nodenext).js +@@ -0,0 +1,57 @@ ++//// [tests/cases/conformance/importDefer/importDeferNamespace.ts] //// ++ ++//// [a.ts] ++export function foo() { ++ console.log("foo from a"); ++} ++ ++//// [b.ts] ++import defer * as aNs from "./a.js"; ++ ++aNs.foo(); ++ ++//// [a.js] ++"use strict"; ++Object.defineProperty(exports, "__esModule", { value: true }); ++exports.foo = foo; ++function foo() { ++ console.log("foo from a"); ++} ++//// [b.js] ++"use strict"; ++var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { ++ if (k2 === undefined) k2 = k; ++ var desc = Object.getOwnPropertyDescriptor(m, k); ++ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { ++ desc = { enumerable: true, get: function() { return m[k]; } }; ++ } ++ Object.defineProperty(o, k2, desc); ++}) : (function(o, m, k, k2) { ++ if (k2 === undefined) k2 = k; ++ o[k2] = m[k]; ++})); ++var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { ++ Object.defineProperty(o, "default", { enumerable: true, value: v }); ++}) : function(o, v) { ++ o["default"] = v; ++}); ++var __importStar = (this && this.__importStar) || (function () { ++ var ownKeys = function(o) { ++ ownKeys = Object.getOwnPropertyNames || function (o) { ++ var ar = []; ++ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; ++ return ar; ++ }; ++ return ownKeys(o); ++ }; ++ return function (mod) { ++ if (mod && mod.__esModule) return mod; ++ var result = {}; ++ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); ++ __setModuleDefault(result, mod); ++ return result; ++ }; ++})(); ++Object.defineProperty(exports, "__esModule", { value: true }); ++const aNs = __importStar(require("./a.js")); ++aNs.foo(); +diff --git a/tests/baselines/reference/importDeferNamespace(module=nodenext).symbols b/tests/baselines/reference/importDeferNamespace(module=nodenext).symbols +new file mode 100644 +index 000000000..eca0a04a7 +--- /dev/null ++++ b/tests/baselines/reference/importDeferNamespace(module=nodenext).symbols +@@ -0,0 +1,21 @@ ++//// [tests/cases/conformance/importDefer/importDeferNamespace.ts] //// ++ ++=== a.ts === ++export function foo() { ++>foo : Symbol(foo, Decl(a.ts, 0, 0)) ++ ++ console.log("foo from a"); ++>console.log : Symbol(Console.log, Decl(lib.dom.d.ts, --, --)) ++>console : Symbol(console, Decl(lib.dom.d.ts, --, --)) ++>log : Symbol(Console.log, Decl(lib.dom.d.ts, --, --)) ++} ++ ++=== b.ts === ++import defer * as aNs from "./a.js"; ++>aNs : Symbol(aNs, Decl(b.ts, 0, 12)) ++ ++aNs.foo(); ++>aNs.foo : Symbol(aNs.foo, Decl(a.ts, 0, 0)) ++>aNs : Symbol(aNs, Decl(b.ts, 0, 12)) ++>foo : Symbol(aNs.foo, Decl(a.ts, 0, 0)) ++ +diff --git a/tests/baselines/reference/importDeferNamespace(module=nodenext).types b/tests/baselines/reference/importDeferNamespace(module=nodenext).types +new file mode 100644 +index 000000000..3f99c7848 +--- /dev/null ++++ b/tests/baselines/reference/importDeferNamespace(module=nodenext).types +@@ -0,0 +1,35 @@ ++//// [tests/cases/conformance/importDefer/importDeferNamespace.ts] //// ++ ++=== a.ts === ++export function foo() { ++>foo : () => void ++> : ^^^^^^^^^^ ++ ++ console.log("foo from a"); ++>console.log("foo from a") : void ++> : ^^^^ ++>console.log : (...data: any[]) => void ++> : ^^^^ ^^ ^^^^^ ++>console : Console ++> : ^^^^^^^ ++>log : (...data: any[]) => void ++> : ^^^^ ^^ ^^^^^ ++>"foo from a" : "foo from a" ++> : ^^^^^^^^^^^^ ++} ++ ++=== b.ts === ++import defer * as aNs from "./a.js"; ++>aNs : typeof aNs ++> : ^^^^^^^^^^ ++ ++aNs.foo(); ++>aNs.foo() : void ++> : ^^^^ ++>aNs.foo : () => void ++> : ^^^^^^^^^^ ++>aNs : typeof aNs ++> : ^^^^^^^^^^ ++>foo : () => void ++> : ^^^^^^^^^^ ++ +diff --git a/tests/baselines/reference/importDeferNamespace(module=preserve).js b/tests/baselines/reference/importDeferNamespace(module=preserve).js +new file mode 100644 +index 000000000..29d60657f +--- /dev/null ++++ b/tests/baselines/reference/importDeferNamespace(module=preserve).js +@@ -0,0 +1,19 @@ ++//// [tests/cases/conformance/importDefer/importDeferNamespace.ts] //// ++ ++//// [a.ts] ++export function foo() { ++ console.log("foo from a"); ++} ++ ++//// [b.ts] ++import defer * as aNs from "./a.js"; ++ ++aNs.foo(); ++ ++//// [a.js] ++export function foo() { ++ console.log("foo from a"); ++} ++//// [b.js] ++import defer * as aNs from "./a.js"; ++aNs.foo(); +diff --git a/tests/baselines/reference/importDeferNamespace(module=preserve).symbols b/tests/baselines/reference/importDeferNamespace(module=preserve).symbols +new file mode 100644 +index 000000000..eca0a04a7 +--- /dev/null ++++ b/tests/baselines/reference/importDeferNamespace(module=preserve).symbols +@@ -0,0 +1,21 @@ ++//// [tests/cases/conformance/importDefer/importDeferNamespace.ts] //// ++ ++=== a.ts === ++export function foo() { ++>foo : Symbol(foo, Decl(a.ts, 0, 0)) ++ ++ console.log("foo from a"); ++>console.log : Symbol(Console.log, Decl(lib.dom.d.ts, --, --)) ++>console : Symbol(console, Decl(lib.dom.d.ts, --, --)) ++>log : Symbol(Console.log, Decl(lib.dom.d.ts, --, --)) ++} ++ ++=== b.ts === ++import defer * as aNs from "./a.js"; ++>aNs : Symbol(aNs, Decl(b.ts, 0, 12)) ++ ++aNs.foo(); ++>aNs.foo : Symbol(aNs.foo, Decl(a.ts, 0, 0)) ++>aNs : Symbol(aNs, Decl(b.ts, 0, 12)) ++>foo : Symbol(aNs.foo, Decl(a.ts, 0, 0)) ++ +diff --git a/tests/baselines/reference/importDeferNamespace(module=preserve).types b/tests/baselines/reference/importDeferNamespace(module=preserve).types +new file mode 100644 +index 000000000..3f99c7848 +--- /dev/null ++++ b/tests/baselines/reference/importDeferNamespace(module=preserve).types +@@ -0,0 +1,35 @@ ++//// [tests/cases/conformance/importDefer/importDeferNamespace.ts] //// ++ ++=== a.ts === ++export function foo() { ++>foo : () => void ++> : ^^^^^^^^^^ ++ ++ console.log("foo from a"); ++>console.log("foo from a") : void ++> : ^^^^ ++>console.log : (...data: any[]) => void ++> : ^^^^ ^^ ^^^^^ ++>console : Console ++> : ^^^^^^^ ++>log : (...data: any[]) => void ++> : ^^^^ ^^ ^^^^^ ++>"foo from a" : "foo from a" ++> : ^^^^^^^^^^^^ ++} ++ ++=== b.ts === ++import defer * as aNs from "./a.js"; ++>aNs : typeof aNs ++> : ^^^^^^^^^^ ++ ++aNs.foo(); ++>aNs.foo() : void ++> : ^^^^ ++>aNs.foo : () => void ++> : ^^^^^^^^^^ ++>aNs : typeof aNs ++> : ^^^^^^^^^^ ++>foo : () => void ++> : ^^^^^^^^^^ ++ +diff --git a/tests/baselines/reference/importDeferTypeConflict1.errors.txt b/tests/baselines/reference/importDeferTypeConflict1.errors.txt +new file mode 100644 +index 000000000..138cfa68e +--- /dev/null ++++ b/tests/baselines/reference/importDeferTypeConflict1.errors.txt +@@ -0,0 +1,28 @@ ++b.ts(1,19): error TS1005: '=' expected. ++b.ts(1,21): error TS2304: Cannot find name 'as'. ++b.ts(1,24): error TS1005: ';' expected. ++b.ts(1,24): error TS2304: Cannot find name 'ns1'. ++b.ts(1,28): error TS1434: Unexpected keyword or identifier. ++b.ts(1,28): error TS2304: Cannot find name 'from'. ++ ++ ++==== a.ts (0 errors) ==== ++ export function foo() { ++ console.log("foo from a"); ++ } ++ ++==== b.ts (6 errors) ==== ++ import type defer * as ns1 from "a"; ++ ~ ++!!! error TS1005: '=' expected. ++ ~~ ++!!! error TS2304: Cannot find name 'as'. ++ ~~~ ++!!! error TS1005: ';' expected. ++ ~~~ ++!!! error TS2304: Cannot find name 'ns1'. ++ ~~~~ ++!!! error TS1434: Unexpected keyword or identifier. ++ ~~~~ ++!!! error TS2304: Cannot find name 'from'. ++ +\ No newline at end of file +diff --git a/tests/baselines/reference/importDeferTypeConflict1.js b/tests/baselines/reference/importDeferTypeConflict1.js +new file mode 100644 +index 000000000..0577f6a08 +--- /dev/null ++++ b/tests/baselines/reference/importDeferTypeConflict1.js +@@ -0,0 +1,20 @@ ++//// [tests/cases/conformance/importDefer/importDeferTypeConflict1.ts] //// ++ ++//// [a.ts] ++export function foo() { ++ console.log("foo from a"); ++} ++ ++//// [b.ts] ++import type defer * as ns1 from "a"; ++ ++ ++//// [a.js] ++export function foo() { ++ console.log("foo from a"); ++} ++//// [b.js] ++ * as; ++ns1; ++from; ++"a"; +diff --git a/tests/baselines/reference/importDeferTypeConflict1.symbols b/tests/baselines/reference/importDeferTypeConflict1.symbols +new file mode 100644 +index 000000000..961367f24 +--- /dev/null ++++ b/tests/baselines/reference/importDeferTypeConflict1.symbols +@@ -0,0 +1,16 @@ ++//// [tests/cases/conformance/importDefer/importDeferTypeConflict1.ts] //// ++ ++=== a.ts === ++export function foo() { ++>foo : Symbol(foo, Decl(a.ts, 0, 0)) ++ ++ console.log("foo from a"); ++>console.log : Symbol(Console.log, Decl(lib.dom.d.ts, --, --)) ++>console : Symbol(console, Decl(lib.dom.d.ts, --, --)) ++>log : Symbol(Console.log, Decl(lib.dom.d.ts, --, --)) ++} ++ ++=== b.ts === ++import type defer * as ns1 from "a"; ++>defer : Symbol(defer, Decl(b.ts, 0, 0)) ++ +diff --git a/tests/baselines/reference/importDeferTypeConflict1.types b/tests/baselines/reference/importDeferTypeConflict1.types +new file mode 100644 +index 000000000..ea2a7ef94 +--- /dev/null ++++ b/tests/baselines/reference/importDeferTypeConflict1.types +@@ -0,0 +1,39 @@ ++//// [tests/cases/conformance/importDefer/importDeferTypeConflict1.ts] //// ++ ++=== a.ts === ++export function foo() { ++>foo : () => void ++> : ^^^^^^^^^^ ++ ++ console.log("foo from a"); ++>console.log("foo from a") : void ++> : ^^^^ ++>console.log : (...data: any[]) => void ++> : ^^^^ ^^ ^^^^^ ++>console : Console ++> : ^^^^^^^ ++>log : (...data: any[]) => void ++> : ^^^^ ^^ ^^^^^ ++>"foo from a" : "foo from a" ++> : ^^^^^^^^^^^^ ++} ++ ++=== b.ts === ++import type defer * as ns1 from "a"; ++>defer : any ++> : ^^^ ++> : any ++> : ^^^ ++>* as : number ++> : ^^^^^^ ++> : any ++> : ^^^ ++>as : any ++> : ^^^ ++>ns1 : any ++> : ^^^ ++>from : any ++> : ^^^ ++>"a" : "a" ++> : ^^^ ++ +diff --git a/tests/baselines/reference/importDeferTypeConflict2.errors.txt b/tests/baselines/reference/importDeferTypeConflict2.errors.txt +new file mode 100644 +index 000000000..2387d3e34 +--- /dev/null ++++ b/tests/baselines/reference/importDeferTypeConflict2.errors.txt +@@ -0,0 +1,28 @@ ++b.ts(1,19): error TS1005: 'from' expected. ++b.ts(1,19): error TS1141: String literal expected. ++b.ts(1,24): error TS1005: ';' expected. ++b.ts(1,24): error TS2304: Cannot find name 'ns1'. ++b.ts(1,28): error TS1434: Unexpected keyword or identifier. ++b.ts(1,28): error TS2304: Cannot find name 'from'. ++ ++ ++==== a.ts (0 errors) ==== ++ export function foo() { ++ console.log("foo from a"); ++ } ++ ++==== b.ts (6 errors) ==== ++ import defer type * as ns1 from "a"; ++ ~ ++!!! error TS1005: 'from' expected. ++ ~~~~ ++!!! error TS1141: String literal expected. ++ ~~~ ++!!! error TS1005: ';' expected. ++ ~~~ ++!!! error TS2304: Cannot find name 'ns1'. ++ ~~~~ ++!!! error TS1434: Unexpected keyword or identifier. ++ ~~~~ ++!!! error TS2304: Cannot find name 'from'. ++ +\ No newline at end of file +diff --git a/tests/baselines/reference/importDeferTypeConflict2.js b/tests/baselines/reference/importDeferTypeConflict2.js +new file mode 100644 +index 000000000..1c06d7046 +--- /dev/null ++++ b/tests/baselines/reference/importDeferTypeConflict2.js +@@ -0,0 +1,20 @@ ++//// [tests/cases/conformance/importDefer/importDeferTypeConflict2.ts] //// ++ ++//// [a.ts] ++export function foo() { ++ console.log("foo from a"); ++} ++ ++//// [b.ts] ++import defer type * as ns1 from "a"; ++ ++ ++//// [a.js] ++export function foo() { ++ console.log("foo from a"); ++} ++//// [b.js] ++ns1; ++from; ++"a"; ++export {}; +diff --git a/tests/baselines/reference/importDeferTypeConflict2.symbols b/tests/baselines/reference/importDeferTypeConflict2.symbols +new file mode 100644 +index 000000000..ea867e3cf +--- /dev/null ++++ b/tests/baselines/reference/importDeferTypeConflict2.symbols +@@ -0,0 +1,16 @@ ++//// [tests/cases/conformance/importDefer/importDeferTypeConflict2.ts] //// ++ ++=== a.ts === ++export function foo() { ++>foo : Symbol(foo, Decl(a.ts, 0, 0)) ++ ++ console.log("foo from a"); ++>console.log : Symbol(Console.log, Decl(lib.dom.d.ts, --, --)) ++>console : Symbol(console, Decl(lib.dom.d.ts, --, --)) ++>log : Symbol(Console.log, Decl(lib.dom.d.ts, --, --)) ++} ++ ++=== b.ts === ++import defer type * as ns1 from "a"; ++>type : Symbol(type, Decl(b.ts, 0, 6)) ++ +diff --git a/tests/baselines/reference/importDeferTypeConflict2.types b/tests/baselines/reference/importDeferTypeConflict2.types +new file mode 100644 +index 000000000..bbcc915ad +--- /dev/null ++++ b/tests/baselines/reference/importDeferTypeConflict2.types +@@ -0,0 +1,37 @@ ++//// [tests/cases/conformance/importDefer/importDeferTypeConflict2.ts] //// ++ ++=== a.ts === ++export function foo() { ++>foo : () => void ++> : ^^^^^^^^^^ ++ ++ console.log("foo from a"); ++>console.log("foo from a") : void ++> : ^^^^ ++>console.log : (...data: any[]) => void ++> : ^^^^ ^^ ^^^^^ ++>console : Console ++> : ^^^^^^^ ++>log : (...data: any[]) => void ++> : ^^^^ ^^ ^^^^^ ++>"foo from a" : "foo from a" ++> : ^^^^^^^^^^^^ ++} ++ ++=== b.ts === ++import defer type * as ns1 from "a"; ++>type : any ++> : ^^^ ++>* as : number ++> : ^^^^^^ ++> : any ++> : ^^^ ++>as : any ++> : ^^^ ++>ns1 : any ++> : ^^^ ++>from : any ++> : ^^^ ++>"a" : "a" ++> : ^^^ ++ +diff --git a/tests/baselines/reference/importMetaPropertyInvalidInCall.errors.txt b/tests/baselines/reference/importMetaPropertyInvalidInCall.errors.txt +new file mode 100644 +index 000000000..6ab3da501 +--- /dev/null ++++ b/tests/baselines/reference/importMetaPropertyInvalidInCall.errors.txt +@@ -0,0 +1,12 @@ ++b.ts(1,8): error TS18061: 'foo' is not a valid meta-property for keyword 'import'. Did you mean 'meta' or 'defer'? ++b.ts(2,8): error TS17012: 'foo' is not a valid meta-property for keyword 'import'. Did you mean 'meta'? ++ ++ ++==== b.ts (2 errors) ==== ++ import.foo(); ++ ~~~ ++!!! error TS18061: 'foo' is not a valid meta-property for keyword 'import'. Did you mean 'meta' or 'defer'? ++ import.foo; ++ ~~~ ++!!! error TS17012: 'foo' is not a valid meta-property for keyword 'import'. Did you mean 'meta'? ++ +\ No newline at end of file +diff --git a/tests/baselines/reference/importMetaPropertyInvalidInCall.js b/tests/baselines/reference/importMetaPropertyInvalidInCall.js +new file mode 100644 +index 000000000..74f24f160 +--- /dev/null ++++ b/tests/baselines/reference/importMetaPropertyInvalidInCall.js +@@ -0,0 +1,10 @@ ++//// [tests/cases/conformance/importDefer/importMetaPropertyInvalidInCall.ts] //// ++ ++//// [b.ts] ++import.foo(); ++import.foo; ++ ++ ++//// [b.js] ++import.foo(); ++import.foo; +diff --git a/tests/baselines/reference/importMetaPropertyInvalidInCall.symbols b/tests/baselines/reference/importMetaPropertyInvalidInCall.symbols +new file mode 100644 +index 000000000..1d7cd9b50 +--- /dev/null ++++ b/tests/baselines/reference/importMetaPropertyInvalidInCall.symbols +@@ -0,0 +1,7 @@ ++//// [tests/cases/conformance/importDefer/importMetaPropertyInvalidInCall.ts] //// ++ ++=== b.ts === ++ ++import.foo(); ++import.foo; ++ +diff --git a/tests/baselines/reference/importMetaPropertyInvalidInCall.types b/tests/baselines/reference/importMetaPropertyInvalidInCall.types +new file mode 100644 +index 000000000..f30ad2b5f +--- /dev/null ++++ b/tests/baselines/reference/importMetaPropertyInvalidInCall.types +@@ -0,0 +1,17 @@ ++//// [tests/cases/conformance/importDefer/importMetaPropertyInvalidInCall.ts] //// ++ ++=== b.ts === ++import.foo(); ++>import.foo() : any ++> : ^^^ ++>import.foo : any ++> : ^^^ ++>foo : any ++> : ^^^ ++ ++import.foo; ++>import.foo : any ++> : ^^^ ++>foo : any ++> : ^^^ ++ +diff --git a/tests/baselines/reference/skipJSDocParsing/link-ParseForTypeErrors-file.js.diff b/tests/baselines/reference/skipJSDocParsing/link-ParseForTypeErrors-file.js.diff +index e85d3dac9..f9a6bdcff 100644 +--- a/tests/baselines/reference/skipJSDocParsing/link-ParseForTypeErrors-file.js.diff ++++ b/tests/baselines/reference/skipJSDocParsing/link-ParseForTypeErrors-file.js.diff +@@ -1,7 +1,7 @@ + =================================================================== + --- default + +++ ParseForTypeErrors +-@@ -214,7 +214,7 @@ ++@@ -216,7 +216,7 @@ + "typeReferenceDirectives": [], + "libReferenceDirectives": [], + "amdDependencies": [], +diff --git a/tests/baselines/reference/skipJSDocParsing/link-ParseForTypeErrors-file.ts.diff b/tests/baselines/reference/skipJSDocParsing/link-ParseForTypeErrors-file.ts.diff +index d54b75b0a..93dd08f83 100644 +--- a/tests/baselines/reference/skipJSDocParsing/link-ParseForTypeErrors-file.ts.diff ++++ b/tests/baselines/reference/skipJSDocParsing/link-ParseForTypeErrors-file.ts.diff +@@ -1,7 +1,7 @@ + =================================================================== + --- default + +++ ParseForTypeErrors +-@@ -214,6 +214,6 @@ ++@@ -216,6 +216,6 @@ + "typeReferenceDirectives": [], + "libReferenceDirectives": [], + "amdDependencies": [], +diff --git a/tests/baselines/reference/skipJSDocParsing/link-ParseForTypeInfo-file.js.diff b/tests/baselines/reference/skipJSDocParsing/link-ParseForTypeInfo-file.js.diff +index 894c809d3..8e9b6490c 100644 +--- a/tests/baselines/reference/skipJSDocParsing/link-ParseForTypeInfo-file.js.diff ++++ b/tests/baselines/reference/skipJSDocParsing/link-ParseForTypeInfo-file.js.diff +@@ -1,7 +1,7 @@ + =================================================================== + --- default + +++ ParseForTypeInfo +-@@ -214,7 +214,7 @@ ++@@ -216,7 +216,7 @@ + "typeReferenceDirectives": [], + "libReferenceDirectives": [], + "amdDependencies": [], +diff --git a/tests/baselines/reference/skipJSDocParsing/link-ParseForTypeInfo-file.ts.diff b/tests/baselines/reference/skipJSDocParsing/link-ParseForTypeInfo-file.ts.diff +index 0c2bff5a4..5a838cf84 100644 +--- a/tests/baselines/reference/skipJSDocParsing/link-ParseForTypeInfo-file.ts.diff ++++ b/tests/baselines/reference/skipJSDocParsing/link-ParseForTypeInfo-file.ts.diff +@@ -1,7 +1,7 @@ + =================================================================== + --- default + +++ ParseForTypeInfo +-@@ -88,52 +88,9 @@ ++@@ -89,52 +89,9 @@ + "pos": 69, + "end": 69, + "hasTrailingComma": false, +@@ -55,7 +55,7 @@ + "length": 2, + "pos": 0, + "end": 70, +-@@ -214,6 +171,6 @@ ++@@ -216,6 +173,6 @@ + "typeReferenceDirectives": [], + "libReferenceDirectives": [], + "amdDependencies": [], +diff --git a/tests/baselines/reference/skipJSDocParsing/link-ParseNone-file.js.diff b/tests/baselines/reference/skipJSDocParsing/link-ParseNone-file.js.diff +index 3a1028bb0..8d86662fa 100644 +--- a/tests/baselines/reference/skipJSDocParsing/link-ParseNone-file.js.diff ++++ b/tests/baselines/reference/skipJSDocParsing/link-ParseNone-file.js.diff +@@ -1,7 +1,7 @@ + =================================================================== + --- default + +++ ParseNone +-@@ -88,52 +88,9 @@ ++@@ -89,52 +89,9 @@ + "pos": 69, + "end": 69, + "hasTrailingComma": false, +@@ -55,7 +55,7 @@ + "length": 2, + "pos": 0, + "end": 70, +-@@ -214,7 +171,6 @@ ++@@ -216,7 +173,6 @@ + "typeReferenceDirectives": [], + "libReferenceDirectives": [], + "amdDependencies": [], +diff --git a/tests/baselines/reference/skipJSDocParsing/link-ParseNone-file.ts.diff b/tests/baselines/reference/skipJSDocParsing/link-ParseNone-file.ts.diff +index 41135dc24..c2edc9324 100644 +--- a/tests/baselines/reference/skipJSDocParsing/link-ParseNone-file.ts.diff ++++ b/tests/baselines/reference/skipJSDocParsing/link-ParseNone-file.ts.diff +@@ -1,7 +1,7 @@ + =================================================================== + --- default + +++ ParseNone +-@@ -88,52 +88,9 @@ ++@@ -89,52 +89,9 @@ + "pos": 69, + "end": 69, + "hasTrailingComma": false, +@@ -55,7 +55,7 @@ + "length": 2, + "pos": 0, + "end": 70, +-@@ -214,6 +171,6 @@ ++@@ -216,6 +173,6 @@ + "typeReferenceDirectives": [], + "libReferenceDirectives": [], + "amdDependencies": [], +diff --git a/tests/baselines/reference/typeofImportDefer.errors.txt b/tests/baselines/reference/typeofImportDefer.errors.txt +new file mode 100644 +index 000000000..ba3bcabcc +--- /dev/null ++++ b/tests/baselines/reference/typeofImportDefer.errors.txt +@@ -0,0 +1,22 @@ ++b.ts(1,30): error TS1005: '(' expected. ++b.ts(1,30): error TS1141: String literal expected. ++b.ts(1,36): error TS1005: ')' expected. ++b.ts(1,44): error TS2339: Property 'Foo' does not exist on type '"./a"'. ++ ++ ++==== a.ts (0 errors) ==== ++ export interface Foo { ++ x: number; ++ } ++ ++==== b.ts (4 errors) ==== ++ export type X = typeof import.defer("./a").Foo; ++ ~ ++!!! error TS1005: '(' expected. ++ ~~~~~~ ++!!! error TS1141: String literal expected. ++ ~ ++!!! error TS1005: ')' expected. ++ ~~~ ++!!! error TS2339: Property 'Foo' does not exist on type '"./a"'. ++ +\ No newline at end of file +diff --git a/tests/baselines/reference/typeofImportDefer.js b/tests/baselines/reference/typeofImportDefer.js +new file mode 100644 +index 000000000..b7ca45eed +--- /dev/null ++++ b/tests/baselines/reference/typeofImportDefer.js +@@ -0,0 +1,16 @@ ++//// [tests/cases/conformance/importDefer/typeofImportDefer.ts] //// ++ ++//// [a.ts] ++export interface Foo { ++ x: number; ++} ++ ++//// [b.ts] ++export type X = typeof import.defer("./a").Foo; ++ ++ ++//// [a.js] ++export {}; ++//// [b.js] ++("./a").Foo; ++export {}; +diff --git a/tests/baselines/reference/typeofImportDefer.symbols b/tests/baselines/reference/typeofImportDefer.symbols +new file mode 100644 +index 000000000..8c57d91a3 +--- /dev/null ++++ b/tests/baselines/reference/typeofImportDefer.symbols +@@ -0,0 +1,16 @@ ++//// [tests/cases/conformance/importDefer/typeofImportDefer.ts] //// ++ ++=== a.ts === ++export interface Foo { ++>Foo : Symbol(Foo, Decl(a.ts, 0, 0)) ++ ++ x: number; ++>x : Symbol(Foo.x, Decl(a.ts, 0, 22)) ++} ++ ++=== b.ts === ++export type X = typeof import.defer("./a").Foo; ++>X : Symbol(X, Decl(b.ts, 0, 0)) ++> : Symbol(unknown) ++>defer : Symbol(unknown.defer) ++ +diff --git a/tests/baselines/reference/typeofImportDefer.types b/tests/baselines/reference/typeofImportDefer.types +new file mode 100644 +index 000000000..3822bcedd +--- /dev/null ++++ b/tests/baselines/reference/typeofImportDefer.types +@@ -0,0 +1,24 @@ ++//// [tests/cases/conformance/importDefer/typeofImportDefer.ts] //// ++ ++=== a.ts === ++export interface Foo { ++ x: number; ++>x : number ++> : ^^^^^^ ++} ++ ++=== b.ts === ++export type X = typeof import.defer("./a").Foo; ++>X : any ++> : ^^^ ++> : any ++> : ^^^ ++>("./a").Foo : any ++> : ^^^ ++>("./a") : "./a" ++> : ^^^^^ ++>"./a" : "./a" ++> : ^^^^^ ++>Foo : any ++> : ^^^ ++ +diff --git a/tests/cases/conformance/importDefer/dynamicImportDefer.ts b/tests/cases/conformance/importDefer/dynamicImportDefer.ts +new file mode 100644 +index 000000000..7d444f21a +--- /dev/null ++++ b/tests/cases/conformance/importDefer/dynamicImportDefer.ts +@@ -0,0 +1,12 @@ ++// @module: preserve,esnext,nodenext,es2020,es2015,commonjs ++// @target: es2020 ++ ++// @filename: a.ts ++export function foo() { ++ console.log("foo from a"); ++} ++ ++// @filename: b.ts ++import.defer("./a.js").then(ns => { ++ ns.foo(); ++}); +diff --git a/tests/cases/conformance/importDefer/dynamicImportDeferInvalidStandalone.ts b/tests/cases/conformance/importDefer/dynamicImportDeferInvalidStandalone.ts +new file mode 100644 +index 000000000..cc60c2064 +--- /dev/null ++++ b/tests/cases/conformance/importDefer/dynamicImportDeferInvalidStandalone.ts +@@ -0,0 +1,10 @@ ++// @module: esnext ++ ++// @filename: b.ts ++import.defer; ++ ++(import.defer)("a"); ++ ++Function(import.defer); ++ ++import.defer +\ No newline at end of file +diff --git a/tests/cases/conformance/importDefer/exportDeferInvalid.ts b/tests/cases/conformance/importDefer/exportDeferInvalid.ts +new file mode 100644 +index 000000000..0d0dc587b +--- /dev/null ++++ b/tests/cases/conformance/importDefer/exportDeferInvalid.ts +@@ -0,0 +1,8 @@ ++// @module: esnext ++// @filename: a.ts ++export function foo() { ++ console.log("foo from a"); ++} ++ ++// @filename: b.ts ++export defer * as ns from "a"; +diff --git a/tests/cases/conformance/importDefer/importDefaultBindingDefer.ts b/tests/cases/conformance/importDefer/importDefaultBindingDefer.ts +new file mode 100644 +index 000000000..bcbacf6c1 +--- /dev/null ++++ b/tests/cases/conformance/importDefer/importDefaultBindingDefer.ts +@@ -0,0 +1,10 @@ ++// @module: esnext ++// @filename: a.ts ++export default function defer() { ++ console.log("defer from a"); ++} ++ ++// @filename: b.ts ++import defer from "a"; ++ ++defer(); +\ No newline at end of file +diff --git a/tests/cases/conformance/importDefer/importDeferComments.ts b/tests/cases/conformance/importDefer/importDeferComments.ts +new file mode 100644 +index 000000000..ce480f942 +--- /dev/null ++++ b/tests/cases/conformance/importDefer/importDeferComments.ts +@@ -0,0 +1,6 @@ ++// @module: esnext ++// @filename: a.ts ++export {}; ++ ++// @filename: b.ts ++/*1*/ import /*2*/ defer /*3*/ * /*4*/ as /*5*/ aNs /*6*/ from /*7*/ "a" /*8*/; +diff --git a/tests/cases/conformance/importDefer/importDeferDeclaration.ts b/tests/cases/conformance/importDefer/importDeferDeclaration.ts +new file mode 100644 +index 000000000..3ba8dc008 +--- /dev/null ++++ b/tests/cases/conformance/importDefer/importDeferDeclaration.ts +@@ -0,0 +1,12 @@ ++// @declaration: true ++// @module: esnext ++ ++// @filename: a.ts ++export interface Foo { ++ x: number; ++} ++ ++// @filename: b.ts ++import defer * as ns from "./a.js"; ++ ++export type X = { foo: ns.Foo }; +diff --git a/tests/cases/conformance/importDefer/importDeferInvalidDefault.ts b/tests/cases/conformance/importDefer/importDeferInvalidDefault.ts +new file mode 100644 +index 000000000..d3f02c8d1 +--- /dev/null ++++ b/tests/cases/conformance/importDefer/importDeferInvalidDefault.ts +@@ -0,0 +1,11 @@ ++ ++// @module: esnext ++// @filename: a.ts ++export default function foo() { ++ console.log("foo from a"); ++} ++ ++// @filename: b.ts ++import defer foo from "a"; ++ ++foo(); +\ No newline at end of file +diff --git a/tests/cases/conformance/importDefer/importDeferInvalidNamed.ts b/tests/cases/conformance/importDefer/importDeferInvalidNamed.ts +new file mode 100644 +index 000000000..078f5a132 +--- /dev/null ++++ b/tests/cases/conformance/importDefer/importDeferInvalidNamed.ts +@@ -0,0 +1,10 @@ ++// @module: esnext ++// @filename: a.ts ++export function foo() { ++ console.log("foo from a"); ++} ++ ++// @filename: b.ts ++import defer { foo } from "a"; ++ ++foo(); +\ No newline at end of file +diff --git a/tests/cases/conformance/importDefer/importDeferNamespace.ts b/tests/cases/conformance/importDefer/importDeferNamespace.ts +new file mode 100644 +index 000000000..435bca1f4 +--- /dev/null ++++ b/tests/cases/conformance/importDefer/importDeferNamespace.ts +@@ -0,0 +1,12 @@ ++// @module: preserve,esnext,nodenext,es2020,es2015,commonjs ++// @target: es2020 ++ ++// @filename: a.ts ++export function foo() { ++ console.log("foo from a"); ++} ++ ++// @filename: b.ts ++import defer * as aNs from "./a.js"; ++ ++aNs.foo(); +\ No newline at end of file +diff --git a/tests/cases/conformance/importDefer/importDeferTypeConflict1.ts b/tests/cases/conformance/importDefer/importDeferTypeConflict1.ts +new file mode 100644 +index 000000000..5cf5ef7c5 +--- /dev/null ++++ b/tests/cases/conformance/importDefer/importDeferTypeConflict1.ts +@@ -0,0 +1,8 @@ ++// @module: esnext ++// @filename: a.ts ++export function foo() { ++ console.log("foo from a"); ++} ++ ++// @filename: b.ts ++import type defer * as ns1 from "a"; +diff --git a/tests/cases/conformance/importDefer/importDeferTypeConflict2.ts b/tests/cases/conformance/importDefer/importDeferTypeConflict2.ts +new file mode 100644 +index 000000000..a12aa3529 +--- /dev/null ++++ b/tests/cases/conformance/importDefer/importDeferTypeConflict2.ts +@@ -0,0 +1,8 @@ ++// @module: esnext ++// @filename: a.ts ++export function foo() { ++ console.log("foo from a"); ++} ++ ++// @filename: b.ts ++import defer type * as ns1 from "a"; +diff --git a/tests/cases/conformance/importDefer/importMetaPropertyInvalidInCall.ts b/tests/cases/conformance/importDefer/importMetaPropertyInvalidInCall.ts +new file mode 100644 +index 000000000..3fb3a0c96 +--- /dev/null ++++ b/tests/cases/conformance/importDefer/importMetaPropertyInvalidInCall.ts +@@ -0,0 +1,5 @@ ++// @module: esnext ++ ++// @filename: b.ts ++import.foo(); ++import.foo; +diff --git a/tests/cases/conformance/importDefer/typeofImportDefer.ts b/tests/cases/conformance/importDefer/typeofImportDefer.ts +new file mode 100644 +index 000000000..2e45fbe97 +--- /dev/null ++++ b/tests/cases/conformance/importDefer/typeofImportDefer.ts +@@ -0,0 +1,9 @@ ++// @module: esnext ++ ++// @filename: a.ts ++export interface Foo { ++ x: number; ++} ++ ++// @filename: b.ts ++export type X = typeof import.defer("./a").Foo; +diff --git a/tests/cases/conformance/jsdoc/importDeferJsdoc.ts b/tests/cases/conformance/jsdoc/importDeferJsdoc.ts +new file mode 100644 +index 000000000..1e5e79294 +--- /dev/null ++++ b/tests/cases/conformance/jsdoc/importDeferJsdoc.ts +@@ -0,0 +1,17 @@ ++// @checkJs: true ++// @allowJs: true ++// @declaration: true ++// @emitDeclarationOnly: true ++ ++// @filename: /types.ts ++export type X = 1; ++ ++// @filename: /foo.js ++/** ++ * @import defer * as ns from "./types" ++ */ ++ ++/** ++ * @type { ns.X } ++ */ ++let a = 2; diff --git a/TypeScript_4/tests/private/eval_tests_aug.patch b/TypeScript_4/tests/private/eval_tests_aug.patch new file mode 100644 index 0000000000000000000000000000000000000000..f5d299d867d6299590c17a2130fc7aaf88162870 --- /dev/null +++ b/TypeScript_4/tests/private/eval_tests_aug.patch @@ -0,0 +1,837 @@ +diff --git a/tests/baselines/reference/dynamicImportDeferAug(module=commonjs).errors.txt b/tests/baselines/reference/dynamicImportDeferAug(module=commonjs).errors.txt +new file mode 100644 +index 0000000..f775d8c +--- /dev/null ++++ b/tests/baselines/reference/dynamicImportDeferAug(module=commonjs).errors.txt +@@ -0,0 +1,18 @@ ++main.ts(1,18): error TS18060: Deferred imports are only supported when the '--module' flag is set to 'esnext' or 'preserve'. ++ ++ ++==== dep.ts (0 errors) ==== ++ export const value = 1; ++ export function read() { ++ return value; ++ } ++ ++==== main.ts (1 errors) ==== ++ const deferred = import.defer("./dep.js"); ++ ~~~~~~~~~~~~~~~~~~~~~~~~ ++!!! error TS18060: Deferred imports are only supported when the '--module' flag is set to 'esnext' or 'preserve'. ++ deferred.then(ns => { ++ ns.read(); ++ ns.value; ++ }); ++ +\ No newline at end of file +diff --git a/tests/baselines/reference/dynamicImportDeferAug(module=commonjs).js b/tests/baselines/reference/dynamicImportDeferAug(module=commonjs).js +new file mode 100644 +index 0000000..b92b789 +--- /dev/null ++++ b/tests/baselines/reference/dynamicImportDeferAug(module=commonjs).js +@@ -0,0 +1,31 @@ ++//// [tests/cases/conformance/importDefer/dynamicImportDeferAug.ts] //// ++ ++//// [dep.ts] ++export const value = 1; ++export function read() { ++ return value; ++} ++ ++//// [main.ts] ++const deferred = import.defer("./dep.js"); ++deferred.then(ns => { ++ ns.read(); ++ ns.value; ++}); ++ ++ ++//// [dep.js] ++"use strict"; ++Object.defineProperty(exports, "__esModule", { value: true }); ++exports.value = void 0; ++exports.read = read; ++exports.value = 1; ++function read() { ++ return exports.value; ++} ++//// [main.js] ++const deferred = import.defer("./dep.js"); ++deferred.then(ns => { ++ ns.read(); ++ ns.value; ++}); +diff --git a/tests/baselines/reference/dynamicImportDeferAug(module=commonjs).symbols b/tests/baselines/reference/dynamicImportDeferAug(module=commonjs).symbols +new file mode 100644 +index 0000000..7ee379c +--- /dev/null ++++ b/tests/baselines/reference/dynamicImportDeferAug(module=commonjs).symbols +@@ -0,0 +1,36 @@ ++//// [tests/cases/conformance/importDefer/dynamicImportDeferAug.ts] //// ++ ++=== dep.ts === ++export const value = 1; ++>value : Symbol(value, Decl(dep.ts, 0, 12)) ++ ++export function read() { ++>read : Symbol(read, Decl(dep.ts, 0, 23)) ++ ++ return value; ++>value : Symbol(value, Decl(dep.ts, 0, 12)) ++} ++ ++=== main.ts === ++const deferred = import.defer("./dep.js"); ++>deferred : Symbol(deferred, Decl(main.ts, 0, 5)) ++>"./dep.js" : Symbol("dep", Decl(dep.ts, 0, 0)) ++ ++deferred.then(ns => { ++>deferred.then : Symbol(Promise.then, Decl(lib.es5.d.ts, --, --)) ++>deferred : Symbol(deferred, Decl(main.ts, 0, 5)) ++>then : Symbol(Promise.then, Decl(lib.es5.d.ts, --, --)) ++>ns : Symbol(ns, Decl(main.ts, 1, 14)) ++ ++ ns.read(); ++>ns.read : Symbol(read, Decl(dep.ts, 0, 23)) ++>ns : Symbol(ns, Decl(main.ts, 1, 14)) ++>read : Symbol(read, Decl(dep.ts, 0, 23)) ++ ++ ns.value; ++>ns.value : Symbol(value, Decl(dep.ts, 0, 12)) ++>ns : Symbol(ns, Decl(main.ts, 1, 14)) ++>value : Symbol(value, Decl(dep.ts, 0, 12)) ++ ++}); ++ +diff --git a/tests/baselines/reference/dynamicImportDeferAug(module=commonjs).types b/tests/baselines/reference/dynamicImportDeferAug(module=commonjs).types +new file mode 100644 +index 0000000..a156d92 +--- /dev/null ++++ b/tests/baselines/reference/dynamicImportDeferAug(module=commonjs).types +@@ -0,0 +1,63 @@ ++//// [tests/cases/conformance/importDefer/dynamicImportDeferAug.ts] //// ++ ++=== dep.ts === ++export const value = 1; ++>value : 1 ++> : ^ ++>1 : 1 ++> : ^ ++ ++export function read() { ++>read : () => number ++> : ^^^^^^^^^^^^ ++ ++ return value; ++>value : 1 ++> : ^ ++} ++ ++=== main.ts === ++const deferred = import.defer("./dep.js"); ++>deferred : Promise ++> : ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ++>import.defer("./dep.js") : Promise ++> : ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ++>defer : any ++> : ^^^ ++>"./dep.js" : "./dep.js" ++> : ^^^^^^^^^^ ++ ++deferred.then(ns => { ++>deferred.then(ns => { ns.read(); ns.value;}) : Promise ++> : ^^^^^^^^^^^^^ ++>deferred.then : (onfulfilled?: (value: typeof import("dep")) => TResult1 | PromiseLike, onrejected?: (reason: any) => TResult2 | PromiseLike) => Promise ++> : ^ ^^^^^^^^^^^^^^^^^^^^^^^^^ ^^^^^^^^^^ ^^^^ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ^^^^ ^^ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ++>deferred : Promise ++> : ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ++>then : (onfulfilled?: (value: typeof import("dep")) => TResult1 | PromiseLike, onrejected?: (reason: any) => TResult2 | PromiseLike) => Promise ++> : ^ ^^^^^^^^^^^^^^^^^^^^^^^^^ ^^^^^^^^^^ ^^^^ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ^^^^ ^^ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ++>ns => { ns.read(); ns.value;} : (ns: typeof import("dep")) => void ++> : ^ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ++>ns : typeof import("dep") ++> : ^^^^^^^^^^^^^^^^^^^^ ++ ++ ns.read(); ++>ns.read() : number ++> : ^^^^^^ ++>ns.read : () => number ++> : ^^^^^^^^^^^^ ++>ns : typeof import("dep") ++> : ^^^^^^^^^^^^^^^^^^^^ ++>read : () => number ++> : ^^^^^^^^^^^^ ++ ++ ns.value; ++>ns.value : 1 ++> : ^ ++>ns : typeof import("dep") ++> : ^^^^^^^^^^^^^^^^^^^^ ++>value : 1 ++> : ^ ++ ++}); ++ +diff --git a/tests/baselines/reference/dynamicImportDeferAug(module=esnext).js b/tests/baselines/reference/dynamicImportDeferAug(module=esnext).js +new file mode 100644 +index 0000000..0019eae +--- /dev/null ++++ b/tests/baselines/reference/dynamicImportDeferAug(module=esnext).js +@@ -0,0 +1,27 @@ ++//// [tests/cases/conformance/importDefer/dynamicImportDeferAug.ts] //// ++ ++//// [dep.ts] ++export const value = 1; ++export function read() { ++ return value; ++} ++ ++//// [main.ts] ++const deferred = import.defer("./dep.js"); ++deferred.then(ns => { ++ ns.read(); ++ ns.value; ++}); ++ ++ ++//// [dep.js] ++export const value = 1; ++export function read() { ++ return value; ++} ++//// [main.js] ++const deferred = import.defer("./dep.js"); ++deferred.then(ns => { ++ ns.read(); ++ ns.value; ++}); +diff --git a/tests/baselines/reference/dynamicImportDeferAug(module=esnext).symbols b/tests/baselines/reference/dynamicImportDeferAug(module=esnext).symbols +new file mode 100644 +index 0000000..7ee379c +--- /dev/null ++++ b/tests/baselines/reference/dynamicImportDeferAug(module=esnext).symbols +@@ -0,0 +1,36 @@ ++//// [tests/cases/conformance/importDefer/dynamicImportDeferAug.ts] //// ++ ++=== dep.ts === ++export const value = 1; ++>value : Symbol(value, Decl(dep.ts, 0, 12)) ++ ++export function read() { ++>read : Symbol(read, Decl(dep.ts, 0, 23)) ++ ++ return value; ++>value : Symbol(value, Decl(dep.ts, 0, 12)) ++} ++ ++=== main.ts === ++const deferred = import.defer("./dep.js"); ++>deferred : Symbol(deferred, Decl(main.ts, 0, 5)) ++>"./dep.js" : Symbol("dep", Decl(dep.ts, 0, 0)) ++ ++deferred.then(ns => { ++>deferred.then : Symbol(Promise.then, Decl(lib.es5.d.ts, --, --)) ++>deferred : Symbol(deferred, Decl(main.ts, 0, 5)) ++>then : Symbol(Promise.then, Decl(lib.es5.d.ts, --, --)) ++>ns : Symbol(ns, Decl(main.ts, 1, 14)) ++ ++ ns.read(); ++>ns.read : Symbol(read, Decl(dep.ts, 0, 23)) ++>ns : Symbol(ns, Decl(main.ts, 1, 14)) ++>read : Symbol(read, Decl(dep.ts, 0, 23)) ++ ++ ns.value; ++>ns.value : Symbol(value, Decl(dep.ts, 0, 12)) ++>ns : Symbol(ns, Decl(main.ts, 1, 14)) ++>value : Symbol(value, Decl(dep.ts, 0, 12)) ++ ++}); ++ +diff --git a/tests/baselines/reference/dynamicImportDeferAug(module=esnext).types b/tests/baselines/reference/dynamicImportDeferAug(module=esnext).types +new file mode 100644 +index 0000000..a156d92 +--- /dev/null ++++ b/tests/baselines/reference/dynamicImportDeferAug(module=esnext).types +@@ -0,0 +1,63 @@ ++//// [tests/cases/conformance/importDefer/dynamicImportDeferAug.ts] //// ++ ++=== dep.ts === ++export const value = 1; ++>value : 1 ++> : ^ ++>1 : 1 ++> : ^ ++ ++export function read() { ++>read : () => number ++> : ^^^^^^^^^^^^ ++ ++ return value; ++>value : 1 ++> : ^ ++} ++ ++=== main.ts === ++const deferred = import.defer("./dep.js"); ++>deferred : Promise ++> : ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ++>import.defer("./dep.js") : Promise ++> : ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ++>defer : any ++> : ^^^ ++>"./dep.js" : "./dep.js" ++> : ^^^^^^^^^^ ++ ++deferred.then(ns => { ++>deferred.then(ns => { ns.read(); ns.value;}) : Promise ++> : ^^^^^^^^^^^^^ ++>deferred.then : (onfulfilled?: (value: typeof import("dep")) => TResult1 | PromiseLike, onrejected?: (reason: any) => TResult2 | PromiseLike) => Promise ++> : ^ ^^^^^^^^^^^^^^^^^^^^^^^^^ ^^^^^^^^^^ ^^^^ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ^^^^ ^^ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ++>deferred : Promise ++> : ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ++>then : (onfulfilled?: (value: typeof import("dep")) => TResult1 | PromiseLike, onrejected?: (reason: any) => TResult2 | PromiseLike) => Promise ++> : ^ ^^^^^^^^^^^^^^^^^^^^^^^^^ ^^^^^^^^^^ ^^^^ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ^^^^ ^^ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ++>ns => { ns.read(); ns.value;} : (ns: typeof import("dep")) => void ++> : ^ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ++>ns : typeof import("dep") ++> : ^^^^^^^^^^^^^^^^^^^^ ++ ++ ns.read(); ++>ns.read() : number ++> : ^^^^^^ ++>ns.read : () => number ++> : ^^^^^^^^^^^^ ++>ns : typeof import("dep") ++> : ^^^^^^^^^^^^^^^^^^^^ ++>read : () => number ++> : ^^^^^^^^^^^^ ++ ++ ns.value; ++>ns.value : 1 ++> : ^ ++>ns : typeof import("dep") ++> : ^^^^^^^^^^^^^^^^^^^^ ++>value : 1 ++> : ^ ++ ++}); ++ +diff --git a/tests/baselines/reference/dynamicImportDeferAug(module=preserve).js b/tests/baselines/reference/dynamicImportDeferAug(module=preserve).js +new file mode 100644 +index 0000000..0019eae +--- /dev/null ++++ b/tests/baselines/reference/dynamicImportDeferAug(module=preserve).js +@@ -0,0 +1,27 @@ ++//// [tests/cases/conformance/importDefer/dynamicImportDeferAug.ts] //// ++ ++//// [dep.ts] ++export const value = 1; ++export function read() { ++ return value; ++} ++ ++//// [main.ts] ++const deferred = import.defer("./dep.js"); ++deferred.then(ns => { ++ ns.read(); ++ ns.value; ++}); ++ ++ ++//// [dep.js] ++export const value = 1; ++export function read() { ++ return value; ++} ++//// [main.js] ++const deferred = import.defer("./dep.js"); ++deferred.then(ns => { ++ ns.read(); ++ ns.value; ++}); +diff --git a/tests/baselines/reference/dynamicImportDeferAug(module=preserve).symbols b/tests/baselines/reference/dynamicImportDeferAug(module=preserve).symbols +new file mode 100644 +index 0000000..7ee379c +--- /dev/null ++++ b/tests/baselines/reference/dynamicImportDeferAug(module=preserve).symbols +@@ -0,0 +1,36 @@ ++//// [tests/cases/conformance/importDefer/dynamicImportDeferAug.ts] //// ++ ++=== dep.ts === ++export const value = 1; ++>value : Symbol(value, Decl(dep.ts, 0, 12)) ++ ++export function read() { ++>read : Symbol(read, Decl(dep.ts, 0, 23)) ++ ++ return value; ++>value : Symbol(value, Decl(dep.ts, 0, 12)) ++} ++ ++=== main.ts === ++const deferred = import.defer("./dep.js"); ++>deferred : Symbol(deferred, Decl(main.ts, 0, 5)) ++>"./dep.js" : Symbol("dep", Decl(dep.ts, 0, 0)) ++ ++deferred.then(ns => { ++>deferred.then : Symbol(Promise.then, Decl(lib.es5.d.ts, --, --)) ++>deferred : Symbol(deferred, Decl(main.ts, 0, 5)) ++>then : Symbol(Promise.then, Decl(lib.es5.d.ts, --, --)) ++>ns : Symbol(ns, Decl(main.ts, 1, 14)) ++ ++ ns.read(); ++>ns.read : Symbol(read, Decl(dep.ts, 0, 23)) ++>ns : Symbol(ns, Decl(main.ts, 1, 14)) ++>read : Symbol(read, Decl(dep.ts, 0, 23)) ++ ++ ns.value; ++>ns.value : Symbol(value, Decl(dep.ts, 0, 12)) ++>ns : Symbol(ns, Decl(main.ts, 1, 14)) ++>value : Symbol(value, Decl(dep.ts, 0, 12)) ++ ++}); ++ +diff --git a/tests/baselines/reference/dynamicImportDeferAug(module=preserve).types b/tests/baselines/reference/dynamicImportDeferAug(module=preserve).types +new file mode 100644 +index 0000000..a156d92 +--- /dev/null ++++ b/tests/baselines/reference/dynamicImportDeferAug(module=preserve).types +@@ -0,0 +1,63 @@ ++//// [tests/cases/conformance/importDefer/dynamicImportDeferAug.ts] //// ++ ++=== dep.ts === ++export const value = 1; ++>value : 1 ++> : ^ ++>1 : 1 ++> : ^ ++ ++export function read() { ++>read : () => number ++> : ^^^^^^^^^^^^ ++ ++ return value; ++>value : 1 ++> : ^ ++} ++ ++=== main.ts === ++const deferred = import.defer("./dep.js"); ++>deferred : Promise ++> : ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ++>import.defer("./dep.js") : Promise ++> : ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ++>defer : any ++> : ^^^ ++>"./dep.js" : "./dep.js" ++> : ^^^^^^^^^^ ++ ++deferred.then(ns => { ++>deferred.then(ns => { ns.read(); ns.value;}) : Promise ++> : ^^^^^^^^^^^^^ ++>deferred.then : (onfulfilled?: (value: typeof import("dep")) => TResult1 | PromiseLike, onrejected?: (reason: any) => TResult2 | PromiseLike) => Promise ++> : ^ ^^^^^^^^^^^^^^^^^^^^^^^^^ ^^^^^^^^^^ ^^^^ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ^^^^ ^^ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ++>deferred : Promise ++> : ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ++>then : (onfulfilled?: (value: typeof import("dep")) => TResult1 | PromiseLike, onrejected?: (reason: any) => TResult2 | PromiseLike) => Promise ++> : ^ ^^^^^^^^^^^^^^^^^^^^^^^^^ ^^^^^^^^^^ ^^^^ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ^^^^ ^^ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ++>ns => { ns.read(); ns.value;} : (ns: typeof import("dep")) => void ++> : ^ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ++>ns : typeof import("dep") ++> : ^^^^^^^^^^^^^^^^^^^^ ++ ++ ns.read(); ++>ns.read() : number ++> : ^^^^^^ ++>ns.read : () => number ++> : ^^^^^^^^^^^^ ++>ns : typeof import("dep") ++> : ^^^^^^^^^^^^^^^^^^^^ ++>read : () => number ++> : ^^^^^^^^^^^^ ++ ++ ns.value; ++>ns.value : 1 ++> : ^ ++>ns : typeof import("dep") ++> : ^^^^^^^^^^^^^^^^^^^^ ++>value : 1 ++> : ^ ++ ++}); ++ +diff --git a/tests/baselines/reference/dynamicImportDeferInvalidAccessAug.errors.txt b/tests/baselines/reference/dynamicImportDeferInvalidAccessAug.errors.txt +new file mode 100644 +index 0000000..5c8f53f +--- /dev/null ++++ b/tests/baselines/reference/dynamicImportDeferInvalidAccessAug.errors.txt +@@ -0,0 +1,18 @@ ++main.ts(1,28): error TS1005: '(' expected. ++main.ts(3,14): error TS1005: '(' expected. ++main.ts(5,22): error TS1005: '(' expected. ++ ++ ++==== main.ts (3 errors) ==== ++ const callee = import.defer; ++ ++!!! error TS1005: '(' expected. ++ ++ (import.defer)("./dep.js"); ++ ++!!! error TS1005: '(' expected. ++ ++ Function(import.defer); ++ ++!!! error TS1005: '(' expected. ++ +\ No newline at end of file +diff --git a/tests/baselines/reference/dynamicImportDeferInvalidAccessAug.js b/tests/baselines/reference/dynamicImportDeferInvalidAccessAug.js +new file mode 100644 +index 0000000..1620760 +--- /dev/null ++++ b/tests/baselines/reference/dynamicImportDeferInvalidAccessAug.js +@@ -0,0 +1,14 @@ ++//// [tests/cases/conformance/importDefer/dynamicImportDeferInvalidAccessAug.ts] //// ++ ++//// [main.ts] ++const callee = import.defer; ++ ++(import.defer)("./dep.js"); ++ ++Function(import.defer); ++ ++ ++//// [main.js] ++var callee = import.defer; ++(import.defer)("./dep.js"); ++Function(import.defer); +diff --git a/tests/baselines/reference/dynamicImportDeferInvalidAccessAug.symbols b/tests/baselines/reference/dynamicImportDeferInvalidAccessAug.symbols +new file mode 100644 +index 0000000..7c038b6 +--- /dev/null ++++ b/tests/baselines/reference/dynamicImportDeferInvalidAccessAug.symbols +@@ -0,0 +1,11 @@ ++//// [tests/cases/conformance/importDefer/dynamicImportDeferInvalidAccessAug.ts] //// ++ ++=== main.ts === ++const callee = import.defer; ++>callee : Symbol(callee, Decl(main.ts, 0, 5)) ++ ++(import.defer)("./dep.js"); ++ ++Function(import.defer); ++>Function : Symbol(Function, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --)) ++ +diff --git a/tests/baselines/reference/dynamicImportDeferInvalidAccessAug.types b/tests/baselines/reference/dynamicImportDeferInvalidAccessAug.types +new file mode 100644 +index 0000000..6083b71 +--- /dev/null ++++ b/tests/baselines/reference/dynamicImportDeferInvalidAccessAug.types +@@ -0,0 +1,33 @@ ++//// [tests/cases/conformance/importDefer/dynamicImportDeferInvalidAccessAug.ts] //// ++ ++=== main.ts === ++const callee = import.defer; ++>callee : any ++> : ^^^ ++>import.defer : any ++> : ^^^ ++>defer : any ++> : ^^^ ++ ++(import.defer)("./dep.js"); ++>(import.defer)("./dep.js") : any ++> : ^^^ ++>(import.defer) : any ++> : ^^^ ++>import.defer : any ++> : ^^^ ++>defer : any ++> : ^^^ ++>"./dep.js" : "./dep.js" ++> : ^^^^^^^^^^ ++ ++Function(import.defer); ++>Function(import.defer) : Function ++> : ^^^^^^^^ ++>Function : FunctionConstructor ++> : ^^^^^^^^^^^^^^^^^^^ ++>import.defer : any ++> : ^^^ ++>defer : any ++> : ^^^ ++ +diff --git a/tests/baselines/reference/importDeferInvalidBindingsAug.errors.txt b/tests/baselines/reference/importDeferInvalidBindingsAug.errors.txt +new file mode 100644 +index 0000000..3dd5215 +--- /dev/null ++++ b/tests/baselines/reference/importDeferInvalidBindingsAug.errors.txt +@@ -0,0 +1,19 @@ ++main.ts(1,8): error TS18058: Default imports are not allowed in a deferred import. ++main.ts(2,8): error TS18059: Named imports are not allowed in a deferred import. ++ ++ ++==== dep.ts (0 errors) ==== ++ export const foo = 1; ++ export default foo; ++ ++==== main.ts (2 errors) ==== ++ import defer foo from "./dep.js"; ++ ~~~~~~~~~ ++!!! error TS18058: Default imports are not allowed in a deferred import. ++ import defer { foo as namedFoo } from "./dep.js"; ++ ~~~~~~~~~~~~~~~~~~~~~~~~~ ++!!! error TS18059: Named imports are not allowed in a deferred import. ++ ++ foo; ++ namedFoo; ++ +\ No newline at end of file +diff --git a/tests/baselines/reference/importDeferInvalidBindingsAug.js b/tests/baselines/reference/importDeferInvalidBindingsAug.js +new file mode 100644 +index 0000000..fa5082b +--- /dev/null ++++ b/tests/baselines/reference/importDeferInvalidBindingsAug.js +@@ -0,0 +1,22 @@ ++//// [tests/cases/conformance/importDefer/importDeferInvalidBindingsAug.ts] //// ++ ++//// [dep.ts] ++export const foo = 1; ++export default foo; ++ ++//// [main.ts] ++import defer foo from "./dep.js"; ++import defer { foo as namedFoo } from "./dep.js"; ++ ++foo; ++namedFoo; ++ ++ ++//// [dep.js] ++export var foo = 1; ++export default foo; ++//// [main.js] ++import defer foo from "./dep.js"; ++import defer { foo as namedFoo } from "./dep.js"; ++foo; ++namedFoo; +diff --git a/tests/baselines/reference/importDeferInvalidBindingsAug.symbols b/tests/baselines/reference/importDeferInvalidBindingsAug.symbols +new file mode 100644 +index 0000000..e1aefd8 +--- /dev/null ++++ b/tests/baselines/reference/importDeferInvalidBindingsAug.symbols +@@ -0,0 +1,23 @@ ++//// [tests/cases/conformance/importDefer/importDeferInvalidBindingsAug.ts] //// ++ ++=== dep.ts === ++export const foo = 1; ++>foo : Symbol(foo, Decl(dep.ts, 0, 12)) ++ ++export default foo; ++>foo : Symbol(foo, Decl(dep.ts, 0, 12)) ++ ++=== main.ts === ++import defer foo from "./dep.js"; ++>foo : Symbol(foo, Decl(main.ts, 0, 6)) ++ ++import defer { foo as namedFoo } from "./dep.js"; ++>foo : Symbol(foo, Decl(dep.ts, 0, 12)) ++>namedFoo : Symbol(namedFoo, Decl(main.ts, 1, 14)) ++ ++foo; ++>foo : Symbol(foo, Decl(main.ts, 0, 6)) ++ ++namedFoo; ++>namedFoo : Symbol(namedFoo, Decl(main.ts, 1, 14)) ++ +diff --git a/tests/baselines/reference/importDeferInvalidBindingsAug.types b/tests/baselines/reference/importDeferInvalidBindingsAug.types +new file mode 100644 +index 0000000..3b6e49b +--- /dev/null ++++ b/tests/baselines/reference/importDeferInvalidBindingsAug.types +@@ -0,0 +1,32 @@ ++//// [tests/cases/conformance/importDefer/importDeferInvalidBindingsAug.ts] //// ++ ++=== dep.ts === ++export const foo = 1; ++>foo : 1 ++> : ^ ++>1 : 1 ++> : ^ ++ ++export default foo; ++>foo : 1 ++> : ^ ++ ++=== main.ts === ++import defer foo from "./dep.js"; ++>foo : 1 ++> : ^ ++ ++import defer { foo as namedFoo } from "./dep.js"; ++>foo : 1 ++> : ^ ++>namedFoo : 1 ++> : ^ ++ ++foo; ++>foo : 1 ++> : ^ ++ ++namedFoo; ++>namedFoo : 1 ++> : ^ ++ +diff --git a/tests/baselines/reference/importTypeOnlyAug.js b/tests/baselines/reference/importTypeOnlyAug.js +new file mode 100644 +index 0000000..cb7779d +--- /dev/null ++++ b/tests/baselines/reference/importTypeOnlyAug.js +@@ -0,0 +1,17 @@ ++//// [tests/cases/conformance/externalModules/importTypeOnlyAug.ts] //// ++ ++//// [types.ts] ++export interface Box { ++ value: string; ++} ++ ++//// [main.ts] ++import type { Box } from "./types.js"; ++ ++export const make = (value: string): Box => ({ value }); ++ ++ ++//// [types.js] ++export {}; ++//// [main.js] ++export const make = (value) => ({ value }); +diff --git a/tests/baselines/reference/importTypeOnlyAug.symbols b/tests/baselines/reference/importTypeOnlyAug.symbols +new file mode 100644 +index 0000000..3343fb8 +--- /dev/null ++++ b/tests/baselines/reference/importTypeOnlyAug.symbols +@@ -0,0 +1,20 @@ ++//// [tests/cases/conformance/externalModules/importTypeOnlyAug.ts] //// ++ ++=== types.ts === ++export interface Box { ++>Box : Symbol(Box, Decl(types.ts, 0, 0)) ++ ++ value: string; ++>value : Symbol(Box.value, Decl(types.ts, 0, 22)) ++} ++ ++=== main.ts === ++import type { Box } from "./types.js"; ++>Box : Symbol(Box, Decl(main.ts, 0, 13)) ++ ++export const make = (value: string): Box => ({ value }); ++>make : Symbol(make, Decl(main.ts, 2, 12)) ++>value : Symbol(value, Decl(main.ts, 2, 21)) ++>Box : Symbol(Box, Decl(main.ts, 0, 13)) ++>value : Symbol(value, Decl(main.ts, 2, 46)) ++ +diff --git a/tests/baselines/reference/importTypeOnlyAug.types b/tests/baselines/reference/importTypeOnlyAug.types +new file mode 100644 +index 0000000..594acdb +--- /dev/null ++++ b/tests/baselines/reference/importTypeOnlyAug.types +@@ -0,0 +1,28 @@ ++//// [tests/cases/conformance/externalModules/importTypeOnlyAug.ts] //// ++ ++=== types.ts === ++export interface Box { ++ value: string; ++>value : string ++> : ^^^^^^ ++} ++ ++=== main.ts === ++import type { Box } from "./types.js"; ++>Box : Box ++> : ^^^ ++ ++export const make = (value: string): Box => ({ value }); ++>make : (value: string) => Box ++> : ^ ^^ ^^^^^ ++>(value: string): Box => ({ value }) : (value: string) => Box ++> : ^ ^^ ^^^^^ ++>value : string ++> : ^^^^^^ ++>({ value }) : { value: string; } ++> : ^^^^^^^^^^^^^^^^^^ ++>{ value } : { value: string; } ++> : ^^^^^^^^^^^^^^^^^^ ++>value : string ++> : ^^^^^^ ++ +diff --git a/tests/cases/conformance/externalModules/importTypeOnlyAug.ts b/tests/cases/conformance/externalModules/importTypeOnlyAug.ts +new file mode 100644 +index 0000000..3ea1728 +--- /dev/null ++++ b/tests/cases/conformance/externalModules/importTypeOnlyAug.ts +@@ -0,0 +1,12 @@ ++// @module: esnext ++// @target: es2020 ++ ++// @filename: types.ts ++export interface Box { ++ value: string; ++} ++ ++// @filename: main.ts ++import type { Box } from "./types.js"; ++ ++export const make = (value: string): Box => ({ value }); +diff --git a/tests/cases/conformance/importDefer/dynamicImportDeferAug.ts b/tests/cases/conformance/importDefer/dynamicImportDeferAug.ts +new file mode 100644 +index 0000000..d23ba08 +--- /dev/null ++++ b/tests/cases/conformance/importDefer/dynamicImportDeferAug.ts +@@ -0,0 +1,15 @@ ++// @module: preserve,esnext,commonjs ++// @target: es2020 ++ ++// @filename: dep.ts ++export const value = 1; ++export function read() { ++ return value; ++} ++ ++// @filename: main.ts ++const deferred = import.defer("./dep.js"); ++deferred.then(ns => { ++ ns.read(); ++ ns.value; ++}); +diff --git a/tests/cases/conformance/importDefer/dynamicImportDeferInvalidAccessAug.ts b/tests/cases/conformance/importDefer/dynamicImportDeferInvalidAccessAug.ts +new file mode 100644 +index 0000000..14500a0 +--- /dev/null ++++ b/tests/cases/conformance/importDefer/dynamicImportDeferInvalidAccessAug.ts +@@ -0,0 +1,8 @@ ++// @module: esnext ++ ++// @filename: main.ts ++const callee = import.defer; ++ ++(import.defer)("./dep.js"); ++ ++Function(import.defer); +diff --git a/tests/cases/conformance/importDefer/importDeferInvalidBindingsAug.ts b/tests/cases/conformance/importDefer/importDeferInvalidBindingsAug.ts +new file mode 100644 +index 0000000..da46e3c +--- /dev/null ++++ b/tests/cases/conformance/importDefer/importDeferInvalidBindingsAug.ts +@@ -0,0 +1,12 @@ ++// @module: esnext ++ ++// @filename: dep.ts ++export const foo = 1; ++export default foo; ++ ++// @filename: main.ts ++import defer foo from "./dep.js"; ++import defer { foo as namedFoo } from "./dep.js"; ++ ++foo; ++namedFoo; diff --git a/TypeScript_4/tests/private/f2p.txt b/TypeScript_4/tests/private/f2p.txt new file mode 100644 index 0000000000000000000000000000000000000000..e5ec0d59ab5f76aa55c1afb0b5f8b26b4ab54126 --- /dev/null +++ b/TypeScript_4/tests/private/f2p.txt @@ -0,0 +1,2 @@ +tests/cases/conformance/importDefer/importDeferDeclaration.ts +tests/cases/conformance/importDefer/importDeferNamespace.ts diff --git a/TypeScript_4/tests/private/f2p_aug.txt b/TypeScript_4/tests/private/f2p_aug.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc1c9ede47e4a96ae7e4e26f264807a2818462bb --- /dev/null +++ b/TypeScript_4/tests/private/f2p_aug.txt @@ -0,0 +1,3 @@ +tests/cases/conformance/importDefer/dynamicImportDeferAug.ts +tests/cases/conformance/importDefer/dynamicImportDeferInvalidAccessAug.ts +tests/cases/conformance/importDefer/importDeferInvalidBindingsAug.ts diff --git a/TypeScript_4/tests/private/omitted.patch b/TypeScript_4/tests/private/omitted.patch new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/TypeScript_4/tests/private/p2p.txt b/TypeScript_4/tests/private/p2p.txt new file mode 100644 index 0000000000000000000000000000000000000000..cda019e2844030b09ffa1d2c3b62c3eb8a9b218a --- /dev/null +++ b/TypeScript_4/tests/private/p2p.txt @@ -0,0 +1,49 @@ +tests/cases/conformance/externalModules/exportsAndImports1.ts +tests/cases/conformance/externalModules/exportAssignmentAndDeclaration.ts +tests/cases/conformance/externalModules/exportAssignmentGenericType.ts +tests/cases/conformance/externalModules/duplicateExportAssignments.ts +tests/cases/conformance/externalModules/exportAssignImportedIdentifier.ts +tests/cases/conformance/externalModules/commonJSImportAsPrimaryExpression.ts +tests/cases/conformance/externalModules/commonJSImportNotAsPrimaryExpression.ts +tests/cases/conformance/es6/moduleExportsCommonjs/anonymousDefaultExportsCommonjs.ts +tests/cases/conformance/es6/moduleExportsCommonjs/defaultExportsGetExportedCommonjs.ts +tests/cases/conformance/es6/moduleExportsCommonjs/decoratedDefaultExportsGetExportedCommonjs.ts +tests/cases/conformance/externalModules/amdImportAsPrimaryExpression.ts +tests/cases/conformance/externalModules/amdImportNotAsPrimaryExpression.ts +tests/cases/conformance/externalModules/asiPreventsParsingAsAmbientExternalModule01.ts +tests/cases/conformance/externalModules/asiPreventsParsingAsAmbientExternalModule02.ts +tests/cases/conformance/externalModules/circularReference.ts +tests/cases/conformance/externalModules/commonJsImportBindingElementNarrowType.ts +tests/cases/conformance/externalModules/es6/es6modulekind.ts +tests/cases/conformance/externalModules/es6/es6modulekindExportClassNameWithObject.ts +tests/cases/conformance/externalModules/es6/es6modulekindWithES2015Target.ts +tests/cases/conformance/externalModules/es6/es6modulekindWithES5Target.ts +tests/cases/conformance/externalModules/es6/es6modulekindWithES5Target10.ts +tests/cases/conformance/externalModules/es6/es6modulekindWithES5Target11.ts +tests/cases/conformance/externalModules/es6/es6modulekindWithES5Target12.ts +tests/cases/conformance/externalModules/es6/es6modulekindWithES5Target2.ts +tests/cases/conformance/externalModules/es6/es6modulekindWithES5Target3.ts +tests/cases/conformance/externalModules/es6/es6modulekindWithES5Target4.ts +tests/cases/conformance/externalModules/es6/es6modulekindWithES5Target5.ts +tests/cases/conformance/externalModules/es6/es6modulekindWithES5Target6.ts +tests/cases/conformance/externalModules/es6/es6modulekindWithES5Target7.ts +tests/cases/conformance/externalModules/es6/es6modulekindWithES5Target8.ts +tests/cases/conformance/externalModules/es6/es6modulekindWithES5Target9.ts +tests/cases/conformance/externalModules/esnext/esnextmodulekind.ts +tests/cases/conformance/externalModules/esnext/esnextmodulekindWithES2015Target.ts +tests/cases/conformance/externalModules/esnext/esnextmodulekindWithES5Target.ts +tests/cases/conformance/externalModules/esnext/esnextmodulekindWithES5Target10.ts +tests/cases/conformance/externalModules/esnext/esnextmodulekindWithES5Target11.ts +tests/cases/conformance/externalModules/esnext/esnextmodulekindWithES5Target12.ts +tests/cases/conformance/externalModules/esnext/esnextmodulekindWithES5Target2.ts +tests/cases/conformance/externalModules/esnext/esnextmodulekindWithES5Target3.ts +tests/cases/conformance/externalModules/esnext/esnextmodulekindWithES5Target4.ts +tests/cases/conformance/externalModules/esnext/esnextmodulekindWithES5Target5.ts +tests/cases/conformance/externalModules/esnext/esnextmodulekindWithES5Target6.ts +tests/cases/conformance/externalModules/esnext/esnextmodulekindWithES5Target7.ts +tests/cases/conformance/externalModules/esnext/esnextmodulekindWithES5Target8.ts +tests/cases/conformance/externalModules/esnext/esnextmodulekindWithES5Target9.ts +tests/cases/conformance/externalModules/esnext/exnextmodulekindExportClassNameWithObject.ts +tests/cases/conformance/externalModules/exportAmbientClassNameWithObject.ts +tests/cases/conformance/externalModules/exportAssignDottedName.ts +tests/cases/conformance/externalModules/exportAssignNonIdentifier.ts diff --git a/TypeScript_4/tests/private/p2p_aug.txt b/TypeScript_4/tests/private/p2p_aug.txt new file mode 100644 index 0000000000000000000000000000000000000000..5f4dbd3eec1f920e8eddd1c12a73cfac861c7d39 --- /dev/null +++ b/TypeScript_4/tests/private/p2p_aug.txt @@ -0,0 +1 @@ +tests/cases/conformance/externalModules/importTypeOnlyAug.ts diff --git a/TypeScript_4/tests/private/run_tests.sh b/TypeScript_4/tests/private/run_tests.sh new file mode 100644 index 0000000000000000000000000000000000000000..e1ecd40b8dfe4bf2e80b33f4157f2d0bf8cf6cb8 --- /dev/null +++ b/TypeScript_4/tests/private/run_tests.sh @@ -0,0 +1,151 @@ +#!/usr/bin/env bash +# LoLBench runner for TypeScript PR-60757 (import defer). +# Selectors are conformance .ts case paths; the runner runs each via +# `hereby runtests --tests ` (baseline comparison) and classifies +# PASS/FAIL/ERROR from the mocha summary. +set -uo pipefail + +PRIV=/opt/lolbench/private +SRC=/workspace/typescript +MODE=${LOLBENCH_MODE:-eval} +SUITE=${LOLBENCH_SUITE:-orig} +INSTANCE_ID="TypeScript_PR-60757_import-defer" + +log(){ echo "[run_tests $MODE/$SUITE] $*" >&2; } +read_selectors(){ + local path=$1 + if [ -f "$path" ]; then + grep -v '^\s*$' "$path" + fi +} +mapfile -t ORIG_FAIL_TO_PASS < <(read_selectors "$PRIV/f2p.txt") +mapfile -t ORIG_PASS_TO_PASS < <(read_selectors "$PRIV/p2p.txt") +mapfile -t AUG_FAIL_TO_PASS < <(read_selectors "$PRIV/f2p_aug.txt") +mapfile -t AUG_PASS_TO_PASS < <(read_selectors "$PRIV/p2p_aug.txt") +case "$SUITE" in + orig) + FAIL_TO_PASS=("${ORIG_FAIL_TO_PASS[@]}") + PASS_TO_PASS=("${ORIG_PASS_TO_PASS[@]}") + ;; + aug) + FAIL_TO_PASS=("${AUG_FAIL_TO_PASS[@]}") + PASS_TO_PASS=("${AUG_PASS_TO_PASS[@]}") + ;; + union) + FAIL_TO_PASS=("${ORIG_FAIL_TO_PASS[@]}" "${AUG_FAIL_TO_PASS[@]}") + PASS_TO_PASS=("${ORIG_PASS_TO_PASS[@]}" "${AUG_PASS_TO_PASS[@]}") + ;; + *) die "unknown LOLBENCH_SUITE=$SUITE";; +esac + +emit_error(){ + local cat=$1 applied=$2 bs=$3 + python3 - "$cat" "$applied" "$bs" "$INSTANCE_ID" "${#FAIL_TO_PASS[@]}" "${#PASS_TO_PASS[@]}" "$SUITE" <<'EOF' >/out/agent_report.json +import json,sys +cat,ap,bs,inst,fn,pn,su=sys.argv[1:8] +print(json.dumps({"instance_id":inst,"suite":su,"applied":ap.lower()=="true","build":{"status":bs}, + "f2p":{"passed":0,"failed":0,"errored":int(fn),"skipped":0,"total":int(fn)}, + "p2p":{"passed":0,"failed":0,"errored":int(pn),"skipped":0,"total":int(pn)}, + "resolved":False,"error_categories":[cat]},indent=2)) +EOF +} +die(){ log "FATAL: $*"; emit_error harness_error false skipped; exit 0; } + +SRC_PATCH="" +case "$MODE" in + validate_pre) SRC_PATCH="";; + validate_post) + if [ -f /solution/solution.patch ]; then + SRC_PATCH=/solution/solution.patch + else + SRC_PATCH="$PRIV/solution.patch" + fi ;; + eval) + [ -f /in/solution.patch ] || { emit_error missing_solution_patch false skipped; exit 0; } + AGENT_PATCH=/tmp/lolbench_agent_patch.diff + cp /in/solution.patch "$AGENT_PATCH" + chmod 0600 "$AGENT_PATCH" + SRC_PATCH="$AGENT_PATCH";; + *) die "unknown LOLBENCH_MODE=$MODE";; +esac + +cd "$SRC" +git config --global --add safe.directory "$SRC" +git reset --hard >/dev/null 2>&1; git clean -fd >/dev/null 2>&1 + +if [ -n "$SRC_PATCH" ]; then + git apply --check "$SRC_PATCH" 2>/tmp/a.err || { log "solution patch fail"; cat /tmp/a.err>&2; emit_error patch_apply_failure false skipped; exit 0; } + git apply "$SRC_PATCH" + # LoLBench eval-patch-collision guard (re-verify remediation): if the agent patch touched files the + # eval test patches own (test fixtures the agent must not modify), restore + # those paths (both sides of every diff/rename) to the base state so + # eval_tests(.aug).patch always applies. Agent source changes are preserved. + for _lb_ep in "$PRIV/eval_helpers.patch" "$PRIV/eval_tests.patch" "$PRIV/eval_tests_aug.patch"; do + [ -f "$_lb_ep" ] || continue + { sed -n 's|^diff --git a/\(.*\) b/\(.*\)$|\1\n\2|p' "$_lb_ep" + sed -n 's|^rename from \(.*\)$|\1|p' "$_lb_ep" + sed -n 's|^rename to \(.*\)$|\1|p' "$_lb_ep"; } | sort -u | while read -r _lb_f; do + [ -n "$_lb_f" ] || continue + git checkout HEAD -- "$_lb_f" >/dev/null 2>&1 || rm -f "$_lb_f" >/dev/null 2>&1 || true + done + done +fi +git apply --check "$PRIV/eval_tests.patch" 2>/tmp/a.err || { log "eval patch fail"; cat /tmp/a.err>&2; emit_error eval_patch_apply_failure true skipped; exit 0; } +git apply "$PRIV/eval_tests.patch" +if [[ "$SUITE" == "aug" || "$SUITE" == "union" ]]; then + git apply --check "$PRIV/eval_tests_aug.patch" 2>/tmp/a.err || { log "eval aug patch fail"; cat /tmp/a.err>&2; emit_error eval_aug_patch_apply_failure true skipped; exit 0; } + git apply "$PRIV/eval_tests_aug.patch" +fi + +# Build compiler + test harness from patched source (incremental). +log "building (hereby tests)" +if ! npx hereby tests > /out/build.log 2>&1; then + log "build failed"; tail -40 /out/build.log >&2 + emit_error build_failure true failed; exit 0 +fi + +run_one(){ + # echoes PASSED/FAILED/ERROR for a conformance .ts case selector + local sel="$1" + local name; name=$(basename "$sel" .ts) + local out rc + out=$(timeout -k 5s "${LOLBENCH_TEST_TIMEOUT:-120s}" npx hereby runtests --tests "$name" --no-color 2>&1) + rc=$? + echo "$out" >> /out/runtests.log + if [ "$rc" -eq 124 ] || [ "$rc" -eq 137 ]; then echo "ERROR" + elif echo "$out" | grep -qE "[1-9][0-9]* (failing|failed)"; then echo "FAILED" + elif echo "$out" | grep -qE "\b[1-9][0-9]* (passing|passed)\b"; then echo "PASSED" + else echo "ERROR"; fi +} + +: > /out/runtests.log +declare -a F2P_RES P2P_RES +for t in "${FAIL_TO_PASS[@]}"; do F2P_RES+=("$(run_one "$t")"); done +for t in "${PASS_TO_PASS[@]}"; do P2P_RES+=("$(run_one "$t")"); done + +printf '%s\n' "${FAIL_TO_PASS[@]}" > /tmp/lolbench_f2p_selected.txt +printf '%s\n' "${PASS_TO_PASS[@]}" > /tmp/lolbench_p2p_selected.txt +python3 - "$INSTANCE_ID" "$MODE" "$SUITE" /tmp/lolbench_f2p_selected.txt /tmp/lolbench_p2p_selected.txt <", + "log_parser": "generic_log", + "solution_patch_sha256": "6370b4b1f32041c7a987377f78a51ecdd002896b0d68d92cfd4b3bace414994d", + "eval_tests_patch_sha256": "03ce385b71ddbc9464fb46486b726b73b9d303f4fc13c2f4fa52b0d02b141849", + "triage": { + "audit_note": "Triage metadata was normalized during the 2026-06-10 bundle completeness audit and expanded on 2026-06-15 with pre-existing P2P conformance selectors; selector files remain the authoritative test selection.", + "fail_to_pass": { + "tests/cases/conformance/importDefer/importDeferDeclaration.ts": { + "system_reason": "Retained F2P selector; detailed triage was not recorded before normalization." + }, + "tests/cases/conformance/importDefer/importDeferNamespace.ts": { + "system_reason": "Retained F2P selector; detailed triage was not recorded before normalization." + } + }, + "pass_to_pass": { + "tests/cases/conformance/externalModules/exportsAndImports1.ts": { + "system_reason": "Retained original P2P selector; pre-existing externalModules conformance case untouched by PR-60757." + }, + "tests/cases/conformance/externalModules/exportAssignmentAndDeclaration.ts": { + "system_reason": "Pre-existing externalModules conformance case; guards unchanged import/export behavior outside the import defer requirement surface." + }, + "tests/cases/conformance/externalModules/exportAssignmentGenericType.ts": { + "system_reason": "Pre-existing externalModules conformance case; guards unchanged import/export behavior outside the import defer requirement surface." + }, + "tests/cases/conformance/externalModules/duplicateExportAssignments.ts": { + "system_reason": "Pre-existing externalModules conformance case; guards unchanged import/export behavior outside the import defer requirement surface." + }, + "tests/cases/conformance/externalModules/exportAssignImportedIdentifier.ts": { + "system_reason": "Pre-existing externalModules conformance case; guards unchanged import/export behavior outside the import defer requirement surface." + }, + "tests/cases/conformance/externalModules/commonJSImportAsPrimaryExpression.ts": { + "system_reason": "Pre-existing externalModules conformance case; guards unchanged import/export behavior outside the import defer requirement surface." + }, + "tests/cases/conformance/externalModules/commonJSImportNotAsPrimaryExpression.ts": { + "system_reason": "Pre-existing externalModules conformance case; guards unchanged import/export behavior outside the import defer requirement surface." + }, + "tests/cases/conformance/es6/moduleExportsCommonjs/anonymousDefaultExportsCommonjs.ts": { + "system_reason": "Pre-existing moduleExportsCommonjs conformance case; guards unchanged CommonJS module export behavior outside the import defer requirement surface." + }, + "tests/cases/conformance/es6/moduleExportsCommonjs/defaultExportsGetExportedCommonjs.ts": { + "system_reason": "Pre-existing moduleExportsCommonjs conformance case; guards unchanged CommonJS module export behavior outside the import defer requirement surface." + }, + "tests/cases/conformance/es6/moduleExportsCommonjs/decoratedDefaultExportsGetExportedCommonjs.ts": { + "system_reason": "Pre-existing moduleExportsCommonjs conformance case; guards unchanged CommonJS module export behavior outside the import defer requirement surface." + }, + "tests/cases/conformance/externalModules/amdImportAsPrimaryExpression.ts": { + "system_reason": "Pre-existing externalModules conformance case; guards unchanged import/export behavior outside the import defer requirement surface." + }, + "tests/cases/conformance/externalModules/amdImportNotAsPrimaryExpression.ts": { + "system_reason": "Pre-existing externalModules conformance case; guards unchanged import/export behavior outside the import defer requirement surface." + }, + "tests/cases/conformance/externalModules/asiPreventsParsingAsAmbientExternalModule01.ts": { + "system_reason": "Pre-existing externalModules conformance case; guards unchanged import/export behavior outside the import defer requirement surface." + }, + "tests/cases/conformance/externalModules/asiPreventsParsingAsAmbientExternalModule02.ts": { + "system_reason": "Pre-existing externalModules conformance case; guards unchanged import/export behavior outside the import defer requirement surface." + }, + "tests/cases/conformance/externalModules/circularReference.ts": { + "system_reason": "Pre-existing externalModules conformance case; guards unchanged import/export behavior outside the import defer requirement surface." + }, + "tests/cases/conformance/externalModules/commonJsImportBindingElementNarrowType.ts": { + "system_reason": "Pre-existing externalModules conformance case; guards unchanged import/export behavior outside the import defer requirement surface." + }, + "tests/cases/conformance/externalModules/es6/es6modulekind.ts": { + "system_reason": "Pre-existing externalModules conformance case; guards unchanged import/export behavior outside the import defer requirement surface." + }, + "tests/cases/conformance/externalModules/es6/es6modulekindExportClassNameWithObject.ts": { + "system_reason": "Pre-existing externalModules conformance case; guards unchanged import/export behavior outside the import defer requirement surface." + }, + "tests/cases/conformance/externalModules/es6/es6modulekindWithES2015Target.ts": { + "system_reason": "Pre-existing externalModules conformance case; guards unchanged import/export behavior outside the import defer requirement surface." + }, + "tests/cases/conformance/externalModules/es6/es6modulekindWithES5Target.ts": { + "system_reason": "Pre-existing externalModules conformance case; guards unchanged import/export behavior outside the import defer requirement surface." + }, + "tests/cases/conformance/externalModules/es6/es6modulekindWithES5Target10.ts": { + "system_reason": "Pre-existing externalModules conformance case; guards unchanged import/export behavior outside the import defer requirement surface." + }, + "tests/cases/conformance/externalModules/es6/es6modulekindWithES5Target11.ts": { + "system_reason": "Pre-existing externalModules conformance case; guards unchanged import/export behavior outside the import defer requirement surface." + }, + "tests/cases/conformance/externalModules/es6/es6modulekindWithES5Target12.ts": { + "system_reason": "Pre-existing externalModules conformance case; guards unchanged import/export behavior outside the import defer requirement surface." + }, + "tests/cases/conformance/externalModules/es6/es6modulekindWithES5Target2.ts": { + "system_reason": "Pre-existing externalModules conformance case; guards unchanged import/export behavior outside the import defer requirement surface." + }, + "tests/cases/conformance/externalModules/es6/es6modulekindWithES5Target3.ts": { + "system_reason": "Pre-existing externalModules conformance case; guards unchanged import/export behavior outside the import defer requirement surface." + }, + "tests/cases/conformance/externalModules/es6/es6modulekindWithES5Target4.ts": { + "system_reason": "Pre-existing externalModules conformance case; guards unchanged import/export behavior outside the import defer requirement surface." + }, + "tests/cases/conformance/externalModules/es6/es6modulekindWithES5Target5.ts": { + "system_reason": "Pre-existing externalModules conformance case; guards unchanged import/export behavior outside the import defer requirement surface." + }, + "tests/cases/conformance/externalModules/es6/es6modulekindWithES5Target6.ts": { + "system_reason": "Pre-existing externalModules conformance case; guards unchanged import/export behavior outside the import defer requirement surface." + }, + "tests/cases/conformance/externalModules/es6/es6modulekindWithES5Target7.ts": { + "system_reason": "Pre-existing externalModules conformance case; guards unchanged import/export behavior outside the import defer requirement surface." + }, + "tests/cases/conformance/externalModules/es6/es6modulekindWithES5Target8.ts": { + "system_reason": "Pre-existing externalModules conformance case; guards unchanged import/export behavior outside the import defer requirement surface." + }, + "tests/cases/conformance/externalModules/es6/es6modulekindWithES5Target9.ts": { + "system_reason": "Pre-existing externalModules conformance case; guards unchanged import/export behavior outside the import defer requirement surface." + }, + "tests/cases/conformance/externalModules/esnext/esnextmodulekind.ts": { + "system_reason": "Pre-existing externalModules conformance case; guards unchanged import/export behavior outside the import defer requirement surface." + }, + "tests/cases/conformance/externalModules/esnext/esnextmodulekindWithES2015Target.ts": { + "system_reason": "Pre-existing externalModules conformance case; guards unchanged import/export behavior outside the import defer requirement surface." + }, + "tests/cases/conformance/externalModules/esnext/esnextmodulekindWithES5Target.ts": { + "system_reason": "Pre-existing externalModules conformance case; guards unchanged import/export behavior outside the import defer requirement surface." + }, + "tests/cases/conformance/externalModules/esnext/esnextmodulekindWithES5Target10.ts": { + "system_reason": "Pre-existing externalModules conformance case; guards unchanged import/export behavior outside the import defer requirement surface." + }, + "tests/cases/conformance/externalModules/esnext/esnextmodulekindWithES5Target11.ts": { + "system_reason": "Pre-existing externalModules conformance case; guards unchanged import/export behavior outside the import defer requirement surface." + }, + "tests/cases/conformance/externalModules/esnext/esnextmodulekindWithES5Target12.ts": { + "system_reason": "Pre-existing externalModules conformance case; guards unchanged import/export behavior outside the import defer requirement surface." + }, + "tests/cases/conformance/externalModules/esnext/esnextmodulekindWithES5Target2.ts": { + "system_reason": "Pre-existing externalModules conformance case; guards unchanged import/export behavior outside the import defer requirement surface." + }, + "tests/cases/conformance/externalModules/esnext/esnextmodulekindWithES5Target3.ts": { + "system_reason": "Pre-existing externalModules conformance case; guards unchanged import/export behavior outside the import defer requirement surface." + }, + "tests/cases/conformance/externalModules/esnext/esnextmodulekindWithES5Target4.ts": { + "system_reason": "Pre-existing externalModules conformance case; guards unchanged import/export behavior outside the import defer requirement surface." + }, + "tests/cases/conformance/externalModules/esnext/esnextmodulekindWithES5Target5.ts": { + "system_reason": "Pre-existing externalModules conformance case; guards unchanged import/export behavior outside the import defer requirement surface." + }, + "tests/cases/conformance/externalModules/esnext/esnextmodulekindWithES5Target6.ts": { + "system_reason": "Pre-existing externalModules conformance case; guards unchanged import/export behavior outside the import defer requirement surface." + }, + "tests/cases/conformance/externalModules/esnext/esnextmodulekindWithES5Target7.ts": { + "system_reason": "Pre-existing externalModules conformance case; guards unchanged import/export behavior outside the import defer requirement surface." + }, + "tests/cases/conformance/externalModules/esnext/esnextmodulekindWithES5Target8.ts": { + "system_reason": "Pre-existing externalModules conformance case; guards unchanged import/export behavior outside the import defer requirement surface." + }, + "tests/cases/conformance/externalModules/esnext/esnextmodulekindWithES5Target9.ts": { + "system_reason": "Pre-existing externalModules conformance case; guards unchanged import/export behavior outside the import defer requirement surface." + }, + "tests/cases/conformance/externalModules/esnext/exnextmodulekindExportClassNameWithObject.ts": { + "system_reason": "Pre-existing externalModules conformance case; guards unchanged import/export behavior outside the import defer requirement surface." + }, + "tests/cases/conformance/externalModules/exportAmbientClassNameWithObject.ts": { + "system_reason": "Pre-existing externalModules conformance case; guards unchanged import/export behavior outside the import defer requirement surface." + }, + "tests/cases/conformance/externalModules/exportAssignDottedName.ts": { + "system_reason": "Pre-existing externalModules conformance case; guards unchanged import/export behavior outside the import defer requirement surface." + }, + "tests/cases/conformance/externalModules/exportAssignNonIdentifier.ts": { + "system_reason": "Pre-existing externalModules conformance case; guards unchanged import/export behavior outside the import defer requirement surface." + } + } + }, + "augmented": { + "suite_support": { + "env_var": "LOLBENCH_SUITE", + "values": [ + "orig", + "aug", + "union" + ] + }, + "eval_tests_patch": "eval_tests_aug.patch", + "eval_tests_aug_patch_sha256": "c76090e3a20cabdbb9341bdb3784b9d52b3b8d999853fc0698f506e28d60ed3c", + "f2p_aug_sha256": "87d65ffb4472d09ae22a7c1bc0d6a869041fee0b9507ba7d6c5d704e49114e19", + "p2p_aug_sha256": "ba6d84aa942f66f6a47021909ae1c54f169ecd96c18e1d82e5791e8934ecc87b", + "fail_to_pass": [ + "tests/cases/conformance/importDefer/dynamicImportDeferAug.ts", + "tests/cases/conformance/importDefer/dynamicImportDeferInvalidAccessAug.ts", + "tests/cases/conformance/importDefer/importDeferInvalidBindingsAug.ts" + ], + "pass_to_pass": [ + "tests/cases/conformance/externalModules/importTypeOnlyAug.ts" + ], + "targets_mutants": [ + "mutant_001_defer_import_phase_not_recorded", + "mutant_002_factory_drops_defer_phase", + "mutant_003_emitter_prints_defer_as_type", + "mutant_004_preserve_module_rejected", + "mutant_005_deferred_named_imports_allowed", + "mutant_006_deferred_default_imports_allowed", + "mutant_007_import_defer_call_not_import_call", + "mutant_008_import_defer_flagged_as_import_meta", + "mutant_009_import_defer_module_kind_not_checked", + "mutant_010_defer_preserved_in_declaration_emit", + "mutant_011_import_defer_is_expression_node", + "mutant_012_import_defer_meta_property_rejected" + ], + "coverage_gate": { + "minimum_line_coverage_percent": 80, + "status": "passed", + "coverage_report": "coverage_out/coverage_report_union.json", + "augmented_coverage_report": "coverage_out/coverage_report_aug.json", + "previous_baseline_coverage_report": "coverage_out/coverage_report.json", + "previous_baseline_union_line_coverage_percent": 82.7, + "union_line_coverage_percent": 87.9, + "executable_statements_in_patch": 173, + "union_covered_statements": 152, + "coverage_complete": true, + "failed_tries": 0, + "augmented_line_coverage_percent": 85.0, + "original_covered_statements": 143, + "augmented_covered_statements": 147, + "coverage_report_sha256": "596ba343f2bc8b6c40b04d95ca0f0feabaf691efe55bba1bd4b5f0c7caa03191", + "previous_baseline_coverage_report_sha256": "95cbb8b3be25706864ee04a6a04f4129f53fd07ef570c20b5ca02824f4a46da8", + "augmented_coverage_report_sha256": "514e21b23770ea34d4fae471b83f0c0113e70cc1ea968d114fc0f8282dd70d55", + "measurement_note": "Coverage refreshed on 2026-06-15 with current repo selector and eval patch files mounted into the local Docker image; expanded original P2P raises original-suite P2P coverage while union remains above the 80% gate." + }, + "validation": { + "status": "passed", + "validated_at": "2026-06-15", + "validation_output": "repo-mounted validation: /private/tmp/ts60757_validate_union_pre_repo and /private/tmp/ts60757_validate_union_post_repo", + "mutants_total": 12, + "mutants_killed_by_union": 12, + "surviving_mutants": [], + "mutants_killed": [ + "mutant_001_defer_import_phase_not_recorded", + "mutant_002_factory_drops_defer_phase", + "mutant_003_emitter_prints_defer_as_type", + "mutant_004_preserve_module_rejected", + "mutant_005_deferred_named_imports_allowed", + "mutant_006_deferred_default_imports_allowed", + "mutant_007_import_defer_call_not_import_call", + "mutant_008_import_defer_flagged_as_import_meta", + "mutant_009_import_defer_module_kind_not_checked", + "mutant_010_defer_preserved_in_declaration_emit", + "mutant_011_import_defer_is_expression_node", + "mutant_012_import_defer_meta_property_rejected" + ] + }, + "triage": { + "test_level_policy": "Augmented tests are TypeScript conformance source cases compared to committed baselines. They exercise language syntax and compiler behavior through the existing hereby conformance runner and do not import or call compiler source functions/classes directly.", + "fail_to_pass": { + "tests/cases/conformance/importDefer/dynamicImportDeferAug.ts": { + "requirement_sections": [ + "Proposal", + "Semantics" + ], + "public_surface": "TypeScript conformance source input compiled by the existing hereby runtests harness.", + "mutants_targeted": [ + "mutant_007_import_defer_call_not_import_call", + "mutant_008_import_defer_flagged_as_import_meta", + "mutant_009_import_defer_module_kind_not_checked", + "mutant_012_import_defer_meta_property_rejected" + ], + "rationale": "Pins the PR-shipped deferred dynamic import form across preserve, esnext, and commonjs module modes, checking accepted module modes, commonjs diagnostics, emit, symbols, and types through public conformance baselines." + }, + "tests/cases/conformance/importDefer/dynamicImportDeferInvalidAccessAug.ts": { + "requirement_sections": [ + "Semantics" + ], + "public_surface": "TypeScript conformance source input compiled by the existing hereby runtests harness.", + "mutants_targeted": [ + "mutant_011_import_defer_is_expression_node" + ], + "rationale": "Pins that standalone or parenthesized import.defer is not an ordinary expression by expecting the parser/type baselines for invalid meta-property usage." + }, + "tests/cases/conformance/importDefer/importDeferInvalidBindingsAug.ts": { + "requirement_sections": [ + "Proposal", + "Semantics" + ], + "public_surface": "TypeScript conformance source input compiled by the existing hereby runtests harness.", + "mutants_targeted": [ + "mutant_005_deferred_named_imports_allowed", + "mutant_006_deferred_default_imports_allowed" + ], + "rationale": "Pins the proposal restriction that deferred static imports only expose namespace bindings by expecting diagnostics for default and named deferred imports in one conformance case." + } + }, + "pass_to_pass": { + "tests/cases/conformance/externalModules/importTypeOnlyAug.ts": { + "requirement_sections": [ + "Proposal" + ], + "public_surface": "Existing TypeScript import type syntax compiled by the conformance runner, outside the new import defer syntax.", + "no_modification_clause": "The PR migrates ImportClause internals from isTypeOnly to phaseModifier; pre-existing type-only import syntax and emit behavior should remain unchanged.", + "rationale": "Adds a stable P2P guard for type-only import emit, symbols, and types using language syntax that predates the PR and does not invoke compiler source symbols." + } + } + } + }, + "coverage": { + "orig": 82.7, + "aug": 85.0, + "union": 87.9, + "denominator": "union_executable_lines" + }, + "p2p_entry_count": 49, + "f2p_entry_count": 2 +} diff --git a/TypeScript_4/tests/report_to_reward.py b/TypeScript_4/tests/report_to_reward.py new file mode 100644 index 0000000000000000000000000000000000000000..791099eb21b973afac269ec8757b8fbac9753ec7 --- /dev/null +++ b/TypeScript_4/tests/report_to_reward.py @@ -0,0 +1,73 @@ +#!/usr/bin/env python3 +import argparse +import json +from pathlib import Path + + +def rate(bucket): + total = float(bucket.get("total", 0) or 0) + if total <= 0: + return 0.0 + return float(bucket.get("passed", 0) or 0) / total + + +def write_json(path, payload): + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(json.dumps(payload, indent=2, sort_keys=True) + "\n") + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument("--suite", default="union") + parser.add_argument("--missing-patch") + parser.add_argument("--invalid-suite", action="store_true") + parser.add_argument("--runner-rc", type=int, default=0) + parser.add_argument("agent_report") + parser.add_argument("reward_file") + args = parser.parse_args() + + report_path = Path(args.agent_report) + reward_path = Path(args.reward_file) + + if args.invalid_suite: + reward = {"reward": 0.0, "resolved": 0.0, "applied": 0.0, "build_ok": 0.0, "f2p_pass_rate": 0.0, "p2p_pass_rate": 0.0, "harness_ok": 1.0} + sanitized = {"instance_id": "TypeScript_4", "suite": args.suite, "applied": False, "resolved": False, "error_categories": ["invalid_lolbench_suite"]} + write_json(report_path, sanitized) + write_json(reward_path, reward) + print(f"LoLBench reward=0 invalid suite {args.suite!r}") + return 0 + + if args.missing_patch: + reward = {"reward": 0.0, "resolved": 0.0, "applied": 0.0, "build_ok": 0.0, "f2p_pass_rate": 0.0, "p2p_pass_rate": 0.0, "harness_ok": 1.0} + sanitized = {"instance_id": "TypeScript_4", "suite": args.suite, "applied": False, "resolved": False, "error_categories": ["missing_solution_patch"]} + write_json(report_path, sanitized) + write_json(reward_path, reward) + print("LoLBench reward=0 missing solution patch") + return 0 + + if not report_path.exists(): + reward = {"reward": 0.0, "resolved": 0.0, "applied": 0.0, "build_ok": 0.0, "f2p_pass_rate": 0.0, "p2p_pass_rate": 0.0, "harness_ok": 0.0} + write_json(reward_path, reward) + print(f"LoLBench reward=0 no agent_report.json runner_rc={args.runner_rc}") + return 0 + + report = json.loads(report_path.read_text()) + build_status = report.get("build", {}).get("status") + resolved = bool(report.get("resolved")) + applied = bool(report.get("applied")) + reward = { + "reward": 1.0 if resolved else 0.0, + "resolved": 1.0 if resolved else 0.0, + "applied": 1.0 if applied else 0.0, + "build_ok": 1.0 if build_status == "ok" else 0.0, + "f2p_pass_rate": rate(report.get("f2p", {})), + "p2p_pass_rate": rate(report.get("p2p", {})), + "harness_ok": 1.0 if args.runner_rc == 0 else 0.0, + } + write_json(reward_path, reward) + print("LoLBench reward={reward} resolved={resolved} f2p={f2p_pass_rate:.3f} p2p={p2p_pass_rate:.3f}".format(**reward)) + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/TypeScript_4/tests/test.sh b/TypeScript_4/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..45ba2abd4f682d021752e6966a772a0ee2edb9f5 --- /dev/null +++ b/TypeScript_4/tests/test.sh @@ -0,0 +1,43 @@ +#!/usr/bin/env bash +set -euo pipefail + +suite=${LOLBENCH_SUITE:-union} +mode=${LOLBENCH_MODE:-eval} +patch=${LOLBENCH_SOLUTION_PATCH:-/logs/artifacts/solution.patch} +private_log=/tmp/lolbench-private-run.log + +mkdir -p /logs/verifier /logs/artifacts /in /out + +case "$suite" in + orig|aug|union) ;; + *) + python3 /tests/report_to_reward.py --suite "$suite" --invalid-suite /out/agent_report.json /logs/verifier/reward.json + exit 0 + ;; +esac + +if [ "$mode" = "eval" ] && [ ! -s "$patch" ]; then + python3 /tests/report_to_reward.py --suite "$suite" --missing-patch "$patch" /out/agent_report.json /logs/verifier/reward.json + exit 0 +fi + +if [ "$mode" = "eval" ]; then + cp "$patch" /in/solution.patch + chmod 0400 /in/solution.patch +fi + +set +e +LOLBENCH_MODE="$mode" LOLBENCH_SUITE="$suite" /opt/lolbench/private/run_tests.sh >"$private_log" 2>&1 +runner_rc=$? +set -e + +cp "$private_log" /logs/verifier/private_run.log +if [ -f /out/grader_report.json ]; then + cp /out/grader_report.json /logs/verifier/grader_report.json +fi + +python3 /tests/report_to_reward.py --suite "$suite" --runner-rc "$runner_rc" /out/agent_report.json /logs/verifier/reward.json + +if [ -f /out/agent_report.json ]; then + cp /out/agent_report.json /logs/verifier/agent_report.json +fi diff --git a/arrow_1/README.md b/arrow_1/README.md new file mode 100644 index 0000000000000000000000000000000000000000..aa6edd62de03e0ed2edc76ec92fbc1ab3425e899 --- /dev/null +++ b/arrow_1/README.md @@ -0,0 +1,87 @@ +# LoLBench Harbor Task: arrow_1 + +This is a Harbor-format LoLBench task generated from `Apache-Arrow_PR-240_PR-45459`. + +Selected source instance: + +- Harbor ID: `arrow_1` +- PR: `apache/arrow#45459` +- Base commit: `f9c18462db2af84a795e393985bbc615873ee3e7` +- Test modes: `orig, aug, union` +- Default/canonical mode: `union` +- Harbor image: `smartdub26/lolbench-linux:arrow_1-1.0.0` +- Docker Hub image: `smartdub26/lolbench-linux:arrow_1-1.0.0` + +## Image Setup + +Prefer the published Docker Hub image when it is available. Harbor refers to +the image as `smartdub26/lolbench-linux:arrow_1-1.0.0`, so Docker can pull it +directly when it is not present locally: + +```bash +docker pull smartdub26/lolbench-linux:arrow_1-1.0.0 +``` + +Only if the Docker Hub image is unavailable, build the single task image +locally: + +```bash +docker build -t lolbench/arrow_1:1.0.0 harbor_tasks/arrow_1/environment +docker tag lolbench/arrow_1:1.0.0 smartdub26/lolbench-linux:arrow_1-1.0.0 +``` + +The image contains the processed source tree at the base commit under +`/workspace/arrow`. Harbor must not mount a host source checkout +for the agent. + +## Run an Agent + +```bash +.harbor-venv/bin/harbor run \ + -p harbor_tasks/arrow_1 \ + -a codex \ + -m "" \ + --job-name arrow_1_agent_union \ + --jobs-dir harbor_runs/arrow_1 \ + --no-delete \ + --n-concurrent 1 \ + --ve LOLBENCH_SUITE=union +``` + +After implementing the requirement, the agent must clean any test-file edits +and run: + +```bash +lolbench-submit +``` + +## Evaluate a Patch + +Choose one mode with `LOLBENCH_SUITE=orig`, `aug`, or `union`; if unset, the +task defaults to `union`. + +```bash +PATCH="$(pwd)/path/to/solution.patch" + +.harbor-venv/bin/harbor run \ + -p harbor_tasks/arrow_1 \ + -a oracle \ + --job-name arrow_1_eval_union \ + --jobs-dir harbor_runs/arrow_1 \ + --no-delete \ + --n-concurrent 1 \ + --mounts '[{"type":"bind","source":"'"$PATCH"'","target":"/candidate/solution.patch","read_only":true}]' \ + --ae LOLBENCH_ORACLE_PATCH=/candidate/solution.patch \ + --ve LOLBENCH_SUITE=union +``` + +Outputs: + +```bash +find harbor_runs/arrow_1/arrow_1_eval_union -path '*/verifier/agent_report.json' -print +find harbor_runs/arrow_1/arrow_1_eval_union -path '*/verifier/reward.json' -print +``` + +`tests/docker-compose.yaml` is a verifier-only Harbor overlay. It mounts +`tests/`, `tests/private/`, and `solution/` into the separate verifier +container; none of those paths are mounted into the agent container. diff --git a/arrow_1/environment/Dockerfile b/arrow_1/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..7a79d80f0513404f29659e4c2067614f6fa997db --- /dev/null +++ b/arrow_1/environment/Dockerfile @@ -0,0 +1,85 @@ +# LoLBench eval image: Apache-Arrow PR-45459 (Parquet GEOMETRY/GEOGRAPHY types) +# PR: https://github.com/apache/arrow/pull/45459 +# base_commit: f9c18462db2af84a795e393985bbc615873ee3e7 +# +# C++ Parquet geospatial logical types. F2P = parquet-schema-test +# (TestLogicalTypeOperation.LogicalTypeRepresentation, exercises +# LogicalType::Geometry/Geography — named in the requirement doc, §6-exempt). +# P2P = the arrow-array-test core binary (parquet-independent, stable). +ARG BASE_IMAGE=lolbench/arrow-base:1 +FROM ${BASE_IMAGE} +ARG BASE_COMMIT=f9c18462db2af84a795e393985bbc615873ee3e7 +RUN mkdir -p /opt/lolbench/private /in /out /workspace +WORKDIR /workspace +RUN git init arrow && cd arrow && \ + git remote add origin https://github.com/apache/arrow.git && \ + git -c protocol.version=0 fetch --no-tags origin ${BASE_COMMIT} && \ + git checkout FETCH_HEAD && \ + git config user.email lolbench@local && \ + git config user.name lolbench && \ + if ! git diff --quiet || ! git diff --cached --quiet || [ -n "$(git ls-files --others --exclude-standard)" ]; then \ + git add -A && git -c commit.gpgsign=false commit -q -m "LoLBench environment overlay"; \ + fi && \ + git tag -f base && git tag -f lolbench-base && \ + git for-each-ref --format='%(refname)' refs/heads refs/remotes refs/tags | \ + while read ref; do \ + case "$ref" in refs/tags/base|refs/tags/lolbench-base) ;; *) git update-ref -d "$ref" ;; esac; \ + done && \ + ( git remote remove origin 2>/dev/null || true ) && \ + rm -f .git/FETCH_HEAD && \ + git reflog expire --expire=now --all && \ + git repack -Ad && \ + git prune --expire=now && \ + git config --global --add safe.directory /workspace/arrow +WORKDIR /workspace/arrow +# Configure C++ with Parquet + tests; pre-build the two test binaries we use +# (and their deps) so eval runs are incremental. +# Test binaries link conda's libthrift/libre2 which need GLIBCXX_3.4.3x; build +# with conda-forge compilers so the matching libstdc++ is used at link time. +RUN bash -lc 'source /opt/conda/etc/profile.d/conda.sh && conda activate base && \ + mamba install -y -c conda-forge compilers > /tmp/compilers.log 2>&1 || (tail -30 /tmp/compilers.log; exit 1)' +RUN bash -lc '\ +set -e ; source /opt/conda/etc/profile.d/conda.sh && conda activate base ; \ +mkdir -p /workspace/build && cd /workspace/build && \ +cmake -GNinja \ + -DCMAKE_C_COMPILER="$CC" -DCMAKE_CXX_COMPILER="$CXX" \ + -DCMAKE_BUILD_TYPE=Release \ + -DARROW_SIMD_LEVEL=AVX2 \ + -DARROW_RUNTIME_SIMD_LEVEL=AVX2 \ + -DARROW_BUILD_TESTS=ON \ + -DARROW_PARQUET=ON \ + -DARROW_DEPENDENCY_SOURCE=CONDA \ + -DARROW_WITH_RAPIDJSON=ON \ + -DARROW_FILESYSTEM=ON -DARROW_COMPUTE=ON -DARROW_JSON=ON -DARROW_CSV=ON \ + -DARROW_WITH_SNAPPY=ON -DARROW_WITH_ZSTD=ON -DARROW_WITH_LZ4=ON \ + -DARROW_S3=OFF -DARROW_GCS=OFF -DARROW_AZURE=OFF \ + /workspace/arrow/cpp && \ +ninja -j"${LOLBENCH_MAKE_JOBS:-4}" parquet-schema-test arrow-array-test \ +' + +# Harbor runtime adapter: keep the image public/agent-safe. +RUN if ! command -v rg >/dev/null 2>&1; then \ + if command -v apt-get >/dev/null 2>&1; then apt-get update && apt-get install -y --no-install-recommends ripgrep && rm -rf /var/lib/apt/lists/*; \ + elif command -v apk >/dev/null 2>&1; then apk add --no-cache ripgrep; \ + elif command -v dnf >/dev/null 2>&1; then dnf install -y ripgrep && dnf clean all; \ + elif command -v yum >/dev/null 2>&1; then yum install -y ripgrep && yum clean all; \ + else echo 'ripgrep is required by the agent harness' >&2; exit 1; fi; \ + fi +RUN mkdir -p /opt/lolbench /logs/artifacts /logs/agent /logs/verifier /in /out && \ + if ! id -u agent >/dev/null 2>&1; then useradd -m -s /bin/bash agent; fi && \ + mkdir -p /home/agent/.cache/opencode/bin && \ + ln -sf "$(command -v rg)" /home/agent/.cache/opencode/bin/rg +COPY metadata.json /opt/lolbench/metadata.json +COPY lolbench-submit /usr/local/bin/lolbench-submit +RUN chmod +x /usr/local/bin/lolbench-submit && \ + git config --global --add safe.directory /workspace/arrow && \ + if [ -d /workspace/arrow/.git ]; then \ + cd /workspace/arrow && git ls-files --others --exclude-standard | sort > /opt/lolbench/base_untracked.txt; \ + else \ + : > /opt/lolbench/base_untracked.txt; \ + fi && \ + chown -R agent:agent /workspace /in /out /logs /home/agent/.cache +USER agent +WORKDIR /workspace/arrow +ENV LOLBENCH_INSTANCE_ID=arrow_1 +ENV LOLBENCH_SOURCE_SLUG=Apache-Arrow_PR-240_PR-45459 diff --git a/arrow_1/environment/docker-compose.yaml b/arrow_1/environment/docker-compose.yaml new file mode 100644 index 0000000000000000000000000000000000000000..7ed45f87dc9faf9df284f5b10d6d2289781ff254 --- /dev/null +++ b/arrow_1/environment/docker-compose.yaml @@ -0,0 +1,3 @@ +services: + main: + pull_policy: missing diff --git a/arrow_1/environment/lolbench-submit b/arrow_1/environment/lolbench-submit new file mode 100644 index 0000000000000000000000000000000000000000..db92f16d4548e7e883591d865c71e4719e65857b --- /dev/null +++ b/arrow_1/environment/lolbench-submit @@ -0,0 +1,56 @@ +#!/usr/bin/env bash +set -euo pipefail +export LC_ALL=C + +resolve_repo() { + if [ "$#" -gt 0 ] && [ -n "${1:-}" ]; then + printf '%s\n' "$1" + return + fi + if git -C "$PWD" rev-parse --show-toplevel >/dev/null 2>&1; then + git -C "$PWD" rev-parse --show-toplevel + return + fi + find /workspace -mindepth 1 -maxdepth 1 -type d \ + -exec test -d '{}/.git' ';' -print 2>/dev/null | LC_ALL=C sort | head -n 1 +} + +if [ "$#" -gt 0 ]; then + repo=$(resolve_repo "$1") +else + repo=$(resolve_repo) +fi +out=${LOLBENCH_PATCH_OUT:-/logs/artifacts/solution.patch} + +if [ -z "$repo" ] || [ ! -d "$repo/.git" ]; then + echo "error: no git repository found; run from /workspace/ or pass the repo path" >&2 + exit 2 +fi + +mkdir -p "$(dirname "$out")" +cd "$repo" +git rev-parse --is-inside-work-tree >/dev/null + +baseline=/opt/lolbench/base_untracked.txt +current=$(mktemp) +new_files=$(mktemp) +trap 'rm -f "$current" "$new_files"' EXIT + +git ls-files --others --exclude-standard | sort > "$current" +if [ -f "$baseline" ]; then + comm -13 "$baseline" "$current" > "$new_files" +else + cp "$current" "$new_files" +fi + +if [ -s "$new_files" ]; then + xargs -r git add -N -- < "$new_files" +fi + +git diff --binary > "$out" + +if [ ! -s "$out" ]; then + echo "warning: wrote an empty solution patch to $out" >&2 +else + echo "wrote solution patch to $out" +fi diff --git a/arrow_1/environment/metadata.json b/arrow_1/environment/metadata.json new file mode 100644 index 0000000000000000000000000000000000000000..1922d236a43697606567fa0d0da85b3ed440729e --- /dev/null +++ b/arrow_1/environment/metadata.json @@ -0,0 +1,22 @@ +{ + "instance_id": "arrow_1", + "source_instance_id": "Apache-Arrow_PR-240_PR-45459", + "source_slug": "Apache-Arrow_PR-240_PR-45459", + "docker_slug": "Apache-Arrow_PR-240_PR-45459", + "dockerhub_image": "smartdub26/lolbench-linux:arrow_1-1.0.0", + "project": "arrow", + "repo": "apache/arrow", + "requirement_doc": "https://github.com/apache/parquet-format/pull/240", + "pr_link": "https://github.com/apache/arrow/pull/45459", + "base_commit": "f9c18462db2af84a795e393985bbc615873ee3e7", + "merge_commit": "e1b7061cb1df3d5fc861fe80557cd7824980346a", + "source_history_policy": "ancestors-only", + "lolbench_test_modes": [ + "orig", + "aug", + "union" + ], + "default_lolbench_suite": "union", + "canonical_lolbench_suite": "union", + "augmentation_available": true +} diff --git a/arrow_1/environment/source_audit.json b/arrow_1/environment/source_audit.json new file mode 100644 index 0000000000000000000000000000000000000000..19bce18d1433d6e5aece7e557be22d8248b04439 --- /dev/null +++ b/arrow_1/environment/source_audit.json @@ -0,0 +1,6 @@ +{ + "source_policy": "dockerfile_fetch_historyless_base_snapshot", + "base_commit": "f9c18462db2af84a795e393985bbc615873ee3e7", + "repo": "apache/arrow", + "note": "The generated Dockerfile fetches the base commit with ancestor history, preserves .git, removes post-base refs/remotes/reflogs, and prunes unreachable future commit objects during image build." +} diff --git a/arrow_1/instruction.md b/arrow_1/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..00e5b8291036fbafe448ad967a7bfc9379fc3a0f --- /dev/null +++ b/arrow_1/instruction.md @@ -0,0 +1,339 @@ +You are working in `/workspace/arrow`, a source tree checked out at +the base commit for this task. Implement the requested behavior in the source +tree, then run: + +```bash +lolbench-submit +``` + +Do not stop after editing files, running tests, or describing the solution. The +task is complete only when `lolbench-submit` has created +`/logs/artifacts/solution.patch`. If that file does not exist, continue +working and run `lolbench-submit` again. + +That command writes your implementation diff to +`/logs/artifacts/solution.patch`, which is the artifact the Harbor verifier +will grade. Before running `lolbench-submit`, clean or revert any test files +you created or modified; test files must not be included in the final +`solution.patch`. + +This environment has no outbound internet access — `curl`/`wget`, `git fetch`/`clone`, package installs, and web fetch/search will all fail. Implement the requirements using only the code already in the workspace and your own knowledge; do not attempt to fetch or search external resources. + +Now please implement the following requirements in the source tree: + +--- + +# Geospatial Definitions +This document contains the specification of geospatial types and statistics. + +# Background + +The Geometry and Geography class hierarchy and its Well-Known Text (WKT) and +Well-Known Binary (WKB) serializations (ISO variant supporting XY, XYZ, XYM, +XYZM) are defined by [OpenGIS Implementation Specification for Geographic +information - Simple feature access - Part 1: Common architecture][sfa-part1], +from [OGC(Open Geospatial Consortium)][ogc]. + +The version of the OGC standard first used here is 1.2.1, but future versions +may also be used if the WKB representation remains wire-compatible. + +[sfa-part1]: https://portal.ogc.org/files/?artifact_id=25355 +[ogc]: https://www.ogc.org/standard/sfa/ + +## Coordinate Reference System + +Coordinate Reference System (CRS) is a mapping of how coordinates refer to +locations on Earth. + +The default CRS `OGC:CRS84` means that the geospatial features must be stored +in the order of longitude/latitude based on the WGS84 datum. + +Custom CRS can be specified by a string value. It is recommended to use an +identifier-based approach like [Spatial reference identifier][srid]. + +For geographic CRS, longitudes are bound by [-180, 180] and latitudes are bound +by [-90, 90]. + +[srid]: https://en.wikipedia.org/wiki/Spatial_reference_system#Identifier + +## Edge Interpolation Algorithm + +An algorithm for interpolating edges, and is one of the following values: + +* `spherical`: edges are interpolated as geodesics on a sphere. +* `vincenty`: [https://en.wikipedia.org/wiki/Vincenty%27s_formulae](https://en.wikipedia.org/wiki/Vincenty%27s_formulae) +* `thomas`: Thomas, Paul D. Spheroidal geodesics, reference systems, & local geometry. US Naval Oceanographic Office, 1970. +* `andoyer`: Thomas, Paul D. Mathematical models for navigation systems. US Naval Oceanographic Office, 1965. +* `karney`: [Karney, Charles FF. "Algorithms for geodesics." Journal of Geodesy 87 (2013): 43-55](https://link.springer.com/content/pdf/10.1007/s00190-012-0578-z.pdf), and [GeographicLib](https://geographiclib.sourceforge.io/) + +# Logical Types + +Two geospatial logical type annotations are supported: +* `GEOMETRY`: geospatial features in the WKB format with linear/planar edges interpolation. See [Geometry](LogicalTypes.md#geometry) +* `GEOGRAPHY`: geospatial features in the WKB format with an explicit (non-linear/non-planar) edges interpolation algorithm. See [Geography](LogicalTypes.md#geography) + +# Statistics + +`GeospatialStatistics` is a struct specific for `GEOMETRY` and `GEOGRAPHY` +logical types to store statistics of a column chunk. It is an optional field in +the `ColumnMetaData` and contains [Bounding Box](#bounding-box) and [Geospatial +Types](#geospatial-types) that are described below in detail. + +On the implementation side, a `GeoStatistics` class accumulates these statistics +for a geospatial column: it updates the bounding box and geometry-type coverage +as values are written, merges partial statistics, compares equality, and encodes +to / decodes from the `GeospatialStatistics` representation. +Implement the WKB bounding-box/statistics helper as production code in +`cpp/src/parquet/geospatial/util_internal.h` and +`cpp/src/parquet/geospatial/util_internal.cc`; `GeoStatistics` should use this +helper to parse WKB values, accumulate `BoundingBox` ranges, and track WKB +geometry type codes. + +## Bounding Box + +A geospatial instance has at least two coordinate dimensions: X and Y for 2D +coordinates of each point. Please note that X is longitude/easting and Y is +latitude/northing. A geospatial instance can optionally have Z and/or M values +associated with each point. + +The Z values introduce the third dimension coordinate. Usually they are used to +indicate the height, or elevation. + +M values are an opportunity for a geospatial instance to express a fourth +dimension as a coordinate value. These values can be used as a linear reference +value (e.g., highway milepost value), a timestamp, or some other value as defined +by the CRS. + +Bounding box is defined as the thrift struct below in the representation of +min/max value pair of coordinates from each axis. Note that X and Y Values are +always present. Z and M are omitted for 2D geospatial instances. + +For the X values only, xmin may be greater than xmax. In this case, an object +in this bounding box may match if it contains an X such that `x >= xmin` OR +`x <= xmax`. This wraparound occurs only when the corresponding bounding box +crosses the antimeridian line. In geographic terminology, the concepts of `xmin`, +`xmax`, `ymin`, and `ymax` are also known as `westernmost`, `easternmost`, +`southernmost` and `northernmost`, respectively. + +For `GEOGRAPHY` types, X and Y values are restricted to the canonical ranges of +[-180, 180] for X and [-90, 90] for Y. + +```thrift +struct BoundingBox { + 1: required double xmin; + 2: required double xmax; + 3: required double ymin; + 4: required double ymax; + 5: optional double zmin; + 6: optional double zmax; + 7: optional double mmin; + 8: optional double mmax; +} +``` + +## Geospatial Types + +A list of geospatial types from all instances in the `GEOMETRY` or `GEOGRAPHY` +column, or an empty list if they are not known. + +This is borrowed from [geometry_types of GeoParquet][geometry-types] except that +values in the list are [WKB (ISO-variant) integer codes][wkb-integer-code]. +Table below shows the most common geospatial types and their codes: + +| Type | XY | XYZ | XYM | XYZM | +| :----------------- | :--- | :--- | :--- | :--: | +| Point | 0001 | 1001 | 2001 | 3001 | +| LineString | 0002 | 1002 | 2002 | 3002 | +| Polygon | 0003 | 1003 | 2003 | 3003 | +| MultiPoint | 0004 | 1004 | 2004 | 3004 | +| MultiLineString | 0005 | 1005 | 2005 | 3005 | +| MultiPolygon | 0006 | 1006 | 2006 | 3006 | +| GeometryCollection | 0007 | 1007 | 2007 | 3007 | + +In addition, the following rules are applied: +- A list of multiple values indicates that multiple geospatial types are present (e.g. `[0003, 0006]`). +- An empty array explicitly signals that the geospatial types are not known. +- The geospatial types in the list must be unique (e.g. `[0001, 0001]` is not valid). + +[geometry-types]: https://github.com/opengeospatial/geoparquet/blob/v1.1.0/format-specs/geoparquet.md?plain=1#L159 +[wkb-integer-code]: https://en.wikipedia.org/wiki/Well-known_text_representation_of_geometry#Well-known_binary + +# CRS Customization + +CRS is represented as a string value. Writer and reader implementations are +responsible for serializing and deserializing the CRS, respectively. + +As a convention to maximize the interoperability, custom CRS values can be +specified by a string of the format `type:identifier`, where `type` is one of +the following values: + +* `srid`: [Spatial reference identifier](https://en.wikipedia.org/wiki/Spatial_reference_system#Identifier), `identifier` is the SRID itself. +* `projjson`: [PROJJSON](https://proj.org/en/stable/specifications/projjson.html), `identifier` is the name of a table property or a file property where the projjson string is stored. + +# Coordinate axis order + +The axis order of the coordinates in WKB and bounding box stored in Parquet +follows the de facto standard for axis order in WKB and is therefore always +(x, y) where x is easting or longitude and y is northing or latitude. This +ordering explicitly overrides the axis order as specified in the CRS. + +## Linked Reference: GeoParquet v1.1.0 — geometry_types + +*Source: https://github.com/opengeospatial/geoparquet/blob/v1.1.0/format-specs/geoparquet.md?plain=1#L159* + +### GeoParquet: geometry_types + +This field captures the geometry types of the geometries in the column, when known. Accepted geometry types are: `"Point"`, `"LineString"`, `"Polygon"`, `"MultiPoint"`, `"MultiLineString"`, `"MultiPolygon"`, `"GeometryCollection"`. + +In addition, the following rules are used: + +- In case of 3D geometries, a `" Z"` suffix gets added (e.g. `["Point Z"]`). +- A list of multiple values indicates that multiple geometry types are present (e.g. `["Polygon", "MultiPolygon"]`). +- An empty array explicitly signals that the geometry types are not known. +- The geometry types in the list must be unique (e.g. `["Point", "Point"]` is not valid). + +It is expected that this field is strictly correct. For example, if having both polygons and multipolygons, it is not sufficient to specify `["MultiPolygon"]`, but it is expected to specify `["Polygon", "MultiPolygon"]`. Or if having 3D points, it is not sufficient to specify `["Point"]`, but it is expected to list `["Point Z"]`. + +## Linked Reference: PROJJSON Specification + +*Source: https://proj.org/en/stable/specifications/projjson.html* + +### PROJJSON: Introduction + +PROJJSON represents a JSON encoding of WKT2:2019 / ISO-19162:2019 standards for geographic information and coordinate reference systems. It maintains semantic equivalence with WKT2:2019 and can be morphed losslessly from/into WKT2:2019. The format targets encoding of coordinate reference system definitions including datums, datum ensembles, coordinate systems, and coordinate operations. + +### PROJJSON: Normative References + +The specification requires foundational knowledge of: +- The JavaScript Object Notation (JSON) Data Interchange Format / IETF RFC 7159 +- WKT2:2019 / ISO-19162:2019 + +Key terms include: +- **JSON elements**: Objects, members, names, values, arrays, numbers, true, false, null (per RFC7159) +- **Integer**: JSON number with no fractional or exponent component +- All WKT2:2019 terminology applies + +### PROJJSON: Schema Structure + +A JSON schema reference exists at: `https://proj.org/schemas/v0.7/projjson.schema.json` + +The schema defines minimum well-formedness constraints. Additional CRS and coordinate operation constraints from WKT2:2019 apply as supplements to JSON schema validation. + +**Schema Version History:** + +- **v0.7**: Added "accuracy" property in ConcatenatedOperation (PROJ 9.2.1) +- **v0.6**: Enhanced with source_crs in abridged_transformation, CoordinateMetadata, datum_epoch, axis range properties, affine coordinate system subtype (PROJ 9.2) +- **v0.5**: Added meridian, temporal_extent, vertical_extent, geoid_models, deformation_models (PROJ 9.1) +- **v0.4**: Extended id object properties (PROJ 8.2) +- **v0.3**: Enhanced BoundCRS properties (PROJ 8.1) +- **v0.2**: Added geoid_model in VerticalCRS +- **v0.1**: Initial version (PROJ 6.2) + +### PROJJSON: High-Level Structure + +A PROJJSON object minimally requires a `type` member indicating the encoded geodetic object type. An optional `$schema` member may reference the applicable JSON schema URL. Sub-objects may omit `type` when unambiguous, though the specification recommends including `type` when JSON schema uses oneOf constructs with alternatives. + +**Valid High-Level Object Types:** + +- **Coordinate Reference Systems:** GeographicCRS, GeodeticCRS, ProjectedCRS, CompoundCRS, BoundCRS; VerticalCRS, EngineeringCRS, TemporalCRS, ParametricCRS; DerivedGeographicCRS, DerivedGeodeticCRS, DerivedProjectedCRS, DerivedVerticalCRS, DerivedEngineeringCRS, DerivedTemporalCRS, DerivedParametricCRS +- **Coordinate Operations:** Transformation, Conversion, ConcatenatedOperation +- **Other Objects:** PrimeMeridian, Ellipsoid, Datum, DatumEnsemble + +### PROJJSON: Identifiers + +Objects support optional `id` or `ids` members for identification. + +The `id` object structure: + +```json +{ + "authority": "string (required, e.g., EPSG, OGC, IGNF)", + "code": "string or integer (required, e.g., 4326 or CRS84)", + "authority_citation": "string (optional)", + "uri": "string (optional)" +} +``` + +The `ids` member accepts an array of such identifier objects. WKT2:2019 recommends omitting inner object identifiers when the parent has identification. + +### PROJJSON: Object Usages + +CRS and coordinate operation objects support optional usage metadata: + +- **scope**: Purpose description (e.g., "Geodesy, topographic mapping") +- **area**: Geographic applicability region +- **bbox**: Bounding box object with required members: + - east_longitude: Eastern extent (-180 to 180) + - west_longitude: Western extent (-180 to 180) + - south_latitude: Southern extent (-90 to 90) + - north_latitude: Northern extent (-90 to 90) +- **remarks**: Informative text not affecting parameters +- **id/ids**: Identifier(s) +- **usages**: Array of usage objects (recommended for multiple extents/scopes) + +### PROJJSON: Units + +Units may be expressed as objects or enumerated strings. + +**Object format:** + +```json +{ + "type": "LinearUnit|AngularUnit|ScaleUnit|TimeUnit|ParametricUnit|Unit (required)", + "name": "string (required)", + "conversion_factor": "number (required in most cases)", + "id": "optional identifier" +} +``` + +**Enumerated string values:** metre, degree, unity. String notation is recommended for brevity when applicable. + +**Unit Omission Rules:** Most numeric parameters require accompanying units. However: + +- Omissible when metre: semi_major_axis, semi_minor_axis, radius (ellipsoid members) +- Omissible when degree: longitude (prime meridian) + +### PROJJSON: Coordinate System + +The WKT ORDER keyword (axis index indicator) is omitted from PROJJSON to prevent misuse, as index position is implicit in array ordering. + +### PROJJSON: GeographicCRS Example + +```json +{ + "$schema": "https://proj.org/schemas/v0.4/projjson.schema.json", + "type": "GeographicCRS", + "name": "NAD83(2011)", + "datum": { + "type": "GeodeticReferenceFrame", + "name": "NAD83 (National Spatial Reference System 2011)", + "ellipsoid": { + "name": "GRS 1980", + "semi_major_axis": 6378137, + "inverse_flattening": 298.257222101 + } + }, + "coordinate_system": { + "subtype": "ellipsoidal", + "axis": [ + {"name": "Geodetic latitude", "abbreviation": "Lat", "direction": "north", "unit": "degree"}, + {"name": "Geodetic longitude", "abbreviation": "Lon", "direction": "east", "unit": "degree"} + ] + }, + "id": {"authority": "EPSG", "code": 6318} +} +``` + +### PROJJSON: Deviations from WKT2:2019 + +**Extensions:** The specification permits Bound CRS objects as CRS definitions wherever allowed under OGC Topic 2 abstract specification and ISO-19111:2019. Notably, compound CRS components may include Bound CRS objects, and Bound CRS may serve as coordinate operation source or target — extensions not permitted in the OGC specification. + +**Omissions:** The specification does not define encoding for triaxial ellipsoid (WKT TRIAXIAL keyword). + +### PROJJSON: Reference Implementation + +PROJJSON appears as input and output within PROJ software since version 6.2. The spatialreference.org website provides CRS definitions in multiple formats including PROJJSON across various authorities. + +## Linked Reference: OGC Simple Feature Access — Part 1 (sfa-part1) + +*Source: https://portal.ogc.org/files/?artifact_id=25355 (inaccessible: large PDF that this environment cannot reliably convert to markdown; the OGC SFA Common Architecture standard 1.2.1 is referenced as the authoritative WKB/WKT specification for the Geometry/Geography class hierarchy used in this proposal)* diff --git a/arrow_1/solution/solution.patch b/arrow_1/solution/solution.patch new file mode 100644 index 0000000000000000000000000000000000000000..4f3a4a2da742f11d45ace860f8ca433dd8ec8595 --- /dev/null +++ b/arrow_1/solution/solution.patch @@ -0,0 +1,2429 @@ +diff --git a/cpp/cmake_modules/ThirdpartyToolchain.cmake b/cpp/cmake_modules/ThirdpartyToolchain.cmake +--- a/cpp/cmake_modules/ThirdpartyToolchain.cmake ++++ b/cpp/cmake_modules/ThirdpartyToolchain.cmake +@@ -374,16 +374,13 @@ target_include_directories(arrow::flatbuffers + # ---------------------------------------------------------------------- + # Some EP's require other EP's + +-if(PARQUET_REQUIRE_ENCRYPTION) +- set(ARROW_JSON ON) +-endif() +- + if(ARROW_WITH_OPENTELEMETRY) + set(ARROW_WITH_NLOHMANN_JSON ON) + set(ARROW_WITH_PROTOBUF ON) + endif() + + if(ARROW_PARQUET) ++ set(ARROW_WITH_RAPIDJSON ON) + set(ARROW_WITH_THRIFT ON) + endif() + +diff --git a/cpp/src/parquet/arrow/schema.cc b/cpp/src/parquet/arrow/schema.cc +--- a/cpp/src/parquet/arrow/schema.cc ++++ b/cpp/src/parquet/arrow/schema.cc +@@ -38,6 +38,7 @@ + #include "parquet/arrow/schema_internal.h" + #include "parquet/arrow/variant_internal.h" + #include "parquet/exception.h" ++#include "parquet/geospatial/util_json_internal.h" + #include "parquet/metadata.h" + #include "parquet/properties.h" + #include "parquet/types.h" +@@ -288,8 +289,8 @@ int FieldIdFromMetadata( + if (::arrow::internal::ParseValue<::arrow::Int32Type>( + field_id_str.c_str(), field_id_str.length(), &field_id)) { + if (field_id < 0) { +- // Thrift should convert any negative value to null but normalize to -1 here in case +- // we later check this in logic. ++ // Thrift should convert any negative value to null but normalize to -1 here in ++ // case we later check this in logic. + return -1; + } + return field_id; +@@ -449,9 +450,9 @@ Status FieldToNode(const std::string& name, const std::shared_ptr& field, + } + case ArrowTypeId::EXTENSION: { + auto ext_type = std::static_pointer_cast<::arrow::ExtensionType>(field->type()); +- // Built-in JSON extension is handled differently. +- if (ext_type->extension_name() == std::string("arrow.json")) { +- // Set physical and logical types and instantiate primitive node. ++ // Set physical and logical types and instantiate primitive node ++ // for extension types ++ if (ext_type->extension_name() == std::string_view("arrow.json")) { + type = ParquetType::BYTE_ARRAY; + logical_type = LogicalType::JSON(); + break; +@@ -460,6 +461,11 @@ Status FieldToNode(const std::string& name, const std::shared_ptr& field, + logical_type = LogicalType::UUID(); + length = 16; + break; ++ } else if (ext_type->extension_name() == std::string_view("geoarrow.wkb")) { ++ type = ParquetType::BYTE_ARRAY; ++ ARROW_ASSIGN_OR_RAISE(logical_type, ++ LogicalTypeFromGeoArrowMetadata(ext_type->Serialize())); ++ break; + } else if (ext_type->extension_name() == std::string("parquet.variant")) { + auto variant_type = std::static_pointer_cast(field->type()); + +@@ -495,6 +501,7 @@ struct SchemaTreeContext { + SchemaManifest* manifest; + ArrowReaderProperties properties; + const SchemaDescriptor* schema; ++ std::shared_ptr metadata; + + void LinkParent(const SchemaField* child, const SchemaField* parent) { + manifest->child_to_parent[child] = parent; +@@ -517,7 +524,7 @@ ::arrow::Result> GetTypeForNode( + int column_index, const schema::PrimitiveNode& primitive_node, + SchemaTreeContext* ctx) { + ARROW_ASSIGN_OR_RAISE(std::shared_ptr storage_type, +- GetArrowType(primitive_node, ctx->properties)); ++ GetArrowType(primitive_node, ctx->properties, ctx->metadata)); + if (ctx->properties.read_dictionary(column_index) && + IsDictionaryReadSupported(*storage_type)) { + return ::arrow::dictionary(::arrow::int32(), storage_type); +@@ -610,8 +617,8 @@ Status MapToSchemaField(const GroupNode& group, LevelInfo current_levels, + return Status::Invalid("Map keys must be annotated as required."); + } + // Arrow doesn't support 1 column maps (i.e. Sets). The options are to either +- // make the values column nullable, or process the map as a list. We choose the latter +- // as it is simpler. ++ // make the values column nullable, or process the map as a list. We choose the ++ // latter as it is simpler. + if (key_value.field_count() == 1) { + return ListToSchemaField(group, current_levels, ctx, parent, out); + } +@@ -1197,6 +1204,7 @@ Status SchemaManifest::Make(const SchemaDescriptor* schema, + ctx.manifest = manifest; + ctx.properties = properties; + ctx.schema = schema; ++ ctx.metadata = metadata; + const GroupNode& schema_node = *schema->group_node(); + manifest->descr = schema; + manifest->schema_fields.resize(schema_node.field_count()); +diff --git a/cpp/src/parquet/arrow/schema_internal.cc b/cpp/src/parquet/arrow/schema_internal.cc +--- a/cpp/src/parquet/arrow/schema_internal.cc ++++ b/cpp/src/parquet/arrow/schema_internal.cc +@@ -20,7 +20,10 @@ + #include "arrow/extension/json.h" + #include "arrow/extension/uuid.h" + #include "arrow/type.h" ++#include "arrow/util/key_value_metadata.h" ++#include "arrow/util/string.h" + ++#include "parquet/geospatial/util_json_internal.h" + #include "parquet/properties.h" + + using ArrowType = ::arrow::DataType; +@@ -112,7 +115,8 @@ Result> MakeArrowTimestamp(const LogicalType& logical + } + + Result> FromByteArray( +- const LogicalType& logical_type, const ArrowReaderProperties& reader_properties) { ++ const LogicalType& logical_type, const ArrowReaderProperties& reader_properties, ++ const std::shared_ptr& metadata) { + switch (logical_type.type()) { + case LogicalType::Type::STRING: + return ::arrow::utf8(); +@@ -129,6 +133,18 @@ Result> FromByteArray( + // When the original Arrow schema isn't stored and Arrow extensions are disabled, + // LogicalType::JSON is read as utf8(). + return ::arrow::utf8(); ++ case LogicalType::Type::GEOMETRY: ++ case LogicalType::Type::GEOGRAPHY: ++ if (reader_properties.get_arrow_extensions_enabled()) { ++ // Attempt creating a GeoArrow extension type (or return binary() if types are not ++ // registered) ++ return GeoArrowTypeFromLogicalType(logical_type, metadata); ++ } ++ ++ // When the original Arrow schema isn't stored, Arrow extensions are disabled, or ++ // the geoarrow.wkb extension type isn't registered, LogicalType::GEOMETRY and ++ // LogicalType::GEOGRAPHY are as binary(). ++ return ::arrow::binary(); + default: + return Status::NotImplemented("Unhandled logical logical_type ", + logical_type.ToString(), " for binary array"); +@@ -196,7 +212,8 @@ Result> FromInt64(const LogicalType& logical_type) { + + Result> GetArrowType( + Type::type physical_type, const LogicalType& logical_type, int type_length, +- const ArrowReaderProperties& reader_properties) { ++ const ArrowReaderProperties& reader_properties, ++ const std::shared_ptr& metadata) { + if (logical_type.is_null()) { + return ::arrow::null(); + } +@@ -220,7 +237,7 @@ Result> GetArrowType( + case ParquetType::DOUBLE: + return ::arrow::float64(); + case ParquetType::BYTE_ARRAY: +- return FromByteArray(logical_type, reader_properties); ++ return FromByteArray(logical_type, reader_properties, metadata); + case ParquetType::FIXED_LEN_BYTE_ARRAY: + return FromFLBA(logical_type, type_length, reader_properties); + default: { +@@ -233,9 +250,10 @@ Result> GetArrowType( + + Result> GetArrowType( + const schema::PrimitiveNode& primitive, +- const ArrowReaderProperties& reader_properties) { ++ const ArrowReaderProperties& reader_properties, ++ const std::shared_ptr& metadata) { + return GetArrowType(primitive.physical_type(), *primitive.logical_type(), +- primitive.type_length(), reader_properties); ++ primitive.type_length(), reader_properties, metadata); + } + + } // namespace parquet::arrow +diff --git a/cpp/src/parquet/arrow/schema_internal.h b/cpp/src/parquet/arrow/schema_internal.h +--- a/cpp/src/parquet/arrow/schema_internal.h ++++ b/cpp/src/parquet/arrow/schema_internal.h +@@ -29,19 +29,22 @@ namespace parquet::arrow { + + using ::arrow::Result; + +-Result> FromByteArray(const LogicalType& logical_type, +- bool use_known_arrow_extensions); ++Result> FromByteArray( ++ const LogicalType& logical_type, bool use_known_arrow_extensions, ++ const std::shared_ptr& metadata = nullptr); + Result> FromFLBA(const LogicalType& logical_type, + int32_t physical_length); + Result> FromInt32(const LogicalType& logical_type); + Result> FromInt64(const LogicalType& logical_type); + + Result> GetArrowType( + Type::type physical_type, const LogicalType& logical_type, int type_length, +- const ArrowReaderProperties& reader_properties); ++ const ArrowReaderProperties& reader_properties, ++ const std::shared_ptr& metadata = nullptr); + + Result> GetArrowType( + const schema::PrimitiveNode& primitive, +- const ArrowReaderProperties& reader_properties); ++ const ArrowReaderProperties& reader_properties, ++ const std::shared_ptr& metadata = nullptr); + + } // namespace parquet::arrow +diff --git a/cpp/src/parquet/column_writer.cc b/cpp/src/parquet/column_writer.cc +--- a/cpp/src/parquet/column_writer.cc ++++ b/cpp/src/parquet/column_writer.cc +@@ -788,6 +788,9 @@ class ColumnWriterImpl { + // Plain-encoded statistics of the whole chunk + virtual StatisticsPair GetChunkStatistics() = 0; + ++ // Geospatial statistics of the whole chunk ++ virtual std::optional GetChunkGeoStatistics() = 0; ++ + // Merges page statistics into chunk statistics, then resets the values + virtual void ResetPageStatistics() = 0; + +@@ -1104,9 +1107,18 @@ int64_t ColumnWriterImpl::Close() { + if (rows_written_ > 0 && chunk_statistics.is_set()) { + metadata_->SetStatistics(chunk_statistics); + } ++ + if (rows_written_ > 0 && chunk_size_statistics.is_set()) { + metadata_->SetSizeStatistics(chunk_size_statistics); + } ++ ++ if (descr_->logical_type() != nullptr && descr_->logical_type()->is_geometry()) { ++ std::optional geo_stats = GetChunkGeoStatistics(); ++ if (geo_stats) { ++ metadata_->SetGeoStatistics(std::move(*geo_stats)); ++ } ++ } ++ + metadata_->SetKeyValueMetadata(key_value_metadata_); + pager_->Close(has_dictionary_, fallback_); + } +@@ -1230,11 +1242,19 @@ class TypedColumnWriterImpl : public ColumnWriterImpl, + current_dict_encoder_ = + dynamic_cast*>(current_encoder_.get()); + +- if (properties->statistics_enabled(descr_->path()) && +- (SortOrder::UNKNOWN != descr_->sort_order())) { +- page_statistics_ = MakeStatistics(descr_, allocator_); +- chunk_statistics_ = MakeStatistics(descr_, allocator_); ++ // GH-46205: Geometry/Geography are the first non-nested logical types to have a ++ // SortOrder::UNKNOWN. Currently, the presence of statistics is tied to ++ // having a known sort order and so null counts will be missing. ++ if (properties->statistics_enabled(descr_->path())) { ++ if (SortOrder::UNKNOWN != descr_->sort_order()) { ++ page_statistics_ = MakeStatistics(descr_, allocator_); ++ chunk_statistics_ = MakeStatistics(descr_, allocator_); ++ } ++ if (descr_->logical_type() != nullptr && descr_->logical_type()->is_geometry()) { ++ chunk_geospatial_statistics_ = std::make_shared(); ++ } + } ++ + if (properties->size_statistics_level() == SizeStatisticsLevel::ColumnChunk || + properties->size_statistics_level() == SizeStatisticsLevel::PageAndColumnChunk) { + page_size_statistics_ = SizeStatistics::Make(descr_); +@@ -1430,6 +1450,14 @@ class TypedColumnWriterImpl : public ColumnWriterImpl, + return result; + } + ++ std::optional GetChunkGeoStatistics() override { ++ if (chunk_geospatial_statistics_) { ++ return chunk_geospatial_statistics_->Encode(); ++ } else { ++ return std::nullopt; ++ } ++ } ++ + void ResetPageStatistics() override { + if (chunk_statistics_ != nullptr) { + chunk_statistics_->Merge(*page_statistics_); +@@ -1494,6 +1522,7 @@ class TypedColumnWriterImpl : public ColumnWriterImpl, + std::shared_ptr chunk_statistics_; + std::unique_ptr page_size_statistics_; + std::shared_ptr chunk_size_statistics_; ++ std::shared_ptr chunk_geospatial_statistics_; + bool pages_change_on_record_boundaries_; + + // If writing a sequence of ::arrow::DictionaryArray to the writer, we keep the +@@ -1719,7 +1748,14 @@ class TypedColumnWriterImpl : public ColumnWriterImpl, + if (page_statistics_ != nullptr) { + page_statistics_->Update(values, num_values, num_nulls); + } ++ + UpdateUnencodedDataBytes(); ++ ++ if constexpr (std::is_same::value) { ++ if (chunk_geospatial_statistics_ != nullptr) { ++ chunk_geospatial_statistics_->Update(values, num_values); ++ } ++ } + } + + /// \brief Write values with spaces and update page statistics accordingly. +@@ -1748,7 +1784,15 @@ class TypedColumnWriterImpl : public ColumnWriterImpl, + page_statistics_->UpdateSpaced(values, valid_bits, valid_bits_offset, + num_spaced_values, num_values, num_nulls); + } ++ + UpdateUnencodedDataBytes(); ++ ++ if constexpr (std::is_same::value) { ++ if (chunk_geospatial_statistics_ != nullptr) { ++ chunk_geospatial_statistics_->UpdateSpaced(values, valid_bits, valid_bits_offset, ++ num_spaced_values, num_values); ++ } ++ } + } + }; + +@@ -1826,6 +1870,12 @@ Status TypedColumnWriterImpl::WriteArrowDictionary( + page_statistics_->IncrementNullCount(num_chunk_levels - non_null_count); + page_statistics_->IncrementNumValues(non_null_count); + page_statistics_->Update(*referenced_dictionary, /*update_counts=*/false); ++ ++ if (chunk_geospatial_statistics_ != nullptr) { ++ throw ParquetException( ++ "Writing dictionary-encoded GEOMETRY or GEOGRAPHY with statistics is not " ++ "supported"); ++ } + }; + + int64_t value_offset = 0; +@@ -2305,7 +2355,12 @@ Status TypedColumnWriterImpl::WriteArrowDense( + page_statistics_->IncrementNullCount(batch_size - non_null); + page_statistics_->IncrementNumValues(non_null); + } ++ + UpdateUnencodedDataBytes(); ++ ++ if (chunk_geospatial_statistics_ != nullptr) { ++ chunk_geospatial_statistics_->Update(*data_slice); ++ } + CommitWriteAndCheckPageLimit(batch_size, batch_num_values, batch_size - non_null, + check_page); + CheckDictionarySizeLimit(); +diff --git a/cpp/src/parquet/geospatial/CMakeLists.txt b/cpp/src/parquet/geospatial/CMakeLists.txt +new file mode 100644 +--- /dev/null ++++ b/cpp/src/parquet/geospatial/CMakeLists.txt +@@ -0,0 +1,18 @@ ++# Licensed to the Apache Software Foundation (ASF) under one ++# or more contributor license agreements. See the NOTICE file ++# distributed with this work for additional information ++# regarding copyright ownership. The ASF licenses this file ++# to you under the Apache License, Version 2.0 (the ++# "License"); you may not use this file except in compliance ++# with the License. You may obtain a copy of the License at ++# ++# http://www.apache.org/licenses/LICENSE-2.0 ++# ++# Unless required by applicable law or agreed to in writing, ++# software distributed under the License is distributed on an ++# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY ++# KIND, either express or implied. See the License for the ++# specific language governing permissions and limitations ++# under the License. ++ ++arrow_install_all_headers("parquet/geospatial") +diff --git a/cpp/src/parquet/geospatial/statistics.cc b/cpp/src/parquet/geospatial/statistics.cc +new file mode 100644 +--- /dev/null ++++ b/cpp/src/parquet/geospatial/statistics.cc +@@ -0,0 +1,393 @@ ++// Licensed to the Apache Software Foundation (ASF) under one ++// or more contributor license agreements. See the NOTICE file ++// distributed with this work for additional information ++// regarding copyright ownership. The ASF licenses this file ++// to you under the Apache License, Version 2.0 (the ++// "License"); you may not use this file except in compliance ++// with the License. You may obtain a copy of the License at ++// ++// http://www.apache.org/licenses/LICENSE-2.0 ++// ++// Unless required by applicable law or agreed to in writing, ++// software distributed under the License is distributed on an ++// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY ++// KIND, either express or implied. See the License for the ++// specific language governing permissions and limitations ++// under the License. ++ ++#include "parquet/geospatial/statistics.h" ++ ++#include ++#include ++#include ++ ++#include "arrow/array.h" ++#include "arrow/type.h" ++#include "arrow/util/bit_run_reader.h" ++#include "parquet/exception.h" ++#include "parquet/geospatial/util_internal.h" ++ ++using arrow::util::SafeLoad; ++ ++namespace parquet::geospatial { ++ ++class GeoStatisticsImpl { ++ public: ++ bool Equals(const GeoStatisticsImpl& other) const { ++ return is_valid_ == other.is_valid_ && ++ bounder_.GeometryTypes() == other.bounder_.GeometryTypes() && ++ bounder_.Bounds() == other.bounder_.Bounds(); ++ } ++ ++ void Merge(const GeoStatisticsImpl& other) { ++ is_valid_ = is_valid_ && other.is_valid_; ++ if (!is_valid_) { ++ return; ++ } ++ ++ // We don't yet support updating wraparound bounds. Rather than throw, ++ // we just mark the X bounds as invalid such that they are not used. ++ auto other_bounds = other.bounder_.Bounds(); ++ if (is_wraparound_x() || other.is_wraparound_x()) { ++ other_bounds.min[0] = kNaN; ++ other_bounds.max[0] = kNaN; ++ } ++ ++ bounder_.MergeBox(other_bounds); ++ std::vector other_geometry_types = other.bounder_.GeometryTypes(); ++ bounder_.MergeGeometryTypes(other_geometry_types); ++ } ++ ++ void Update(const ByteArray* values, int64_t num_values) { ++ if (!is_valid_) { ++ return; ++ } ++ ++ if (is_wraparound_x()) { ++ throw ParquetException("Wraparound X is not suppored by GeoStatistics::Update()"); ++ } ++ ++ for (int64_t i = 0; i < num_values; i++) { ++ const ByteArray& item = values[i]; ++ try { ++ bounder_.MergeGeometry({reinterpret_cast(item.ptr), item.len}); ++ } catch (ParquetException&) { ++ is_valid_ = false; ++ return; ++ } ++ } ++ } ++ ++ void UpdateSpaced(const ByteArray* values, const uint8_t* valid_bits, ++ int64_t valid_bits_offset, int64_t num_spaced_values, ++ int64_t num_values) { ++ DCHECK_GT(num_spaced_values, 0); ++ ++ if (!is_valid_) { ++ return; ++ } ++ ++ if (is_wraparound_x()) { ++ throw ParquetException("Wraparound X is not suppored by GeoStatistics::Update()"); ++ } ++ ++ ::arrow::Status status = ::arrow::internal::VisitSetBitRuns( ++ valid_bits, valid_bits_offset, num_spaced_values, ++ [&](int64_t position, int64_t length) { ++ for (int64_t i = 0; i < length; i++) { ++ ByteArray item = SafeLoad(values + i + position); ++ PARQUET_CATCH_NOT_OK(bounder_.MergeGeometry( ++ {reinterpret_cast(item.ptr), item.len})); ++ } ++ ++ return ::arrow::Status::OK(); ++ }); ++ ++ if (!status.ok()) { ++ is_valid_ = false; ++ } ++ } ++ ++ void Update(const ::arrow::Array& values) { ++ if (!is_valid_) { ++ return; ++ } ++ ++ if (is_wraparound_x()) { ++ throw ParquetException("Wraparound X is not suppored by GeoStatistics::Update()"); ++ } ++ ++ // Note that ::arrow::Type::EXTENSION seems to be handled before this is called ++ switch (values.type_id()) { ++ case ::arrow::Type::BINARY: ++ UpdateArrayImpl<::arrow::BinaryArray>(values); ++ break; ++ case ::arrow::Type::LARGE_BINARY: ++ UpdateArrayImpl<::arrow::LargeBinaryArray>(values); ++ break; ++ // This does not currently handle run-end encoded, dictionary encodings, or views ++ default: ++ throw ParquetException("Unsupported Array type in GeoStatistics::Update(Array): ", ++ values.type()->ToString()); ++ } ++ } ++ ++ void Reset() { ++ bounder_.Reset(); ++ is_valid_ = true; ++ has_geometry_types_ = true; ++ } ++ ++ EncodedGeoStatistics Encode() const { ++ if (!is_valid_) { ++ return {}; ++ } ++ ++ const geospatial::BoundingBox::XYZM& mins = bounder_.Bounds().min; ++ const geospatial::BoundingBox::XYZM& maxes = bounder_.Bounds().max; ++ ++ EncodedGeoStatistics out; ++ ++ if (has_geometry_types_) { ++ out.geospatial_types = bounder_.GeometryTypes(); ++ } ++ ++ bool write_x = !bound_empty(0) && bound_valid(0); ++ bool write_y = !bound_empty(1) && bound_valid(1); ++ bool write_z = write_x && write_y && !bound_empty(2) && bound_valid(2); ++ bool write_m = write_x && write_y && !bound_empty(3) && bound_valid(3); ++ ++ if (write_x && write_y) { ++ out.xmin = mins[0]; ++ out.xmax = maxes[0]; ++ out.ymin = mins[1]; ++ out.ymax = maxes[1]; ++ out.xy_bounds_present = true; ++ } ++ ++ if (write_z) { ++ out.zmin = mins[2]; ++ out.zmax = maxes[2]; ++ out.z_bounds_present = true; ++ } ++ ++ if (write_m) { ++ out.mmin = mins[3]; ++ out.mmax = maxes[3]; ++ out.m_bounds_present = true; ++ } ++ ++ return out; ++ } ++ ++ void Decode(const EncodedGeoStatistics& encoded) { ++ Reset(); ++ ++ geospatial::BoundingBox box; ++ if (encoded.xy_bounds_present) { ++ box.min[0] = encoded.xmin; ++ box.max[0] = encoded.xmax; ++ box.min[1] = encoded.ymin; ++ box.max[1] = encoded.ymax; ++ } else { ++ box.min[0] = kNaN; ++ box.max[0] = kNaN; ++ box.min[1] = kNaN; ++ box.max[1] = kNaN; ++ } ++ ++ if (encoded.z_bounds_present) { ++ box.min[2] = encoded.zmin; ++ box.max[2] = encoded.zmax; ++ } else { ++ box.min[2] = kNaN; ++ box.max[2] = kNaN; ++ } ++ ++ if (encoded.m_bounds_present) { ++ box.min[3] = encoded.mmin; ++ box.max[3] = encoded.mmax; ++ } else { ++ box.min[3] = kNaN; ++ box.max[3] = kNaN; ++ } ++ ++ bounder_.MergeBox(box); ++ bounder_.MergeGeometryTypes(encoded.geospatial_types); ++ has_geometry_types_ = has_geometry_types_ && encoded.geospatial_types_present(); ++ } ++ ++ bool is_wraparound_x() const { ++ return is_wraparound(lower_bound()[0], upper_bound()[0]); ++ } ++ ++ bool is_valid() const { return is_valid_; } ++ ++ bool bounds_empty() const { ++ for (int i = 0; i < kMaxDimensions; i++) { ++ if (!bound_empty(i)) { ++ return false; ++ } ++ } ++ ++ return true; ++ } ++ ++ bool bound_empty(int i) const { ++ return std::isinf(bounder_.Bounds().min[i] - bounder_.Bounds().max[i]); ++ } ++ ++ bool bound_valid(int i) const { ++ return !std::isnan(bounder_.Bounds().min[i]) && !std::isnan(bounder_.Bounds().max[i]); ++ } ++ ++ const std::array& lower_bound() const { ++ return bounder_.Bounds().min; ++ } ++ ++ const std::array& upper_bound() const { ++ return bounder_.Bounds().max; ++ } ++ ++ std::optional> geometry_types() const { ++ if (has_geometry_types_) { ++ return bounder_.GeometryTypes(); ++ } else { ++ return std::nullopt; ++ } ++ } ++ ++ private: ++ geospatial::WKBGeometryBounder bounder_; ++ bool is_valid_ = true; ++ bool has_geometry_types_ = true; ++ ++ template ++ void UpdateArrayImpl(const ::arrow::Array& values) { ++ const auto& binary_array = static_cast(values); ++ for (int64_t i = 0; i < binary_array.length(); ++i) { ++ if (!binary_array.IsNull(i)) { ++ try { ++ bounder_.MergeGeometry(binary_array.GetView(i)); ++ } catch (ParquetException&) { ++ is_valid_ = false; ++ return; ++ } ++ } ++ } ++ } ++ ++ // The Parquet specification allows X bounds to be "wraparound" to allow for ++ // more compact bounding boxes when a geometry happens to include components ++ // on both sides of the antimeridian (e.g., the nation of Fiji). This function ++ // checks for that case (see GeoStatistics::lower_bound/upper_bound for more ++ // details). ++ static bool is_wraparound(double xmin, double xmax) { ++ return !std::isinf(xmin - xmax) && xmin > xmax; ++ } ++}; ++ ++GeoStatistics::GeoStatistics() : impl_(std::make_unique()) {} ++ ++GeoStatistics::GeoStatistics(const EncodedGeoStatistics& encoded) : GeoStatistics() { ++ Decode(encoded); ++} ++ ++GeoStatistics::~GeoStatistics() = default; ++ ++bool GeoStatistics::Equals(const GeoStatistics& other) const { ++ return impl_->Equals(*other.impl_); ++} ++ ++void GeoStatistics::Merge(const GeoStatistics& other) { impl_->Merge(*other.impl_); } ++ ++void GeoStatistics::Update(const ByteArray* values, int64_t num_values) { ++ impl_->Update(values, num_values); ++} ++ ++void GeoStatistics::UpdateSpaced(const ByteArray* values, const uint8_t* valid_bits, ++ int64_t valid_bits_offset, int64_t num_spaced_values, ++ int64_t num_values) { ++ impl_->UpdateSpaced(values, valid_bits, valid_bits_offset, num_spaced_values, ++ num_values); ++} ++ ++void GeoStatistics::Update(const ::arrow::Array& values) { impl_->Update(values); } ++ ++void GeoStatistics::Reset() { impl_->Reset(); } ++ ++bool GeoStatistics::is_valid() const { return impl_->is_valid(); } ++ ++std::optional GeoStatistics::Encode() const { ++ if (is_valid()) { ++ return impl_->Encode(); ++ } else { ++ return std::nullopt; ++ } ++} ++ ++void GeoStatistics::Decode(const EncodedGeoStatistics& encoded) { ++ impl_->Decode(encoded); ++} ++ ++std::array GeoStatistics::lower_bound() const { return impl_->lower_bound(); } ++ ++std::array GeoStatistics::upper_bound() const { return impl_->upper_bound(); } ++ ++std::array GeoStatistics::dimension_empty() const { ++ return {impl_->bound_empty(0), impl_->bound_empty(1), impl_->bound_empty(2), ++ impl_->bound_empty(3)}; ++} ++ ++std::array GeoStatistics::dimension_valid() const { ++ return {impl_->bound_valid(0), impl_->bound_valid(1), impl_->bound_valid(2), ++ impl_->bound_valid(3)}; ++} ++ ++std::optional> GeoStatistics::geometry_types() const { ++ return impl_->geometry_types(); ++} ++ ++std::string GeoStatistics::ToString() const { ++ if (!is_valid()) { ++ return " invalid"; ++ } ++ ++ std::stringstream ss; ++ ss << ""; ++ ++ std::string dim_label("xyzm"); ++ auto dim_valid = dimension_valid(); ++ auto dim_empty = dimension_empty(); ++ auto lower = lower_bound(); ++ auto upper = upper_bound(); ++ ++ for (int i = 0; i < kMaxDimensions; i++) { ++ ss << " " << dim_label[i] << ": "; ++ if (!dim_valid[i]) { ++ ss << "invalid"; ++ } else if (dim_empty[i]) { ++ ss << "empty"; ++ } else { ++ ss << "[" << lower[i] << ", " << upper[i] << "]"; ++ } ++ } ++ ++ std::optional> maybe_geometry_types = geometry_types(); ++ ss << " geometry_types: "; ++ if (maybe_geometry_types.has_value()) { ++ ss << "["; ++ std::string sep(""); ++ for (int32_t geometry_type : *maybe_geometry_types) { ++ ss << sep << geometry_type; ++ sep = ", "; ++ } ++ ss << "]"; ++ } else { ++ ss << "invalid"; ++ } ++ ++ return ss.str(); ++} ++ ++} // namespace parquet::geospatial +diff --git a/cpp/src/parquet/geospatial/statistics.h b/cpp/src/parquet/geospatial/statistics.h +new file mode 100644 +--- /dev/null ++++ b/cpp/src/parquet/geospatial/statistics.h +@@ -0,0 +1,194 @@ ++// Licensed to the Apache Software Foundation (ASF) under one ++// or more contributor license agreements. See the NOTICE file ++// distributed with this work for additional information ++// regarding copyright ownership. The ASF licenses this file ++// to you under the Apache License, Version 2.0 (the ++// "License"); you may not use this file except in compliance ++// with the License. You may obtain a copy of the License at ++// ++// http://www.apache.org/licenses/LICENSE-2.0 ++// ++// Unless required by applicable law or agreed to in writing, ++// software distributed under the License is distributed on an ++// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY ++// KIND, either express or implied. See the License for the ++// specific language governing permissions and limitations ++// under the License. ++ ++#pragma once ++ ++#include ++#include ++#include ++ ++#include "parquet/platform.h" ++#include "parquet/types.h" ++ ++namespace parquet::geospatial { ++ ++/// \brief The maximum number of dimensions represented by a geospatial type ++/// (i.e., X, Y, Z, and M) ++inline constexpr int kMaxDimensions = 4; ++ ++/// \brief NaN, used to represent bounds for which predicate pushdown cannnot ++/// be applied (e.g., because a writer did not provide bounds for a given dimension) ++inline constexpr double kNaN = std::numeric_limits::quiet_NaN(); ++ ++/// \brief Structure represented encoded statistics to be written to and read from Parquet ++/// serialized metadata. ++/// ++/// See the Parquet Thrift definition and GeoStatistics for the specific definition ++/// of field values. ++struct PARQUET_EXPORT EncodedGeoStatistics { ++ bool xy_bounds_present{false}; ++ double xmin{kNaN}; ++ double xmax{kNaN}; ++ double ymin{kNaN}; ++ double ymax{kNaN}; ++ ++ bool z_bounds_present{false}; ++ double zmin{kNaN}; ++ double zmax{kNaN}; ++ ++ bool m_bounds_present{false}; ++ double mmin{kNaN}; ++ double mmax{kNaN}; ++ ++ bool geospatial_types_present() const { return !geospatial_types.empty(); } ++ std::vector geospatial_types; ++}; ++ ++class GeoStatisticsImpl; ++ ++/// \brief Base type for computing geospatial column statistics while writing a file ++/// or representing them when reading a file ++/// ++/// Note that NaN values that were encountered within coordinates are omitted; however, ++/// NaN values that were obtained via decoding encoded statistics are propagated. This ++/// behaviour ensures C++ clients that are inspecting statistics via the column metadata ++/// can detect the case where a writer generated NaNs (even though this implementation ++/// does not generate them). ++/// ++/// The handling of NaN values in coordinates is not well-defined among bounding ++/// implementations except for the WKB convention for POINT EMPTY, which is consistently ++/// represented as a point whose ordinates are all NaN. Any other geometry that contains ++/// NaNs cannot expect defined behaviour here or elsewhere; however, a row group that ++/// contains both NaN-containing and normal (completely finite) geometries should not be ++/// excluded from predicate pushdown. ++/// ++/// EXPERIMENTAL ++class PARQUET_EXPORT GeoStatistics { ++ public: ++ GeoStatistics(); ++ explicit GeoStatistics(const EncodedGeoStatistics& encoded); ++ ++ ~GeoStatistics(); ++ ++ /// \brief Return true if bounds, geometry types, and validity are identical ++ bool Equals(const GeoStatistics& other) const; ++ ++ /// \brief Update these statistics based on previously calculated or decoded statistics ++ /// ++ /// Merging statistics with wraparound X values is not currently supported. Merging ++ /// two GeoStatistics where one or both has a wraparound X range will result in these ++ /// statistics having an X dimension marked as invalid. ++ void Merge(const GeoStatistics& other); ++ ++ /// \brief Update these statistics based on values ++ void Update(const ByteArray* values, int64_t num_values); ++ ++ /// \brief Update these statistics based on the non-null elements of values ++ void UpdateSpaced(const ByteArray* values, const uint8_t* valid_bits, ++ int64_t valid_bits_offset, int64_t num_spaced_values, ++ int64_t num_values); ++ ++ /// \brief Update these statistics based on the non-null elements of values ++ /// ++ /// Currently, BinaryArray and LargeBinaryArray input is supported. ++ void Update(const ::arrow::Array& values); ++ ++ /// \brief Return these statistics to an empty state ++ void Reset(); ++ ++ /// \brief Encode the statistics for serializing to Thrift ++ /// ++ /// If invalid WKB was encountered or if the statistics contain NaN ++ /// for any reason, Encode() will return nullopt to indicate that ++ /// statistics should not be written to thrift. ++ std::optional Encode() const; ++ ++ /// \brief Returns false if invalid WKB was encountered ++ bool is_valid() const; ++ ++ /// \brief Reset existing statistics and populate them from previously-encoded ones ++ void Decode(const EncodedGeoStatistics& encoded); ++ ++ /// \brief Minimum values in XYZM order ++ /// ++ /// For dimensions where dimension_valid() is false, the value will be NaN. For ++ /// dimensions where dimension_empty() is true, the value will be +Inf. ++ /// ++ /// For the first dimension (X) only, wraparound bounds apply where xmin > xmax. In this ++ /// case, these bounds represent the union of the intervals [xmax, Inf] and [-Inf, ++ /// xmin]. This implementation does not yet generate these types of bounds but they may ++ /// be encountered in statistics when reading a Parquet file. ++ std::array lower_bound() const; ++ ++ /// \brief Maximum values in XYZM order ++ /// ++ /// For dimensions where dimension_valid() is false, the value will be NaN. For ++ /// dimensions where dimension_empty() is true, the value will be -Inf. ++ /// ++ /// For the first dimension (X) only, wraparound bounds apply where xmin > xmax. In this ++ /// case, these bounds represent the union of the intervals [xmax, Inf] and [-Inf, ++ /// xmin]. This implementation does not yet generate these types of bounds but they may ++ /// be encountered in statistics when reading a Parquet file. ++ std::array upper_bound() const; ++ ++ /// \brief Dimension emptiness in XYZM order ++ /// ++ /// True for a given dimension if and only if zero non-NaN values were encountered ++ /// in that dimension and dimension_valid() is true for that dimension. ++ /// ++ /// When calculating statistics, zero or more of these values may be true because ++ /// this implementation calculates bounds for all dimensions; however, it may be ++ /// true that zero coordinates were encountered in a given dimension. For example, ++ /// dimension_empty() will return four true values if Update() was not called ++ /// or if Update() was called with only null values. If Update() was provided ++ /// one or more geometries with X and Y dimensions but not Z or M dimensions, ++ /// dimension_empty() will return true, true, false, false. ++ /// ++ /// For statistics read from a Parquet file, dimension_empty() will always contain ++ /// false values because there is no mechanism to communicate an empty interval ++ /// in the Thrift metadata. ++ std::array dimension_empty() const; ++ ++ /// \brief Dimension validity (i.e. presence) in XYZM order ++ /// ++ /// When calculating statistics, this will always be true because this implementation ++ /// calculates statistics for all dimensions. When reading a Parquet file, one or more ++ /// of these values may be false because the file may not have provided bounds for all ++ /// dimensions. ++ /// ++ /// See documentation for dimension_empty(), lower_bound(), and/or upper_bound() for the ++ /// canonical values of those outputs for the dimensions where dimension_valid() is ++ /// false. ++ std::array dimension_valid() const; ++ ++ /// \brief Return the geometry type codes ++ /// ++ /// This implementation always returns sorted output with no duplicates. When ++ /// calculating statistics, a value will always be returned (although the returned ++ /// vector may be empty if Update() was never called or was only called with null ++ /// values). When reading a Parquet file, std::nullopt may be returned because ++ /// the file may not have provided this information. ++ std::optional> geometry_types() const; ++ ++ /// \brief Return a string representation of these statistics ++ std::string ToString() const; ++ ++ private: ++ std::unique_ptr impl_; ++}; ++ ++} // namespace parquet::geospatial +diff --git a/cpp/src/parquet/geospatial/util_internal.cc b/cpp/src/parquet/geospatial/util_internal.cc +new file mode 100644 +--- /dev/null ++++ b/cpp/src/parquet/geospatial/util_internal.cc +@@ -0,0 +1,242 @@ ++// Licensed to the Apache Software Foundation (ASF) under one ++// or more contributor license agreements. See the NOTICE file ++// distributed with this work for additional information ++// regarding copyright ownership. The ASF licenses this file ++// to you under the Apache License, Version 2.0 (the ++// "License"); you may not use this file except in compliance ++// with the License. You may obtain a copy of the License at ++// ++// http://www.apache.org/licenses/LICENSE-2.0 ++// ++// Unless required by applicable law or agreed to in writing, ++// software distributed under the License is distributed on an ++// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY ++// KIND, either express or implied. See the License for the ++// specific language governing permissions and limitations ++// under the License. ++ ++#include "parquet/geospatial/util_internal.h" ++ ++#include ++ ++#include "arrow/util/endian.h" ++#include "arrow/util/macros.h" ++#include "arrow/util/ubsan.h" ++#include "parquet/exception.h" ++ ++namespace parquet::geospatial { ++ ++std::string BoundingBox::ToString() const { ++ std::stringstream ss; ++ ss << "BoundingBox" << std::endl; ++ ss << " x: [" << min[0] << ", " << max[0] << "]" << std::endl; ++ ss << " y: [" << min[1] << ", " << max[1] << "]" << std::endl; ++ ss << " z: [" << min[2] << ", " << max[2] << "]" << std::endl; ++ ss << " m: [" << min[3] << ", " << max[3] << "]" << std::endl; ++ ++ return ss.str(); ++} ++ ++/// \brief Object to keep track of the low-level consumption of a well-known binary ++/// geometry ++/// ++/// Briefly, ISO well-known binary supported by the Parquet spec is an endian byte ++/// (0x01 or 0x00), followed by geometry type + dimensions encoded as a (uint32_t), ++/// followed by geometry-specific data. Coordinate sequences are represented by a ++/// uint32_t (the number of coordinates) plus a sequence of doubles (number of coordinates ++/// multiplied by the number of dimensions). ++class WKBBuffer { ++ public: ++ WKBBuffer() : data_(nullptr), size_(0) {} ++ WKBBuffer(const uint8_t* data, int64_t size) : data_(data), size_(size) {} ++ ++ uint8_t ReadUInt8() { return ReadChecked(); } ++ ++ uint32_t ReadUInt32(bool swap) { ++ auto value = ReadChecked(); ++ if (swap) { ++ return ::arrow::bit_util::ByteSwap(value); ++ } else { ++ return value; ++ } ++ } ++ ++ template ++ void ReadCoords(uint32_t n_coords, bool swap, Visit&& visit) { ++ size_t total_bytes = n_coords * sizeof(Coord); ++ if (size_ < total_bytes) { ++ throw ParquetException("Can't read coordinate sequence of ", total_bytes, ++ " bytes from WKBBuffer with ", size_, " remaining"); ++ } ++ ++ if (swap) { ++ Coord coord; ++ for (uint32_t i = 0; i < n_coords; i++) { ++ coord = ReadUnchecked(); ++ for (auto& c : coord) { ++ c = ::arrow::bit_util::ByteSwap(c); ++ } ++ ++ visit(coord); ++ } ++ } else { ++ for (uint32_t i = 0; i < n_coords; i++) { ++ visit(ReadUnchecked()); ++ } ++ } ++ } ++ ++ size_t size() { return size_; } ++ ++ private: ++ const uint8_t* data_; ++ size_t size_; ++ ++ template ++ T ReadChecked() { ++ if (ARROW_PREDICT_FALSE(size_ < sizeof(T))) { ++ throw ParquetException("Can't read ", sizeof(T), " bytes from WKBBuffer with ", ++ size_, " remaining"); ++ } ++ ++ return ReadUnchecked(); ++ } ++ ++ template ++ T ReadUnchecked() { ++ T out = ::arrow::util::SafeLoadAs(data_); ++ data_ += sizeof(T); ++ size_ -= sizeof(T); ++ return out; ++ } ++}; ++ ++using GeometryTypeAndDimensions = std::pair; ++ ++namespace { ++ ++GeometryTypeAndDimensions ParseGeometryType(uint32_t wkb_geometry_type) { ++ // The number 1000 can be used because WKB geometry types are constructed ++ // on purpose such that this relationship is true (e.g., LINESTRING ZM maps ++ // to 3002). ++ uint32_t geometry_type_component = wkb_geometry_type % 1000; ++ uint32_t dimensions_component = wkb_geometry_type / 1000; ++ ++ auto min_geometry_type_value = static_cast(GeometryType::kValueMin); ++ auto max_geometry_type_value = static_cast(GeometryType::kValueMax); ++ auto min_dimension_value = static_cast(Dimensions::kValueMin); ++ auto max_dimension_value = static_cast(Dimensions::kValueMax); ++ ++ if (geometry_type_component < min_geometry_type_value || ++ geometry_type_component > max_geometry_type_value || ++ dimensions_component < min_dimension_value || ++ dimensions_component > max_dimension_value) { ++ throw ParquetException("Invalid WKB geometry type: ", wkb_geometry_type); ++ } ++ ++ return {static_cast(geometry_type_component), ++ static_cast(dimensions_component)}; ++} ++ ++} // namespace ++ ++std::vector WKBGeometryBounder::GeometryTypes() const { ++ std::vector out(geospatial_types_.begin(), geospatial_types_.end()); ++ std::sort(out.begin(), out.end()); ++ return out; ++} ++ ++void WKBGeometryBounder::MergeGeometry(std::string_view bytes_wkb) { ++ MergeGeometry(::arrow::util::span(reinterpret_cast(bytes_wkb.data()), ++ bytes_wkb.size())); ++} ++ ++void WKBGeometryBounder::MergeGeometry(::arrow::util::span bytes_wkb) { ++ WKBBuffer src{bytes_wkb.data(), static_cast(bytes_wkb.size())}; ++ MergeGeometryInternal(&src, /*record_wkb_type=*/true); ++ if (src.size() != 0) { ++ throw ParquetException("Exepcted zero bytes after consuming WKB but got ", ++ src.size()); ++ } ++} ++ ++void WKBGeometryBounder::MergeGeometryInternal(WKBBuffer* src, bool record_wkb_type) { ++ uint8_t endian = src->ReadUInt8(); ++#if defined(ARROW_LITTLE_ENDIAN) ++ bool swap = endian != 0x01; ++#else ++ bool swap = endian != 0x00; ++#endif ++ ++ uint32_t wkb_geometry_type = src->ReadUInt32(swap); ++ auto geometry_type_and_dimensions = ParseGeometryType(wkb_geometry_type); ++ auto [geometry_type, dimensions] = geometry_type_and_dimensions; ++ ++ // Keep track of geometry types encountered if at the top level ++ if (record_wkb_type) { ++ geospatial_types_.insert(static_cast(wkb_geometry_type)); ++ } ++ ++ switch (geometry_type) { ++ case GeometryType::kPoint: ++ MergeSequence(src, dimensions, 1, swap); ++ break; ++ ++ case GeometryType::kLinestring: { ++ uint32_t n_coords = src->ReadUInt32(swap); ++ MergeSequence(src, dimensions, n_coords, swap); ++ break; ++ } ++ case GeometryType::kPolygon: { ++ uint32_t n_parts = src->ReadUInt32(swap); ++ for (uint32_t i = 0; i < n_parts; i++) { ++ uint32_t n_coords = src->ReadUInt32(swap); ++ MergeSequence(src, dimensions, n_coords, swap); ++ } ++ break; ++ } ++ ++ // These are all encoded the same in WKB, even though this encoding would ++ // allow for parts to be of a different geometry type or different dimensions. ++ // For the purposes of bounding, this does not cause us problems. We pass ++ // record_wkb_type = false because we do not want the child geometry to be ++ // added to the geometry_types list (e.g., for a MultiPoint, we only want ++ // the code for MultiPoint to be added, not the code for Point). ++ case GeometryType::kMultiPoint: ++ case GeometryType::kMultiLinestring: ++ case GeometryType::kMultiPolygon: ++ case GeometryType::kGeometryCollection: { ++ uint32_t n_parts = src->ReadUInt32(swap); ++ for (uint32_t i = 0; i < n_parts; i++) { ++ MergeGeometryInternal(src, /*record_wkb_type*/ false); ++ } ++ break; ++ } ++ } ++} ++ ++void WKBGeometryBounder::MergeSequence(WKBBuffer* src, Dimensions dimensions, ++ uint32_t n_coords, bool swap) { ++ switch (dimensions) { ++ case Dimensions::kXY: ++ src->ReadCoords( ++ n_coords, swap, [&](BoundingBox::XY coord) { box_.UpdateXY(coord); }); ++ break; ++ case Dimensions::kXYZ: ++ src->ReadCoords( ++ n_coords, swap, [&](BoundingBox::XYZ coord) { box_.UpdateXYZ(coord); }); ++ break; ++ case Dimensions::kXYM: ++ src->ReadCoords( ++ n_coords, swap, [&](BoundingBox::XYM coord) { box_.UpdateXYM(coord); }); ++ break; ++ case Dimensions::kXYZM: ++ src->ReadCoords( ++ n_coords, swap, [&](BoundingBox::XYZM coord) { box_.UpdateXYZM(coord); }); ++ break; ++ default: ++ throw ParquetException("Unknown dimensions"); ++ } ++} ++ ++} // namespace parquet::geospatial +diff --git a/cpp/src/parquet/geospatial/util_internal.h b/cpp/src/parquet/geospatial/util_internal.h +new file mode 100644 +--- /dev/null ++++ b/cpp/src/parquet/geospatial/util_internal.h +@@ -0,0 +1,224 @@ ++// Licensed to the Apache Software Foundation (ASF) under one ++// or more contributor license agreements. See the NOTICE file ++// distributed with this work for additional information ++// regarding copyright ownership. The ASF licenses this file ++// to you under the Apache License, Version 2.0 (the ++// "License"); you may not use this file except in compliance ++// with the License. You may obtain a copy of the License at ++// ++// http://www.apache.org/licenses/LICENSE-2.0 ++// ++// Unless required by applicable law or agreed to in writing, ++// software distributed under the License is distributed on an ++// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY ++// KIND, either express or implied. See the License for the ++// specific language governing permissions and limitations ++// under the License. ++ ++#pragma once ++ ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++ ++#include "arrow/util/logging_internal.h" ++#include "parquet/platform.h" ++ ++namespace parquet::geospatial { ++ ++/// \brief Infinity, used to define bounds of empty bounding boxes ++constexpr double kInf = std::numeric_limits::infinity(); ++ ++/// \brief Valid combinations of dimensions allowed by ISO well-known binary ++/// ++/// These values correspond to the 0, 1000, 2000, 3000 component of the WKB integer ++/// geometry type (i.e., the value of geometry_type // 1000). ++enum class Dimensions { ++ kXY = 0, ++ kXYZ = 1, ++ kXYM = 2, ++ kXYZM = 3, ++ kValueMin = 0, ++ kValueMax = 3 ++}; ++ ++/// \brief The supported set of geometry types allowed by ISO well-known binary ++/// ++/// These values correspond to the 1, 2, ..., 7 component of the WKB integer ++/// geometry type (i.e., the value of geometry_type % 1000). ++enum class GeometryType { ++ kPoint = 1, ++ kLinestring = 2, ++ kPolygon = 3, ++ kMultiPoint = 4, ++ kMultiLinestring = 5, ++ kMultiPolygon = 6, ++ kGeometryCollection = 7, ++ kValueMin = 1, ++ kValueMax = 7 ++}; ++ ++/// \brief A collection of intervals representing the encountered ranges of values ++/// in each dimension. ++/// ++/// The Parquet specification also supports wraparound bounding boxes in the X ++/// dimension; however, this structure assumes min < max always as it is used for ++/// the purposes of accumulating this type of bounds. ++/// ++/// This class will ignore any NaN values it visits via UpdateXY[Z[M]](). This is ++/// consistent with GEOS and ensures that ranges are accumulated in the same way that ++/// other statistics in Parquet are accumulated (e.g., statistics of a double column will ++/// return a min/max of all non-NaN values). In WKB specifically, POINT EMPTY is ++/// represented by convention as all ordinate values filled with NaN, so this behaviour ++/// allows for no special-casing of POINT EMPTY in the WKB reader. ++/// ++/// This class will propagate any NaN values (per dimension) that were explicitly ++/// specified via setting mins/maxes directly or by merging another BoundingBox that ++/// contained NaN values. This definition ensures that NaN bounds obtained via ++/// EncodedGeoStatistics (which may have been written by some other writer that generated ++/// NaNs, either on purpose or by accident) are not silently overwritten. ++struct PARQUET_EXPORT BoundingBox { ++ using XY = std::array; ++ using XYZ = std::array; ++ using XYM = std::array; ++ using XYZM = std::array; ++ ++ BoundingBox(const XYZM& mins, const XYZM& maxes) : min(mins), max(maxes) {} ++ BoundingBox() : min{kInf, kInf, kInf, kInf}, max{-kInf, -kInf, -kInf, -kInf} {} ++ ++ BoundingBox(const BoundingBox& other) = default; ++ BoundingBox& operator=(const BoundingBox&) = default; ++ ++ /// \brief Update the X and Y bounds to ensure these bounds contain coord ++ void UpdateXY(::arrow::util::span coord) { ++ DCHECK_EQ(coord.size(), 2); ++ UpdateInternal(coord); ++ } ++ ++ /// \brief Update the X, Y, and Z bounds to ensure these bounds contain coord ++ void UpdateXYZ(::arrow::util::span coord) { ++ DCHECK_EQ(coord.size(), 3); ++ UpdateInternal(coord); ++ } ++ ++ /// \brief Update the X, Y, and M bounds to ensure these bounds contain coord ++ void UpdateXYM(::arrow::util::span coord) { ++ DCHECK_EQ(coord.size(), 3); ++ min[0] = std::min(min[0], coord[0]); ++ min[1] = std::min(min[1], coord[1]); ++ min[3] = std::min(min[3], coord[2]); ++ max[0] = std::max(max[0], coord[0]); ++ max[1] = std::max(max[1], coord[1]); ++ max[3] = std::max(max[3], coord[2]); ++ } ++ ++ /// \brief Update the X, Y, Z, and M bounds to ensure these bounds contain coord ++ void UpdateXYZM(::arrow::util::span coord) { ++ DCHECK_EQ(coord.size(), 4); ++ UpdateInternal(coord); ++ } ++ ++ /// \brief Reset these bounds to an empty state such that they contain no coordinates ++ void Reset() { ++ for (int i = 0; i < 4; i++) { ++ min[i] = kInf; ++ max[i] = -kInf; ++ } ++ } ++ ++ /// \brief Update these bounds such they also contain other ++ void Merge(const BoundingBox& other) { ++ for (int i = 0; i < 4; i++) { ++ if (std::isnan(min[i]) || std::isnan(max[i]) || std::isnan(other.min[i]) || ++ std::isnan(other.max[i])) { ++ min[i] = std::numeric_limits::quiet_NaN(); ++ max[i] = std::numeric_limits::quiet_NaN(); ++ } else { ++ min[i] = std::min(min[i], other.min[i]); ++ max[i] = std::max(max[i], other.max[i]); ++ } ++ } ++ } ++ ++ std::string ToString() const; ++ ++ XYZM min; ++ XYZM max; ++ ++ private: ++ // This works for XY, XYZ, and XYZM ++ template ++ void UpdateInternal(Coord coord) { ++ for (size_t i = 0; i < coord.size(); i++) { ++ min[i] = std::min(min[i], coord[i]); ++ max[i] = std::max(max[i], coord[i]); ++ } ++ } ++}; ++ ++inline bool operator==(const BoundingBox& lhs, const BoundingBox& rhs) { ++ return lhs.min == rhs.min && lhs.max == rhs.max; ++} ++ ++inline bool operator!=(const BoundingBox& lhs, const BoundingBox& rhs) { ++ return !(lhs == rhs); ++} ++ ++inline std::ostream& operator<<(std::ostream& os, const BoundingBox& obj) { ++ os << obj.ToString(); ++ return os; ++} ++ ++class WKBBuffer; ++ ++/// \brief Accumulate a BoundingBox and geometry types based on zero or more well-known ++/// binary blobs ++/// ++/// Note that this class is NOT appropriate for bounding a GEOGRAPHY, ++/// whose bounds are not a function purely of the vertices. Geography bounding ++/// is not yet implemented. ++class PARQUET_EXPORT WKBGeometryBounder { ++ public: ++ /// \brief Accumulate the bounds of a serialized well-known binary geometry ++ /// ++ /// Throws ParquetException for any parse errors encountered. Bounds for ++ /// any encountered coordinates are accumulated and the geometry type of ++ /// the geometry is added to the internal geometry type list. ++ void MergeGeometry(std::string_view bytes_wkb); ++ ++ void MergeGeometry(::arrow::util::span bytes_wkb); ++ ++ /// \brief Accumulate the bounds of a previously-calculated BoundingBox ++ void MergeBox(const BoundingBox& box) { box_.Merge(box); } ++ ++ /// \brief Accumulate a previously-calculated list of geometry types ++ void MergeGeometryTypes(::arrow::util::span geospatial_types) { ++ geospatial_types_.insert(geospatial_types.begin(), geospatial_types.end()); ++ } ++ ++ /// \brief Retrieve the accumulated bounds ++ const BoundingBox& Bounds() const { return box_; } ++ ++ /// \brief Retrieve the accumulated geometry types ++ std::vector GeometryTypes() const; ++ ++ /// \brief Reset the internal bounds and geometry types list to an empty state ++ void Reset() { ++ box_.Reset(); ++ geospatial_types_.clear(); ++ } ++ ++ private: ++ BoundingBox box_; ++ std::unordered_set geospatial_types_; ++ ++ void MergeGeometryInternal(WKBBuffer* src, bool record_wkb_type); ++ ++ void MergeSequence(WKBBuffer* src, Dimensions dimensions, uint32_t n_coords, bool swap); ++}; ++ ++} // namespace parquet::geospatial +diff --git a/cpp/src/parquet/geospatial/util_json_internal.cc b/cpp/src/parquet/geospatial/util_json_internal.cc +new file mode 100644 +--- /dev/null ++++ b/cpp/src/parquet/geospatial/util_json_internal.cc +@@ -0,0 +1,205 @@ ++// Licensed to the Apache Software Foundation (ASF) under one ++// or more contributor license agreements. See the NOTICE file ++// distributed with this work for additional information ++// regarding copyright ownership. The ASF licenses this file ++// to you under the Apache License, Version 2.0 (the ++// "License"); you may not use this file except in compliance ++// with the License. You may obtain a copy of the License at ++// ++// http://www.apache.org/licenses/LICENSE-2.0 ++// ++// Unless required by applicable law or agreed to in writing, ++// software distributed under the License is distributed on an ++// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY ++// KIND, either express or implied. See the License for the ++// specific language governing permissions and limitations ++// under the License. ++ ++#include "parquet/geospatial/util_json_internal.h" ++ ++#include ++ ++#include "arrow/extension_type.h" ++#include "arrow/json/rapidjson_defs.h" // IWYU pragma: keep ++#include "arrow/result.h" ++#include "arrow/util/string.h" ++ ++#include ++#include ++ ++#include "parquet/exception.h" ++#include "parquet/types.h" ++ ++namespace parquet { ++ ++namespace { ++::arrow::Result GeospatialGeoArrowCrsToParquetCrs( ++ const ::arrow::rapidjson::Document& document) { ++ namespace rj = ::arrow::rapidjson; ++ ++ if (!document.HasMember("crs") || document["crs"].IsNull()) { ++ // Parquet GEOMETRY/GEOGRAPHY do not have a concept of a null/missing ++ // CRS, but an omitted one is more likely to have meant "lon/lat" than ++ // a truly unspecified one (i.e., Engineering CRS with arbitrary XY units) ++ return ""; ++ } ++ ++ const auto& json_crs = document["crs"]; ++ if (json_crs.IsString() && (json_crs == "EPSG:4326" || json_crs == "OGC:CRS84")) { ++ // crs can be left empty because these cases both correspond to ++ // longitude/latitude in WGS84 according to the Parquet specification ++ return ""; ++ } else if (json_crs.IsObject()) { ++ // Attempt to detect common PROJJSON representations of longitude/latitude and return ++ // an empty crs to maximize compatibility with readers that do not implement CRS ++ // support. PROJJSON stores this in the "id" member like: ++ // {..., "id": {"authority": "...", "code": "..."}} ++ if (json_crs.HasMember("id")) { ++ const auto& identifier = json_crs["id"]; ++ if (identifier.HasMember("authority") && identifier.HasMember("code")) { ++ if (identifier["authority"] == "OGC" && identifier["code"] == "CRS84") { ++ return ""; ++ } else if (identifier["authority"] == "EPSG" && identifier["code"] == "4326") { ++ return ""; ++ } else if (identifier["authority"] == "EPSG" && identifier["code"] == 4326) { ++ return ""; ++ } ++ } ++ } ++ } ++ ++ // If we could not detect a longitude/latitude CRS, just write the string to the ++ // LogicalType crs (being sure to unescape a JSON string into a regular string) ++ if (json_crs.IsString()) { ++ return json_crs.GetString(); ++ } else { ++ rj::StringBuffer buffer; ++ rj::Writer writer(buffer); ++ json_crs.Accept(writer); ++ return buffer.GetString(); ++ } ++} ++ ++// Utility for ensuring that a Parquet CRS is valid JSON when written to ++// GeoArrow metadata (without escaping it if it is already valid JSON such as ++// a PROJJSON string) ++std::string EscapeCrsAsJsonIfRequired(std::string_view crs); ++ ++::arrow::Result MakeGeoArrowCrsMetadata( ++ std::string_view crs, ++ const std::shared_ptr& metadata) { ++ const std::string kSridPrefix{"srid:"}; ++ const std::string kProjjsonPrefix{"projjson:"}; ++ ++ // Two recommendations are explicitly mentioned in the Parquet format for the ++ // LogicalType crs: ++ // ++ // - "srid:XXXX" as a way to encode an application-specific integer identifier ++ // - "projjson:some_field_name" as a way to avoid repeating PROJJSON strings ++ // unnecessarily (with a suggestion to place them in the file metadata) ++ // ++ // While we don't currently generate those values to reduce the complexity ++ // of the writer, we do interpret these values according to the suggestion in ++ // the format and pass on this information to GeoArrow. ++ if (crs.empty()) { ++ return R"("crs": "OGC:CRS84", "crs_type": "authority_code")"; ++ } else if (::arrow::internal::StartsWith(crs, kSridPrefix)) { ++ return R"("crs": ")" + std::string(crs.substr(kSridPrefix.size())) + ++ R"(", "crs_type": "srid")"; ++ } else if (::arrow::internal::StartsWith(crs, kProjjsonPrefix)) { ++ std::string_view metadata_field = crs.substr(kProjjsonPrefix.size()); ++ if (metadata && metadata->Contains(metadata_field)) { ++ ARROW_ASSIGN_OR_RAISE(std::string projjson_value, metadata->Get(metadata_field)); ++ // This value should be valid JSON, but if it is not, we escape it as a string such ++ // that it can be inspected by the consumer of GeoArrow. ++ return R"("crs": )" + EscapeCrsAsJsonIfRequired(projjson_value) + ++ R"(, "crs_type": "projjson")"; ++ } ++ } ++ ++ // Pass on the string directly to GeoArrow. If the string is already valid JSON, ++ // insert it directly into GeoArrow's "crs" field. Otherwise, escape it and pass it as a ++ // string value. ++ return R"("crs": )" + EscapeCrsAsJsonIfRequired(crs); ++} ++ ++std::string EscapeCrsAsJsonIfRequired(std::string_view crs) { ++ namespace rj = ::arrow::rapidjson; ++ rj::Document document; ++ if (document.Parse(crs.data(), crs.length()).HasParseError()) { ++ rj::StringBuffer buffer; ++ rj::Writer writer(buffer); ++ rj::Value v; ++ v.SetString(crs.data(), static_cast(crs.size())); ++ v.Accept(writer); ++ return std::string(buffer.GetString()); ++ } else { ++ return std::string(crs); ++ } ++} ++ ++} // namespace ++ ++::arrow::Result> LogicalTypeFromGeoArrowMetadata( ++ std::string_view serialized_data) { ++ // Parquet has no way to interpret a null or missing CRS, so we choose the most likely ++ // intent here (that the user meant to use the default Parquet CRS) ++ if (serialized_data.empty() || serialized_data == "{}") { ++ return LogicalType::Geometry(); ++ } ++ ++ namespace rj = ::arrow::rapidjson; ++ rj::Document document; ++ if (document.Parse(serialized_data.data(), serialized_data.length()).HasParseError()) { ++ return ::arrow::Status::Invalid("Invalid serialized JSON data: ", serialized_data); ++ } ++ ++ ARROW_ASSIGN_OR_RAISE(std::string crs, GeospatialGeoArrowCrsToParquetCrs(document)); ++ ++ if (document.HasMember("edges") && document["edges"] == "planar") { ++ return LogicalType::Geometry(crs); ++ } else if (document.HasMember("edges") && document["edges"] == "spherical") { ++ return LogicalType::Geography(crs, ++ LogicalType::EdgeInterpolationAlgorithm::SPHERICAL); ++ } else if (document.HasMember("edges")) { ++ return ::arrow::Status::Invalid("Unsupported GeoArrow edge type: ", serialized_data); ++ } ++ ++ return LogicalType::Geometry(crs); ++} ++ ++::arrow::Result> GeoArrowTypeFromLogicalType( ++ const LogicalType& logical_type, ++ const std::shared_ptr& metadata) { ++ // Check if we have a registered GeoArrow type to read into ++ std::shared_ptr<::arrow::ExtensionType> maybe_geoarrow_wkb = ++ ::arrow::GetExtensionType("geoarrow.wkb"); ++ if (!maybe_geoarrow_wkb) { ++ return ::arrow::binary(); ++ } ++ ++ if (logical_type.is_geometry()) { ++ const auto& geospatial_type = ++ ::arrow::internal::checked_cast(logical_type); ++ ARROW_ASSIGN_OR_RAISE(std::string crs_metadata, ++ MakeGeoArrowCrsMetadata(geospatial_type.crs(), metadata)); ++ ++ std::string serialized_data = std::string("{") + crs_metadata + "}"; ++ return maybe_geoarrow_wkb->Deserialize(::arrow::binary(), serialized_data); ++ } else if (logical_type.is_geography()) { ++ const auto& geospatial_type = ++ ::arrow::internal::checked_cast(logical_type); ++ ARROW_ASSIGN_OR_RAISE(std::string crs_metadata, ++ MakeGeoArrowCrsMetadata(geospatial_type.crs(), metadata)); ++ std::string edges_metadata = ++ R"("edges": ")" + std::string(geospatial_type.algorithm_name()) + R"(")"; ++ std::string serialized_data = ++ std::string("{") + crs_metadata + ", " + edges_metadata + "}"; ++ return maybe_geoarrow_wkb->Deserialize(::arrow::binary(), serialized_data); ++ } else { ++ throw ParquetException("Can't export logical type ", logical_type.ToString(), ++ " as GeoArrow"); ++ } ++} ++ ++} // namespace parquet +diff --git a/cpp/src/parquet/geospatial/util_json_internal.h b/cpp/src/parquet/geospatial/util_json_internal.h +new file mode 100644 +--- /dev/null ++++ b/cpp/src/parquet/geospatial/util_json_internal.h +@@ -0,0 +1,45 @@ ++// Licensed to the Apache Software Foundation (ASF) under one ++// or more contributor license agreements. See the NOTICE file ++// distributed with this work for additional information ++// regarding copyright ownership. The ASF licenses this file ++// to you under the Apache License, Version 2.0 (the ++// "License"); you may not use this file except in compliance ++// with the License. You may obtain a copy of the License at ++// ++// http://www.apache.org/licenses/LICENSE-2.0 ++// ++// Unless required by applicable law or agreed to in writing, ++// software distributed under the License is distributed on an ++// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY ++// KIND, either express or implied. See the License for the ++// specific language governing permissions and limitations ++// under the License. ++ ++#pragma once ++ ++#include ++ ++#include "arrow/util/key_value_metadata.h" ++ ++#include "parquet/types.h" ++ ++namespace parquet { ++ ++/// \brief Compute a Parquet Logical type (Geometry(...) or Geography(...)) from ++/// GeoArrow `ARROW:extension:metadata` (JSON-encoded extension type metadata) ++/// ++/// Returns the appropriate LogicalType or Invalid if the metadata was invalid. ++::arrow::Result> LogicalTypeFromGeoArrowMetadata( ++ std::string_view serialized_data); ++ ++/// \brief Compute a suitable DataType into which a GEOMETRY or GEOGRAPHY type should be ++/// read ++/// ++/// The result of this function depends on whether or not "geoarrow.wkb" has been ++/// registered: if it has, the result will be the registered ExtensionType; if it has not, ++/// the result will be binary(). ++::arrow::Result> GeoArrowTypeFromLogicalType( ++ const LogicalType& logical_type, ++ const std::shared_ptr& metadata); ++ ++} // namespace parquet +diff --git a/cpp/src/parquet/metadata.cc b/cpp/src/parquet/metadata.cc +--- a/cpp/src/parquet/metadata.cc ++++ b/cpp/src/parquet/metadata.cc +@@ -38,6 +38,7 @@ + #include "parquet/schema.h" + #include "parquet/schema_internal.h" + #include "parquet/size_statistics.h" ++#include "parquet/statistics.h" + #include "parquet/thrift_internal.h" + + namespace parquet { +@@ -108,6 +109,17 @@ static std::shared_ptr MakeTypedColumnStats( + metadata.statistics.__isset.null_count, metadata.statistics.__isset.distinct_count); + } + ++static std::shared_ptr MakeColumnGeometryStats( ++ const format::ColumnMetaData& metadata, const ColumnDescriptor* descr) { ++ if (metadata.__isset.geospatial_statistics) { ++ geospatial::EncodedGeoStatistics encoded_geo_stats = ++ FromThrift(metadata.geospatial_statistics); ++ return std::make_shared(std::move(encoded_geo_stats)); ++ } else { ++ return nullptr; ++ } ++} ++ + std::shared_ptr MakeColumnStats(const format::ColumnMetaData& meta_data, + const ColumnDescriptor* descr) { + switch (static_cast(meta_data.type)) { +@@ -268,6 +280,7 @@ class ColumnChunkMetaData::ColumnChunkMetaDataImpl { + size_statistics_->Validate(descr_); + } + possible_stats_ = nullptr; ++ possible_geo_stats_ = nullptr; + InitKeyValueMetadata(); + } + +@@ -298,14 +311,29 @@ class ColumnChunkMetaData::ColumnChunkMetaDataImpl { + descr_->sort_order() == SortOrder::UNKNOWN) { + return false; + } +- if (possible_stats_ == nullptr) { +- possible_stats_ = MakeColumnStats(*column_metadata_, descr_); ++ { ++ // Because we are modifying possible_stats_ in a const method ++ const std::lock_guard guard(stats_mutex_); ++ if (possible_stats_ == nullptr) { ++ possible_stats_ = MakeColumnStats(*column_metadata_, descr_); ++ } + } + EncodedStatistics encodedStatistics = possible_stats_->Encode(); + return writer_version_->HasCorrectStatistics(type(), encodedStatistics, + descr_->sort_order()); + } + ++ inline bool is_geo_stats_set() const { ++ // Because we are modifying possible_geo_stats_ in a const method ++ const std::lock_guard guard(stats_mutex_); ++ if (possible_geo_stats_ == nullptr && ++ column_metadata_->__isset.geospatial_statistics) { ++ possible_geo_stats_ = MakeColumnGeometryStats(*column_metadata_, descr_); ++ } ++ ++ return possible_geo_stats_ != nullptr && possible_geo_stats_->is_valid(); ++ } ++ + inline std::shared_ptr statistics() const { + return is_stats_set() ? possible_stats_ : nullptr; + } +@@ -314,6 +342,10 @@ class ColumnChunkMetaData::ColumnChunkMetaDataImpl { + return size_statistics_; + } + ++ inline std::shared_ptr geospatial_statistics() const { ++ return is_geo_stats_set() ? possible_geo_stats_ : nullptr; ++ } ++ + inline Compression::type compression() const { + return LoadEnumSafe(&column_metadata_->codec); + } +@@ -392,7 +424,9 @@ class ColumnChunkMetaData::ColumnChunkMetaDataImpl { + key_value_metadata_ = FromThriftKeyValueMetadata(*column_metadata_); + } + ++ mutable std::mutex stats_mutex_; + mutable std::shared_ptr possible_stats_; ++ mutable std::shared_ptr possible_geo_stats_; + std::vector encodings_; + std::vector encoding_stats_; + const format::ColumnChunk* column_; +@@ -444,12 +478,18 @@ std::shared_ptr ColumnChunkMetaData::statistics() const { + return impl_->statistics(); + } + ++std::shared_ptr ColumnChunkMetaData::geo_statistics() const { ++ return impl_->geospatial_statistics(); ++} ++ + bool ColumnChunkMetaData::is_stats_set() const { return impl_->is_stats_set(); } + + std::shared_ptr ColumnChunkMetaData::size_statistics() const { + return impl_->size_statistics(); + } + ++bool ColumnChunkMetaData::is_geo_stats_set() const { return impl_->is_geo_stats_set(); } ++ + std::optional ColumnChunkMetaData::bloom_filter_offset() const { + return impl_->bloom_filter_offset(); + } +@@ -1558,6 +1598,10 @@ class ColumnChunkMetaDataBuilder::ColumnChunkMetaDataBuilderImpl { + column_chunk_->meta_data.__set_size_statistics(ToThrift(size_stats)); + } + ++ void SetGeoStatistics(const geospatial::EncodedGeoStatistics& val) { ++ column_chunk_->meta_data.__set_geospatial_statistics(ToThrift(val)); ++ } ++ + void Finish(int64_t num_values, int64_t dictionary_page_offset, + int64_t index_page_offset, int64_t data_page_offset, + int64_t compressed_size, int64_t uncompressed_size, bool has_dictionary, +@@ -1771,6 +1815,11 @@ void ColumnChunkMetaDataBuilder::SetSizeStatistics(const SizeStatistics& size_st + impl_->SetSizeStatistics(size_stats); + } + ++void ColumnChunkMetaDataBuilder::SetGeoStatistics( ++ const geospatial::EncodedGeoStatistics& result) { ++ impl_->SetGeoStatistics(result); ++} ++ + void ColumnChunkMetaDataBuilder::SetKeyValueMetadata( + std::shared_ptr key_value_metadata) { + impl_->SetKeyValueMetadata(std::move(key_value_metadata)); +diff --git a/cpp/src/parquet/metadata.h b/cpp/src/parquet/metadata.h +--- a/cpp/src/parquet/metadata.h ++++ b/cpp/src/parquet/metadata.h +@@ -22,12 +22,12 @@ + #include + #include + #include +-#include + #include + + #include "parquet/encryption/type_fwd.h" + #include "parquet/platform.h" + #include "parquet/properties.h" ++#include "parquet/type_fwd.h" + + namespace parquet { + +@@ -141,8 +141,10 @@ class PARQUET_EXPORT ColumnChunkMetaData { + int64_t num_values() const; + std::shared_ptr path_in_schema() const; + bool is_stats_set() const; ++ bool is_geo_stats_set() const; + std::shared_ptr statistics() const; + std::shared_ptr size_statistics() const; ++ std::shared_ptr geo_statistics() const; + + Compression::type compression() const; + // Indicate if the ColumnChunk compression is supported by the current +@@ -440,6 +442,9 @@ class PARQUET_EXPORT ColumnChunkMetaDataBuilder { + void SetStatistics(const EncodedStatistics& stats); + void SetSizeStatistics(const SizeStatistics& size_stats); + ++ // column geometry statistics ++ void SetGeoStatistics(const geospatial::EncodedGeoStatistics& geo_stats); ++ + void SetKeyValueMetadata(std::shared_ptr key_value_metadata); + + // get the column descriptor +diff --git a/cpp/src/parquet/thrift_internal.h b/cpp/src/parquet/thrift_internal.h +--- a/cpp/src/parquet/thrift_internal.h ++++ b/cpp/src/parquet/thrift_internal.h +@@ -41,6 +41,7 @@ + #include "parquet/encryption/internal_file_decryptor.h" + #include "parquet/encryption/internal_file_encryptor.h" + #include "parquet/exception.h" ++#include "parquet/geospatial/statistics.h" + #include "parquet/platform.h" + #include "parquet/properties.h" + #include "parquet/size_statistics.h" +@@ -232,6 +233,73 @@ static inline AadMetadata FromThrift(format::AesGcmCtrV1 aesGcmCtrV1) { + aesGcmCtrV1.supply_aad_prefix}; + } + ++static inline geospatial::EncodedGeoStatistics FromThrift( ++ const format::GeospatialStatistics& geo_stats) { ++ geospatial::EncodedGeoStatistics out; ++ ++ out.geospatial_types = geo_stats.geospatial_types; ++ ++ if (geo_stats.__isset.bbox) { ++ out.xmin = geo_stats.bbox.xmin; ++ out.xmax = geo_stats.bbox.xmax; ++ out.ymin = geo_stats.bbox.ymin; ++ out.ymax = geo_stats.bbox.ymax; ++ out.xy_bounds_present = true; ++ ++ if (geo_stats.bbox.__isset.zmin && geo_stats.bbox.__isset.zmax) { ++ out.zmin = geo_stats.bbox.zmin; ++ out.zmax = geo_stats.bbox.zmax; ++ out.z_bounds_present = true; ++ } ++ ++ if (geo_stats.bbox.__isset.mmin && geo_stats.bbox.__isset.mmax) { ++ out.mmin = geo_stats.bbox.mmin; ++ out.mmax = geo_stats.bbox.mmax; ++ out.m_bounds_present = true; ++ } ++ } ++ ++ return out; ++} ++ ++static inline format::EdgeInterpolationAlgorithm::type ToThrift( ++ LogicalType::EdgeInterpolationAlgorithm algorithm) { ++ switch (algorithm) { ++ case LogicalType::EdgeInterpolationAlgorithm::SPHERICAL: ++ return format::EdgeInterpolationAlgorithm::SPHERICAL; ++ case LogicalType::EdgeInterpolationAlgorithm::VINCENTY: ++ return format::EdgeInterpolationAlgorithm::VINCENTY; ++ case LogicalType::EdgeInterpolationAlgorithm::THOMAS: ++ return format::EdgeInterpolationAlgorithm::THOMAS; ++ case LogicalType::EdgeInterpolationAlgorithm::ANDOYER: ++ return format::EdgeInterpolationAlgorithm::ANDOYER; ++ case LogicalType::EdgeInterpolationAlgorithm::KARNEY: ++ return format::EdgeInterpolationAlgorithm::KARNEY; ++ default: ++ throw ParquetException("Unknown value for geometry algorithm: ", ++ static_cast(algorithm)); ++ } ++} ++ ++static inline LogicalType::EdgeInterpolationAlgorithm FromThrift( ++ const format::EdgeInterpolationAlgorithm::type algorithm) { ++ switch (algorithm) { ++ case format::EdgeInterpolationAlgorithm::SPHERICAL: ++ return LogicalType::EdgeInterpolationAlgorithm::SPHERICAL; ++ case format::EdgeInterpolationAlgorithm::VINCENTY: ++ return LogicalType::EdgeInterpolationAlgorithm::VINCENTY; ++ case format::EdgeInterpolationAlgorithm::THOMAS: ++ return LogicalType::EdgeInterpolationAlgorithm::THOMAS; ++ case format::EdgeInterpolationAlgorithm::ANDOYER: ++ return LogicalType::EdgeInterpolationAlgorithm::ANDOYER; ++ case format::EdgeInterpolationAlgorithm::KARNEY: ++ return LogicalType::EdgeInterpolationAlgorithm::KARNEY; ++ default: ++ throw ParquetException("Unknown value for geometry algorithm: ", ++ static_cast(algorithm)); ++ } ++} ++ + static inline EncryptionAlgorithm FromThrift(format::EncryptionAlgorithm encryption) { + EncryptionAlgorithm encryption_algorithm; + +@@ -332,6 +400,35 @@ static inline format::SortingColumn ToThrift(SortingColumn sorting_column) { + return thrift_sorting_column; + } + ++static inline format::GeospatialStatistics ToThrift( ++ const geospatial::EncodedGeoStatistics& encoded_geo_stats) { ++ format::GeospatialStatistics geospatial_statistics; ++ ++ geospatial_statistics.__set_geospatial_types(encoded_geo_stats.geospatial_types); ++ ++ if (encoded_geo_stats.xy_bounds_present) { ++ format::BoundingBox bbox; ++ bbox.__set_xmin(encoded_geo_stats.xmin); ++ bbox.__set_xmax(encoded_geo_stats.xmax); ++ bbox.__set_ymin(encoded_geo_stats.ymin); ++ bbox.__set_ymax(encoded_geo_stats.ymax); ++ ++ if (encoded_geo_stats.z_bounds_present) { ++ bbox.__set_zmin(encoded_geo_stats.zmin); ++ bbox.__set_zmax(encoded_geo_stats.zmax); ++ } ++ ++ if (encoded_geo_stats.m_bounds_present) { ++ bbox.__set_mmin(encoded_geo_stats.mmin); ++ bbox.__set_mmax(encoded_geo_stats.mmax); ++ } ++ ++ geospatial_statistics.__set_bbox(std::move(bbox)); ++ } ++ ++ return geospatial_statistics; ++} ++ + static inline format::Statistics ToThrift(const EncodedStatistics& stats) { + format::Statistics statistics; + if (stats.has_min) { +diff --git a/cpp/src/parquet/type_fwd.h b/cpp/src/parquet/type_fwd.h +--- a/cpp/src/parquet/type_fwd.h ++++ b/cpp/src/parquet/type_fwd.h +@@ -83,6 +83,11 @@ class EncodedStatistics; + class Statistics; + struct SizeStatistics; + ++namespace geospatial { ++class GeoStatistics; ++struct EncodedGeoStatistics; ++} // namespace geospatial ++ + class ColumnIndex; + class OffsetIndex; + +diff --git a/cpp/src/parquet/types.cc b/cpp/src/parquet/types.cc +--- a/cpp/src/parquet/types.cc ++++ b/cpp/src/parquet/types.cc +@@ -22,11 +22,16 @@ + #include + #include + ++#include "arrow/json/rapidjson_defs.h" // IWYU pragma: keep + #include "arrow/util/checked_cast.h" + #include "arrow/util/compression.h" + #include "arrow/util/logging_internal.h" + ++#include ++#include ++ + #include "parquet/exception.h" ++#include "parquet/thrift_internal.h" + #include "parquet/types.h" + + #include "generated/parquet_types.h" +@@ -479,6 +484,27 @@ std::shared_ptr LogicalType::FromThrift( + return UUIDLogicalType::Make(); + } else if (type.__isset.FLOAT16) { + return Float16LogicalType::Make(); ++ } else if (type.__isset.GEOMETRY) { ++ std::string crs; ++ if (type.GEOMETRY.__isset.crs) { ++ crs = type.GEOMETRY.crs; ++ } ++ ++ return GeometryLogicalType::Make(std::move(crs)); ++ } else if (type.__isset.GEOGRAPHY) { ++ std::string crs; ++ if (type.GEOGRAPHY.__isset.crs) { ++ crs = type.GEOGRAPHY.crs; ++ } ++ ++ LogicalType::EdgeInterpolationAlgorithm algorithm; ++ if (!type.GEOGRAPHY.__isset.algorithm) { ++ algorithm = LogicalType::EdgeInterpolationAlgorithm::SPHERICAL; ++ } else { ++ algorithm = ::parquet::FromThrift(type.GEOGRAPHY.algorithm); ++ } ++ ++ return GeographyLogicalType::Make(std::move(crs), algorithm); + } else if (type.__isset.VARIANT) { + return VariantLogicalType::Make(); + } else { +@@ -539,6 +565,15 @@ std::shared_ptr LogicalType::Float16() { + return Float16LogicalType::Make(); + } + ++std::shared_ptr LogicalType::Geometry(std::string crs) { ++ return GeometryLogicalType::Make(std::move(crs)); ++} ++ ++std::shared_ptr LogicalType::Geography( ++ std::string crs, LogicalType::EdgeInterpolationAlgorithm algorithm) { ++ return GeographyLogicalType::Make(std::move(crs), algorithm); ++} ++ + std::shared_ptr LogicalType::Variant() { + return VariantLogicalType::Make(); + } +@@ -625,6 +660,8 @@ class LogicalType::Impl { + class BSON; + class UUID; + class Float16; ++ class Geometry; ++ class Geography; + class Variant; + class No; + class Undefined; +@@ -698,6 +735,12 @@ bool LogicalType::is_UUID() const { return impl_->type() == LogicalType::Type::U + bool LogicalType::is_float16() const { + return impl_->type() == LogicalType::Type::FLOAT16; + } ++bool LogicalType::is_geometry() const { ++ return impl_->type() == LogicalType::Type::GEOMETRY; ++} ++bool LogicalType::is_geography() const { ++ return impl_->type() == LogicalType::Type::GEOGRAPHY; ++} + bool LogicalType::is_variant() const { + return impl_->type() == LogicalType::Type::VARIANT; + } +@@ -1630,6 +1673,200 @@ class LogicalType::Impl::Float16 final : public LogicalType::Impl::Incompatible, + + GENERATE_MAKE(Float16) + ++namespace { ++void WriteCrsKeyAndValue(const std::string_view crs, std::ostream& json) { ++ // There is no restriction on the crs value here, and it may contain quotes ++ // or backslashes that would result in invalid JSON if unescaped. ++ namespace rj = ::arrow::rapidjson; ++ rj::StringBuffer buffer; ++ rj::Writer writer(buffer); ++ rj::Value v; ++ v.SetString(crs.data(), static_cast(crs.size())); ++ v.Accept(writer); ++ json << R"(, "crs": )" << buffer.GetString(); ++} ++} // namespace ++ ++class LogicalType::Impl::Geometry final : public LogicalType::Impl::Incompatible, ++ public LogicalType::Impl::SimpleApplicable { ++ public: ++ friend class GeometryLogicalType; ++ ++ std::string ToString() const override; ++ std::string ToJSON() const override; ++ format::LogicalType ToThrift() const override; ++ bool Equals(const LogicalType& other) const override; ++ ++ const std::string& crs() const { return crs_; } ++ ++ private: ++ explicit Geometry(std::string crs) ++ : LogicalType::Impl(LogicalType::Type::GEOMETRY, SortOrder::UNKNOWN), ++ LogicalType::Impl::SimpleApplicable(parquet::Type::BYTE_ARRAY), ++ crs_(std::move(crs)) {} ++ ++ std::string crs_; ++}; ++ ++std::string LogicalType::Impl::Geometry::ToString() const { ++ std::stringstream type; ++ type << "Geometry(crs=" << crs_ << ")"; ++ return type.str(); ++} ++ ++std::string LogicalType::Impl::Geometry::ToJSON() const { ++ std::stringstream json; ++ json << R"({"Type": "Geometry")"; ++ ++ if (!crs_.empty()) { ++ WriteCrsKeyAndValue(crs_, json); ++ } ++ ++ json << "}"; ++ return json.str(); ++} ++ ++format::LogicalType LogicalType::Impl::Geometry::ToThrift() const { ++ format::LogicalType type; ++ format::GeometryType geometry_type; ++ ++ // Canonially export crs of "" as an unset CRS ++ if (!crs_.empty()) { ++ geometry_type.__set_crs(crs_); ++ } ++ ++ type.__set_GEOMETRY(geometry_type); ++ return type; ++} ++ ++bool LogicalType::Impl::Geometry::Equals(const LogicalType& other) const { ++ if (other.is_geometry()) { ++ const auto& other_geometry = checked_cast(other); ++ return crs() == other_geometry.crs(); ++ } else { ++ return false; ++ } ++} ++ ++const std::string& GeometryLogicalType::crs() const { ++ return (dynamic_cast(*impl_)).crs(); ++} ++ ++std::shared_ptr GeometryLogicalType::Make(std::string crs) { ++ auto logical_type = std::shared_ptr(new GeometryLogicalType()); ++ logical_type->impl_.reset(new LogicalType::Impl::Geometry(std::move(crs))); ++ return logical_type; ++} ++ ++class LogicalType::Impl::Geography final : public LogicalType::Impl::Incompatible, ++ public LogicalType::Impl::SimpleApplicable { ++ public: ++ friend class GeographyLogicalType; ++ ++ std::string ToString() const override; ++ std::string ToJSON() const override; ++ format::LogicalType ToThrift() const override; ++ bool Equals(const LogicalType& other) const override; ++ ++ const std::string& crs() const { return crs_; } ++ LogicalType::EdgeInterpolationAlgorithm algorithm() const { return algorithm_; } ++ ++ std::string_view algorithm_name() const { ++ switch (algorithm_) { ++ case LogicalType::EdgeInterpolationAlgorithm::SPHERICAL: ++ return "spherical"; ++ case LogicalType::EdgeInterpolationAlgorithm::VINCENTY: ++ return "vincenty"; ++ case LogicalType::EdgeInterpolationAlgorithm::THOMAS: ++ return "thomas"; ++ case LogicalType::EdgeInterpolationAlgorithm::ANDOYER: ++ return "andoyer"; ++ case LogicalType::EdgeInterpolationAlgorithm::KARNEY: ++ return "karney"; ++ default: ++ return "unknown"; ++ } ++ } ++ ++ private: ++ Geography(std::string crs, LogicalType::EdgeInterpolationAlgorithm algorithm) ++ : LogicalType::Impl(LogicalType::Type::GEOGRAPHY, SortOrder::UNKNOWN), ++ LogicalType::Impl::SimpleApplicable(parquet::Type::BYTE_ARRAY), ++ crs_(std::move(crs)), ++ algorithm_(algorithm) {} ++ ++ std::string crs_; ++ LogicalType::EdgeInterpolationAlgorithm algorithm_; ++}; ++ ++std::string LogicalType::Impl::Geography::ToString() const { ++ std::stringstream type; ++ type << "Geography(crs=" << crs_ << ", algorithm=" << algorithm_name() << ")"; ++ return type.str(); ++} ++ ++std::string LogicalType::Impl::Geography::ToJSON() const { ++ std::stringstream json; ++ json << R"({"Type": "Geography")"; ++ ++ if (!crs_.empty()) { ++ WriteCrsKeyAndValue(crs_, json); ++ } ++ ++ if (algorithm_ != LogicalType::EdgeInterpolationAlgorithm::SPHERICAL) { ++ json << R"(, "algorithm": ")" << algorithm_name() << R"(")"; ++ } ++ ++ json << "}"; ++ return json.str(); ++} ++ ++format::LogicalType LogicalType::Impl::Geography::ToThrift() const { ++ format::LogicalType type; ++ format::GeographyType geography_type; ++ ++ // Canonially export crs of "" as an unset CRS ++ if (!crs_.empty()) { ++ geography_type.__set_crs(crs_); ++ } ++ ++ if (algorithm_ == LogicalType::EdgeInterpolationAlgorithm::SPHERICAL) { ++ // Canonically export spherical algorithm as unset ++ } else { ++ geography_type.__set_algorithm(::parquet::ToThrift(algorithm_)); ++ } ++ ++ type.__set_GEOGRAPHY(geography_type); ++ return type; ++} ++ ++bool LogicalType::Impl::Geography::Equals(const LogicalType& other) const { ++ if (other.is_geography()) { ++ const auto& other_geography = checked_cast(other); ++ return crs() == other_geography.crs() && algorithm() == other_geography.algorithm(); ++ } else { ++ return false; ++ } ++} ++ ++const std::string& GeographyLogicalType::crs() const { ++ return (dynamic_cast(*impl_)).crs(); ++} ++ ++LogicalType::EdgeInterpolationAlgorithm GeographyLogicalType::algorithm() const { ++ return (dynamic_cast(*impl_)).algorithm(); ++} ++ ++std::string_view GeographyLogicalType::algorithm_name() const { ++ return (dynamic_cast(*impl_)).algorithm_name(); ++} ++ ++std::shared_ptr GeographyLogicalType::Make( ++ std::string crs, LogicalType::EdgeInterpolationAlgorithm algorithm) { ++ auto logical_type = std::shared_ptr(new GeographyLogicalType()); ++ logical_type->impl_.reset(new LogicalType::Impl::Geography(std::move(crs), algorithm)); ++ return logical_type; ++} + class LogicalType::Impl::Variant final : public LogicalType::Impl::Incompatible, + public LogicalType::Impl::Inapplicable { + public: +diff --git a/cpp/src/parquet/types.h b/cpp/src/parquet/types.h +--- a/cpp/src/parquet/types.h ++++ b/cpp/src/parquet/types.h +@@ -158,6 +158,8 @@ class PARQUET_EXPORT LogicalType { + BSON, + UUID, + FLOAT16, ++ GEOMETRY, ++ GEOGRAPHY, + VARIANT, + NONE // Not a real logical type; should always be last element + }; +@@ -167,6 +169,15 @@ class PARQUET_EXPORT LogicalType { + enum unit { UNKNOWN = 0, MILLIS = 1, MICROS, NANOS }; + }; + ++ enum class EdgeInterpolationAlgorithm { ++ UNKNOWN = 0, ++ SPHERICAL = 1, ++ VINCENTY = 2, ++ THOMAS = 3, ++ ANDOYER = 4, ++ KARNEY = 5 ++ }; ++ + /// \brief If possible, return a logical type equivalent to the given legacy + /// converted type (and decimal metadata if applicable). + static std::shared_ptr FromConvertedType( +@@ -215,6 +226,12 @@ class PARQUET_EXPORT LogicalType { + static std::shared_ptr Float16(); + static std::shared_ptr Variant(); + ++ static std::shared_ptr Geometry(std::string crs = ""); ++ ++ static std::shared_ptr Geography( ++ std::string crs = "", LogicalType::EdgeInterpolationAlgorithm algorithm = ++ EdgeInterpolationAlgorithm::SPHERICAL); ++ + /// \brief Create a placeholder for when no logical type is specified + static std::shared_ptr None(); + +@@ -268,6 +285,8 @@ class PARQUET_EXPORT LogicalType { + bool is_BSON() const; + bool is_UUID() const; + bool is_float16() const; ++ bool is_geometry() const; ++ bool is_geography() const; + bool is_variant() const; + bool is_none() const; + /// \brief Return true if this logical type is of a known type. +@@ -449,6 +468,30 @@ class PARQUET_EXPORT Float16LogicalType : public LogicalType { + Float16LogicalType() = default; + }; + ++class PARQUET_EXPORT GeometryLogicalType : public LogicalType { ++ public: ++ static std::shared_ptr Make(std::string crs = ""); ++ ++ const std::string& crs() const; ++ ++ private: ++ GeometryLogicalType() = default; ++}; ++ ++class PARQUET_EXPORT GeographyLogicalType : public LogicalType { ++ public: ++ static std::shared_ptr Make( ++ std::string crs = "", LogicalType::EdgeInterpolationAlgorithm algorithm = ++ EdgeInterpolationAlgorithm::SPHERICAL); ++ ++ const std::string& crs() const; ++ LogicalType::EdgeInterpolationAlgorithm algorithm() const; ++ std::string_view algorithm_name() const; ++ ++ private: ++ GeographyLogicalType() = default; ++}; ++ + /// \brief Allowed for group nodes only. + class PARQUET_EXPORT VariantLogicalType : public LogicalType { + public: +diff --git a/cpp/src/parquet/CMakeLists.txt b/cpp/src/parquet/CMakeLists.txt +index bc7e4f3..735653d 100644 +--- a/cpp/src/parquet/CMakeLists.txt ++++ b/cpp/src/parquet/CMakeLists.txt +@@ -171,6 +171,9 @@ set(PARQUET_SRCS + exception.cc + file_reader.cc + file_writer.cc ++ geospatial/statistics.cc ++ geospatial/util_internal.cc ++ geospatial/util_json_internal.cc + level_comparison.cc + level_conversion.cc + metadata.cc +@@ -257,6 +260,10 @@ endif() + if(NOT PARQUET_MINIMAL_DEPENDENCY) + list(APPEND PARQUET_SHARED_LINK_LIBS arrow_shared) + ++ # Add RapidJSON libraries ++ list(APPEND PARQUET_SHARED_PRIVATE_LINK_LIBS RapidJSON) ++ list(APPEND PARQUET_STATIC_LINK_LIBS RapidJSON) ++ + # These are libraries that we will link privately with parquet_shared (as they + # do not need to be linked transitively by other linkers) + list(APPEND PARQUET_SHARED_PRIVATE_LINK_LIBS thrift::thrift) +@@ -352,6 +359,7 @@ endif() + add_subdirectory(api) + add_subdirectory(arrow) + add_subdirectory(encryption) ++add_subdirectory(geospatial) + + arrow_install_all_headers("parquet") + +@@ -362,15 +370,17 @@ install(FILES "${CMAKE_CURRENT_BINARY_DIR}/parquet_version.h" + + add_parquet_test(internals-test + SOURCES +- bloom_filter_test.cc + bloom_filter_reader_test.cc +- properties_test.cc +- statistics_test.cc ++ bloom_filter_test.cc + encoding_test.cc ++ geospatial/statistics_test.cc ++ geospatial/util_internal_test.cc + metadata_test.cc + page_index_test.cc ++ properties_test.cc + public_api_test.cc + size_statistics_test.cc ++ statistics_test.cc + types_test.cc) + + set_source_files_properties(public_api_test.cc PROPERTIES SKIP_UNITY_BUILD_INCLUSION ON) diff --git a/arrow_1/solution/solve.sh b/arrow_1/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..ddb8d33e8f12b7d9378e415f2a0438812937efdc --- /dev/null +++ b/arrow_1/solution/solve.sh @@ -0,0 +1,7 @@ +#!/usr/bin/env bash +set -euo pipefail + +cd /workspace/arrow +patch=${LOLBENCH_ORACLE_PATCH:-/solution/solution.patch} +git apply "$patch" +lolbench-submit diff --git a/arrow_1/task.toml b/arrow_1/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..2c7d48da3062182ad4af92675e02aff24b1dfb25 --- /dev/null +++ b/arrow_1/task.toml @@ -0,0 +1,60 @@ +schema_version = "1.3" + +[task] +name = "lolbench/arrow_1" +description = "Implement Apache Arrow." +authors = [{ name = "LoLBench maintainers" }] +keywords = ["lolbench", "coding-agent", "apache", "arrow", "c"] + +[metadata] +instance_id = "arrow_1" +source_instance_id = "Apache-Arrow_PR-240_PR-45459" +source_slug = "Apache-Arrow_PR-240_PR-45459" +docker_slug = "Apache-Arrow_PR-240_PR-45459" +dockerhub_image = "smartdub26/lolbench-linux:arrow_1-1.0.0" +project = "arrow" +repo = "apache/arrow" +requirement_doc = "https://github.com/apache/parquet-format/pull/240" +pr_link = "https://github.com/apache/arrow/pull/45459" +base_commit = "f9c18462db2af84a795e393985bbc615873ee3e7" +merge_commit = "e1b7061cb1df3d5fc861fe80557cd7824980346a" +test_level = "unit" +source_history_policy = "ancestors-only" +lolbench_test_modes = ["orig", "aug", "union"] +default_lolbench_suite = "union" +canonical_lolbench_suite = "union" +augmentation_available = true +verifier_network_policy = "public" +verifier_network_reason = "The Harbor verifier runs in a separate container and may use network access; migrated LoLBench verifier assets are mounted only in the verifier phase." + +[environment] +build_timeout_sec = 3600.0 +docker_image = "smartdub26/lolbench-linux:arrow_1-1.0.0" +network_mode = "public" +os = "linux" +cpus = 4 +memory_mb = 8192 +storage_mb = 20480 + +[agent] +timeout_sec = 21600.0 +user = "agent" +network_mode = "allowlist" +allowed_hosts = ["openrouter.ai", "api.openai.com", "api.anthropic.com"] + +[verifier] +timeout_sec = 7200.0 +user = "root" +environment_mode = "separate" +network_mode = "public" + +[verifier.env] +LOLBENCH_SUITE = "union" + +[verifier.environment] +docker_image = "smartdub26/lolbench-linux:arrow_1-1.0.0" +network_mode = "public" +os = "linux" +cpus = 4 +memory_mb = 8192 +storage_mb = 20480 diff --git a/arrow_1/tests/docker-compose.yaml b/arrow_1/tests/docker-compose.yaml new file mode 100644 index 0000000000000000000000000000000000000000..f5091b9298e127a1efbe69deeed699c907e025c1 --- /dev/null +++ b/arrow_1/tests/docker-compose.yaml @@ -0,0 +1,16 @@ +services: + main: + pull_policy: missing + volumes: + - type: bind + source: . + target: /tests + read_only: true + - type: bind + source: ./private + target: /opt/lolbench/private + read_only: true + - type: bind + source: ../solution + target: /solution + read_only: true diff --git a/arrow_1/tests/private/eval_tests.patch b/arrow_1/tests/private/eval_tests.patch new file mode 100644 index 0000000000000000000000000000000000000000..6dad76238fa788e2163c80ec287459635716b3dd --- /dev/null +++ b/arrow_1/tests/private/eval_tests.patch @@ -0,0 +1,1397 @@ +diff --git a/cpp/src/parquet/arrow/arrow_reader_writer_test.cc b/cpp/src/parquet/arrow/arrow_reader_writer_test.cc +--- a/cpp/src/parquet/arrow/arrow_reader_writer_test.cc ++++ b/cpp/src/parquet/arrow/arrow_reader_writer_test.cc +@@ -43,6 +43,7 @@ + #include "arrow/scalar.h" + #include "arrow/table.h" + #include "arrow/testing/builder.h" ++#include "arrow/testing/extension_type.h" + #include "arrow/testing/gtest_util.h" + #include "arrow/testing/random.h" + #include "arrow/testing/util.h" +@@ -1481,6 +1482,61 @@ TEST_F(TestJsonParquetIO, JsonExtension) { + this->RoundTripSingleColumn(json_large_array, json_large_array, writer_properties); + } + ++using TestGeoArrowParquetIO = TestParquetIO; ++ ++TEST_F(TestGeoArrowParquetIO, GeoArrowExtension) { ++ ::arrow::ExtensionTypeGuard guard(test::geoarrow_wkb()); ++ ++ // Build a binary WKB array with at least one null value ++ ::arrow::BinaryBuilder builder; ++ ++ for (int k = 0; k < 10; k++) { ++ std::string item = test::MakeWKBPoint( ++ {static_cast(k), static_cast(k + 1)}, false, false); ++ ASSERT_OK(builder.Append(item)); ++ } ++ ASSERT_OK(builder.AppendNull()); ++ for (int k = 0; k < 5; k++) { ++ std::string item = test::MakeWKBPoint( ++ {static_cast(k), static_cast(k + 1)}, false, false); ++ ASSERT_OK(builder.Append(item)); ++ } ++ ++ ASSERT_OK_AND_ASSIGN(const auto binary_array, builder.Finish()); ++ const auto wkb_type = test::geoarrow_wkb_lonlat(); ++ const auto wkb_array = ::arrow::ExtensionType::WrapArray(wkb_type, binary_array); ++ ++ const auto large_wkb_type = test::geoarrow_wkb_lonlat(::arrow::large_binary()); ++ ASSERT_OK_AND_ASSIGN(const auto large_binary_array, ++ ::arrow::compute::Cast(binary_array, ::arrow::large_binary())); ++ const auto large_wkb_array = ++ ::arrow::ExtensionType::WrapArray(large_wkb_type, large_binary_array.make_array()); ++ ++ // When the original Arrow schema isn't stored and Arrow extensions are disabled, ++ // LogicalType::GEOMETRY is read as utf8. ++ auto writer_properties = default_arrow_writer_properties(); ++ ASSERT_NO_FATAL_FAILURE( ++ this->RoundTripSingleColumn(wkb_array, binary_array, writer_properties)); ++ ASSERT_NO_FATAL_FAILURE( ++ this->RoundTripSingleColumn(large_wkb_array, binary_array, writer_properties)); ++ ++ // When the original Arrow schema isn't stored and Arrow extensions are enabled, ++ // LogicalType::GEOMETRY is read as geoarrow.wkb with binary storage. ++ ::parquet::ArrowReaderProperties reader_properties; ++ reader_properties.set_arrow_extensions_enabled(true); ++ ASSERT_NO_FATAL_FAILURE(this->RoundTripSingleColumn( ++ wkb_array, wkb_array, writer_properties, reader_properties)); ++ ASSERT_NO_FATAL_FAILURE(this->RoundTripSingleColumn( ++ large_wkb_array, wkb_array, writer_properties, reader_properties)); ++ ++ // When the original Arrow schema is stored, the stored Arrow type is respected. ++ writer_properties = ::parquet::ArrowWriterProperties::Builder().store_schema()->build(); ++ ASSERT_NO_FATAL_FAILURE( ++ this->RoundTripSingleColumn(wkb_array, wkb_array, writer_properties)); ++ ASSERT_NO_FATAL_FAILURE( ++ this->RoundTripSingleColumn(large_wkb_array, large_wkb_array, writer_properties)); ++} ++ + using TestNullParquetIO = TestParquetIO<::arrow::NullType>; + + TEST_F(TestNullParquetIO, NullColumn) { +diff --git a/cpp/src/parquet/arrow/arrow_schema_test.cc b/cpp/src/parquet/arrow/arrow_schema_test.cc +--- a/cpp/src/parquet/arrow/arrow_schema_test.cc ++++ b/cpp/src/parquet/arrow/arrow_schema_test.cc +@@ -19,7 +19,6 @@ + #include + + #include "gmock/gmock-matchers.h" +-#include "gmock/gmock.h" + #include "gtest/gtest.h" + + #include "parquet/arrow/reader.h" +@@ -35,6 +34,7 @@ + #include "arrow/extension/json.h" + #include "arrow/extension/uuid.h" + #include "arrow/ipc/writer.h" ++#include "arrow/testing/extension_type.h" + #include "arrow/testing/gtest_util.h" + #include "arrow/type.h" + #include "arrow/util/base64.h" +@@ -237,6 +237,10 @@ TEST_F(TestConvertParquetSchema, ParquetAnnotatedFields) { + ::arrow::int64()}, + {"json", LogicalType::JSON(), ParquetType::BYTE_ARRAY, -1, ::arrow::utf8()}, + {"bson", LogicalType::BSON(), ParquetType::BYTE_ARRAY, -1, ::arrow::binary()}, ++ {"geometry", LogicalType::Geometry(), ParquetType::BYTE_ARRAY, -1, ++ ::arrow::binary()}, ++ {"geography", LogicalType::Geography(), ParquetType::BYTE_ARRAY, -1, ++ ::arrow::binary()}, + {"interval", LogicalType::Interval(), ParquetType::FIXED_LEN_BYTE_ARRAY, 12, + ::arrow::fixed_size_binary(12)}, + {"uuid", LogicalType::UUID(), ParquetType::FIXED_LEN_BYTE_ARRAY, 16, +@@ -1090,6 +1094,62 @@ TEST_F(TestConvertParquetSchema, ParquetSchemaArrowUuidExtension) { + } + } + ++TEST_F(TestConvertParquetSchema, ParquetSchemaGeoArrowExtensions) { ++ std::vector parquet_fields; ++ parquet_fields.push_back(PrimitiveNode::Make("geometry", Repetition::OPTIONAL, ++ LogicalType::Geometry(), ++ ParquetType::BYTE_ARRAY)); ++ parquet_fields.push_back(PrimitiveNode::Make("geography", Repetition::OPTIONAL, ++ LogicalType::Geography(), ++ ParquetType::BYTE_ARRAY)); ++ ++ { ++ // Parquet file does not contain Arrow schema. ++ // By default, both fields should be treated as binary() fields in Arrow. ++ auto arrow_schema = ::arrow::schema({::arrow::field("geometry", BINARY, true), ++ ::arrow::field("geography", BINARY, true)}); ++ std::shared_ptr metadata{}; ++ ASSERT_OK(ConvertSchema(parquet_fields, metadata)); ++ CheckFlatSchema(arrow_schema); ++ } ++ ++ { ++ // Parquet file does not contain Arrow schema. ++ // If Arrow extensions are enabled and extensions are registered, ++ // fields will be interpreted as geoarrow_wkb(binary()) extension fields. ++ ::arrow::ExtensionTypeGuard guard(test::geoarrow_wkb()); ++ ++ ArrowReaderProperties props; ++ props.set_arrow_extensions_enabled(true); ++ auto arrow_schema = ::arrow::schema( ++ {::arrow::field( ++ "geometry", ++ test::geoarrow_wkb(R"({"crs": "OGC:CRS84", "crs_type": "authority_code"})"), ++ true), ++ ::arrow::field( ++ "geography", ++ test::geoarrow_wkb( ++ R"({"crs": "OGC:CRS84", "crs_type": "authority_code", "edges": "spherical"})"), ++ true)}); ++ std::shared_ptr metadata{}; ++ ASSERT_OK(ConvertSchema(parquet_fields, metadata, props)); ++ CheckFlatSchema(arrow_schema); ++ } ++ ++ { ++ // Parquet file does not contain Arrow schema. ++ // If Arrow extensions are enabled and extensions are NOT registered, ++ // fields will be interpreted as binary(). ++ ArrowReaderProperties props; ++ props.set_arrow_extensions_enabled(true); ++ auto arrow_schema = ::arrow::schema({::arrow::field("geometry", BINARY, true), ++ ::arrow::field("geography", BINARY, true)}); ++ std::shared_ptr metadata{}; ++ ASSERT_OK(ConvertSchema(parquet_fields, metadata, props)); ++ CheckFlatSchema(arrow_schema); ++ } ++} ++ + class TestConvertArrowSchema : public ::testing::Test { + public: + virtual void SetUp() {} +@@ -1343,6 +1403,96 @@ TEST_F(TestConvertArrowSchema, ParquetFlatPrimitivesAsDictionaries) { + ASSERT_NO_FATAL_FAILURE(CheckFlatSchema(parquet_fields)); + } + ++TEST_F(TestConvertArrowSchema, ParquetGeoArrowCrsLonLat) { ++ // All the Arrow Schemas below should convert to the type defaults for GEOMETRY ++ // and GEOGRAPHY when GeoArrow extension types are registered and the appropriate ++ // writer option is set. ++ ::arrow::ExtensionTypeGuard guard(test::geoarrow_wkb()); ++ ++ std::vector parquet_fields; ++ parquet_fields.push_back(PrimitiveNode::Make("geometry", Repetition::OPTIONAL, ++ LogicalType::Geometry(), ++ ParquetType::BYTE_ARRAY)); ++ parquet_fields.push_back(PrimitiveNode::Make("geography", Repetition::OPTIONAL, ++ LogicalType::Geography(), ++ ParquetType::BYTE_ARRAY)); ++ ++ // There are several ways that longitude/latitude could be specified when coming from ++ // GeoArrow, which allows null, missing, arbitrary strings (e.g., Authority:Code), and ++ // PROJJSON. ++ std::vector geoarrow_lonlat = { ++ "null", R"("OGC:CRS84")", R"("EPSG:4326")", ++ // Purely the parts of the PROJJSON that we inspect to check the lon/lat case ++ R"({"id": {"authority": "OGC", "code": "CRS84"}})", ++ R"({"id": {"authority": "EPSG", "code": "4326"}})", ++ R"({"id": {"authority": "EPSG", "code": 4326}})"}; ++ ++ for (const auto& geoarrow_lonlatish_crs : geoarrow_lonlat) { ++ ARROW_SCOPED_TRACE("crs = ", geoarrow_lonlatish_crs); ++ std::vector> arrow_fields = { ++ ::arrow::field("geometry", ++ test::geoarrow_wkb(R"({"crs": )" + geoarrow_lonlatish_crs + "}"), ++ true), ++ ::arrow::field("geography", ++ test::geoarrow_wkb(R"({"crs": )" + geoarrow_lonlatish_crs + ++ R"(, "edges": "spherical"})"), ++ true)}; ++ ++ ASSERT_OK(ConvertSchema(arrow_fields)); ++ ASSERT_NO_FATAL_FAILURE(CheckFlatSchema(parquet_fields)); ++ } ++} ++ ++TEST_F(TestConvertArrowSchema, ParquetGeoArrowCrsSrid) { ++ // Checks that it is possible to write the srid:xxxx reccomendation from GeoArrow ++ ::arrow::ExtensionTypeGuard guard(test::geoarrow_wkb()); ++ ++ std::vector parquet_fields; ++ parquet_fields.push_back(PrimitiveNode::Make("geometry", Repetition::OPTIONAL, ++ LogicalType::Geometry("srid:1234"), ++ ParquetType::BYTE_ARRAY)); ++ parquet_fields.push_back(PrimitiveNode::Make("geography", Repetition::OPTIONAL, ++ LogicalType::Geography("srid:5678"), ++ ParquetType::BYTE_ARRAY)); ++ ++ std::vector> arrow_fields = { ++ ::arrow::field("geometry", test::geoarrow_wkb(R"({"crs": "srid:1234"})"), true), ++ ::arrow::field("geography", ++ test::geoarrow_wkb(R"({"crs": "srid:5678", "edges": "spherical"})"), ++ true)}; ++ ++ ASSERT_OK(ConvertSchema(arrow_fields)); ++ ASSERT_NO_FATAL_FAILURE(CheckFlatSchema(parquet_fields)); ++} ++ ++TEST_F(TestConvertArrowSchema, ParquetGeoArrowCrsProjjson) { ++ // Checks the conversion from GeoArrow that contains non-lon/lat PROJJSON ++ // to Parquet. Almost all GeoArrow types that arrive at the Parquet reader ++ // will have their CRS expressed in this way. ++ ::arrow::ExtensionTypeGuard guard(test::geoarrow_wkb()); ++ ++ std::vector> arrow_fields = { ++ ::arrow::field("geometry", test::geoarrow_wkb(R"({"crs": {"key0": "value0"}})"), ++ true), ++ ::arrow::field( ++ "geography", ++ test::geoarrow_wkb(R"({"crs": {"key1": "value1"}, "edges": "spherical"})"), ++ true)}; ++ ++ auto arrow_properties = default_arrow_writer_properties(); ++ ASSERT_OK(ConvertSchema(arrow_fields, arrow_properties)); ++ ++ std::vector parquet_fields; ++ parquet_fields.push_back(PrimitiveNode::Make( ++ "geometry", Repetition::OPTIONAL, LogicalType::Geometry(R"({"key0":"value0"})"), ++ ParquetType::BYTE_ARRAY)); ++ parquet_fields.push_back(PrimitiveNode::Make( ++ "geography", Repetition::OPTIONAL, LogicalType::Geography(R"({"key1":"value1"})"), ++ ParquetType::BYTE_ARRAY)); ++ ++ ASSERT_NO_FATAL_FAILURE(CheckFlatSchema(parquet_fields)); ++} ++ + TEST_F(TestConvertArrowSchema, ParquetLists) { + std::vector parquet_fields; + std::vector> arrow_fields; +diff --git a/cpp/src/parquet/column_writer_test.cc b/cpp/src/parquet/column_writer_test.cc +--- a/cpp/src/parquet/column_writer_test.cc ++++ b/cpp/src/parquet/column_writer_test.cc +@@ -35,12 +35,12 @@ + #include "parquet/column_writer.h" + #include "parquet/file_reader.h" + #include "parquet/file_writer.h" ++#include "parquet/geospatial/statistics.h" + #include "parquet/metadata.h" + #include "parquet/platform.h" + #include "parquet/properties.h" + #include "parquet/statistics.h" + #include "parquet/test_util.h" +-#include "parquet/thrift_internal.h" + #include "parquet/types.h" + + namespace bit_util = arrow::bit_util; +@@ -399,6 +399,25 @@ class TestPrimitiveWriter : public PrimitiveTypedTest { + return metadata_accessor->key_value_metadata(); + } + ++ std::unique_ptr metadata_accessor() { ++ // Metadata accessor must be created lazily. ++ // This is because the ColumnChunkMetaData semantics dictate the metadata object is ++ // complete (no changes to the metadata buffer can be made after instantiation) ++ ApplicationVersion app_version(this->writer_properties_->created_by()); ++ return ColumnChunkMetaData::Make(metadata_->contents(), this->descr_, ++ default_reader_properties(), &app_version); ++ } ++ ++ EncodedStatistics metadata_encoded_stats() { return metadata_stats()->Encode(); } ++ ++ std::shared_ptr metadata_stats() { ++ return metadata_accessor()->statistics(); ++ } ++ ++ std::shared_ptr metadata_geo_stats() { ++ return metadata_accessor()->geo_statistics(); ++ } ++ + protected: + int64_t values_read_; + // Keep the reader alive as for ByteArray the lifetime of the ByteArray +@@ -1808,7 +1827,6 @@ TEST_F(TestValuesWriterInt32Type, AllNullsCompressionInPageV2) { + } + + #ifdef ARROW_WITH_ZSTD +- + TEST_F(TestValuesWriterInt32Type, AvoidCompressedInDataPageV2) { + Compression::type compression = Compression::ZSTD; + auto verify_only_one_uncompressed_page = [&](int total_num_values) { +@@ -1849,8 +1867,158 @@ TEST_F(TestValuesWriterInt32Type, AvoidCompressedInDataPageV2) { + verify_only_one_uncompressed_page(/*total_num_values=*/1); + } + } +- + #endif + ++// Test writing and reading geometry columns ++class TestGeometryValuesWriter : public TestPrimitiveWriter { ++ public: ++ void SetUpSchema(Repetition::type repetition, int num_columns) override { ++ std::vector fields; ++ ++ for (int i = 0; i < num_columns; ++i) { ++ std::string name = TestColumnName(i); ++ std::shared_ptr logical_type = ++ GeometryLogicalType::Make("srid:1234"); ++ fields.push_back(schema::PrimitiveNode::Make(name, repetition, logical_type, ++ ByteArrayType::type_num)); ++ } ++ node_ = schema::GroupNode::Make("schema", Repetition::REQUIRED, fields); ++ schema_.Init(node_); ++ } ++ ++ void GenerateData(int64_t num_values, uint32_t seed = 0) { ++ values_.resize(num_values); ++ ++ buffer_.resize(num_values * kWkbPointXYSize); ++ uint8_t* ptr = buffer_.data(); ++ for (int k = 0; k < num_values; k++) { ++ std::string item = test::MakeWKBPoint( ++ {static_cast(k), static_cast(k + 1)}, false, false); ++ std::memcpy(ptr, item.data(), item.size()); ++ values_[k].len = kWkbPointXYSize; ++ values_[k].ptr = ptr; ++ ptr += kWkbPointXYSize; ++ } ++ ++ values_ptr_ = values_.data(); ++ } ++}; ++ ++TEST_F(TestGeometryValuesWriter, TestWriteAndRead) { ++ this->SetUpSchema(Repetition::REQUIRED, 1); ++ this->GenerateData(SMALL_SIZE); ++ size_t num_values = this->values_.size(); ++ auto writer = this->BuildWriter(num_values, ColumnProperties()); ++ writer->WriteBatch(this->values_.size(), nullptr, nullptr, this->values_.data()); ++ ++ writer->Close(); ++ this->ReadColumn(); ++ for (size_t i = 0; i < num_values; i++) { ++ const ByteArray& value = this->values_out_[i]; ++ auto xy = GetWKBPointCoordinateXY(value); ++ EXPECT_TRUE(xy.has_value()); ++ auto expected_x = static_cast(i); ++ auto expected_y = static_cast(i + 1); ++ EXPECT_EQ(*xy, std::make_pair(expected_x, expected_y)); ++ } ++ ++ // Statistics are unset because the sort order is unknown ++ ASSERT_FALSE(metadata_accessor()->is_stats_set()); ++ ASSERT_EQ(metadata_accessor()->statistics(), nullptr); ++ ++ ASSERT_TRUE(metadata_accessor()->is_geo_stats_set()); ++ std::shared_ptr geospatial_statistics = metadata_geo_stats(); ++ ASSERT_TRUE(geospatial_statistics != nullptr); ++ EXPECT_THAT(*geospatial_statistics->geometry_types(), ::testing::ElementsAre(1)); ++ EXPECT_DOUBLE_EQ(0, geospatial_statistics->lower_bound()[0]); ++ EXPECT_DOUBLE_EQ(1, geospatial_statistics->lower_bound()[1]); ++ EXPECT_DOUBLE_EQ(99, geospatial_statistics->upper_bound()[0]); ++ EXPECT_DOUBLE_EQ(100, geospatial_statistics->upper_bound()[1]); ++ EXPECT_THAT(geospatial_statistics->dimension_valid(), ++ ::testing::ElementsAre(true, true, false, false)); ++} ++ ++TEST_F(TestGeometryValuesWriter, TestWriteAndReadSpaced) { ++ this->SetUpSchema(Repetition::OPTIONAL, 1); ++ this->GenerateData(SMALL_SIZE); ++ size_t num_values = this->values_.size(); ++ ++ std::vector definition_levels(num_values, 1); ++ std::vector repetition_levels(num_values, 0); ++ std::vector non_null_indices; ++ ++ // Replace some of the generated data with NULL ++ for (size_t i = 0; i < num_values; i++) { ++ if (i % 3 == 0) { ++ definition_levels[i] = 0; ++ } else { ++ non_null_indices.push_back(i); ++ } ++ } ++ ++ // Construct valid bits using definition levels ++ std::vector valid_bytes(num_values); ++ std::transform(definition_levels.begin(), definition_levels.end(), valid_bytes.begin(), ++ [&](int64_t level) { return static_cast(level); }); ++ std::shared_ptr valid_bits; ++ ASSERT_OK_AND_ASSIGN(valid_bits, ::arrow::internal::BytesToBits(valid_bytes)); ++ ++ auto writer = this->BuildWriter(num_values, ColumnProperties()); ++ writer->WriteBatchSpaced(this->values_.size(), definition_levels.data(), ++ repetition_levels.data(), valid_bits->data(), 0, ++ this->values_.data()); ++ ++ writer->Close(); ++ this->ReadColumn(); ++ size_t expected_values_read = non_null_indices.size(); ++ EXPECT_EQ(expected_values_read, values_read_); ++ for (int64_t i = 0; i < values_read_; i++) { ++ const ByteArray& value = this->values_out_[i]; ++ auto xy = GetWKBPointCoordinateXY(value); ++ EXPECT_TRUE(xy.has_value()); ++ auto expected_x = static_cast(non_null_indices[i]); ++ auto expected_y = static_cast(non_null_indices[i] + 1); ++ EXPECT_EQ(*xy, std::make_pair(expected_x, expected_y)); ++ } ++ ++ std::shared_ptr geospatial_statistics = metadata_geo_stats(); ++ ASSERT_TRUE(geospatial_statistics != nullptr); ++ EXPECT_DOUBLE_EQ(1, geospatial_statistics->lower_bound()[0]); ++ EXPECT_DOUBLE_EQ(2, geospatial_statistics->lower_bound()[1]); ++ EXPECT_DOUBLE_EQ(98, geospatial_statistics->upper_bound()[0]); ++ EXPECT_DOUBLE_EQ(99, geospatial_statistics->upper_bound()[1]); ++ EXPECT_THAT(geospatial_statistics->dimension_valid(), ++ ::testing::ElementsAre(true, true, false, false)); ++} ++ ++TEST_F(TestGeometryValuesWriter, TestWriteAndReadAllNull) { ++ this->SetUpSchema(Repetition::OPTIONAL, 1); ++ this->values_.resize(SMALL_SIZE); ++ std::fill(this->values_.begin(), this->values_.end(), ByteArray{0, nullptr}); ++ this->def_levels_.resize(SMALL_SIZE); ++ std::fill(this->def_levels_.begin(), this->def_levels_.end(), 0); ++ auto writer = this->BuildWriter(SMALL_SIZE); ++ writer->WriteBatch(this->values_.size(), this->def_levels_.data(), nullptr, ++ this->values_ptr_); ++ ++ writer->Close(); ++ this->ReadColumn(); ++ for (int i = 0; i < SMALL_SIZE; i++) { ++ EXPECT_EQ(this->definition_levels_out_[i], 0); ++ } ++ ++ // Statistics are unset because the sort order is unknown ++ ASSERT_FALSE(metadata_accessor()->is_stats_set()); ++ ASSERT_EQ(metadata_accessor()->statistics(), nullptr); ++ ++ // GeoStatistics should exist but all components should be marked as uncalculated ++ ASSERT_TRUE(metadata_accessor()->is_geo_stats_set()); ++ std::shared_ptr geospatial_statistics = metadata_geo_stats(); ++ ASSERT_TRUE(geospatial_statistics != nullptr); ++ EXPECT_THAT(geospatial_statistics->dimension_valid(), ++ ::testing::ElementsAre(false, false, false, false)); ++ EXPECT_EQ(geospatial_statistics->geometry_types(), std::nullopt); ++} ++ + } // namespace test + } // namespace parquet +diff --git a/cpp/src/parquet/geospatial/statistics_test.cc b/cpp/src/parquet/geospatial/statistics_test.cc +new file mode 100644 +--- /dev/null ++++ b/cpp/src/parquet/geospatial/statistics_test.cc +@@ -0,0 +1,399 @@ ++// Licensed to the Apache Software Foundation (ASF) under one ++// or more contributor license agreements. See the NOTICE file ++// distributed with this work for additional information ++// regarding copyright ownership. The ASF licenses this file ++// to you under the Apache License, Version 2.0 (the ++// "License"); you may not use this file except in compliance ++// with the License. You may obtain a copy of the License at ++// ++// http://www.apache.org/licenses/LICENSE-2.0 ++// ++// Unless required by applicable law or agreed to in writing, ++// software distributed under the License is distributed on an ++// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY ++// KIND, either express or implied. See the License for the ++// specific language governing permissions and limitations ++// under the License. ++ ++#include ++#include ++ ++#include "arrow/array/builder_binary.h" ++#include "arrow/compute/api.h" ++#include "arrow/testing/gtest_util.h" ++ ++#include "parquet/geospatial/statistics.h" ++#include "parquet/test_util.h" ++ ++static constexpr double kInf = std::numeric_limits::infinity(); ++ ++namespace parquet::geospatial { ++ ++TEST(TestGeoStatistics, TestDefaults) { ++ GeoStatistics stats; ++ EXPECT_TRUE(stats.geometry_types().has_value()); ++ EXPECT_EQ(stats.geometry_types().value().size(), 0); ++ EXPECT_TRUE(stats.is_valid()); ++ EXPECT_THAT(stats.dimension_empty(), ::testing::ElementsAre(true, true, true, true)); ++ EXPECT_THAT(stats.dimension_valid(), ::testing::ElementsAre(true, true, true, true)); ++ for (int i = 0; i < kMaxDimensions; i++) { ++ EXPECT_EQ(stats.lower_bound()[i], kInf); ++ EXPECT_EQ(stats.upper_bound()[i], -kInf); ++ } ++ ++ EXPECT_TRUE(stats.Equals(GeoStatistics())); ++ ++ // Merging empty with empty should equal empty ++ stats.Merge(GeoStatistics()); ++ EXPECT_TRUE(stats.Equals(GeoStatistics())); ++ ++ // There's no way to encode empty ranges in Thrift, so we pretend that we ++ // didn't calculate them. ++ auto encoded = stats.Encode(); ++ EXPECT_FALSE(encoded->xy_bounds_present); ++ EXPECT_FALSE(encoded->z_bounds_present); ++ EXPECT_FALSE(encoded->m_bounds_present); ++ EXPECT_FALSE(encoded->geospatial_types_present()); ++ ++ // When imported, the statistics marked with everything uncalculated should ++ // be "valid" but should have individual components marked as invalid. ++ GeoStatistics valid_but_uncalculated; ++ valid_but_uncalculated.Decode(*encoded); ++ ++ EXPECT_TRUE(valid_but_uncalculated.is_valid()); ++ EXPECT_THAT(valid_but_uncalculated.dimension_valid(), ++ ::testing::ElementsAre(false, false, false, false)); ++ EXPECT_EQ(valid_but_uncalculated.geometry_types(), std::nullopt); ++} ++ ++TEST(TestGeoStatistics, TestImportEncodedWithNaN) { ++ double nan_dbl = std::numeric_limits::quiet_NaN(); ++ ++ EncodedGeoStatistics encoded_with_nan; ++ encoded_with_nan.xy_bounds_present = true; ++ encoded_with_nan.xmin = nan_dbl; ++ encoded_with_nan.xmax = nan_dbl; ++ encoded_with_nan.ymin = nan_dbl; ++ encoded_with_nan.ymax = nan_dbl; ++ encoded_with_nan.z_bounds_present = true; ++ encoded_with_nan.zmin = nan_dbl; ++ encoded_with_nan.zmax = nan_dbl; ++ encoded_with_nan.m_bounds_present = true; ++ encoded_with_nan.mmin = nan_dbl; ++ encoded_with_nan.mmax = nan_dbl; ++ ++ GeoStatistics stats(encoded_with_nan); ++ EXPECT_THAT(stats.dimension_valid(), ++ ::testing::ElementsAre(false, false, false, false)); ++ for (int i = 0; i < kMaxDimensions; i++) { ++ EXPECT_TRUE(std::isnan(stats.lower_bound()[i])); ++ EXPECT_TRUE(std::isnan(stats.upper_bound()[i])); ++ } ++ ++ // Ensure that if we merge finite values into nans we get dimensions marked as invalid ++ GeoStatistics stats_finite; ++ std::string xyzm0 = test::MakeWKBPoint({10, 11, 12, 13}, true, true); ++ ByteArray item0{xyzm0}; ++ stats_finite.Update(&item0, /*num_values=*/1); ++ ++ stats.Merge(stats_finite); ++ EXPECT_THAT(stats.dimension_valid(), ++ ::testing::ElementsAre(false, false, false, false)); ++ ++ // Ensure that if we merge nans into finite values we also get dimensions marked as ++ // invalid ++ stats_finite.Merge(stats); ++ EXPECT_THAT(stats.dimension_valid(), ++ ::testing::ElementsAre(false, false, false, false)); ++ ++ // Ensure that if we decode nans, we mark the ranges as uncalculated ++ auto encoded = stats.Encode(); ++ EXPECT_FALSE(encoded->xy_bounds_present); ++ EXPECT_FALSE(encoded->z_bounds_present); ++ EXPECT_FALSE(encoded->m_bounds_present); ++} ++ ++TEST(TestGeoStatistics, TestUpdateByteArray) { ++ GeoStatistics stats; ++ ++ // Make items with all dimensions to ensure all dimensions are updated ++ // and returned properly (POINT XYZM has an integer code of 3001) ++ std::string xyzm0 = test::MakeWKBPoint({10, 11, 12, 13}, true, true); ++ ByteArray item0{xyzm0}; ++ ++ stats.Update(&item0, /*num_values=*/1); ++ EXPECT_TRUE(stats.is_valid()); ++ EXPECT_THAT(stats.lower_bound(), ::testing::ElementsAre(10, 11, 12, 13)); ++ EXPECT_THAT(stats.upper_bound(), ::testing::ElementsAre(10, 11, 12, 13)); ++ EXPECT_THAT(*stats.geometry_types(), ::testing::ElementsAre(3001)); ++ EXPECT_THAT(stats.dimension_empty(), ++ ::testing::ElementsAre(false, false, false, false)); ++ ++ std::string xyzm1 = test::MakeWKBPoint({20, 21, 22, 23}, true, true); ++ ByteArray item1{xyzm1}; ++ ++ stats.Update(&item1, /*num_values=*/1); ++ EXPECT_TRUE(stats.is_valid()); ++ EXPECT_THAT(stats.lower_bound(), ::testing::ElementsAre(10, 11, 12, 13)); ++ EXPECT_THAT(stats.upper_bound(), ::testing::ElementsAre(20, 21, 22, 23)); ++ EXPECT_THAT(*stats.geometry_types(), ::testing::ElementsAre(3001)); ++ ++ // Check recreating the statistics with actual values ++ auto encoded = stats.Encode(); ++ EXPECT_TRUE(GeoStatistics(*encoded).Equals(stats)); ++ ++ // Check resetting to the original state ++ stats.Reset(); ++ EXPECT_TRUE(stats.Equals(GeoStatistics())); ++ ++ // Check UpdateSpaced() ++ ++ // A null value that should be skipped ++ std::string xyzm2 = test::MakeWKBPoint({-30, -31, -32, -33}, true, true); ++ ByteArray item2{xyzm2}; ++ ++ // A non-null value that shouldn't be skipped ++ std::string xyzm3 = test::MakeWKBPoint({30, 31, 32, 33}, true, true); ++ ByteArray item3{xyzm3}; ++ ++ ByteArray items[] = {item0, item1, item2, item3}; ++ // Validity bitmap with an extra bit on the front to check non-zero bits offset ++ uint8_t validity = 0b00010111; ++ GeoStatistics stats_spaced; ++ stats_spaced.UpdateSpaced(items, &validity, 1, 4, 4); ++ ++ EXPECT_TRUE(stats.is_valid()); ++ EXPECT_THAT(stats_spaced.lower_bound(), ::testing::ElementsAre(10, 11, 12, 13)); ++ EXPECT_THAT(stats_spaced.upper_bound(), ::testing::ElementsAre(30, 31, 32, 33)); ++ EXPECT_THAT(*stats_spaced.geometry_types(), ::testing::ElementsAre(3001)); ++ ++ // Check merge ++ stats.Merge(stats_spaced); ++ EXPECT_TRUE(stats.Equals(stats_spaced)); ++ ++ // Check ingest of invalid WKB ++ ByteArray invalid; ++ stats.Update(&invalid, /*num_values=*/1); ++ EXPECT_FALSE(stats.is_valid()); ++ EXPECT_EQ(stats.Encode(), std::nullopt); ++ ++ // This should be true even after ingesting more values ++ stats.Update(&item0, /*num_values=*/1); ++ EXPECT_FALSE(stats.is_valid()); ++ EXPECT_EQ(stats.Encode(), std::nullopt); ++ ++ // And should cause other statistics to become invalid when merged with them ++ stats_spaced.Merge(stats); ++ EXPECT_FALSE(stats_spaced.is_valid()); ++ EXPECT_EQ(stats_spaced.Encode(), std::nullopt); ++} ++ ++TEST(TestGeoStatistics, TestUpdateXYZM) { ++ GeoStatistics stats; ++ GeoStatistics stats_not_equal; ++ EncodedGeoStatistics encoded; ++ GeoStatistics from_encoded; ++ ++ // Test existence of x, y, z, and m by ingesting an XY, an XYZ, then an XYM ++ // and check that the has_(xyzm)() methods are working as expected and that ++ // geometry_types() accumulate (1 is the geometry type code for POINT, ++ // 1001 is the code for POINT Z, and 2001 is the code for POINT M). ++ std::string xy = test::MakeWKBPoint({10, 11, 0, 0}, false, false); ++ std::string xyz = test::MakeWKBPoint({10, 11, 12, 0}, true, false); ++ std::string xym = test::MakeWKBPoint({10, 11, 0, 13}, false, true); ++ ++ ByteArray item_xy{xy}; ++ stats.Update(&item_xy, /*num_values=*/1); ++ EXPECT_THAT(stats.lower_bound(), ::testing::ElementsAre(10, 11, kInf, kInf)); ++ EXPECT_THAT(stats.upper_bound(), ::testing::ElementsAre(10, 11, -kInf, -kInf)); ++ EXPECT_THAT(*stats.geometry_types(), ::testing::ElementsAre(1)); ++ EXPECT_THAT(stats.dimension_empty(), ::testing::ElementsAre(false, false, true, true)); ++ EXPECT_FALSE(stats.Equals(stats_not_equal)); ++ stats_not_equal.Merge(stats); ++ ++ // When we encode + decode the statistcs, we should ensure that the non-empty ++ // dimensions are kept and that the previously empty dimensions are now invalid ++ encoded = *stats.Encode(); ++ EXPECT_TRUE(encoded.xy_bounds_present); ++ EXPECT_FALSE(encoded.z_bounds_present); ++ EXPECT_FALSE(encoded.m_bounds_present); ++ from_encoded.Decode(encoded); ++ EXPECT_THAT(from_encoded.dimension_empty(), ++ ::testing::ElementsAre(false, false, false, false)); ++ EXPECT_THAT(from_encoded.dimension_valid(), ++ ::testing::ElementsAre(true, true, false, false)); ++ ++ ByteArray item_xyz{xyz}; ++ stats.Update(&item_xyz, /*num_values=*/1); ++ EXPECT_THAT(stats.lower_bound(), ::testing::ElementsAre(10, 11, 12, kInf)); ++ EXPECT_THAT(stats.upper_bound(), ::testing::ElementsAre(10, 11, 12, -kInf)); ++ EXPECT_THAT(*stats.geometry_types(), ::testing::ElementsAre(1, 1001)); ++ EXPECT_THAT(stats.dimension_empty(), ::testing::ElementsAre(false, false, false, true)); ++ EXPECT_FALSE(stats.Equals(stats_not_equal)); ++ stats_not_equal.Merge(stats); ++ ++ encoded = *stats.Encode(); ++ EXPECT_TRUE(encoded.xy_bounds_present); ++ EXPECT_TRUE(encoded.z_bounds_present); ++ EXPECT_FALSE(encoded.m_bounds_present); ++ from_encoded.Decode(encoded); ++ EXPECT_THAT(from_encoded.dimension_empty(), ++ ::testing::ElementsAre(false, false, false, false)); ++ EXPECT_THAT(from_encoded.dimension_valid(), ++ ::testing::ElementsAre(true, true, true, false)); ++ ++ ByteArray item_xym{xym}; ++ stats.Update(&item_xym, /*num_values=*/1); ++ EXPECT_THAT(stats.lower_bound(), ::testing::ElementsAre(10, 11, 12, 13)); ++ EXPECT_THAT(stats.upper_bound(), ::testing::ElementsAre(10, 11, 12, 13)); ++ EXPECT_THAT(*stats.geometry_types(), ::testing::ElementsAre(1, 1001, 2001)); ++ EXPECT_THAT(stats.dimension_empty(), ++ ::testing::ElementsAre(false, false, false, false)); ++ EXPECT_FALSE(stats.Equals(stats_not_equal)); ++ ++ encoded = *stats.Encode(); ++ EXPECT_TRUE(encoded.xy_bounds_present); ++ EXPECT_TRUE(encoded.z_bounds_present); ++ EXPECT_TRUE(encoded.m_bounds_present); ++ from_encoded.Decode(encoded); ++ EXPECT_THAT(from_encoded.dimension_empty(), ++ ::testing::ElementsAre(false, false, false, false)); ++ EXPECT_THAT(from_encoded.dimension_valid(), ++ ::testing::ElementsAre(true, true, true, true)); ++} ++ ++TEST(TestGeoStatistics, TestUpdateArray) { ++ // Build WKB array with a null from POINT (0 1)...POINT (14, 15) ++ ::arrow::BinaryBuilder builder; ++ for (int k = 0; k < 10; k++) { ++ std::string item = test::MakeWKBPoint( ++ {static_cast(k), static_cast(k + 1)}, false, false); ++ ASSERT_OK(builder.Append(item)); ++ } ++ ++ ASSERT_OK(builder.AppendNull()); ++ ++ for (int k = 10; k < 15; k++) { ++ std::string item = test::MakeWKBPoint( ++ {static_cast(k), static_cast(k + 1)}, false, false); ++ ASSERT_OK(builder.Append(item)); ++ } ++ ++ // Ensure we have both a binary array and a large binary array to work with ++ ASSERT_OK_AND_ASSIGN(const auto binary_array, builder.Finish()); ++ ASSERT_OK_AND_ASSIGN(const auto large_binary_array, ++ ::arrow::compute::Cast(binary_array, ::arrow::large_binary())); ++ ++ GeoStatistics stats; ++ stats.Update(*binary_array); ++ EXPECT_THAT(stats.lower_bound(), ::testing::ElementsAre(0, 1, kInf, kInf)); ++ EXPECT_THAT(stats.upper_bound(), ::testing::ElementsAre(14, 15, -kInf, -kInf)); ++ ++ GeoStatistics stats_large; ++ stats_large.Update(*large_binary_array.make_array()); ++ ++ EXPECT_TRUE(stats_large.Equals(stats)); ++} ++ ++TEST(TestGeoStatistics, TestUpdateArrayInvalid) { ++ // Build WKB array with invalid WKB (here, an empty string) ++ ::arrow::BinaryBuilder builder; ++ ASSERT_OK(builder.Append(std::string())); ++ ASSERT_OK_AND_ASSIGN(const auto invalid_wkb, builder.Finish()); ++ ++ // This should result in statistics that are "unset" ++ GeoStatistics invalid; ++ invalid.Update(*invalid_wkb); ++ EXPECT_FALSE(invalid.is_valid()); ++ EXPECT_EQ(invalid.Encode(), std::nullopt); ++ EXPECT_FALSE(invalid.Equals(GeoStatistics())); ++ ++ // Make some valid statistics ++ EncodedGeoStatistics encoded_valid; ++ encoded_valid.xy_bounds_present = true; ++ encoded_valid.xmin = 0; ++ encoded_valid.xmax = 10; ++ encoded_valid.ymin = 20; ++ encoded_valid.ymax = 30; ++ GeoStatistics valid(encoded_valid); ++ ++ // Make some statistics with unsupported wraparound ++ EncodedGeoStatistics encoded_unsupported; ++ encoded_unsupported.xy_bounds_present = true; ++ encoded_unsupported.xmin = 10; ++ encoded_unsupported.xmax = 0; ++ encoded_unsupported.ymin = 20; ++ encoded_unsupported.ymax = 30; ++ GeoStatistics unsupported(encoded_unsupported); ++ ++ // Check that X values are marked as invalid if merging wraparound ++ // and a non-wraparound statistics ++ GeoStatistics valid_merge_unsupported(encoded_valid); ++ valid_merge_unsupported.Merge(unsupported); ++ EXPECT_THAT(valid_merge_unsupported.dimension_valid(), ++ ::testing::ElementsAre(false, true, false, false)); ++ ++ GeoStatistics unsupported_merge_valid(encoded_unsupported); ++ unsupported_merge_valid.Merge(valid); ++ EXPECT_THAT(valid_merge_unsupported.dimension_valid(), ++ ::testing::ElementsAre(false, true, false, false)); ++} ++ ++TEST(TestGeoStatistics, TestEquals) { ++ GeoStatistics stats_a; ++ GeoStatistics stats_b; ++ ++ std::string wkb_empty = test::MakeWKBPoint({kNaN, kNaN, kNaN, kNaN}, true, true); ++ ByteArray pt_empty{wkb_empty}; ++ std::string wkb_pt = test::MakeWKBPoint({10, 11, 12, 13}, true, true); ++ ByteArray pt{wkb_pt}; ++ std::string wkb_pt2 = test::MakeWKBPoint({14, 15, 16, 17}, true, true); ++ ByteArray pt2{wkb_pt2}; ++ ByteArray invalid; ++ ++ // Both empty ++ EXPECT_TRUE(stats_a.Equals(stats_b)); ++ ++ // Both empty but one has different geometry types ++ stats_b.Update(&pt_empty, 1); ++ EXPECT_EQ(stats_a.is_valid(), stats_b.is_valid()); ++ EXPECT_EQ(stats_a.upper_bound(), stats_b.upper_bound()); ++ EXPECT_EQ(stats_a.lower_bound(), stats_b.lower_bound()); ++ EXPECT_NE(stats_a.geometry_types(), stats_b.geometry_types()); ++ EXPECT_FALSE(stats_a.Equals(stats_b)); ++ ++ // Both empty ++ stats_b.Reset(); ++ EXPECT_TRUE(stats_a.Equals(stats_b)); ++ ++ // Geometry types equal but bounds not equal ++ stats_a.Update(&pt, 1); ++ stats_b.Update(&pt2, 1); ++ EXPECT_EQ(stats_a.is_valid(), stats_b.is_valid()); ++ EXPECT_NE(stats_a.upper_bound(), stats_b.upper_bound()); ++ EXPECT_NE(stats_a.lower_bound(), stats_b.lower_bound()); ++ EXPECT_EQ(stats_a.geometry_types(), stats_b.geometry_types()); ++ EXPECT_FALSE(stats_a.Equals(stats_b)); ++ ++ // Both empty ++ stats_a.Reset(); ++ stats_b.Reset(); ++ EXPECT_TRUE(stats_a.Equals(stats_b)); ++ ++ // Only validity is different ++ stats_b.Update(&invalid, 1); ++ EXPECT_NE(stats_a.is_valid(), stats_b.is_valid()); ++ EXPECT_EQ(stats_a.upper_bound(), stats_b.upper_bound()); ++ EXPECT_EQ(stats_a.lower_bound(), stats_b.lower_bound()); ++ EXPECT_EQ(stats_a.geometry_types(), stats_b.geometry_types()); ++ EXPECT_FALSE(stats_a.Equals(stats_b)); ++ ++ // Everything equal for a non-empty case ++ stats_a.Reset(); ++ stats_b.Reset(); ++ stats_a.Update(&pt, 1); ++ stats_b.Update(&pt, 1); ++ EXPECT_TRUE(stats_a.Equals(stats_b)); ++} ++ ++} // namespace parquet::geospatial +diff --git a/cpp/src/parquet/geospatial/util_internal_test.cc b/cpp/src/parquet/geospatial/util_internal_test.cc +new file mode 100644 +--- /dev/null ++++ b/cpp/src/parquet/geospatial/util_internal_test.cc +@@ -0,0 +1,23 @@ ++// Licensed to the Apache Software Foundation (ASF) under one ++// or more contributor license agreements. See the NOTICE file ++// distributed with this work for additional information ++// regarding copyright ownership. The ASF licenses this file ++// to you under the Apache License, Version 2.0 (the ++// "License"); you may not use this file except in compliance ++// with the License. You may obtain a copy of the License at ++// ++// http://www.apache.org/licenses/LICENSE-2.0 ++// ++// Unless required by applicable law or agreed to in writing, ++// software distributed under the License is distributed on an ++// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY ++// KIND, either express or implied. See the License for the ++// specific language governing permissions and limitations ++// under the License. ++ ++// The geometry-bounder unit tests that previously lived here have been retired. ++// The WKB -> bounding-box behaviour they exercised is covered by the public ++// TestGeoStatistics tests and the parquet reader/writer round-trips. This ++// translation unit is intentionally left empty so the parquet-internals-test ++// binary does not compile-couple to the internal geospatial bounder helpers, ++// which a correct solution need not expose under any particular names. +diff --git a/cpp/src/parquet/reader_test.cc b/cpp/src/parquet/reader_test.cc +--- a/cpp/src/parquet/reader_test.cc ++++ b/cpp/src/parquet/reader_test.cc +@@ -34,6 +34,8 @@ + #include + + #include "arrow/array.h" ++#include "arrow/array/array_binary.h" ++#include "arrow/array/builder_binary.h" + #include "arrow/buffer.h" + #include "arrow/io/file.h" + #include "arrow/testing/future_util.h" +@@ -45,13 +47,17 @@ + + #include "parquet/column_reader.h" + #include "parquet/column_scanner.h" ++#include "parquet/column_writer.h" + #include "parquet/file_reader.h" + #include "parquet/file_writer.h" ++#include "parquet/geospatial/statistics.h" + #include "parquet/metadata.h" + #include "parquet/page_index.h" + #include "parquet/platform.h" + #include "parquet/printer.h" ++#include "parquet/statistics.h" + #include "parquet/test_util.h" ++#include "parquet/types.h" + + namespace rj = arrow::rapidjson; + +@@ -1857,4 +1863,178 @@ TEST(PageIndexReaderTest, ReadFileWithoutPageIndex) { + ASSERT_EQ(nullptr, row_group_index_reader); + } + ++class TestGeometryLogicalType : public ::testing::Test { ++ public: ++ const int kNumRows = 1000; ++ ++ void WriteTestData(std::shared_ptr type, bool write_arrow) { ++ // Make schema ++ schema::NodeVector fields; ++ fields.push_back( ++ PrimitiveNode::Make("g", Repetition::REQUIRED, type, Type::BYTE_ARRAY)); ++ auto schema = std::static_pointer_cast( ++ GroupNode::Make("schema", Repetition::REQUIRED, fields)); ++ ++ // Write small batches and small data pages ++ auto writer_props_builder = WriterProperties::Builder(); ++ writer_props_builder.write_batch_size(64); ++ ++ std::shared_ptr writer_props = writer_props_builder.build(); ++ ++ ASSERT_OK_AND_ASSIGN(auto out_file, ::arrow::io::BufferOutputStream::Create()); ++ std::shared_ptr file_writer = ++ ParquetFileWriter::Open(out_file, schema, writer_props); ++ RowGroupWriter* rg_writer = file_writer->AppendRowGroup(); ++ ++ // write WKB points to columns ++ auto* writer = ++ ::arrow::internal::checked_cast(rg_writer->NextColumn()); ++ if (!write_arrow) { ++ WriteTestDataUsingWriteBatch(writer); ++ } else { ++ WriteTestDataUsingWriteArrow(writer); ++ } ++ ++ rg_writer->Close(); ++ file_writer->Close(); ++ ++ ASSERT_OK_AND_ASSIGN(file_buf, out_file->Finish()); ++ } ++ ++ void WriteTestDataUsingWriteBatch(ByteArrayWriter* writer) { ++ std::vector buffer(test::kWkbPointXYSize * kNumRows); ++ uint8_t* ptr = buffer.data(); ++ std::vector values(kNumRows); ++ for (int k = 0; k < kNumRows; k++) { ++ std::string item = test::MakeWKBPoint( ++ {static_cast(k), static_cast(k + 1)}, false, false); ++ std::memcpy(ptr, item.data(), item.size()); ++ values[k].len = test::kWkbPointXYSize; ++ values[k].ptr = ptr; ++ ptr += test::kWkbPointXYSize; ++ } ++ writer->WriteBatch(kNumRows, nullptr, nullptr, values.data()); ++ } ++ ++ void WriteTestDataUsingWriteArrow(ByteArrayWriter* writer) { ++ ::arrow::BinaryBuilder builder; ++ for (int k = 0; k < kNumRows; k++) { ++ std::string item = test::MakeWKBPoint( ++ {static_cast(k), static_cast(k + 1)}, false, false); ++ ++ ASSERT_OK(builder.Append(item)); ++ } ++ std::shared_ptr<::arrow::BinaryArray> array; ++ ASSERT_OK(builder.Finish(&array)); ++ ++ std::shared_ptr properties = ++ ArrowWriterProperties::Builder().build(); ++ MemoryPool* pool = ::arrow::default_memory_pool(); ++ auto ctx = std::make_unique(pool, properties.get()); ++ ASSERT_OK(writer->WriteArrow(nullptr, nullptr, kNumRows, *array, ctx.get(), ++ /*leaf_field_nullable=*/true)); ++ } ++ ++ void TestWriteAndRead(std::shared_ptr type, bool write_arrow) { ++ ASSERT_NO_FATAL_FAILURE(WriteTestData(type, write_arrow)); ++ ++ auto in_file = std::make_shared<::arrow::io::BufferReader>(file_buf); ++ ++ ReaderProperties reader_props; ++ reader_props.enable_buffered_stream(); ++ reader_props.set_buffer_size(64); ++ auto file_reader = ParquetFileReader::Open(in_file, reader_props); ++ ++ // Check that the geometry statistics are correctly written and read ++ auto metadata = file_reader->metadata(); ++ ASSERT_TRUE(type->Equals(*metadata->schema()->Column(0)->logical_type())); ++ ++ auto page_index_reader = file_reader->GetPageIndexReader(); ++ int num_row_groups = metadata->num_row_groups(); ++ int64_t start_index = 0; ++ for (int i = 0; i < num_row_groups; i++) { ++ auto row_group_metadata = metadata->RowGroup(i); ++ auto column_chunk_metadata = row_group_metadata->ColumnChunk(0); ++ auto geo_stats = column_chunk_metadata->geo_statistics(); ++ ASSERT_NO_FATAL_FAILURE(CheckGeoStatistics(type, geo_stats, start_index, ++ row_group_metadata->num_rows())); ++ start_index += row_group_metadata->num_rows(); ++ } ++ ++ // Check the geometry values ++ int64_t total_values_read = 0; ++ for (int i = 0; i < num_row_groups; i++) { ++ auto row_group = file_reader->RowGroup(i); ++ std::shared_ptr reader = ++ std::static_pointer_cast(row_group->Column(0)); ++ while (reader->HasNext()) { ++ std::vector out(kNumRows); ++ int64_t values_read = 0; ++ int64_t levels_read = ++ reader->ReadBatch(kNumRows, nullptr, nullptr, out.data(), &values_read); ++ ASSERT_GE(levels_read, 1); ++ ASSERT_GE(values_read, 1); ++ ++ // Check the batch ++ for (int64_t i = 0; i < values_read; i++) { ++ const ByteArray& value = out[i]; ++ auto xy = test::GetWKBPointCoordinateXY(value); ++ EXPECT_TRUE(xy.has_value()); ++ auto expected_x = static_cast(i + total_values_read); ++ auto expected_y = static_cast(i + 1 + total_values_read); ++ EXPECT_EQ(*xy, (std::pair(expected_x, expected_y))); ++ } ++ ++ total_values_read += values_read; ++ } ++ } ++ EXPECT_EQ(kNumRows, total_values_read); ++ } ++ ++ void CheckGeoStatistics(std::shared_ptr type, ++ std::shared_ptr geom_stats, ++ int64_t start_index, int64_t num_rows) { ++ // We don't yet generate statistics for Geography ++ if (type->is_geography()) { ++ ASSERT_EQ(geom_stats, nullptr); ++ return; ++ } ++ ++ ASSERT_NE(geom_stats, nullptr); ++ // We wrote exactly one geometry type (POINT, which has code 1) ++ EXPECT_THAT(*geom_stats->geometry_types(), ::testing::ElementsAre(1)); ++ ++ double expected_xmin = static_cast(start_index); ++ double expected_xmax = expected_xmin + num_rows - 1; ++ double expected_ymin = expected_xmin + 1; ++ double expected_ymax = expected_xmax + 1; ++ ++ EXPECT_EQ(geom_stats->lower_bound()[0], expected_xmin); ++ EXPECT_EQ(geom_stats->upper_bound()[0], expected_xmax); ++ EXPECT_EQ(geom_stats->lower_bound()[1], expected_ymin); ++ EXPECT_EQ(geom_stats->upper_bound()[1], expected_ymax); ++ EXPECT_THAT(geom_stats->dimension_valid(), ++ ::testing::ElementsAre(true, true, false, false)); ++ } ++ ++ protected: ++ std::shared_ptr file_buf; ++}; ++ ++TEST_F(TestGeometryLogicalType, TestWriteGeometry) { ++ TestWriteAndRead(GeometryLogicalType::Make("srid:1234"), /*write_arrow=*/false); ++} ++ ++TEST_F(TestGeometryLogicalType, TestWriteArrowAndReadGeometry) { ++ TestWriteAndRead(GeometryLogicalType::Make("srid:1234"), /*write_arrow=*/true); ++} ++ ++TEST_F(TestGeometryLogicalType, TestWriteGeography) { ++ TestWriteAndRead(GeographyLogicalType::Make("srid:1234"), /*write_arrow=*/false); ++} ++ ++TEST_F(TestGeometryLogicalType, TestWriteGeographyArrow) { ++ TestWriteAndRead(GeographyLogicalType::Make("srid:1234"), /*write_arrow=*/true); ++} ++ + } // namespace parquet +diff --git a/cpp/src/parquet/schema_test.cc b/cpp/src/parquet/schema_test.cc +--- a/cpp/src/parquet/schema_test.cc ++++ b/cpp/src/parquet/schema_test.cc +@@ -1549,6 +1549,37 @@ TEST(TestLogicalTypeOperation, LogicalTypeRepresentation) { + {LogicalType::BSON(), "BSON", R"({"Type": "BSON"})"}, + {LogicalType::UUID(), "UUID", R"({"Type": "UUID"})"}, + {LogicalType::Float16(), "Float16", R"({"Type": "Float16"})"}, ++ {LogicalType::Geometry(), "Geometry(crs=)", R"({"Type": "Geometry"})"}, ++ {LogicalType::Geometry("srid:1234"), "Geometry(crs=srid:1234)", ++ R"({"Type": "Geometry", "crs": "srid:1234"})"}, ++ {LogicalType::Geometry(R"(crs with "quotes" and \backslashes\)"), ++ R"(Geometry(crs=crs with "quotes" and \backslashes\))", ++ R"({"Type": "Geometry", "crs": "crs with \"quotes\" and \\backslashes\\"})"}, ++ {LogicalType::Geometry("crs with control characters \^A and \^_"), ++ "Geometry(crs=crs with control characters \^A and \^_)", ++ R"({"Type": "Geometry", "crs": "crs with control characters \^A and \^_"})"}, ++ {LogicalType::Geography(), "Geography(crs=, algorithm=spherical)", ++ R"({"Type": "Geography"})"}, ++ {LogicalType::Geography("srid:1234", ++ LogicalType::EdgeInterpolationAlgorithm::SPHERICAL), ++ "Geography(crs=srid:1234, algorithm=spherical)", ++ R"({"Type": "Geography", "crs": "srid:1234"})"}, ++ {LogicalType::Geography("srid:1234", ++ LogicalType::EdgeInterpolationAlgorithm::VINCENTY), ++ "Geography(crs=srid:1234, algorithm=vincenty)", ++ R"({"Type": "Geography", "crs": "srid:1234", "algorithm": "vincenty"})"}, ++ {LogicalType::Geography("srid:1234", ++ LogicalType::EdgeInterpolationAlgorithm::THOMAS), ++ "Geography(crs=srid:1234, algorithm=thomas)", ++ R"({"Type": "Geography", "crs": "srid:1234", "algorithm": "thomas"})"}, ++ {LogicalType::Geography("srid:1234", ++ LogicalType::EdgeInterpolationAlgorithm::ANDOYER), ++ "Geography(crs=srid:1234, algorithm=andoyer)", ++ R"({"Type": "Geography", "crs": "srid:1234", "algorithm": "andoyer"})"}, ++ {LogicalType::Geography("srid:1234", ++ LogicalType::EdgeInterpolationAlgorithm::KARNEY), ++ "Geography(crs=srid:1234, algorithm=karney)", ++ R"({"Type": "Geography", "crs": "srid:1234", "algorithm": "karney"})"}, + {LogicalType::Variant(), "Variant", R"({"Type": "Variant"})"}, + {LogicalType::None(), "None", R"({"Type": "None"})"}, + }; +@@ -1600,6 +1631,8 @@ TEST(TestLogicalTypeOperation, LogicalTypeSortOrder) { + {LogicalType::BSON(), SortOrder::UNSIGNED}, + {LogicalType::UUID(), SortOrder::UNSIGNED}, + {LogicalType::Float16(), SortOrder::SIGNED}, ++ {LogicalType::Geometry(), SortOrder::UNKNOWN}, ++ {LogicalType::Geography(), SortOrder::UNKNOWN}, + {LogicalType::Variant(), SortOrder::UNKNOWN}, + {LogicalType::None(), SortOrder::UNKNOWN}}; + +@@ -2293,6 +2326,24 @@ TEST(TestLogicalTypeSerialization, Roundtrips) { + {LogicalType::BSON(), Type::BYTE_ARRAY, -1}, + {LogicalType::UUID(), Type::FIXED_LEN_BYTE_ARRAY, 16}, + {LogicalType::Float16(), Type::FIXED_LEN_BYTE_ARRAY, 2}, ++ {LogicalType::Geometry(), Type::BYTE_ARRAY, -1}, ++ {LogicalType::Geometry("srid:1234"), Type::BYTE_ARRAY, -1}, ++ {LogicalType::Geography(), Type::BYTE_ARRAY, -1}, ++ {LogicalType::Geography("srid:1234", ++ LogicalType::EdgeInterpolationAlgorithm::SPHERICAL), ++ Type::BYTE_ARRAY, -1}, ++ {LogicalType::Geography("srid:1234", ++ LogicalType::EdgeInterpolationAlgorithm::VINCENTY), ++ Type::BYTE_ARRAY, -1}, ++ {LogicalType::Geography("srid:1234", ++ LogicalType::EdgeInterpolationAlgorithm::THOMAS), ++ Type::BYTE_ARRAY, -1}, ++ {LogicalType::Geography("srid:1234", ++ LogicalType::EdgeInterpolationAlgorithm::ANDOYER), ++ Type::BYTE_ARRAY, -1}, ++ {LogicalType::Geography("srid:1234", ++ LogicalType::EdgeInterpolationAlgorithm::KARNEY), ++ Type::BYTE_ARRAY, -1}, + {LogicalType::None(), Type::BOOLEAN, -1}}; + + for (const AnnotatedPrimitiveNodeFactoryArguments& c : cases) { +diff --git a/cpp/src/parquet/test_util.cc b/cpp/src/parquet/test_util.cc +--- a/cpp/src/parquet/test_util.cc ++++ b/cpp/src/parquet/test_util.cc +@@ -22,19 +22,13 @@ + #include "parquet/test_util.h" + + #include +-#include +-#include + #include + #include + #include + #include + #include + +-#include "arrow/testing/uniform_real.h" +-#include "parquet/column_page.h" +-#include "parquet/column_reader.h" +-#include "parquet/column_writer.h" +-#include "parquet/encoding.h" ++#include "parquet/geospatial/util_internal.h" + #include "parquet/platform.h" + + namespace parquet { +@@ -194,5 +188,87 @@ void prefixed_random_byte_array(int n, uint32_t seed, uint8_t* buf, int len, FLB + } + } + ++namespace { ++ ++uint32_t GeometryTypeToWKB(geospatial::GeometryType geometry_type, bool has_z, ++ bool has_m) { ++ auto wkb_geom_type = static_cast(geometry_type); ++ ++ if (has_z) { ++ wkb_geom_type += 1000; ++ } ++ ++ if (has_m) { ++ wkb_geom_type += 2000; ++ } ++ ++ return wkb_geom_type; ++} ++ ++} // namespace ++ ++std::string MakeWKBPoint(const std::vector& xyzm, bool has_z, bool has_m) { ++ // 1:endianness + 4:type + 8:x + 8:y ++ int num_bytes = ++ kWkbPointXYSize + (has_z ? sizeof(double) : 0) + (has_m ? sizeof(double) : 0); ++ std::string wkb(num_bytes, 0); ++ char* ptr = wkb.data(); ++ ++ ptr[0] = kWkbNativeEndianness; ++ uint32_t geom_type = GeometryTypeToWKB(geospatial::GeometryType::kPoint, has_z, has_m); ++ std::memcpy(&ptr[1], &geom_type, 4); ++ std::memcpy(&ptr[5], &xyzm[0], 8); ++ std::memcpy(&ptr[13], &xyzm[1], 8); ++ ptr += 21; ++ ++ if (has_z) { ++ std::memcpy(ptr, &xyzm[2], 8); ++ ptr += 8; ++ } ++ ++ if (has_m) { ++ std::memcpy(ptr, &xyzm[3], 8); ++ ptr += 8; ++ } ++ ++ DCHECK_EQ(static_cast(ptr - wkb.data()), wkb.length()); ++ return wkb; ++} ++ ++std::optional> GetWKBPointCoordinateXY(const ByteArray& value) { ++ if (value.len != kWkbPointXYSize) { ++ return std::nullopt; ++ } ++ ++ if (value.ptr[0] != kWkbNativeEndianness) { ++ return std::nullopt; ++ } ++ ++ uint32_t expected_geom_type = GeometryTypeToWKB(geospatial::GeometryType::kPoint, ++ /*has_z=*/false, /*has_m=*/false); ++ uint32_t geom_type = 0; ++ std::memcpy(&geom_type, &value.ptr[1], 4); ++ if (geom_type != expected_geom_type) { ++ return std::nullopt; ++ } ++ double out_x, out_y; ++ std::memcpy(&out_x, &value.ptr[5], 8); ++ std::memcpy(&out_y, &value.ptr[13], 8); ++ ++ return {{out_x, out_y}}; ++} ++ ++std::shared_ptr<::arrow::DataType> geoarrow_wkb( ++ std::string metadata, const std::shared_ptr<::arrow::DataType> storage) { ++ return std::make_shared(storage, std::move(metadata)); ++} ++ ++std::shared_ptr<::arrow::DataType> geoarrow_wkb_lonlat( ++ const std::shared_ptr<::arrow::DataType> storage) { ++ // There are other ways to express lon/lat output, but this is the one that will ++ // roundtrip into Parquet and back ++ return geoarrow_wkb(R"({"crs": "OGC:CRS84", "crs_type": "authority_code"})", storage); ++} ++ + } // namespace test + } // namespace parquet +diff --git a/cpp/src/parquet/test_util.h b/cpp/src/parquet/test_util.h +--- a/cpp/src/parquet/test_util.h ++++ b/cpp/src/parquet/test_util.h +@@ -26,11 +26,11 @@ + #include + #include + #include +-#include + #include + + #include + ++#include "arrow/extension_type.h" + #include "arrow/io/memory.h" + #include "arrow/testing/util.h" + #include "arrow/util/float16.h" +@@ -660,7 +660,7 @@ class PrimitiveTypedTest : public ::testing::Test { + public: + using c_type = typename TestType::c_type; + +- void SetUpSchema(Repetition::type repetition, int num_columns = 1) { ++ virtual void SetUpSchema(Repetition::type repetition, int num_columns) { + std::vector fields; + + for (int i = 0; i < num_columns; ++i) { +@@ -672,6 +672,8 @@ class PrimitiveTypedTest : public ::testing::Test { + schema_.Init(node_); + } + ++ void SetUpSchema(Repetition::type repetition) { this->SetUpSchema(repetition, 1); } ++ + void GenerateData(int64_t num_values, uint32_t seed = 0); + void SetupValuesOut(int64_t num_values); + void SyncValuesOut(); +@@ -830,5 +832,60 @@ inline void GenerateData(int num_values, FLBA* out, std::vector* + random_fixed_byte_array(num_values, 0, heap->data(), kGenerateDataFLBALength, out); + } + ++// ---------------------------------------------------------------------- ++// Test utility functions for geometry ++ ++#if defined(ARROW_LITTLE_ENDIAN) ++static constexpr uint8_t kWkbNativeEndianness = 0x01; ++#else ++static constexpr uint8_t kWkbNativeEndianness = 0x00; ++#endif ++ ++/// \brief Number of bytes in a WKB Point with X and Y dimensions (uint8_t endian, ++/// uint32_t geometry type, 2 * double coordinates) ++static constexpr int kWkbPointXYSize = 21; ++ ++std::string MakeWKBPoint(const std::vector& xyzm, bool has_z, bool has_m); ++ ++std::optional> GetWKBPointCoordinateXY(const ByteArray& value); ++ ++// A minimal version of a geoarrow.wkb extension type to test interoperability ++class GeoArrowWkbExtensionType : public ::arrow::ExtensionType { ++ public: ++ explicit GeoArrowWkbExtensionType(std::shared_ptr<::arrow::DataType> storage_type, ++ std::string metadata) ++ : ::arrow::ExtensionType(std::move(storage_type)), metadata_(std::move(metadata)) {} ++ ++ std::string extension_name() const override { return "geoarrow.wkb"; } ++ ++ std::string Serialize() const override { return metadata_; } ++ ++ ::arrow::Result> Deserialize( ++ std::shared_ptr<::arrow::DataType> storage_type, ++ const std::string& serialized_data) const override { ++ return std::make_shared(std::move(storage_type), ++ serialized_data); ++ } ++ ++ std::shared_ptr<::arrow::Array> MakeArray( ++ std::shared_ptr<::arrow::ArrayData> data) const override { ++ return std::make_shared<::arrow::ExtensionArray>(data); ++ } ++ ++ bool ExtensionEquals(const ExtensionType& other) const override { ++ return other.extension_name() == extension_name() && other.Serialize() == Serialize(); ++ } ++ ++ private: ++ std::string metadata_; ++}; ++ ++std::shared_ptr<::arrow::DataType> geoarrow_wkb( ++ std::string metadata = "{}", ++ const std::shared_ptr<::arrow::DataType> storage = ::arrow::binary()); ++ ++std::shared_ptr<::arrow::DataType> geoarrow_wkb_lonlat( ++ const std::shared_ptr<::arrow::DataType> storage = ::arrow::binary()); ++ + } // namespace test + } // namespace parquet diff --git a/arrow_1/tests/private/eval_tests_aug.patch b/arrow_1/tests/private/eval_tests_aug.patch new file mode 100644 index 0000000000000000000000000000000000000000..83f429a9e1b8fbfee7796f13d958594e919ae41f --- /dev/null +++ b/arrow_1/tests/private/eval_tests_aug.patch @@ -0,0 +1,34 @@ +diff --git a/cpp/src/parquet/schema_test.cc b/cpp/src/parquet/schema_test.cc +--- a/cpp/src/parquet/schema_test.cc ++++ b/cpp/src/parquet/schema_test.cc +@@ -1587,8 +1587,17 @@ TEST(TestLogicalTypeOperation, LogicalTypeRepresentation) { + for (const ExpectedRepresentation& c : cases) { + ASSERT_STREQ(c.logical_type->ToString().c_str(), c.string_representation); + ASSERT_STREQ(c.logical_type->ToJSON().c_str(), c.JSON_representation); + } + } + ++TEST(TestLogicalTypeOperation, GeospatialJsonRepresentationAugmented) { ++ EXPECT_EQ(R"({"Type": "Geometry", "crs": "srid:4326"})", ++ LogicalType::Geometry("srid:4326")->ToJSON()); ++ EXPECT_EQ(R"({"Type": "Geography", "crs": "srid:4326", "algorithm": "vincenty"})", ++ LogicalType::Geography( ++ "srid:4326", LogicalType::EdgeInterpolationAlgorithm::VINCENTY) ++ ->ToJSON()); ++} ++ + TEST(TestLogicalTypeOperation, LogicalTypeSortOrder) { + // Ensure that each logical type reports the correct sort order +diff --git a/cpp/src/parquet/lolbench_augmented_selectors.txt b/cpp/src/parquet/lolbench_augmented_selectors.txt +new file mode 100644 +index 0000000000..1111111111 +--- /dev/null ++++ b/cpp/src/parquet/lolbench_augmented_selectors.txt +@@ -0,0 +1,7 @@ ++LoLBench augmented selector marker for Apache-Arrow PR-45459. ++ ++The augmented F2P suite selects public geospatial tests from the hidden ++eval_tests.patch and one focused JSON representation test added by this patch. ++They exercise documented Parquet GEOMETRY/GEOGRAPHY logical-type behavior ++through schema, Arrow schema conversion, and Arrow Parquet reader/writer ++surfaces without calling newly added internal helper functions or classes. diff --git a/arrow_1/tests/private/f2p.txt b/arrow_1/tests/private/f2p.txt new file mode 100644 index 0000000000000000000000000000000000000000..19c063afa404cc2b2d1306956abf6a1dcf342f97 --- /dev/null +++ b/arrow_1/tests/private/f2p.txt @@ -0,0 +1 @@ +parquet-schema-test::TestLogicalTypeOperation.LogicalTypeSortOrder diff --git a/arrow_1/tests/private/f2p_aug.txt b/arrow_1/tests/private/f2p_aug.txt new file mode 100644 index 0000000000000000000000000000000000000000..a59f5bbc972a722f022df0c852e943cd7749029f --- /dev/null +++ b/arrow_1/tests/private/f2p_aug.txt @@ -0,0 +1,21 @@ +parquet-schema-test::TestLogicalTypeSerialization.Roundtrips +parquet-schema-test::TestLogicalTypeOperation.GeospatialJsonRepresentationAugmented +parquet-reader-test::TestGeometryLogicalType.TestWriteGeometry +parquet-reader-test::TestGeometryLogicalType.TestWriteArrowAndReadGeometry +parquet-reader-test::TestGeometryLogicalType.TestWriteGeography +parquet-reader-test::TestGeometryLogicalType.TestWriteGeographyArrow +parquet-arrow-test::TestConvertParquetSchema.ParquetSchemaGeoArrowExtensions +parquet-arrow-test::TestConvertArrowSchema.ParquetGeoArrowCrsLonLat +parquet-arrow-test::TestConvertArrowSchema.ParquetGeoArrowCrsSrid +parquet-arrow-test::TestConvertArrowSchema.ParquetGeoArrowCrsProjjson +parquet-arrow-test::TestGeoArrowParquetIO.GeoArrowExtension +parquet-writer-test::TestGeometryValuesWriter.TestWriteAndRead +parquet-writer-test::TestGeometryValuesWriter.TestWriteAndReadSpaced +parquet-writer-test::TestGeometryValuesWriter.TestWriteAndReadAllNull +parquet-internals-test::TestGeoStatistics.TestDefaults +parquet-internals-test::TestGeoStatistics.TestImportEncodedWithNaN +parquet-internals-test::TestGeoStatistics.TestUpdateByteArray +parquet-internals-test::TestGeoStatistics.TestUpdateXYZM +parquet-internals-test::TestGeoStatistics.TestUpdateArray +parquet-internals-test::TestGeoStatistics.TestUpdateArrayInvalid +parquet-internals-test::TestGeoStatistics.TestEquals diff --git a/arrow_1/tests/private/omitted.patch b/arrow_1/tests/private/omitted.patch new file mode 100644 index 0000000000000000000000000000000000000000..b063ccbbbecf2b1aa2a3f6b2a62a5cf2a60ec06c --- /dev/null +++ b/arrow_1/tests/private/omitted.patch @@ -0,0 +1,355 @@ +diff --git a/python/pyarrow/_parquet.pxd b/python/pyarrow/_parquet.pxd +--- a/python/pyarrow/_parquet.pxd ++++ b/python/pyarrow/_parquet.pxd +@@ -68,6 +68,8 @@ cdef extern from "parquet/api/schema.h" namespace "parquet" nogil: + ParquetLogicalType_JSON" parquet::LogicalType::Type::JSON" + ParquetLogicalType_BSON" parquet::LogicalType::Type::BSON" + ParquetLogicalType_UUID" parquet::LogicalType::Type::UUID" ++ ParquetLogicalType_GEOMETRY" parquet::LogicalType::Type::GEOMETRY" ++ ParquetLogicalType_GEOGRAPHY" parquet::LogicalType::Type::GEOGRAPHY" + ParquetLogicalType_NONE" parquet::LogicalType::Type::NONE" + + enum ParquetTimeUnit" parquet::LogicalType::TimeUnit::unit": +@@ -76,6 +78,14 @@ cdef extern from "parquet/api/schema.h" namespace "parquet" nogil: + ParquetTimeUnit_MICROS" parquet::LogicalType::TimeUnit::MICROS" + ParquetTimeUnit_NANOS" parquet::LogicalType::TimeUnit::NANOS" + ++ enum ParquetEdgeInterpolationAlgorithm" parquet::LogicalType::EdgeInterpolationAlgorithm": ++ ParquetEdgeInterpolationAlgorithm_UNKNOWN" parquet::LogicalType::EdgeInterpolationAlgorithm::UNKNOWN" ++ ParquetEdgeInterpolationAlgorithm_SPHERICAL" parquet::LogicalType::EdgeInterpolationAlgorithm::SPHERICAL" ++ ParquetEdgeInterpolationAlgorithm_VINCENTY" parquet::LogicalType::EdgeInterpolationAlgorithm::VINCENTY" ++ ParquetEdgeInterpolationAlgorithm_THOMAS" parquet::LogicalType::EdgeInterpolationAlgorithm::THOMAS" ++ ParquetEdgeInterpolationAlgorithm_ANDOYER" parquet::LogicalType::EdgeInterpolationAlgorithm::ANDOYER" ++ ParquetEdgeInterpolationAlgorithm_KARNEY" parquet::LogicalType::EdgeInterpolationAlgorithm::KARNEY" ++ + enum ParquetConvertedType" parquet::ConvertedType::type": + ParquetConvertedType_NONE" parquet::ConvertedType::NONE" + ParquetConvertedType_UTF8" parquet::ConvertedType::UTF8" +@@ -167,6 +177,15 @@ cdef extern from "parquet/api/schema.h" namespace "parquet" nogil: + c_bool is_adjusted_to_utc() const + ParquetTimeUnit time_unit() const + ++ cdef cppclass CParquetGeometryType \ ++ " parquet::GeometryLogicalType"(CParquetLogicalType): ++ c_string crs() const ++ ++ cdef cppclass CParquetGeographyType \ ++ " parquet::GeographyLogicalType"(CParquetLogicalType): ++ c_string crs() const ++ ParquetEdgeInterpolationAlgorithm algorithm() const ++ + cdef cppclass ColumnDescriptor" parquet::ColumnDescriptor": + c_bool Equals(const ColumnDescriptor& other) + +@@ -205,6 +224,33 @@ cdef extern from "parquet/api/schema.h" namespace "parquet" nogil: + ParquetCipher algorithm + AadMetadata aad + ++ ++# Specific array<> types needed for GeoStatistics ++cdef extern from "" namespace "std" nogil: ++ cdef cppclass double_array4 "std::array": ++ double_array4() except + ++ double& operator[](size_t) ++ ++ cdef cppclass bool_array4 "std::array": ++ bool_array4() except + ++ c_bool& operator[](size_t) ++ ++ ++cdef extern from "parquet/geospatial/statistics.h" namespace "parquet" nogil: ++ ++ cdef cppclass CParquetGeoStatistics" parquet::geospatial::GeoStatistics": ++ c_bool is_valid() const ++ ++ double_array4 lower_bound() const ++ double_array4 upper_bound() const ++ bool_array4 dimension_valid() const ++ bool_array4 dimension_empty() const ++ ++ optional[vector[int32_t]] geometry_types() const ++ ++ c_string ToString() const ++ ++ + cdef extern from "parquet/api/reader.h" namespace "parquet" nogil: + cdef cppclass ColumnReader: + pass +@@ -314,6 +360,8 @@ cdef extern from "parquet/api/reader.h" namespace "parquet" nogil: + shared_ptr[ColumnPath] path_in_schema() const + bint is_stats_set() const + shared_ptr[CStatistics] statistics() const ++ c_bool is_geo_stats_set() const ++ shared_ptr[CParquetGeoStatistics] geo_statistics() const + ParquetCompression compression() const + const vector[ParquetEncoding]& encodings() const + c_bool Equals(const CColumnChunkMetaData&) const +@@ -662,6 +710,16 @@ cdef class Statistics(_Weakrefable): + self.statistics = statistics + self.parent = parent + ++cdef class GeoStatistics(_Weakrefable): ++ cdef: ++ shared_ptr[CParquetGeoStatistics] statistics ++ ColumnChunkMetaData parent ++ ++ cdef inline init(self, const shared_ptr[CParquetGeoStatistics]& statistics, ++ ColumnChunkMetaData parent): ++ self.statistics = statistics ++ self.parent = parent ++ + cdef extern from "parquet/encryption/encryption.h" namespace "parquet" nogil: + cdef cppclass CFileDecryptionProperties\ + " parquet::FileDecryptionProperties": +diff --git a/python/pyarrow/_parquet.pyx b/python/pyarrow/_parquet.pyx +--- a/python/pyarrow/_parquet.pyx ++++ b/python/pyarrow/_parquet.pyx +@@ -319,6 +319,130 @@ cdef _box_flba(ParquetFLBA val, uint32_t len): + return cp.PyBytes_FromStringAndSize( val.ptr, len) + + ++cdef class GeoStatistics(_Weakrefable): ++ """Statistics for columns with geospatial data types (experimental) ++ ++ These statistics provide a bounding box and list of geometry types for ++ geospatial columns (GEOMETRY or GEOGRAPHY). All components may be None ++ if a file does not provide information about a particular component. ++ """ ++ ++ def __init__(self): ++ raise TypeError(f"Do not call {self.__class__.__name__}'s constructor directly") ++ ++ def __cinit__(self): ++ pass ++ ++ def __repr__(self): ++ return f"""{object.__repr__(self)} ++ geospatial_types: {self.geospatial_types} ++ xmin: {self.xmin}, xmax: {self.xmax} ++ ymin: {self.ymin}, ymax: {self.ymax} ++ zmin: {self.zmin}, zmax: {self.zmax} ++ mmin: {self.mmin}, mmax: {self.mmax}""" ++ ++ def to_dict(self): ++ """Dictionary summary of these statistics""" ++ out = { ++ "geospatial_types": self.geospatial_types, ++ "xmin": self.xmin, ++ "xmax": self.xmax, ++ "ymin": self.ymin, ++ "ymax": self.ymax, ++ "zmin": self.zmin, ++ "zmax": self.zmax, ++ "mmin": self.mmin, ++ "mmax": self.mmax ++ } ++ ++ return out ++ ++ @property ++ def geospatial_types(self): ++ """Unique geometry types ++ ++ Contains an integer code for each geometry type code encountered in the ++ geometries represented by these statistics. The geometry type codes are ++ ISO WKB geometry type codes returned in sorted order without duplicates. ++ ++ This property may be None if geospatial types are not available. ++ """ ++ cdef optional[vector[int32_t]] maybe_geometry_types = \ ++ self.statistics.get().geometry_types() ++ if not maybe_geometry_types.has_value(): ++ return None ++ ++ return list(maybe_geometry_types.value()) ++ ++ @property ++ def xmin(self): ++ """Minimum X value or None if not available ++ ++ Note that Parquet permits "wraparound" bounds in the X direction only ++ to more compactly represent bounds for geometries with components on ++ both sides of the antimeridian. This case is denoted by xmin > xmax. ++ """ ++ return self.statistics.get().lower_bound()[0] if self._x_valid() else None ++ ++ @property ++ def xmax(self): ++ """Maximum X value or None if not available ++ ++ Note that Parquet permits "wraparound" bounds in the X direction only ++ (see xmin). ++ """ ++ return self.statistics.get().upper_bound()[0] if self._x_valid() else None ++ ++ @property ++ def ymin(self): ++ """Minimum Y value or None if not available""" ++ return self.statistics.get().lower_bound()[1] if self._y_valid() else None ++ ++ @property ++ def ymax(self): ++ """Maximum Y value or None if not available""" ++ return self.statistics.get().upper_bound()[1] if self._y_valid() else None ++ ++ @property ++ def zmin(self): ++ """Minimum Z value or None if not available""" ++ return self.statistics.get().lower_bound()[2] if self._z_valid() else None ++ ++ @property ++ def zmax(self): ++ """Maximum Z value or None if not available""" ++ return self.statistics.get().upper_bound()[2] if self._z_valid() else None ++ ++ @property ++ def mmin(self): ++ """Minimum M value or None if not available""" ++ return self.statistics.get().lower_bound()[3] if self._m_valid() else None ++ ++ @property ++ def mmax(self): ++ """Maximum M value or None if not available""" ++ return self.statistics.get().upper_bound()[3] if self._m_valid() else None ++ ++ # Helpers to calculate the availability of a given dimension. For statistics ++ # read from a file, dimension_empty should always be false because there is ++ # no way to represent an empty range in Thrift; however, we check to be safe. ++ def _x_valid(self): ++ return self.statistics.get().dimension_valid()[0] \ ++ and not self.statistics.get().dimension_empty()[0] ++ ++ def _y_valid(self): ++ return self.statistics.get().dimension_valid()[1] \ ++ and not self.statistics.get().dimension_empty()[1] ++ ++ def _z_valid(self): ++ return self.statistics.get().dimension_valid()[2] \ ++ and not self.statistics.get().dimension_empty()[2] ++ ++ def _m_valid(self): ++ return self.statistics.get().dimension_valid()[3] \ ++ and not self.statistics.get().dimension_empty()[3] ++ ++ + cdef class ColumnChunkMetaData(_Weakrefable): + """Column metadata for a single row group.""" + +@@ -330,6 +454,7 @@ cdef class ColumnChunkMetaData(_Weakrefable): + + def __repr__(self): + statistics = indent(repr(self.statistics), 4 * ' ') ++ geo_statistics = indent(repr(self.geo_statistics), 4 * ' ') + return """{0} + file_offset: {1} + file_path: {2} +@@ -339,20 +464,23 @@ cdef class ColumnChunkMetaData(_Weakrefable): + is_stats_set: {6} + statistics: + {7} +- compression: {8} +- encodings: {9} +- has_dictionary_page: {10} +- dictionary_page_offset: {11} +- data_page_offset: {12} +- total_compressed_size: {13} +- total_uncompressed_size: {14}""".format(object.__repr__(self), ++ geo_statistics: ++{8} ++ compression: {9} ++ encodings: {10} ++ has_dictionary_page: {11} ++ dictionary_page_offset: {12} ++ data_page_offset: {13} ++ total_compressed_size: {14} ++ total_uncompressed_size: {15}""".format(object.__repr__(self), + self.file_offset, + self.file_path, + self.physical_type, + self.num_values, + self.path_in_schema, + self.is_stats_set, + statistics, ++ geo_statistics, + self.compression, + self.encodings, + self.has_dictionary_page, +@@ -371,6 +499,11 @@ cdef class ColumnChunkMetaData(_Weakrefable): + Dictionary with a key for each attribute of this class. + """ + statistics = self.statistics.to_dict() if self.is_stats_set else None ++ if self.is_geo_stats_set: ++ geo_statistics = self.geo_statistics.to_dict() ++ else: ++ geo_statistics = None ++ + d = dict( + file_offset=self.file_offset, + file_path=self.file_path, +@@ -379,6 +512,7 @@ cdef class ColumnChunkMetaData(_Weakrefable): + path_in_schema=self.path_in_schema, + is_stats_set=self.is_stats_set, + statistics=statistics, ++ geo_statistics=geo_statistics, + compression=self.compression, + encodings=self.encodings, + has_dictionary_page=self.has_dictionary_page, +@@ -450,6 +584,21 @@ cdef class ColumnChunkMetaData(_Weakrefable): + statistics.init(self.metadata.statistics(), self) + return statistics + ++ @property ++ def is_geo_stats_set(self): ++ """Whether or not geometry statistics are present in metadata (bool).""" ++ return self.metadata.is_geo_stats_set() ++ ++ @property ++ def geo_statistics(self): ++ """Statistics for column chunk (:class:`GeoStatistics`).""" ++ c_geo_statistics = self.metadata.geo_statistics() ++ if not c_geo_statistics or not c_geo_statistics.get().is_valid(): ++ return None ++ cdef GeoStatistics geo_statistics = GeoStatistics.__new__(GeoStatistics) ++ geo_statistics.init(c_geo_statistics, self) ++ return geo_statistics ++ + @property + def compression(self): + """ +diff --git a/python/pyarrow/parquet/core.py b/python/pyarrow/parquet/core.py +--- a/python/pyarrow/parquet/core.py ++++ b/python/pyarrow/parquet/core.py +@@ -1270,9 +1270,9 @@ class ParquetDataset: + page_checksum_verification : bool, default False + If True, verify the page checksum for each page read from the file. + arrow_extensions_enabled : bool, default False +- If True, read Parquet logical types as Arrow extension types where possible, +- (e.g., read JSON as the canonical `arrow.json` extension type or UUID as +- the canonical `arrow.uuid` extension type). ++ If True, read Parquet logical types as Arrow extension types where possible, ++ (e.g., read JSON as the canonical `arrow.json` extension type or UUID as ++ the canonical `arrow.uuid` extension type). + + Examples + -------- +@@ -1287,7 +1287,6 @@ def __init__(self, path_or_paths, filesystem=None, schema=None, *, filters=None, + thrift_container_size_limit=None, + page_checksum_verification=False, + arrow_extensions_enabled=False): +- + import pyarrow.dataset as ds + + # map format arguments +@@ -1686,9 +1685,9 @@ def partitioning(self): + page_checksum_verification : bool, default False + If True, verify the checksum for each page read from the file. + arrow_extensions_enabled : bool, default False +- If True, read Parquet logical types as Arrow extension types where possible, +- (e.g., read JSON as the canonical `arrow.json` extension type or UUID as +- the canonical `arrow.uuid` extension type). ++ If True, read Parquet logical types as Arrow extension types where possible, ++ (e.g., read JSON as the canonical `arrow.json` extension type or UUID as ++ the canonical `arrow.uuid` extension type). + + Returns + ------- diff --git a/arrow_1/tests/private/p2p.txt b/arrow_1/tests/private/p2p.txt new file mode 100644 index 0000000000000000000000000000000000000000..d92100d8575346e5c82599e41fff66c4cf00b83a --- /dev/null +++ b/arrow_1/tests/private/p2p.txt @@ -0,0 +1,50 @@ +arrow-array-test::TestArray.TestNullCount +arrow-array-test::TestArray.TestSlicePreservesAllNullCount +arrow-array-test::TestArray.TestLength +arrow-array-test::TestArray.TestNullToString +arrow-array-test::TestArray.TestSliceSafe +arrow-array-test::TestArray.TestEquality +arrow-array-test::TestArray.TestNullArrayEquality +arrow-array-test::TestArray.SliceRecomputeNullCount +arrow-array-test::TestArray.NullArraySliceNullCount +arrow-array-test::TestArray.TestIsNullIsValid +arrow-array-test::TestArray.TestIsNullIsValidNoNulls +arrow-array-test::TestArray.BuildLargeInMemoryArray +arrow-array-test::TestArray.TestMakeArrayOfNull +arrow-array-test::TestArray.TestMakeArrayOfNullUnion +arrow-array-test::TestArray.TestValidateNullCount +arrow-array-test::TestArray.TestValidValues +arrow-array-test::TestArray.TestMakeArrayFromScalar +arrow-array-test::TestArray.TestMakeArrayFromScalarSliced +arrow-array-test::TestArray.TestMakeArrayFromDictionaryScalar +arrow-array-test::TestArray.TestMakeArrayFromMapScalar +arrow-array-test::TestArray.TestMakeEmptyArray +arrow-array-test::TestArray.TestFillFromScalar +arrow-array-test::TestArray.TestConcurrentFillFromScalar +arrow-array-test::TestArray.ExtensionSpanRoundTrip +arrow-array-test::TestArray.TestAppendArraySlice +arrow-array-test::TestArray.TestBinaryViewAppendArraySlice +arrow-array-test::TestArray.ValidateBuffersPrimitive +arrow-array-test::TestNullBuilder.Basics +arrow-array-test::TestPrimitiveArray.CtorNoValidityBitmap +arrow-array-test::TestBuilder.TestReserve +arrow-array-test::TestBuilder.TestResizeDownsize +arrow-array-test::TestBooleanArray.TrueCountFalseCount +arrow-array-test::TestPrimitiveAdHoc.TestType +arrow-array-test::TestPrimitiveAdHoc.FloatingApproxEquals +arrow-array-test::TestPrimitiveAdHoc.FloatingSliceApproxEquals +arrow-array-test::TestPrimitiveAdHoc.FloatingNanEquality +arrow-array-test::TestPrimitiveAdHoc.FloatingInfinityEquality +arrow-array-test::TestPrimitiveAdHoc.FloatingZeroEquality +arrow-array-test::NumericBuilderAccessors.TestSettersGetters +arrow-array-test::TestPrimitiveBuilder/0.TestInit +arrow-array-test::TestPrimitiveBuilder/0.TestAppendNull +arrow-array-test::TestPrimitiveBuilder/0.TestAppendOptional +arrow-array-test::TestPrimitiveBuilder/0.TestAppendNulls +arrow-array-test::TestPrimitiveBuilder/0.TestAppendEmptyValue +arrow-array-test::TestPrimitiveBuilder/0.TestArrayDtorDealloc +arrow-array-test::TestPrimitiveBuilder/0.Equality +arrow-array-test::TestPrimitiveBuilder/0.SliceEquality +arrow-array-test::TestPrimitiveBuilder/0.TestAppendScalar +arrow-array-test::TestPrimitiveBuilder/0.TestAppendValues +arrow-array-test::TestPrimitiveBuilder/0.TestTypedFinish diff --git a/arrow_1/tests/private/p2p_aug.txt b/arrow_1/tests/private/p2p_aug.txt new file mode 100644 index 0000000000000000000000000000000000000000..37e52df83683b27a88022533df45562d56ace882 --- /dev/null +++ b/arrow_1/tests/private/p2p_aug.txt @@ -0,0 +1 @@ +arrow-buffer-test diff --git a/arrow_1/tests/private/run_tests.sh b/arrow_1/tests/private/run_tests.sh new file mode 100644 index 0000000000000000000000000000000000000000..57d71665c0529ffe08f833140dcfd8a0a8eb0b3b --- /dev/null +++ b/arrow_1/tests/private/run_tests.sh @@ -0,0 +1,142 @@ +#!/usr/bin/env bash +# LoLBench runner for Apache-Arrow PR-45459 (Parquet GEOMETRY/GEOGRAPHY). +# Selectors: "" or "::". +# NOTE: no `set -u` — conda's binutils activation scripts reference unbound vars. +set -o pipefail +PRIV=/opt/lolbench/private +SRC=/workspace/arrow +ABLD=/workspace/build +MODE=${LOLBENCH_MODE:-eval} +SUITE=${LOLBENCH_SUITE:-orig} +INSTANCE_ID="Apache-Arrow_PR-240_PR-45459" +log(){ echo "[run_tests $MODE/$SUITE] $*" >&2; } +read_selectors(){ + for file in "$@"; do + [ -f "$file" ] || continue + grep -v '^[[:space:]]*$' "$file" || true + done +} +APPLY_AUG=0 +case "$SUITE" in + orig) + mapfile -t FAIL_TO_PASS < <(read_selectors "$PRIV/f2p.txt") + mapfile -t PASS_TO_PASS < <(read_selectors "$PRIV/p2p.txt") + ;; + aug) + mapfile -t FAIL_TO_PASS < <(read_selectors "$PRIV/f2p_aug.txt") + mapfile -t PASS_TO_PASS < <(read_selectors "$PRIV/p2p_aug.txt") + APPLY_AUG=1 + ;; + union) + mapfile -t FAIL_TO_PASS < <(read_selectors "$PRIV/f2p.txt" "$PRIV/f2p_aug.txt") + mapfile -t PASS_TO_PASS < <(read_selectors "$PRIV/p2p.txt" "$PRIV/p2p_aug.txt") + APPLY_AUG=1 + ;; + *) + mapfile -t FAIL_TO_PASS < <(read_selectors "$PRIV/f2p.txt") + mapfile -t PASS_TO_PASS < <(read_selectors "$PRIV/p2p.txt") + ;; +esac +emit_error(){ + local cat=$1 applied=$2 bs=$3 + python3 - "$cat" "$applied" "$bs" "$INSTANCE_ID" "${#FAIL_TO_PASS[@]}" "${#PASS_TO_PASS[@]}" "$SUITE" <<'EOF' >/out/agent_report.json +import json,sys +cat,ap,bs,inst,fn,pn,su=sys.argv[1:8] +print(json.dumps({"instance_id":inst,"suite":su,"applied":ap.lower()=="true","build":{"status":bs}, + "f2p":{"passed":0,"failed":0,"errored":int(fn),"skipped":0,"total":int(fn)}, + "p2p":{"passed":0,"failed":0,"errored":int(pn),"skipped":0,"total":int(pn)}, + "resolved":False,"error_categories":[cat]},indent=2)) +EOF +} +die(){ log "FATAL: $*"; emit_error harness_error false skipped; exit 0; } +SRC_PATCH="" +case "$MODE" in + validate_pre) SRC_PATCH="";; + validate_post) + if [ -f /solution/solution.patch ]; then + SRC_PATCH=/solution/solution.patch + else + SRC_PATCH="$PRIV/solution.patch" + fi ;; + eval) [ -f /in/solution.patch ] || { emit_error missing_solution_patch false skipped; exit 0; } + AGENT_PATCH=/tmp/lolbench_agent_patch.diff + cp /in/solution.patch "$AGENT_PATCH"; SRC_PATCH="$AGENT_PATCH";; + *) die "unknown LOLBENCH_MODE=$MODE";; +esac +cd "$SRC" +git config --global --add safe.directory "$SRC" +git reset --hard >/dev/null 2>&1; git clean -fdq >/dev/null 2>&1 +if [ -n "$SRC_PATCH" ]; then + git apply --check "$SRC_PATCH" 2>/tmp/a.err || { log "solution patch fail"; cat /tmp/a.err>&2; emit_error patch_apply_failure false skipped; exit 0; } + git apply "$SRC_PATCH" + # LoLBench eval-patch-collision guard (re-verify remediation): if the agent patch touched files the + # eval test patches own (test fixtures the agent must not modify), restore + # those paths (both sides of every diff/rename) to the base state so + # eval_tests(.aug).patch always applies. Agent source changes are preserved. + for _lb_ep in "$PRIV/eval_helpers.patch" "$PRIV/eval_tests.patch" "$PRIV/eval_tests_aug.patch"; do + [ -f "$_lb_ep" ] || continue + { sed -n 's|^diff --git a/\(.*\) b/\(.*\)$|\1\n\2|p' "$_lb_ep" + sed -n 's|^rename from \(.*\)$|\1|p' "$_lb_ep" + sed -n 's|^rename to \(.*\)$|\1|p' "$_lb_ep"; } | sort -u | while read -r _lb_f; do + [ -n "$_lb_f" ] || continue + git checkout HEAD -- "$_lb_f" >/dev/null 2>&1 || rm -f "$_lb_f" >/dev/null 2>&1 || true + done + done +fi +git apply --check "$PRIV/eval_tests.patch" 2>/tmp/a.err || { log "eval patch fail"; cat /tmp/a.err>&2; emit_error eval_patch_apply_failure true skipped; exit 0; } +git apply "$PRIV/eval_tests.patch" +if [ "$APPLY_AUG" -eq 1 ] && [ -s "$PRIV/eval_tests_aug.patch" ]; then + git apply --check "$PRIV/eval_tests_aug.patch" 2>/tmp/a.err || { log "eval aug patch fail"; cat /tmp/a.err>&2; emit_error eval_aug_patch_apply_failure true skipped; exit 0; } + git apply "$PRIV/eval_tests_aug.patch" +fi + +source /opt/conda/etc/profile.d/conda.sh && conda activate base +export PARQUET_TEST_DATA="$SRC/cpp/submodules/parquet-testing/data" + +run_one(){ + # selector: binary or binary::gtest_filter ; build (incremental) then run + local sel="$1" bin filt out + bin="${sel%%::*}"; filt="" + case "$sel" in *"::"*) filt="${sel##*::}";; esac + if ! ninja -C "$ABLD" "$bin" >> /out/build.log 2>&1; then + echo "ERROR"; return + fi + local args=() + [ -n "$filt" ] && args+=(--gtest_filter="$filt") + out=$("$ABLD/release/$bin" "${args[@]}" 2>&1) + echo "$out" >> /out/gtest.log + if echo "$out" | grep -qE "\[ FAILED \]|\[ ERROR \]"; then echo "FAILED" + elif echo "$out" | grep -qE "\[==========\] 0 tests"; then echo "ERROR" + elif echo "$out" | grep -qE "\[ PASSED \]"; then echo "PASSED" + else echo "ERROR"; fi +} +: > /out/build.log; : > /out/gtest.log +declare -a F2P_RES P2P_RES +for t in "${FAIL_TO_PASS[@]}"; do F2P_RES+=("$(run_one "$t")"); done +for t in "${PASS_TO_PASS[@]}"; do P2P_RES+=("$(run_one "$t")"); done +printf '%s\n' "${FAIL_TO_PASS[@]}" > /tmp/lolbench_f2p_selected.txt +printf '%s\n' "${PASS_TO_PASS[@]}" > /tmp/lolbench_p2p_selected.txt +python3 - "$INSTANCE_ID" "$MODE" "$SUITE" /tmp/lolbench_f2p_selected.txt /tmp/lolbench_p2p_selected.txt <", + "log_parser": "generic_log", + "solution_patch_sha256": "a754586f47f0b84e989155ef01ef2fab24bf0995bb169a8f7834759353787b58", + "eval_tests_patch_sha256": "d37dffaad09e99f282629643db8cc200342f89181cc664114a6263a8ba25bfaa", + "triage": { + "audit_note": "Triage metadata was normalized during the 2026-06-10 bundle completeness audit; selector files remain the authoritative test selection.", + "fail_to_pass": { + "parquet-schema-test::TestLogicalTypeOperation.LogicalTypeSortOrder": { + "system_reason": "Retained F2P selector; detailed triage was not recorded before normalization." + } + }, + "pass_to_pass": { + "_summary": "The original broad arrow-array-test P2P selector was split into 50 concrete pre-existing gtest filters from the same unchanged core Arrow array binary. These filters guard array, builder, primitive, and numeric-builder behavior outside the Parquet GEOMETRY/GEOGRAPHY requirement surface." + } + }, + "p2p_expansion": { + "updated_at": "2026-06-14", + "source_command": "arrow-array-test --gtest_list_tests", + "p2p_count_before": 1, + "p2p_count_after": 50, + "p2p_aug_count": 1, + "union_p2p_count": 51, + "pre_existing_upstream_tests_only": true, + "synthesized_selectors_added_to_p2p_txt": false, + "validation": { + "orig_pre": { + "f2p": { + "passed": 0, + "failed": 0, + "errored": 1, + "total": 1 + }, + "p2p": { + "passed": 50, + "failed": 0, + "errored": 0, + "total": 50 + }, + "resolved": false + }, + "orig_post": { + "f2p": { + "passed": 1, + "failed": 0, + "errored": 0, + "total": 1 + }, + "p2p": { + "passed": 50, + "failed": 0, + "errored": 0, + "total": 50 + }, + "resolved": true + }, + "union_post": { + "f2p": { + "passed": 28, + "failed": 0, + "errored": 0, + "total": 28 + }, + "p2p": { + "passed": 51, + "failed": 0, + "errored": 0, + "total": 51 + }, + "resolved": true + } + }, + "coverage": { + "orig": 3.46, + "union": 86.69, + "coverage_report_orig": "coverage_out/coverage_report_orig.json", + "coverage_report_union": "coverage_out/coverage_report_union.json" + } + }, + "coverage": { + "orig": 3.4, + "aug": 86.7, + "union": 86.7, + "denominator": "union_executable_lines" + }, + "coverage_gap_note": "Complete original-suite coverage is below 50%: the selected F2P gtest exercises Parquet logical-type sort-order behavior, while large geospatial implementation areas added by the PR remain unhit by the current public selected tests. Requires future F2P augmentation to satisfy the 50% floor.", + "augmented": { + "eval_tests_aug_patch_sha256": "3bc615efe5d1ce6346a48f19c9fb40542bad4e2487dc889eb5eb8109f0943e92", + "f2p_aug_sha256": "1f026a1b83d6cc49224443d76f366128bc809f512afefc636821805ad4d8fcd6", + "p2p_aug_sha256": "5e85b030a10fd8fec58fe3ce5aad0ffd01b505f9ea898bb081dd8f0d76b2c129", + "fail_to_pass": [ + "parquet-schema-test::TestLogicalTypeSerialization.Roundtrips", + "parquet-schema-test::TestLogicalTypeOperation.GeospatialJsonRepresentationAugmented", + "parquet-reader-test::TestGeometryLogicalType.TestWriteGeometry", + "parquet-reader-test::TestGeometryLogicalType.TestWriteArrowAndReadGeometry", + "parquet-reader-test::TestGeometryLogicalType.TestWriteGeography", + "parquet-reader-test::TestGeometryLogicalType.TestWriteGeographyArrow", + "parquet-arrow-test::TestConvertParquetSchema.ParquetSchemaGeoArrowExtensions", + "parquet-arrow-test::TestConvertArrowSchema.ParquetGeoArrowCrsLonLat", + "parquet-arrow-test::TestConvertArrowSchema.ParquetGeoArrowCrsSrid", + "parquet-arrow-test::TestConvertArrowSchema.ParquetGeoArrowCrsProjjson", + "parquet-arrow-test::TestGeoArrowParquetIO.GeoArrowExtension", + "parquet-writer-test::TestGeometryValuesWriter.TestWriteAndRead", + "parquet-writer-test::TestGeometryValuesWriter.TestWriteAndReadSpaced", + "parquet-writer-test::TestGeometryValuesWriter.TestWriteAndReadAllNull", + "parquet-internals-test::TestGeoStatistics.TestDefaults", + "parquet-internals-test::TestGeoStatistics.TestImportEncodedWithNaN", + "parquet-internals-test::TestGeoStatistics.TestUpdateByteArray", + "parquet-internals-test::TestGeoStatistics.TestUpdateXYZM", + "parquet-internals-test::TestGeoStatistics.TestUpdateArray", + "parquet-internals-test::TestGeoStatistics.TestUpdateArrayInvalid", + "parquet-internals-test::TestGeoStatistics.TestEquals" + ], + "pass_to_pass": [ + "arrow-buffer-test" + ], + "targets_mutants": [ + "mutant_001_geometry_sort_order_signed", + "mutant_002_geography_sort_order_signed", + "mutant_003_geometry_factory_drops_crs", + "mutant_004_geography_factory_drops_algorithm", + "mutant_005_missing_geography_algorithm_vincenty", + "mutant_006_geometry_json_omits_crs", + "mutant_007_geography_json_omits_algorithm", + "mutant_008_geometry_thrift_omits_crs", + "mutant_009_geography_thrift_omits_algorithm", + "mutant_010_geoarrow_write_ignores_metadata", + "mutant_011_geospatial_read_always_binary", + "mutant_012_geoarrow_spherical_read_as_geometry", + "mutant_013_geoarrow_geography_omits_edges" + ], + "unreachable_mutants": {}, + "coverage": { + "orig": 3.46, + "aug": 86.69, + "union": 86.69, + "union_covered": 632, + "executable_lines_in_patch": 729, + "denominator": "union_executable_lines", + "coverage_complete": true + }, + "coverage_gate": "pass", + "coverage_note": "Union coverage 86.69% (632/729 executable solution.patch lines), above the 80% target (attempt 3; attempts 1-2 were 50.8%/68.2%). The augmented C++ gtest cases (cpp/src/parquet/schema_test.cc) drive the Parquet geospatial LogicalType surface (Geometry/Geography logical types, CRS, edge-interpolation algorithm, JSON/Thrift serialization round-trips, GeoArrow read/write) over the public parquet schema/reader API. Union suite kills all 13/13 geospatial mutants. Per-selector detail in test_augmentation/audit.json.", + "triage": { + "test_level_policy": "Augmented F2P are public-API C++ gtest cases (parquet-schema-test, parquet-reader-test, etc.) exercising the documented Parquet geospatial Logical Types surface (Sections 4 Edge Interpolation, 5 Logical Types, 6 Statistics of the requirement doc). Selectors cover symbols and concepts documented in requirement_docs/Apache-Arrow_PR-240_PR-45459.md: GEOMETRY, GEOGRAPHY, WKB, GeospatialStatistics, Bounding Box, and geospatial type codes. The focused augmented JSON gtest uses the documented LogicalType Geometry/Geography public factories already used by the original bundle. The augmented P2P (arrow-buffer-test) is a pre-existing buffer test untouched by the geospatial PR, guarding neighboring Arrow behavior. Tests are synthetic LoLBench augmentation files and do not modify existing tests.", + "fail_to_pass": { + "_summary": "27 selectors over the Parquet geospatial LogicalType public surface (LogicalType serialization round-trips, Geometry/Geography write+read, CRS/edge-algorithm propagation, GeoArrow encode/decode). Map to requirement Sections 4-6. Per-selector requirement_sections + mutant mapping in test_augmentation/audit.json." + }, + "pass_to_pass": { + "_summary": "arrow-buffer-test: pre-existing, stable across all 13 mutants; not asserting the geospatial requirement behavior, guards adjacent Arrow buffer behavior." + } + } + } +} diff --git a/arrow_1/tests/report_to_reward.py b/arrow_1/tests/report_to_reward.py new file mode 100644 index 0000000000000000000000000000000000000000..56265f2eb95c98c2ad1c2f3a420c130e718e86e7 --- /dev/null +++ b/arrow_1/tests/report_to_reward.py @@ -0,0 +1,73 @@ +#!/usr/bin/env python3 +import argparse +import json +from pathlib import Path + + +def rate(bucket): + total = float(bucket.get("total", 0) or 0) + if total <= 0: + return 0.0 + return float(bucket.get("passed", 0) or 0) / total + + +def write_json(path, payload): + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(json.dumps(payload, indent=2, sort_keys=True) + "\n") + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument("--suite", default="union") + parser.add_argument("--missing-patch") + parser.add_argument("--invalid-suite", action="store_true") + parser.add_argument("--runner-rc", type=int, default=0) + parser.add_argument("agent_report") + parser.add_argument("reward_file") + args = parser.parse_args() + + report_path = Path(args.agent_report) + reward_path = Path(args.reward_file) + + if args.invalid_suite: + reward = {"reward": 0.0, "resolved": 0.0, "applied": 0.0, "build_ok": 0.0, "f2p_pass_rate": 0.0, "p2p_pass_rate": 0.0, "harness_ok": 1.0} + sanitized = {"instance_id": "arrow_1", "suite": args.suite, "applied": False, "resolved": False, "error_categories": ["invalid_lolbench_suite"]} + write_json(report_path, sanitized) + write_json(reward_path, reward) + print(f"LoLBench reward=0 invalid suite {args.suite!r}") + return 0 + + if args.missing_patch: + reward = {"reward": 0.0, "resolved": 0.0, "applied": 0.0, "build_ok": 0.0, "f2p_pass_rate": 0.0, "p2p_pass_rate": 0.0, "harness_ok": 1.0} + sanitized = {"instance_id": "arrow_1", "suite": args.suite, "applied": False, "resolved": False, "error_categories": ["missing_solution_patch"]} + write_json(report_path, sanitized) + write_json(reward_path, reward) + print("LoLBench reward=0 missing solution patch") + return 0 + + if not report_path.exists(): + reward = {"reward": 0.0, "resolved": 0.0, "applied": 0.0, "build_ok": 0.0, "f2p_pass_rate": 0.0, "p2p_pass_rate": 0.0, "harness_ok": 0.0} + write_json(reward_path, reward) + print(f"LoLBench reward=0 no agent_report.json runner_rc={args.runner_rc}") + return 0 + + report = json.loads(report_path.read_text()) + build_status = report.get("build", {}).get("status") + resolved = bool(report.get("resolved")) + applied = bool(report.get("applied")) + reward = { + "reward": 1.0 if resolved else 0.0, + "resolved": 1.0 if resolved else 0.0, + "applied": 1.0 if applied else 0.0, + "build_ok": 1.0 if build_status == "ok" else 0.0, + "f2p_pass_rate": rate(report.get("f2p", {})), + "p2p_pass_rate": rate(report.get("p2p", {})), + "harness_ok": 1.0 if args.runner_rc == 0 else 0.0, + } + write_json(reward_path, reward) + print("LoLBench reward={reward} resolved={resolved} f2p={f2p_pass_rate:.3f} p2p={p2p_pass_rate:.3f}".format(**reward)) + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/arrow_1/tests/test.sh b/arrow_1/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..45ba2abd4f682d021752e6966a772a0ee2edb9f5 --- /dev/null +++ b/arrow_1/tests/test.sh @@ -0,0 +1,43 @@ +#!/usr/bin/env bash +set -euo pipefail + +suite=${LOLBENCH_SUITE:-union} +mode=${LOLBENCH_MODE:-eval} +patch=${LOLBENCH_SOLUTION_PATCH:-/logs/artifacts/solution.patch} +private_log=/tmp/lolbench-private-run.log + +mkdir -p /logs/verifier /logs/artifacts /in /out + +case "$suite" in + orig|aug|union) ;; + *) + python3 /tests/report_to_reward.py --suite "$suite" --invalid-suite /out/agent_report.json /logs/verifier/reward.json + exit 0 + ;; +esac + +if [ "$mode" = "eval" ] && [ ! -s "$patch" ]; then + python3 /tests/report_to_reward.py --suite "$suite" --missing-patch "$patch" /out/agent_report.json /logs/verifier/reward.json + exit 0 +fi + +if [ "$mode" = "eval" ]; then + cp "$patch" /in/solution.patch + chmod 0400 /in/solution.patch +fi + +set +e +LOLBENCH_MODE="$mode" LOLBENCH_SUITE="$suite" /opt/lolbench/private/run_tests.sh >"$private_log" 2>&1 +runner_rc=$? +set -e + +cp "$private_log" /logs/verifier/private_run.log +if [ -f /out/grader_report.json ]; then + cp /out/grader_report.json /logs/verifier/grader_report.json +fi + +python3 /tests/report_to_reward.py --suite "$suite" --runner-rc "$runner_rc" /out/agent_report.json /logs/verifier/reward.json + +if [ -f /out/agent_report.json ]; then + cp /out/agent_report.json /logs/verifier/agent_report.json +fi diff --git a/arrow_2/README.md b/arrow_2/README.md new file mode 100644 index 0000000000000000000000000000000000000000..61c946a3ad6c5d03bb2b4472921649a0445297b4 --- /dev/null +++ b/arrow_2/README.md @@ -0,0 +1,87 @@ +# LoLBench Harbor Task: arrow_2 + +This is a Harbor-format LoLBench task generated from `Apache-Arrow_Issue-45750_PR-45360`. + +Selected source instance: + +- Harbor ID: `arrow_2` +- PR: `apache/arrow#45360` +- Base commit: `12424cdf2fda068e973ebd89cda045fee297943a` +- Test modes: `orig, aug, union` +- Default/canonical mode: `union` +- Harbor image: `smartdub26/lolbench-linux:arrow_2-1.0.0` +- Docker Hub image: `smartdub26/lolbench-linux:arrow_2-1.0.0` + +## Image Setup + +Prefer the published Docker Hub image when it is available. Harbor refers to +the image as `smartdub26/lolbench-linux:arrow_2-1.0.0`, so Docker can pull it +directly when it is not present locally: + +```bash +docker pull smartdub26/lolbench-linux:arrow_2-1.0.0 +``` + +Only if the Docker Hub image is unavailable, build the single task image +locally: + +```bash +docker build -t lolbench/arrow_2:1.0.0 harbor_tasks/arrow_2/environment +docker tag lolbench/arrow_2:1.0.0 smartdub26/lolbench-linux:arrow_2-1.0.0 +``` + +The image contains the processed source tree at the base commit under +`/workspace/arrow`. Harbor must not mount a host source checkout +for the agent. + +## Run an Agent + +```bash +.harbor-venv/bin/harbor run \ + -p harbor_tasks/arrow_2 \ + -a codex \ + -m "" \ + --job-name arrow_2_agent_union \ + --jobs-dir harbor_runs/arrow_2 \ + --no-delete \ + --n-concurrent 1 \ + --ve LOLBENCH_SUITE=union +``` + +After implementing the requirement, the agent must clean any test-file edits +and run: + +```bash +lolbench-submit +``` + +## Evaluate a Patch + +Choose one mode with `LOLBENCH_SUITE=orig`, `aug`, or `union`; if unset, the +task defaults to `union`. + +```bash +PATCH="$(pwd)/path/to/solution.patch" + +.harbor-venv/bin/harbor run \ + -p harbor_tasks/arrow_2 \ + -a oracle \ + --job-name arrow_2_eval_union \ + --jobs-dir harbor_runs/arrow_2 \ + --no-delete \ + --n-concurrent 1 \ + --mounts '[{"type":"bind","source":"'"$PATCH"'","target":"/candidate/solution.patch","read_only":true}]' \ + --ae LOLBENCH_ORACLE_PATCH=/candidate/solution.patch \ + --ve LOLBENCH_SUITE=union +``` + +Outputs: + +```bash +find harbor_runs/arrow_2/arrow_2_eval_union -path '*/verifier/agent_report.json' -print +find harbor_runs/arrow_2/arrow_2_eval_union -path '*/verifier/reward.json' -print +``` + +`tests/docker-compose.yaml` is a verifier-only Harbor overlay. It mounts +`tests/`, `tests/private/`, and `solution/` into the separate verifier +container; none of those paths are mounted into the agent container. diff --git a/arrow_2/environment/Dockerfile b/arrow_2/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..ff1c974d844233dc7cb089fd5dccc66b00e081b5 --- /dev/null +++ b/arrow_2/environment/Dockerfile @@ -0,0 +1,131 @@ +# LoLBench eval image: Apache-Arrow PR-45360 +# Requirement: Issue-45750 C++/Python/Parquet — Content Defined Chunking +# base_commit: 12424cdf2fda068e973ebd89cda045fee297943a +# +# Agent-facing contract (the agent does NOT run anything inside this +# image; the evaluator runs the container after the agent submits a +# solution.patch): +# +# docker run --rm \ +# -v $(pwd)/solution.patch:/in/solution.patch:ro \ +# -v $(pwd)/out:/out \ +# lolbench/apache-arrow-pr-45360:1 +# +# Because the agent's code never executes here, the container runs every +# step as root — no agent UID, no chown of /opt/conda, no runuser dance. +# +# Layered build per docs/executable_environment_plan.md §4: +# layer 1: condaforge/mambaforge +# layer 2: lolbench/arrow-base:1 (conda env with Arrow build deps) +# layer 3: THIS image (source @ base_commit + pre-built Arrow + private bundle) + +ARG BASE_IMAGE=lolbench/arrow-base:1 +FROM ${BASE_IMAGE} + +ARG BASE_COMMIT=12424cdf2fda068e973ebd89cda045fee297943a + +# ---- Per-instance dirs ------------------------------------------------ +# /opt/lolbench/private/ holds the eval-side artifacts (eval_tests.patch, +# selectors, golden solution.patch, run_tests.sh). We keep the path name +# `private` to document intent; perms are default since the container is +# only ever run by the trusted evaluator. +RUN mkdir -p /opt/lolbench/private /in /out /workspace + +# ---- Source tree at base_commit --------------------------------------- +# Fetch the upstream base commit with ancestor history, then keep only refs +# reachable from the processed LoLBench baseline. +WORKDIR /workspace +RUN git init arrow && \ + cd arrow && \ + git remote add origin https://github.com/apache/arrow.git && \ + git fetch --no-tags origin ${BASE_COMMIT} && \ + git checkout ${BASE_COMMIT} && \ + echo 'version = "21.0.0.dev0"' > python/pyarrow/_generated_version.py && \ + git config user.email lolbench@local && \ + git config user.name lolbench && \ + git add -f python/pyarrow/_generated_version.py && \ + if ! git diff --quiet || ! git diff --cached --quiet || [ -n "$(git ls-files --others --exclude-standard)" ]; then \ + git add -A && git add -f python/pyarrow/_generated_version.py && git -c commit.gpgsign=false commit -q -m "LoLBench environment overlay"; \ + fi && \ + git tag -f base && git tag -f lolbench-base && \ + git for-each-ref --format='%(refname)' refs/heads refs/remotes refs/tags | \ + while read ref; do \ + case "$ref" in refs/tags/base|refs/tags/lolbench-base) ;; *) git update-ref -d "$ref" ;; esac; \ + done && \ + ( git remote remove origin 2>/dev/null || true ) && \ + rm -f .git/FETCH_HEAD && \ + git reflog expire --expire=now --all && \ + git repack -Ad && \ + git prune --expire=now && \ + git config --global --add safe.directory /workspace/arrow + +# ---- Pre-build Arrow C++ + PyArrow + pandas (single layer) ------------ +# Folding all three installs into one RUN keeps the layer count small. +RUN bash -lc '\ +set -e ; \ +source /opt/conda/etc/profile.d/conda.sh && conda activate base ; \ +mkdir -p /workspace/build && cd /workspace/build && \ +cmake -GNinja \ + -DCMAKE_INSTALL_PREFIX=/opt/conda \ + -DCMAKE_BUILD_TYPE=Release \ + -DARROW_SIMD_LEVEL=AVX2 \ + -DARROW_RUNTIME_SIMD_LEVEL=AVX2 \ + -DARROW_BUILD_STATIC=OFF \ + -DARROW_BUILD_TESTS=OFF \ + -DARROW_BUILD_UTILITIES=OFF \ + -DARROW_DEPENDENCY_SOURCE=CONDA \ + -DARROW_PARQUET=ON \ + -DARROW_PYTHON=OFF \ + -DARROW_FILESYSTEM=ON \ + -DARROW_DATASET=ON \ + -DARROW_COMPUTE=ON \ + -DARROW_JSON=ON \ + -DARROW_CSV=ON \ + -DARROW_ACERO=ON \ + -DARROW_S3=OFF -DARROW_GCS=OFF -DARROW_AZURE=OFF \ + -DARROW_WITH_BROTLI=ON -DARROW_WITH_SNAPPY=ON -DARROW_WITH_LZ4=ON -DARROW_WITH_ZSTD=ON -DARROW_WITH_BZ2=ON \ + /workspace/arrow/cpp && \ +ninja -j4 install ; \ +cd /workspace/arrow/python && \ +PYARROW_WITH_PARQUET=1 PYARROW_PARALLEL=4 PYARROW_CMAKE_GENERATOR=Ninja \ + pip install -e . --no-build-isolation ; \ +mamba install -y -c conda-forge pandas && \ +mamba clean --all -y \ +' + +# ---- Eval bundle ------------------------------------------------------ +# All eval-side files live in the instance directory's root. The +# previous public/ + private/ split was only a distribution-policy +# label; since the container runs as root throughout, a single bundle +# directory is simpler. The path /opt/lolbench/private/ is kept inside +# the container as a stable name for tooling. +# Augmented (opt-in) suite — see docs/test_augmentation_plan.md §10. +# These sidecar files are independent of the original eval contract; if the +# evaluator never passes LOLBENCH_SUITE=aug|union, they are unused. + +# Harbor runtime adapter: keep the image public/agent-safe. +RUN if ! command -v rg >/dev/null 2>&1; then \ + if command -v apt-get >/dev/null 2>&1; then apt-get update && apt-get install -y --no-install-recommends ripgrep && rm -rf /var/lib/apt/lists/*; \ + elif command -v apk >/dev/null 2>&1; then apk add --no-cache ripgrep; \ + elif command -v dnf >/dev/null 2>&1; then dnf install -y ripgrep && dnf clean all; \ + elif command -v yum >/dev/null 2>&1; then yum install -y ripgrep && yum clean all; \ + else echo 'ripgrep is required by the agent harness' >&2; exit 1; fi; \ + fi +RUN mkdir -p /opt/lolbench /logs/artifacts /logs/agent /logs/verifier /in /out && \ + if ! id -u agent >/dev/null 2>&1; then useradd -m -s /bin/bash agent; fi && \ + mkdir -p /home/agent/.cache/opencode/bin && \ + ln -sf "$(command -v rg)" /home/agent/.cache/opencode/bin/rg +COPY metadata.json /opt/lolbench/metadata.json +COPY lolbench-submit /usr/local/bin/lolbench-submit +RUN chmod +x /usr/local/bin/lolbench-submit && \ + git config --global --add safe.directory /workspace/arrow && \ + if [ -d /workspace/arrow/.git ]; then \ + cd /workspace/arrow && git ls-files --others --exclude-standard | sort > /opt/lolbench/base_untracked.txt; \ + else \ + : > /opt/lolbench/base_untracked.txt; \ + fi && \ + chown -R agent:agent /workspace /in /out /logs /home/agent/.cache +USER agent +WORKDIR /workspace/arrow +ENV LOLBENCH_INSTANCE_ID=arrow_2 +ENV LOLBENCH_SOURCE_SLUG=Apache-Arrow_Issue-45750_PR-45360 diff --git a/arrow_2/environment/docker-compose.yaml b/arrow_2/environment/docker-compose.yaml new file mode 100644 index 0000000000000000000000000000000000000000..7ed45f87dc9faf9df284f5b10d6d2289781ff254 --- /dev/null +++ b/arrow_2/environment/docker-compose.yaml @@ -0,0 +1,3 @@ +services: + main: + pull_policy: missing diff --git a/arrow_2/environment/lolbench-submit b/arrow_2/environment/lolbench-submit new file mode 100644 index 0000000000000000000000000000000000000000..db92f16d4548e7e883591d865c71e4719e65857b --- /dev/null +++ b/arrow_2/environment/lolbench-submit @@ -0,0 +1,56 @@ +#!/usr/bin/env bash +set -euo pipefail +export LC_ALL=C + +resolve_repo() { + if [ "$#" -gt 0 ] && [ -n "${1:-}" ]; then + printf '%s\n' "$1" + return + fi + if git -C "$PWD" rev-parse --show-toplevel >/dev/null 2>&1; then + git -C "$PWD" rev-parse --show-toplevel + return + fi + find /workspace -mindepth 1 -maxdepth 1 -type d \ + -exec test -d '{}/.git' ';' -print 2>/dev/null | LC_ALL=C sort | head -n 1 +} + +if [ "$#" -gt 0 ]; then + repo=$(resolve_repo "$1") +else + repo=$(resolve_repo) +fi +out=${LOLBENCH_PATCH_OUT:-/logs/artifacts/solution.patch} + +if [ -z "$repo" ] || [ ! -d "$repo/.git" ]; then + echo "error: no git repository found; run from /workspace/ or pass the repo path" >&2 + exit 2 +fi + +mkdir -p "$(dirname "$out")" +cd "$repo" +git rev-parse --is-inside-work-tree >/dev/null + +baseline=/opt/lolbench/base_untracked.txt +current=$(mktemp) +new_files=$(mktemp) +trap 'rm -f "$current" "$new_files"' EXIT + +git ls-files --others --exclude-standard | sort > "$current" +if [ -f "$baseline" ]; then + comm -13 "$baseline" "$current" > "$new_files" +else + cp "$current" "$new_files" +fi + +if [ -s "$new_files" ]; then + xargs -r git add -N -- < "$new_files" +fi + +git diff --binary > "$out" + +if [ ! -s "$out" ]; then + echo "warning: wrote an empty solution patch to $out" >&2 +else + echo "wrote solution patch to $out" +fi diff --git a/arrow_2/environment/metadata.json b/arrow_2/environment/metadata.json new file mode 100644 index 0000000000000000000000000000000000000000..aa48685e58f015d961fb4e8d920d0dcd9dd112f3 --- /dev/null +++ b/arrow_2/environment/metadata.json @@ -0,0 +1,22 @@ +{ + "instance_id": "arrow_2", + "source_instance_id": "Apache-Arrow_Issue-45750_PR-45360", + "source_slug": "Apache-Arrow_Issue-45750_PR-45360", + "docker_slug": "Apache-Arrow_Issue-45750_PR-45360", + "dockerhub_image": "smartdub26/lolbench-linux:arrow_2-1.0.0", + "project": "arrow", + "repo": "apache/arrow", + "requirement_doc": "https://github.com/apache/arrow/issues/45750", + "pr_link": "https://github.com/apache/arrow/pull/45360", + "base_commit": "12424cdf2fda068e973ebd89cda045fee297943a", + "merge_commit": "1cc2e4b690e467f548dc4131f9b392a864a132aa", + "source_history_policy": "ancestors-only", + "lolbench_test_modes": [ + "orig", + "aug", + "union" + ], + "default_lolbench_suite": "union", + "canonical_lolbench_suite": "union", + "augmentation_available": true +} diff --git a/arrow_2/environment/source_audit.json b/arrow_2/environment/source_audit.json new file mode 100644 index 0000000000000000000000000000000000000000..3d63c4fb132601fe5072c66cfb3ec7b641ca85ca --- /dev/null +++ b/arrow_2/environment/source_audit.json @@ -0,0 +1,6 @@ +{ + "source_policy": "dockerfile_fetch_historyless_base_snapshot", + "base_commit": "12424cdf2fda068e973ebd89cda045fee297943a", + "repo": "apache/arrow", + "note": "The generated Dockerfile fetches the base commit with ancestor history, preserves .git, removes post-base refs/remotes/reflogs, and prunes unreachable future commit objects during image build." +} diff --git a/arrow_2/instruction.md b/arrow_2/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..2525439ce794be8f7493e5e8a1759229ca5e6ce9 --- /dev/null +++ b/arrow_2/instruction.md @@ -0,0 +1,63 @@ +You are working in `/workspace/arrow`, a source tree checked out at +the base commit for this task. Implement the requested behavior in the source +tree, then run: + +```bash +lolbench-submit +``` + +Do not stop after editing files, running tests, or describing the solution. The +task is complete only when `lolbench-submit` has created +`/logs/artifacts/solution.patch`. If that file does not exist, continue +working and run `lolbench-submit` again. + +That command writes your implementation diff to +`/logs/artifacts/solution.patch`, which is the artifact the Harbor verifier +will grade. Before running `lolbench-submit`, clean or revert any test files +you created or modified; test files must not be included in the final +`solution.patch`. + +This environment has no outbound internet access — `curl`/`wget`, `git fetch`/`clone`, package installs, and web fetch/search will all fail. Implement the requirements using only the code already in the workspace and your own knowledge; do not attempt to fetch or search external resources. + +Now please implement the following requirements in the source tree: + +--- + +# [C++][Python][Parquet] Support Content-Defined Chunking of Parquet files + +### Describe the enhancement requested + +## Rationale + +Unlike the traditional approach where pages are split once a page's size reaches the default limit (typically 1MB), this implementation splits pages based on the chunk boundaries identified by the chunker. Consequently, the resulting chunks will have variable sizes but will be more resilient to data modifications such as updates, inserts, and deletes. This method enhances the robustness and efficiency of data storage and retrieval in Apache Parquet by ensuring that identical data segments are consistently chunked in the same manner, regardless of their position within the dataset. + +On the writer side this behavior is controlled by a new `use_content_defined_chunking` write option, which is `False` by default. It accepts either a boolean — `True` turns on content-defined chunking with default parameters — or a dictionary that tunes the chunker via the keys `min_chunk_size` and `max_chunk_size` (the lower and upper bounds on chunk size) and the optional `norm_level` (default `0`), which pulls the chunk-size distribution closer to the average as it is increased. + +## Parquet Deduplication + +The space savings can be significant, see some test results generated on test data containing a series of snapshots from a database: + +``` +┏━━━━━━━━━━━━┳━━━━━━━━━━━━┳━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━━━━┓ +┃ ┃ ┃ ┃ Compressed Chunk ┃ ┃ Compressed Dedup ┃ Transmitted XTool ┃ +┃ Title ┃ Total Size ┃ Chunk Size ┃ Size ┃ Dedup Ratio ┃ Ratio ┃ Bytes ┃ +┡━━━━━━━━━━━━╇━━━━━━━━━━━━╇━━━━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━━━━┩ +│ JSONLines │ 93.0 GiB │ 64.9 GiB │ 12.4 GiB │ 70% │ 13% │ 13.5 GiB │ +│ Parquet │ 16.2 GiB │ 15.0 GiB │ 13.4 GiB │ 93% │ 83% │ 13.5 GiB │ +│ CDC ZSTD │ 8.8 GiB │ 5.6 GiB │ 5.6 GiB │ 64% │ 64% │ 6.1 GiB │ +│ CDC Snappy │ 16.2 GiB │ 8.6 GiB │ 8.1 GiB │ 53% │ 50% │ 9.4 GiB │ +└────────────┴────────────┴────────────┴──────────────────────┴─────────────┴──────────────────────┴──────────────────────┘ +``` + +The results are calculated by simulating a content addressable storage system like [Hugging Face Hub](https://xethub.com/blog/from-files-to-chunks-improving-hf-storage-efficiency) or [restic](https://restic.net/). + +![Image](https://github.com/user-attachments/assets/17de78c1-66aa-4a73-ad6a-6fffc4ef4d4c) + +## Example of inserting records into a parquet file + +The following heatmaps show common byte blocks of a parquet file before and after inserting some records. The green parts are common whereas the red parts are different, hence must be stored twice. Using CDC chunking CAS systems can achieve much higher deduplication ratios. + +Image + +There is an evaluation tool available at https://github.com/kszucs/de with lot more examples and heatmaps comparing various scenarios: updates, deletes, insertions and appends. + diff --git a/arrow_2/solution/solution.patch b/arrow_2/solution/solution.patch new file mode 100644 index 0000000000000000000000000000000000000000..03ea4cbe1337e468623011bfae9aa40d47f9dc58 --- /dev/null +++ b/arrow_2/solution/solution.patch @@ -0,0 +1,1801 @@ +diff --git a/.gitattributes b/.gitattributes +--- a/.gitattributes ++++ b/.gitattributes +@@ -1,4 +1,5 @@ + cpp/src/arrow/util/bpacking_*_generated.h linguist-generated=true ++cpp/src/parquet/chunker_*_generated.h linguist-generated=true + cpp/src/generated/*.cpp linguist-generated=true + cpp/src/generated/*.h linguist-generated=true + go/**/*.s linguist-generated=true +diff --git a/cpp/src/parquet/CMakeLists.txt b/cpp/src/parquet/CMakeLists.txt +--- a/cpp/src/parquet/CMakeLists.txt ++++ b/cpp/src/parquet/CMakeLists.txt +@@ -160,6 +160,7 @@ set(PARQUET_SRCS + arrow/writer.cc + bloom_filter.cc + bloom_filter_reader.cc ++ chunker_internal.cc + column_reader.cc + column_scanner.cc + column_writer.cc +@@ -399,6 +400,8 @@ add_parquet_test(writer-test + file_serialize_test.cc + stream_writer_test.cc) + ++add_parquet_test(chunker-test SOURCES chunker_internal_test.cc) ++ + add_parquet_test(arrow-test + SOURCES + arrow/arrow_metadata_test.cc +diff --git a/cpp/src/parquet/chunker_internal.cc b/cpp/src/parquet/chunker_internal.cc +new file mode 100644 +--- /dev/null ++++ b/cpp/src/parquet/chunker_internal.cc +@@ -0,0 +1,429 @@ ++// Licensed to the Apache Software Foundation (ASF) under one ++// or more contributor license agreements. See the NOTICE file ++// distributed with this work for additional information ++// regarding copyright ownership. The ASF licenses this file ++// to you under the Apache License, Version 2.0 (the ++// "License"); you may not use this file except in compliance ++// with the License. You may obtain a copy of the License at ++// ++// http://www.apache.org/licenses/LICENSE-2.0 ++// ++// Unless required by applicable law or agreed to in writing, ++// software distributed under the License is distributed on an ++// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY ++// KIND, either express or implied. See the License for the ++// specific language governing permissions and limitations ++// under the License. ++ ++#include "parquet/chunker_internal.h" ++ ++#include ++#include ++#include ++#include ++ ++#include "arrow/array.h" ++#include "arrow/util/bit_util.h" ++#include "arrow/util/logging_internal.h" ++#include "arrow/visit_type_inline.h" ++#include "parquet/chunker_internal_generated.h" ++#include "parquet/exception.h" ++#include "parquet/level_conversion.h" ++ ++namespace parquet::internal { ++ ++using ::arrow::internal::checked_cast; ++ ++static_assert(std::size(kGearhashTable) == kNumGearhashTables, ++ "should update CDC code to reflect number of generated hash tables"); ++static_assert(sizeof(kGearhashTable) == kNumGearhashTables * 256 * 8, ++ "each table should have 256 entries of 64 bit values"); ++ ++namespace { ++ ++/// Calculate the mask to use for the rolling hash, the mask is used to determine if a ++/// new chunk should be created based on the rolling hash value. The mask is calculated ++/// based on the min_chunk_size, max_chunk_size and norm_level parameters. ++/// ++/// Assuming that the gear hash hash random values with a uniform distribution, then each ++/// bit in the actual value of rolling_hash_ has even probability of being set so a mask ++/// with the top N bits set has a probability of 1/2^N of matching the rolling hash. This ++/// is the judgment criteria for the original gear hash based content-defined chunking. ++/// The main drawback of this approach is the non-uniform distribution of the chunk sizes. ++/// ++/// Later on the FastCDC has improved the process by introducing: ++/// - sub-minimum chunk cut-point skipping (not hashing the first `min_chunk_size` bytes) ++/// - chunk size normalization (using two masks) ++/// ++/// This implementation uses cut-point skipping because it improves the overall ++/// performance and a more accurate alternative to have less skewed chunk size ++/// distribution. Instead of using two different masks (one with a lower and one with a ++/// higher probability of matching and switching them based on the actual chunk size), we ++/// rather use 8 different gear hash tables and require having 8 consecutive matches while ++/// switching between the used hashtables. This approach is based on central limit theorem ++/// and approximates normal distribution of the chunk sizes. ++// ++// @param min_chunk_size The minimum chunk size (default 256KiB) ++// @param max_chunk_size The maximum chunk size (default 1MiB) ++// @param norm_level Normalization level (default 0) ++// @return The mask used to compare against the rolling hash ++uint64_t CalculateMask(int64_t min_chunk_size, int64_t max_chunk_size, int norm_level) { ++ if (min_chunk_size < 0) { ++ throw ParquetException("min_chunk_size must be non-negative"); ++ } ++ if (max_chunk_size <= min_chunk_size) { ++ throw ParquetException("max_chunk_size must be greater than min_chunk_size"); ++ } ++ ++ // calculate the average size of the chunks ++ int64_t avg_chunk_size = (min_chunk_size + max_chunk_size) / 2; ++ // since we are skipping the first `min_chunk_size` bytes for each chunk, we need to ++ // target a smaller chunk size to reach the average size after skipping the first ++ // `min_chunk_size` bytes; also divide by the number of gearhash tables to have a ++ // a more gaussian-like distribution ++ int64_t target_size = (avg_chunk_size - min_chunk_size) / kNumGearhashTables; ++ ++ // assuming that the gear hash has a uniform distribution, we can calculate the mask ++ // by taking the floor(log2(target_size)) ++ int mask_bits = std::max(0, ::arrow::bit_util::NumRequiredBits(target_size) - 1); ++ ++ // a user defined `norm_level` can be used to adjust the mask size, hence the matching ++ // probability, by increasing the norm_level we increase the probability of matching ++ // the mask, forcing the distribution closer to the average size; norm_level is 0 by ++ // default ++ int effective_bits = mask_bits - norm_level; ++ ++ if (effective_bits < 1 || effective_bits > 63) { ++ throw ParquetException( ++ "The number of bits in the CDC mask must be between 1 and 63, got " + ++ std::to_string(effective_bits)); ++ } else { ++ // create the mask by setting the top bits ++ return std::numeric_limits::max() << (64 - effective_bits); ++ } ++} ++ ++} // namespace ++ ++class ContentDefinedChunker::Impl { ++ public: ++ Impl(const LevelInfo& level_info, int64_t min_chunk_size, int64_t max_chunk_size, ++ int norm_level) ++ : level_info_(level_info), ++ min_chunk_size_(min_chunk_size), ++ max_chunk_size_(max_chunk_size), ++ rolling_hash_mask_(CalculateMask(min_chunk_size, max_chunk_size, norm_level)) {} ++ ++ uint64_t GetRollingHashMask() const { return rolling_hash_mask_; } ++ ++ void Roll(bool value) { ++ // Update the rolling hash with a boolean value, set has_matched_ to true if the hash ++ // matches the ++ if (++chunk_size_ < min_chunk_size_) { ++ // short-circuit if we haven't reached the minimum chunk size, this speeds up the ++ // chunking process since the gearhash doesn't need to be updated ++ return; ++ } ++ rolling_hash_ = (rolling_hash_ << 1) + kGearhashTable[nth_run_][value]; ++ has_matched_ = has_matched_ || ((rolling_hash_ & rolling_hash_mask_) == 0); ++ } ++ ++ template ++ void Roll(const uint8_t* value) { ++ // Update the rolling hash with a compile-time known sized value, set has_matched_ to ++ // true if the hash matches the mask. ++ chunk_size_ += kByteWidth; ++ if (chunk_size_ < min_chunk_size_) { ++ // short-circuit if we haven't reached the minimum chunk size, this speeds up the ++ // chunking process since the gearhash doesn't need to be updated ++ return; ++ } ++ for (size_t i = 0; i < kByteWidth; ++i) { ++ rolling_hash_ = (rolling_hash_ << 1) + kGearhashTable[nth_run_][value[i]]; ++ has_matched_ = has_matched_ || ((rolling_hash_ & rolling_hash_mask_) == 0); ++ } ++ } ++ ++ template ++ void Roll(const T* value) { ++ return Roll(reinterpret_cast(value)); ++ } ++ ++ void Roll(const uint8_t* value, int64_t length) { ++ // Update the rolling hash with a binary-like value, set has_matched_ to true if the ++ // hash matches the mask. ++ chunk_size_ += length; ++ if (chunk_size_ < min_chunk_size_) { ++ // short-circuit if we haven't reached the minimum chunk size, this speeds up the ++ // chunking process since the gearhash doesn't need to be updated ++ return; ++ } ++ for (auto i = 0; i < length; ++i) { ++ rolling_hash_ = (rolling_hash_ << 1) + kGearhashTable[nth_run_][value[i]]; ++ has_matched_ = has_matched_ || ((rolling_hash_ & rolling_hash_mask_) == 0); ++ } ++ } ++ ++ bool NeedNewChunk() { ++ // decide whether to create a new chunk based on the rolling hash; has_matched_ is ++ // set to true if we encountered a match since the last NeedNewChunk() call ++ if (ARROW_PREDICT_FALSE(has_matched_)) { ++ has_matched_ = false; ++ // in order to have a normal distribution of chunk sizes, we only create a new chunk ++ // if the adjused mask matches the rolling hash 8 times in a row, each run uses a ++ // different gearhash table (gearhash's chunk size has geometric distribution, and ++ // we use central limit theorem to approximate normal distribution, see ++ // section 6.2.1 in paper https://www.cidrdb.org/cidr2023/papers/p43-low.pdf) ++ if (ARROW_PREDICT_FALSE(++nth_run_ >= kNumGearhashTables)) { ++ // note that we choose not to reset the rolling hash state here, nor anywhere else ++ // in the code, in practice this doesn't seem to affect the chunking effectiveness ++ nth_run_ = 0; ++ chunk_size_ = 0; ++ return true; ++ } ++ } ++ if (ARROW_PREDICT_FALSE(chunk_size_ >= max_chunk_size_)) { ++ // we have a hard limit on the maximum chunk size, note that we don't reset the ++ // rolling hash state here, so the next NeedNewChunk() call will continue from the ++ // current state ++ chunk_size_ = 0; ++ return true; ++ } ++ return false; ++ } ++ ++ void ValidateChunks(const std::vector& chunks, int64_t num_levels) const { ++ // chunks must be non-empty and monotonic increasing ++ ARROW_DCHECK(!chunks.empty()); ++ ++ // the first chunk must start at the first level ++ auto first_chunk = chunks.front(); ++ ARROW_DCHECK_EQ(first_chunk.level_offset, 0); ++ ARROW_DCHECK_EQ(first_chunk.value_offset, 0); ++ ++ // the following chunks must be contiguous, non-overlapping and monotonically ++ // increasing ++ auto sum_levels = first_chunk.levels_to_write; ++ for (size_t i = 1; i < chunks.size(); ++i) { ++ auto chunk = chunks[i]; ++ auto prev_chunk = chunks[i - 1]; ++ ARROW_DCHECK_GT(chunk.levels_to_write, 0); ++ ARROW_DCHECK_GE(chunk.value_offset, prev_chunk.value_offset); ++ ARROW_DCHECK_EQ(chunk.level_offset, ++ prev_chunk.level_offset + prev_chunk.levels_to_write); ++ sum_levels += chunk.levels_to_write; ++ } ++ ARROW_DCHECK_EQ(sum_levels, num_levels); ++ ++ // the last chunk must end at the last level ++ auto last_chunk = chunks.back(); ++ ARROW_DCHECK_EQ(last_chunk.level_offset + last_chunk.levels_to_write, num_levels); ++ } ++ ++ template ++ std::vector Calculate(const int16_t* def_levels, const int16_t* rep_levels, ++ int64_t num_levels, const RollFunc& RollValue) { ++ // Calculate the chunk boundaries for typed Arrow arrays. ++ // ++ // The chunking state is maintained across the entire column without being reset ++ // between pages and row groups. This enables that the chunking process can be ++ // continued between different WriteArrow calls. ++ // ++ // Below we go over the (def_level, rep_level, value) triplets one by one while ++ // adjusting the column-global rolling hash based on the triplet. Whenever the ++ // rolling hash matches a predefined mask it sets the `has_matched_` flag to true. ++ // ++ // After each triplet NeedNewChunk() is called to evaluate if we need to create ++ // a new chunk. If the rolling hash matches the mask `kNumGearhashTables` times in ++ // row (required for better chunk size distribution) and satisfies the chunk size ++ // requirements, we create a new chunk. See the `NeedNewChunk()` method for more ++ // details. ++ std::vector chunks; ++ int64_t offset; ++ int64_t prev_offset = 0; ++ int64_t prev_value_offset = 0; ++ bool has_def_levels = level_info_.def_level > 0; ++ bool has_rep_levels = level_info_.rep_level > 0; ++ ++ if (!has_rep_levels && !has_def_levels) { ++ // fastest path for non-nested non-null data ++ for (offset = 0; offset < num_levels; ++offset) { ++ RollValue(offset); ++ if (NeedNewChunk()) { ++ chunks.push_back({prev_offset, prev_offset, offset - prev_offset}); ++ prev_offset = offset; ++ } ++ } ++ // set the previous value offset to add the last chunk ++ prev_value_offset = prev_offset; ++ } else if (!has_rep_levels) { ++ // non-nested data with nulls ++ int16_t def_level; ++ for (int64_t offset = 0; offset < num_levels; ++offset) { ++ def_level = def_levels[offset]; ++ ++ Roll(&def_level); ++ if (def_level == level_info_.def_level) { ++ RollValue(offset); ++ } ++ if (NeedNewChunk()) { ++ chunks.push_back({prev_offset, prev_offset, offset - prev_offset}); ++ prev_offset = offset; ++ } ++ } ++ // set the previous value offset to add the last chunk ++ prev_value_offset = prev_offset; ++ } else { ++ // nested data with nulls ++ int16_t def_level; ++ int16_t rep_level; ++ int64_t value_offset = 0; ++ ++ for (offset = 0; offset < num_levels; ++offset) { ++ def_level = def_levels[offset]; ++ rep_level = rep_levels[offset]; ++ ++ Roll(&def_level); ++ Roll(&rep_level); ++ if (def_level == level_info_.def_level) { ++ RollValue(value_offset); ++ } ++ ++ if (rep_level == 0 && NeedNewChunk()) { ++ // if we are at a record boundary and need a new chunk, we create a new chunk ++ auto levels_to_write = offset - prev_offset; ++ if (levels_to_write > 0) { ++ chunks.push_back({prev_offset, prev_value_offset, levels_to_write}); ++ prev_offset = offset; ++ prev_value_offset = value_offset; ++ } ++ } ++ if (def_level >= level_info_.repeated_ancestor_def_level) { ++ // we only increment the value offset if we have a leaf value ++ ++value_offset; ++ } ++ } ++ } ++ ++ // add the last chunk if we have any levels left ++ if (prev_offset < num_levels) { ++ chunks.push_back({prev_offset, prev_value_offset, num_levels - prev_offset}); ++ } ++#ifndef NDEBUG ++ ValidateChunks(chunks, num_levels); ++#endif ++ ++ return chunks; ++ } ++ ++ template ++ std::vector CalculateFixedWidth(const int16_t* def_levels, ++ const int16_t* rep_levels, int64_t num_levels, ++ const ::arrow::Array& values) { ++ const uint8_t* raw_values = ++ values.data()->GetValues(/*i=*/1, /*absolute_offset=*/0) + ++ values.offset() * kByteWidth; ++ return Calculate(def_levels, rep_levels, num_levels, [&](int64_t i) { ++ return Roll(&raw_values[i * kByteWidth]); ++ }); ++ } ++ ++ template ++ std::vector CalculateBinaryLike(const int16_t* def_levels, ++ const int16_t* rep_levels, int64_t num_levels, ++ const ::arrow::Array& values) { ++ const auto& array = checked_cast(values); ++ return Calculate(def_levels, rep_levels, num_levels, [&](int64_t i) { ++ typename ArrayType::offset_type length; ++ const uint8_t* value = array.GetValue(i, &length); ++ Roll(value, length); ++ }); ++ } ++ ++ std::vector GetChunks(const int16_t* def_levels, const int16_t* rep_levels, ++ int64_t num_levels, const ::arrow::Array& values) { ++ auto handle_type = [&](auto&& type) -> std::vector { ++ using ArrowType = std::decay_t; ++ if constexpr (ArrowType::type_id == ::arrow::Type::NA) { ++ return Calculate(def_levels, rep_levels, num_levels, [](int64_t) {}); ++ } else if constexpr (ArrowType::type_id == ::arrow::Type::BOOL) { ++ const auto& array = static_cast(values); ++ return Calculate(def_levels, rep_levels, num_levels, ++ [&](int64_t i) { Roll(array.Value(i)); }); ++ } else if constexpr (ArrowType::type_id == ::arrow::Type::FIXED_SIZE_BINARY) { ++ const auto& array = static_cast(values); ++ const auto byte_width = array.byte_width(); ++ return Calculate(def_levels, rep_levels, num_levels, ++ [&](int64_t i) { Roll(array.GetValue(i), byte_width); }); ++ } else if constexpr (ArrowType::type_id == ::arrow::Type::EXTENSION) { ++ const auto& array = static_cast(values); ++ return GetChunks(def_levels, rep_levels, num_levels, *array.storage()); ++ } else if constexpr (::arrow::is_primitive(ArrowType::type_id)) { ++ using c_type = typename ArrowType::c_type; ++ return CalculateFixedWidth(def_levels, rep_levels, num_levels, ++ values); ++ } else if constexpr (::arrow::is_decimal(ArrowType::type_id)) { ++ return CalculateFixedWidth(def_levels, rep_levels, ++ num_levels, values); ++ } else if constexpr (::arrow::is_binary_like(ArrowType::type_id)) { ++ return CalculateBinaryLike<::arrow::BinaryArray>(def_levels, rep_levels, ++ num_levels, values); ++ } else if constexpr (::arrow::is_large_binary_like(ArrowType::type_id)) { ++ return CalculateBinaryLike<::arrow::LargeBinaryArray>(def_levels, rep_levels, ++ num_levels, values); ++ } else if constexpr (::arrow::is_dictionary(ArrowType::type_id)) { ++ return GetChunks(def_levels, rep_levels, num_levels, ++ *static_cast(values).indices()); ++ } else { ++ throw ParquetException("Unsupported Arrow array type " + ++ values.type()->ToString()); ++ } ++ }; ++ return ::arrow::VisitType(*values.type(), handle_type); ++ } ++ ++ private: ++ // Reference to the column's level information ++ const internal::LevelInfo& level_info_; ++ // Minimum chunk size in bytes, the rolling hash will not be updated until this size is ++ // reached for each chunk. Note that all data sent through the hash function is counted ++ // towards the chunk size, including definition and repetition levels. ++ const int64_t min_chunk_size_; ++ const int64_t max_chunk_size_; ++ // The mask to match the rolling hash against to determine if a new chunk should be ++ // created. The mask is calculated based on min/max chunk size and the normalization ++ // level. ++ const uint64_t rolling_hash_mask_; ++ ++ // Whether the rolling hash has matched the mask since the last chunk creation. This ++ // flag is set true by the Roll() function when the mask is matched and reset to false ++ // by NeedNewChunk() method. ++ bool has_matched_ = false; ++ // The current run of the rolling hash, used to normalize the chunk size distribution ++ // by requiring multiple consecutive matches to create a new chunk. ++ int8_t nth_run_ = 0; ++ // Current chunk size in bytes, reset to 0 when a new chunk is created. ++ int64_t chunk_size_ = 0; ++ // Rolling hash state, never reset only initialized once for the entire column. ++ uint64_t rolling_hash_ = 0; ++}; ++ ++ContentDefinedChunker::ContentDefinedChunker(const LevelInfo& level_info, ++ int64_t min_chunk_size, ++ int64_t max_chunk_size, int norm_level) ++ : impl_(new Impl(level_info, min_chunk_size, max_chunk_size, norm_level)) {} ++ ++ContentDefinedChunker::~ContentDefinedChunker() = default; ++ ++std::vector ContentDefinedChunker::GetChunks(const int16_t* def_levels, ++ const int16_t* rep_levels, ++ int64_t num_levels, ++ const ::arrow::Array& values) { ++ return impl_->GetChunks(def_levels, rep_levels, num_levels, values); ++} ++ ++uint64_t ContentDefinedChunker::GetRollingHashMask() const { ++ return impl_->GetRollingHashMask(); ++} ++ ++} // namespace parquet::internal +diff --git a/cpp/src/parquet/chunker_internal.h b/cpp/src/parquet/chunker_internal.h +new file mode 100644 +--- /dev/null ++++ b/cpp/src/parquet/chunker_internal.h +@@ -0,0 +1,144 @@ ++// Licensed to the Apache Software Foundation (ASF) under one ++// or more contributor license agreements. See the NOTICE file ++// distributed with this work for additional information ++// regarding copyright ownership. The ASF licenses this file ++// to you under the Apache License, Version 2.0 (the ++// "License"); you may not use this file except in compliance ++// with the License. You may obtain a copy of the License at ++// ++// http://www.apache.org/licenses/LICENSE-2.0 ++// ++// Unless required by applicable law or agreed to in writing, ++// software distributed under the License is distributed on an ++// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY ++// KIND, either express or implied. See the License for the ++// specific language governing permissions and limitations ++// under the License. ++ ++#pragma once ++ ++#include ++#include ++ ++#include "arrow/array.h" ++#include "parquet/level_conversion.h" ++ ++namespace parquet::internal { ++ ++// Represents a chunk of data with level offsets and value offsets due to the ++// record shredding for nested data. ++struct Chunk { ++ // The start offset of this chunk inside the given levels ++ int64_t level_offset; ++ // The start offset of this chunk inside the given values array ++ int64_t value_offset; ++ // The length of the chunk in levels ++ int64_t levels_to_write; ++}; ++ ++/// CDC (Content-Defined Chunking) is a technique that divides data into variable-sized ++/// chunks based on the content of the data itself, rather than using fixed-size ++/// boundaries. ++/// ++/// For example, given this sequence of values in a column: ++/// ++/// File1: [1,2,3, 4,5,6, 7,8,9] ++/// chunk1 chunk2 chunk3 ++/// ++/// Assume there is an inserted value between 3 and 4: ++/// ++/// File2: [1,2,3,0, 4,5,6, 7,8,9] ++/// new-chunk chunk2 chunk3 ++/// ++/// The chunking process will adjust to maintain stable boundaries across data ++/// modifications. Each chunk defines a new parquet data page which is contiguously ++/// written out to the file. Since each page compressed independently, the files' contents ++/// would look like the following with unique page identifiers: ++/// ++/// File1: [Page1][Page2][Page3]... ++/// File2: [Page4][Page2][Page3]... ++/// ++/// Then the parquet file is being uploaded to a content addressable storage (CAS) system ++/// which splits the bytes stream into content defined blobs. The CAS system will ++/// calculate a unique identifier for each blob, then store the blob in a key-value store. ++/// If the same blob is encountered again, the system can refer to the hash instead of ++/// physically storing the blob again. In the example above, the CAS system would store ++/// Page1, Page2, Page3, and Page4 only once and the required metadata to reassemble the ++/// files. ++/// While the deduplication is performed by the CAS system, the parquet chunker makes it ++/// possible to efficiently deduplicate the data by consistently dividing the data into ++/// chunks. ++/// ++/// Implementation details: ++/// ++/// Only the parquet writer must be aware of the content defined chunking, the reader ++/// doesn't need to know about it. Each parquet column writer holds a ++/// ContentDefinedChunker instance depending on the writer's properties. The chunker's ++/// state is maintained across the entire column without being reset between pages and row ++/// groups. ++/// ++/// The chunker receives the record shredded column data (def_levels, rep_levels, values) ++/// and goes over the (def_level, rep_level, value) triplets one by one while adjusting ++/// the column-global rolling hash based on the triplet. Whenever the rolling hash matches ++/// a predefined mask, the chunker creates a new chunk. The chunker returns a vector of ++/// Chunk objects that represent the boundaries of the chunks. ++/// Note that the boundaries are deterministically calculated exclusively based on the ++/// data itself, so the same data will always produce the same chunks - given the same ++/// chunker configuration. ++/// ++/// References: ++/// - FastCDC: a Fast and Efficient Content-Defined Chunking Approach for Data ++/// Deduplication ++/// https://www.usenix.org/system/files/conference/atc16/atc16-paper-xia.pdf ++/// - Git is for Data (chunk size normalization used here is described in section 6.2.1): ++/// https://www.cidrdb.org/cidr2023/papers/p43-low.pdf ++class PARQUET_EXPORT ContentDefinedChunker { ++ public: ++ /// Create a new ContentDefinedChunker instance ++ /// ++ /// @param level_info Information about definition and repetition levels ++ /// @param min_chunk_size Minimum chunk size in bytes ++ /// The rolling hash will not be updated until this size is reached for each chunk. ++ /// Note that all data sent through the hash function is counted towards the chunk ++ /// size, including definition and repetition levels if present. ++ /// @param max_chunk_size Maximum chunk size in bytes ++ /// The chunker creates a new chunk whenever the chunk size exceeds this value. The ++ /// chunk size distribution approximates a normal distribution between min_chunk_size ++ /// and max_chunk_size. Note that the parquet writer has a related `data_pagesize` ++ // property that controls the maximum size of a parquet data page after encoding. ++ /// While setting `data_pagesize` to a smaller value than `max_chunk_size` doesn't ++ /// affect the chunking effectiveness, it results in more small parquet data pages. ++ /// @param norm_level Normalization level to center the chunk size around the average ++ /// size more aggressively, default 0. ++ /// Increasing the normalization level increases the probability of finding a chunk ++ /// boundary, improving the deduplication ratio, but also increases the number of ++ /// small chunks resulting in many small parquet data pages. The default value ++ /// provides a good balance between deduplication ratio and fragmentation. ++ /// Use norm_level=1 or norm_level=2 to reach a higher deduplication ratio at the ++ /// expense of fragmentation. ++ ContentDefinedChunker(const LevelInfo& level_info, int64_t min_chunk_size, ++ int64_t max_chunk_size, int norm_level = 0); ++ ~ContentDefinedChunker(); ++ ++ /// Get the chunk boundaries for the given column data ++ /// ++ /// @param def_levels Definition levels ++ /// @param rep_levels Repetition levels ++ /// @param num_levels Number of levels ++ /// @param values Column values as an Arrow array ++ /// @return Vector of Chunk objects representing the chunk boundaries ++ std::vector GetChunks(const int16_t* def_levels, const int16_t* rep_levels, ++ int64_t num_levels, const ::arrow::Array& values); ++ ++ private: ++ /// @brief Get the rolling hash mask used to determine chunk boundaries, used for ++ /// testing the mask calculation. ++ uint64_t GetRollingHashMask() const; ++ ++ class Impl; ++ std::unique_ptr impl_; ++ ++ friend class TestCDC; ++}; ++ ++} // namespace parquet::internal +diff --git a/cpp/src/parquet/chunker_internal_codegen.py b/cpp/src/parquet/chunker_internal_codegen.py +new file mode 100644 +--- /dev/null ++++ b/cpp/src/parquet/chunker_internal_codegen.py +@@ -0,0 +1,125 @@ ++#!/usr/bin/env python ++ ++# Licensed to the Apache Software Foundation (ASF) under one ++# or more contributor license agreements. See the NOTICE file ++# distributed with this work for additional information ++# regarding copyright ownership. The ASF licenses this file ++# to you under the Apache License, Version 2.0 (the ++# "License"); you may not use this file except in compliance ++# with the License. You may obtain a copy of the License at ++# ++# http://www.apache.org/licenses/LICENSE-2.0 ++# ++# Unless required by applicable law or agreed to in writing, ++# software distributed under the License is distributed on an ++# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY ++# KIND, either express or implied. See the License for the ++# specific language governing permissions and limitations ++# under the License. ++ ++""" ++Produce the given number gearhash tables for rolling hash calculations. ++ ++Each table consists of 256 64-bit integer values and by default 8 tables are ++produced. The tables are written to a header file that can be included in the ++C++ code. ++ ++The generated numbers are deterministic "random" numbers created by MD5 hashing ++a fixed seed and the table index. This ensures that the tables are the same ++across different runs and platforms. The function of generating the numbers is ++less important as long as they have sufficiently uniform distribution. ++ ++Reference implementations: ++- https://github.com/Borelset/destor/blob/master/src/chunking/fascdc_chunking.c ++- https://github.com/nlfiedler/fastcdc-rs/blob/master/examples/table64.rs ++ ++Usage: ++ python chunker_internal_codegen.py [ntables] ++ ++ ntables: Number of gearhash tables to generate (default 8), the ++ the C++ implementation expects 8 tables so this should not be ++ changed unless the C++ code is also updated. ++ ++ The generated header file is written to ./chunker_internal_generated.h ++""" ++ ++import hashlib ++import pathlib ++import sys ++from io import StringIO ++ ++ ++template = """\ ++// Licensed to the Apache Software Foundation (ASF) under one ++// or more contributor license agreements. See the NOTICE file ++// distributed with this work for additional information ++// regarding copyright ownership. The ASF licenses this file ++// to you under the Apache License, Version 2.0 (the ++// "License"); you may not use this file except in compliance ++// with the License. You may obtain a copy of the License at ++// ++// http://www.apache.org/licenses/LICENSE-2.0 ++// ++// Unless required by applicable law or agreed to in writing, ++// software distributed under the License is distributed on an ++// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY ++// KIND, either express or implied. See the License for the ++// specific language governing permissions and limitations ++// under the License. ++ ++#pragma once ++ ++#include ++ ++namespace parquet::internal {{ ++ ++constexpr int64_t kNumGearhashTables = {ntables}; ++ ++constexpr uint64_t kGearhashTable[{ntables}][256] = {{ ++{content}}}; ++ ++}} // namespace parquet::internal ++""" ++ ++ ++def generate_hash(n: int, seed: int): ++ """Produce predictable hash values for a given seed and n using MD5. ++ ++ The value can be arbitrary as long as it is deterministic and has a uniform ++ distribution. The MD5 hash is used to produce a 16 character hexadecimal ++ string which is then converted to a 64-bit integer. ++ """ ++ value = bytes([seed] * 64 + [n] * 64) ++ hasher = hashlib.md5(value) ++ return hasher.hexdigest()[:16] ++ ++ ++def generate_hashtable(seed: int, length=256): ++ """Generate and render a single gearhash table.""" ++ table = [generate_hash(n, seed=seed) for n in range(length)] ++ ++ out = StringIO() ++ out.write(f" {{// seed = {seed}\n") ++ for i in range(0, length, 4): ++ values = [f"0x{value}" for value in table[i : i + 4]] ++ values = ", ".join(values) ++ out.write(f" {values}") ++ if i < length - 4: ++ out.write(",\n") ++ out.write("}") ++ ++ return out.getvalue() ++ ++ ++def generate_header(ntables=8, relative_path="chunker_internal_generated.h"): ++ """Generate a header file with multiple gearhash tables.""" ++ path = pathlib.Path(__file__).parent / relative_path ++ tables = [generate_hashtable(seed) for seed in range(ntables)] ++ content = ",\n".join(tables) ++ text = template.format(ntables=ntables, content=content) ++ path.write_text(text) ++ ++ ++if __name__ == "__main__": ++ ntables = int(sys.argv[1]) if len(sys.argv) > 1 else 8 ++ generate_header(ntables) +diff --git a/cpp/src/parquet/chunker_internal_generated.h b/cpp/src/parquet/chunker_internal_generated.h +new file mode 100644 +--- /dev/null ++++ b/cpp/src/parquet/chunker_internal_generated.h +@@ -0,0 +1,548 @@ ++// Licensed to the Apache Software Foundation (ASF) under one ++// or more contributor license agreements. See the NOTICE file ++// distributed with this work for additional information ++// regarding copyright ownership. The ASF licenses this file ++// to you under the Apache License, Version 2.0 (the ++// "License"); you may not use this file except in compliance ++// with the License. You may obtain a copy of the License at ++// ++// http://www.apache.org/licenses/LICENSE-2.0 ++// ++// Unless required by applicable law or agreed to in writing, ++// software distributed under the License is distributed on an ++// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY ++// KIND, either express or implied. See the License for the ++// specific language governing permissions and limitations ++// under the License. ++ ++#pragma once ++ ++#include ++ ++namespace parquet::internal { ++ ++constexpr int64_t kNumGearhashTables = 8; ++ ++constexpr uint64_t kGearhashTable[8][256] = { ++ {// seed = 0 ++ 0xf09f35a563783945, 0x0dcc5b3bc5ae410a, 0x63f1ea8d22554270, 0xfbe5ee7bd05a7b61, ++ 0x3f692ed5e9934aba, 0xaab3755952250eb8, 0xdefb168dc2888fa5, 0x501b36f7c77a7d47, ++ 0xd2fff45d1989642d, 0x80217c1c600e30a6, 0xb9469ee2e43df7ac, 0x3654b76a61999706, ++ 0x6ea73dfe5de0c6b6, 0xdfd662e1937a589d, 0x0dbe0cc74b188a68, 0xde45f4e6d73ffc6f, ++ 0xcdf7a7759e70d87e, 0x5d6a951b8d38c310, 0xdc9423c3813fcf2c, 0x25dc2976e167ffce, ++ 0xc2555baa1d031c84, 0x115bc3f2230a3ab6, 0xd4b10260f350bede, 0xdfd3501ab447d723, ++ 0x022e79217edaf167, 0x1635e2255c5a7526, 0xa0a750350cc77102, 0xc027133e05d39f56, ++ 0xd949459779cf0387, 0xb92f1464f5c688c2, 0xd9ac5f3e8b42f2f3, 0xdf02bb6f5ecaac21, ++ 0x8156f988fac7bfa4, 0xe4580f97bede2ec8, 0x44fe7d17a76fca32, 0x885f59bd54c2014c, ++ 0x435e63ec655ffae9, 0x5ebc51930967b1f1, 0x5428c2084ac29e47, 0x9465938fec30e36b, ++ 0xc7cb3de4977772cd, 0x15692d7c201e8c3a, 0x505ee65cdc4b17f4, 0x7d9839a0a7aead6b, ++ 0xeef5f5b6a0105291, 0x76c2fb232ce7f5bf, 0x5c13893c1c3ff3a9, 0x65b6b547d4442f98, ++ 0xb8ad7487c8c96fce, 0x906bcf51c99974f8, 0x2f56e48bb943a48c, 0xbc9ab109f82d3a44, ++ 0xcd5160cdc8c7e735, 0xbe9acb9df3427732, 0x386b91d477d7fade, 0x36be463621dd5af2, ++ 0xcbe6a2faffd627a8, 0x9c8fd528463a2f5a, 0xb9b88c6bb802b184, 0xb414b4e665c597c7, ++ 0xbedb142568209556, 0x5360d81c25429dce, 0x63a69a960a952f37, 0xc900d63899e1b503, ++ 0x1abc63a8b37c7728, 0xa8b3a8b6409080eb, 0x495e391f662959f6, 0xdf1e136f3e12229b, ++ 0x33d5fc526b0dd38d, 0x321221ae2abfac63, 0x7fde18351fda7395, 0xed79fe5c3a6aa4c3, ++ 0x2dd6965a4867d8d4, 0x54813ca20fe8799b, 0x5d59ea6456465c39, 0x0de0c294d1936b81, ++ 0x4aaf0755002c588c, 0x3530a1857ad04c6d, 0xb8a64f4ce184442b, 0xe0def10bceedfa17, ++ 0x46e38d0a443757ec, 0x9795a1c645ee16d7, 0x7e531def245eac8a, 0x683b25c43a0716cf, ++ 0x884583d372da219d, 0x5b06b62c910416e5, 0x54b6902fbebd3dbe, 0x931198d40a761a75, ++ 0xead7d8e830013590, 0x80b4d5dc99bfaced, 0xf98272c8108a1ad2, 0x1adce054289a0ec6, ++ 0x7d53a1143c56b465, 0x497fbe4f00c92b52, 0x525e4cc2e81ebd69, 0xc94478e0d5508ff6, ++ 0xb8a5da83c196d07c, 0x7667a921b65b0603, 0xf236fabbdefe6cd1, 0x53da978d19a92b98, ++ 0xc604f6e97087124d, 0x2cbd27221924b094, 0x65cd1102c985b1d2, 0x08c0755dc1a97eb4, ++ 0x5e0419e921c0fef1, 0x282d2c1196f84a29, 0xe21117fcfc5793f7, 0xcf4e985dc38e6c2e, ++ 0xd521f4f264d55616, 0xde69b04c485f2a10, 0x59410e245305178a, 0xceab1d477c943601, ++ 0xa9805732d71ee5e9, 0x054cd443896974f6, 0xf2b517717a423a3e, 0x09517937fa9fac95, ++ 0x4938233e9ca871e3, 0x9132cbaf56f83ec0, 0x4703421ed1dd027d, 0xfd9933f4e6f1ec4e, ++ 0xf237c7fded2274a8, 0xdf4616efe68cd7b4, 0x5e46de0f39f0a380, 0x3d41e0c6d8e095b0, ++ 0xc5272f8a5bb2df09, 0x68aa78e8301fb964, 0xbf5b5b52c8e32ae0, 0xbf28ed3df74bdcf7, ++ 0xd6198f64c833815a, 0x8cd99d2974267544, 0xd90560ea4465ff2c, 0x571d65ad7ad59261, ++ 0x309453518baa367a, 0xa60538377bc79fb2, 0xace515da1ab4183c, 0xf56d3c8d891d1c5b, ++ 0x5b0d8370b59def49, 0x775866ce7c83c762, 0x3d76085695c8e18a, 0xba064d1a9af1b114, ++ 0xc84ef7cd7b98b521, 0x90b9231681c2bc37, 0x37e2b13e6f585b6b, 0x1d0a34e55e0f369f, ++ 0x86bb8019cf41447c, 0x4b95c6ef55b3f71f, 0x3b6ed1660732b310, 0x617eee603d137f21, ++ 0xf4f6278b464f3bbc, 0xdfb763b720da205a, 0x353478899b871cb7, 0xe45fbbff574cc41e, ++ 0x1a94b60847907d72, 0xb10eef051eff67a5, 0xf0e012ec6a284d40, 0xcc1cd1a11b926d7c, ++ 0xcf9d9c5453e19cad, 0x270febcc0fc0e86b, 0xd6567568778b781e, 0x7323b98965eeb46b, ++ 0xccecd374567086ff, 0xef7b44bfc497a704, 0xebc479c051a9f0a5, 0xc9b7410e3e00a235, ++ 0x1d084f7ecdf83dab, 0xc8a9a97e33ba8ba3, 0x8c75318f5b2350d6, 0xaa3cd5d0c684bdda, ++ 0xa81125fe0901bedf, 0xf7bcd76020edfc93, 0x834ee4c12e75874f, 0xb2bb8a7beb44fa14, ++ 0x32cd26f50a4f4e4d, 0x0fc5817ca55d959a, 0xd6e4ae2e3ae10718, 0x074abdcceb8d6e38, ++ 0xc0cc5f4f9b3a9c43, 0x1115d364363595b2, 0x69861db2eb19f2e8, 0x59b8d804cf92bc67, ++ 0x9bac9785e5e4b863, 0x7fa0e17a41869561, 0x10d3c9633f0c709c, 0x534a03deee6bc44a, ++ 0x73b1f7201257f581, 0x46fd6a11e2e0706b, 0x494abb554946e67a, 0xb5d6da317864dc8e, ++ 0x402ded9238f39687, 0xd8fa37d2cbd6d290, 0xcc818293fcb06791, 0x6482ab344806cd4d, ++ 0x0956e6ee9d8eb60b, 0x01fee622d8465ac8, 0xae7ece370cbd9c35, 0x7ff09e937a177279, ++ 0xa2c29ee7a33ca5f1, 0x990e8dbee083923b, 0x4a819b72f610863a, 0xddecfad79d3f08be, ++ 0x627372480fac20a7, 0x802154d6eca2db4c, 0x8fcf02e42f805e55, 0x040a911ff8cea977, ++ 0xbb544485bc64d0d4, 0xaddde1aeb406d0fb, 0xf6b35fae23dce66f, 0xc07a9fb3645d2f9b, ++ 0xccd113907e9c0fed, 0xd17af369984fd213, 0x9223823c59a083e7, 0xe19d475606b81013, ++ 0xe181ac116a90e57a, 0x71f7b6258c6def4c, 0x2246f34b45964f7c, 0xd74aedaea2d31751, ++ 0xb1add86e5dd305d1, 0xeb9ba881f16d6471, 0xef7600e036f5c6ff, 0x1d50bc9735b8fb85, ++ 0xe63942bd1f3e2969, 0x9241ba9f8b3f4e72, 0xee8bb2bca07d35b6, 0x55cd55dab522654e, ++ 0x94d0cfa7c1a6845d, 0x02f9845d559884c3, 0x8ce70ea21063b560, 0xd70998028ef08b74, ++ 0xdfdb5bbee310876b, 0x4e21b2e348256d16, 0xde007a981c13debc, 0xe51950cbbddabfdd, ++ 0xd223301dbe9957c1, 0x084b8634cc2cce4b, 0x90e551378aa9d70c, 0x833b533ac633e448, ++ 0x7891e232882da57f, 0xa1bf26f0163ce2b3, 0xf33a0171eb9c68d5, 0x2e7de18ca69b3fa2, ++ 0x666fd6f175619199, 0x1239d37edb5feb9f, 0xfa9fc9382e61ff5c, 0x3ca4ad427e3c126f, ++ 0x37c6dd4c2c31ae6e, 0x1f1bacb619d427b2, 0x7dd09f5d10759afe, 0xc8d941432327d733, ++ 0x2b389ba25e1d43a7, 0xa4e3030c3740ff21, 0xcc56dae13fd37463, 0x2481457c175b560f, ++ 0x9deb35bde77c5c41, 0x847aa6ea5549a0c3, 0xcde01bb48b6e7f02, 0x15a28844e64cb211}, ++ {// seed = 1 ++ 0xecfcba92fe5691a3, 0x71377799fea34699, 0xb284c9096fa614e5, 0x54534170f40de6c8, ++ 0xbbd804d45884fba3, 0x44929a896388c8a1, 0x79b712508e0fa3b1, 0xeb53ab280af31054, ++ 0x351ea23a6319da7a, 0x2fbe55d9819d85a2, 0x34f4b6568dcd28b1, 0x8c94ea5e5d82967a, ++ 0x09068d333a46d3c5, 0x762ad4f64cb73381, 0xd5c6db5ef0e22640, 0x36d8ab5a36175680, ++ 0xd41fe333cdc3525a, 0xa1f51dbdf20ce781, 0x1410a95e786c8be6, 0x96b7499a670c2b41, ++ 0x3912e1037835d893, 0x272c5bd83e1e9115, 0x2ea7f91cad82a0d6, 0xcd10e85662ce9931, ++ 0xedad49be8d5e8b74, 0x7ccd8fe0f37d12bc, 0xfac0482005eed593, 0x4513991681f6c8b0, ++ 0x2804d612eb0ad37d, 0x7cca9e8412b81d34, 0x85ffd6707192b7b8, 0xea0560aeea954411, ++ 0x0122d28226102bba, 0xf51c47cdbd22fdd1, 0x3707d851183ff17c, 0xaef5a1465f3e902d, ++ 0xbcb38c2d8736a04f, 0x4025317e864bef15, 0x8d3f66d86e1ea58f, 0xc16759a3d97ed79a, ++ 0x1c62abdc0659f2f5, 0x23b3eb4e699bd28f, 0x5083c4fceed3ccaf, 0xa65bf34562cc989c, ++ 0xaa5865932fd79064, 0xf24d08d268c24593, 0x7fbd00a215196999, 0x7812cd366d752964, ++ 0x62e8dcb27ef3d945, 0xf08b7984e1b946dc, 0x547d23ad9a5c1dcf, 0x496b1fb249b27fb7, ++ 0xcd692e1db5f3b3ba, 0x41931e39f1e1bc61, 0x286c6a7d7edae82b, 0x17ef6638b6c4ca6e, ++ 0x609beb5a2576a934, 0xcc5e16fe4a69b83c, 0xbbd14d08b078fc24, 0x2a617680f481cb94, ++ 0x81dbbd5f86e6d039, 0xeb8205e1fc8ecc3c, 0xe5e3bb576faa8042, 0x5d6f1eb9d9df01b5, ++ 0x9a47b8739c10fb44, 0x398a7caad7ea7696, 0x9c0fc1d7c46adde6, 0x67cd6de0a51978a6, ++ 0x68ccc4b77a21cca4, 0x1e067066b82f415c, 0xf7ddade6535e1819, 0xf2185c884291751b, ++ 0xc322b7381fcbe34f, 0x242f593e88290b9b, 0x8e11ccc0ea5e84a3, 0x40e3a2e3346db8a2, ++ 0xf18bfc3ad2931a2c, 0x2468397394b00144, 0xeae199cce14e6817, 0x05b462686c75a1ae, ++ 0xda096cb859c51673, 0xd87aeb967a906bef, 0xaabc74493cb02fe6, 0x74d48fc2e7da143e, ++ 0x6ec1c8fed3f2c1fd, 0xe01e0704b463f18e, 0xc3d88a4d3a8056e4, 0xd01ae0ffab6c8f3f, ++ 0x881ba052620ae7c7, 0xcea033aef0a823a5, 0x8d2cad91d83df1e3, 0x18746d205e66dbe9, ++ 0x3061f8e58d046650, 0xd819c59f0ce2cf8b, 0x144e89e93635e870, 0x3415e88279b21651, ++ 0xd6f7ab944b86c3fa, 0x45f1dd15d0f67bdc, 0xbf0d97c7f4fa24f4, 0x34a7de520a57fcd2, ++ 0x4ba86fda03e9e2bc, 0xa7995265a025b552, 0x698f6819d5f51cf7, 0xd07dbe9d8a156981, ++ 0x2683945373857fc1, 0x116f8a84f96167de, 0x8bc832bd85595ebf, 0xb206519d74fdfafa, ++ 0xde9519b2e9b5cc5f, 0x16fdd6f2da1d8163, 0x7ba32bd48ef56f11, 0x6f4e4d7ee8b29717, ++ 0xd31576dde7468aad, 0x023bb08848676045, 0xf6dcc083178160b7, 0x42035f426250e683, ++ 0x343732993cfed89f, 0x0640a870a22d3d58, 0x65cff80b53b4ae6a, 0x27996fa17ab05215, ++ 0xfd5db01401b21a04, 0x894508784bc1673c, 0x5bfcf43a2380e27d, 0x4cd6dcc2715583b7, ++ 0xa43b3763e7d4c902, 0x6da83e12ef0c1257, 0xfe80a602b0335aff, 0x293a7d8f4ff344de, ++ 0xb4ae7c2b8956bf5a, 0x6b45432d38254b4d, 0xd086acbdf15d9455, 0xa4d19e43f41ea87b, ++ 0xf01f13ba4bb87fbf, 0xca582cf301a299ff, 0x0ddad3d45298fa7d, 0x0646a130459c3999, ++ 0xc08e3af3747e2cee, 0xfc7db8aa9ed67295, 0x783b329e7bd79d5f, 0x732dbc607957af7b, ++ 0x8e446ac19fb26555, 0xff1dfa4d61dc89a5, 0xb6fbc46bd8d011d8, 0x185147ec5779f0d7, ++ 0x6eb2cf6149a5380f, 0xb0e773df803a1eae, 0xc07706c5519bfce5, 0xc35abcf54fa95f14, ++ 0x40a01d99a38608ea, 0x776dcd6f603c277f, 0x6ae12389b1d6d0bb, 0x8bd981448df92bb9, ++ 0x426a6a7ca21a2c16, 0x87efd5b71c1bad26, 0x71fb7fc4cd41de48, 0xdd9033c45619d463, ++ 0x40eaab322654cef7, 0xe077fffed6f3e3a2, 0x375a4dbef9384447, 0x2066b009d2c4a100, ++ 0xeca4a5794a068447, 0x2128f64bddf341a1, 0x738b4bb1be90bd61, 0x433772cf3813d52e, ++ 0x9540c88add8e4474, 0x0b6d5decd21d3519, 0x654ead966745642d, 0xe1bfb03c3b4bdb4c, ++ 0x0b977a9937515b1f, 0x0a4587509ef63870, 0xe89f0de1d9cfd44a, 0x23a91390272e7f68, ++ 0xd92defbc9096b8d8, 0x004db87174612539, 0xc88ecaabdd1a71f1, 0x050de38393073346, ++ 0x8af1426d7964e038, 0xf352c4fef8ad5c87, 0x6f26bc7408e26548, 0x0d41543fd9bf3084, ++ 0xfc4e07553a840fc6, 0x5ef117de86a555a9, 0x1f11c42dffb5ae1b, 0x4147648f07490fa5, ++ 0x09b35fd7671b21aa, 0x1453b14f7ccca481, 0x944f6fcce4c9b2ba, 0x5b08dd2e3583dc06, ++ 0xe0220df78dc9c22d, 0x1c200b9506cbf666, 0x8a0b7465eadb523b, 0xfbcb43a91a1e2d80, ++ 0xe697f44be3c36a58, 0x2f8a8e48fb7e350d, 0x7baba71b8920d55f, 0x10edc0216105bc96, ++ 0x52db07c79d7a7a63, 0x1916e8cef9452ac3, 0x5cbbbf21f867b6cc, 0xadd583365a690a4b, ++ 0x4e4ca2c8bffc2fdb, 0xf5fe3416d2eebcfe, 0x839af8b85e452476, 0x8496c0c54ad44e16, ++ 0x6c46f1ecad4482bf, 0xb794cad76ae18715, 0x67b762eec7c62985, 0x52dc9e68df5b3a53, ++ 0x0cc7e444b422a5f9, 0xadbfe90841c112b0, 0xfe37b136f0ca5c34, 0xcfe9e47948a8d73e, ++ 0xee90572b86a30d91, 0x549e72d8262830aa, 0x3361564b469f32c6, 0x1e6eba9e0d2648e2, ++ 0x5f8e2b2ac5fcb4eb, 0xe4224fa5f71f7cc6, 0x7357a9230c76757b, 0xcad70f74aaf6b702, ++ 0xeef28ced23894cc2, 0x753fdd3352aefd68, 0x1fed6ba90bbeb9d2, 0x05316f4ab4034b4b, ++ 0x3396df022b9f63d6, 0x82d7125a7cfd0935, 0x3519a71caf1f87f0, 0xd1dfb7a5cc3974be, ++ 0xbfae40ecbdbbcc2a, 0x152c11778e08dd54, 0x4a96566a6c848554, 0x3a84d621c340cdd7, ++ 0xfd47aa1887e2fb03, 0xa63cae94b2f1d099, 0xed61783f3e5b75e0, 0xefd44864106019be, ++ 0x145ff78b80b081aa, 0x34670e5fcea9230e, 0x876ef976328db371, 0x4221f3a5269942a6, ++ 0x95315cbd85c648f4, 0x3ca344dc7c3b1600, 0x38421ea39ff28780, 0x31dbeee967c0435c, ++ 0x27437c3e268402e7, 0xdd0cf8343312a654, 0x965ab9dad1d8aa29, 0xf871706dd3e23509, ++ 0xce23d06c7a25e699, 0x1b37d59382b27589, 0x3407f004723d6324, 0x56efb69cdb5deaa1, ++ 0xf46cdd2b9fd604e0, 0xcad3ca79fdac69bd, 0x7252802a574e63cb, 0xc281fb8acc6ec1d3}, ++ {// seed = 2 ++ 0xdd16cb672ba6979c, 0x3954eaa9ec41ae41, 0x52cb802771d2966d, 0xf57ed8eb0d0294f2, ++ 0x768be23c71da2219, 0x6131e22d95a84ad3, 0xd849e4e49bb15842, 0x18e8e5c4978cf00d, ++ 0x3af5e5867ce1f9bd, 0x06c75a9fffe83d63, 0xe8de75a00b58a065, 0x0a773251bc0d755a, ++ 0x629dc21e54548329, 0x2a168f5e5a883e70, 0x33547375f0996c86, 0xdfcb4c7680451322, ++ 0x55c1ecaaaa57e397, 0x4546c346c24f5a31, 0x6f8f0401dfabc86c, 0x7760d2d36ee340b4, ++ 0xf6448e48bdeb229d, 0xba70e1633b4dba65, 0x069cda561e273054, 0xa010b6a84aebf340, ++ 0x5c23b8229eee34b6, 0xea63c926d90153af, 0x7d7de27b3e43ec1b, 0xea119541eddc3491, ++ 0xf1259daeddfc724c, 0x2873ca9a67730647, 0xa1e7710dade32607, 0x758de030b61d43fd, ++ 0xd2c9bcbfa475edb4, 0x18ade47bb8a0aa29, 0xf7a74af0ff1aea88, 0x6f8873274a987162, ++ 0x6963e8d876f4d282, 0xd435d4fe448c6c5b, 0x93ec80ba404cafff, 0xcf90d24c509e41e7, ++ 0x5f0fc8a62923e36e, 0x9224878fe458f3a4, 0xd9a039edf1945bcd, 0x0877d1892c288441, ++ 0x75205491f4b4740b, 0x30f9d2d523a9085b, 0x4b7f4029fa097c99, 0x170bb013745709d4, ++ 0x7087af537f11ef2e, 0x28c62b88e08fc464, 0x84bbcb3e0bb56271, 0x485a4b099165c681, ++ 0x357c63357caa9292, 0x819eb7d1aee2d27e, 0xdaa759eb9c0f8c9d, 0x42cdc36729cc3db5, ++ 0x9489aa852eddbb06, 0x8161e4f85a84e6d4, 0xa964863fdad3eb29, 0xcc095ddbce1a6702, ++ 0x3ecfadbb8dc2ce58, 0x971316509b95a231, 0xc8f484d1dbc38427, 0xae9c510c463574c0, ++ 0xdf2b31179600c21a, 0x440de87bada4dfa3, 0xbd8d30f3f6fb7522, 0x84e6d7f678a0e2d0, ++ 0x0ec4d74323e15975, 0xf6947610dad6d9ab, 0x73a55a95d73fe3a5, 0x3e5f623024d37eda, ++ 0x8d99a728d95d9344, 0x8b82a7956c4acdc4, 0x7faeaea4385b27f6, 0x540625ff4aa2ff21, ++ 0x4aa43b3ebd92ce2b, 0x899646a6df2da807, 0x49225115780942d7, 0xe16606636af89525, ++ 0xb980bcf893888e33, 0xf9ed57695291b0d8, 0x5c6dd14464619afa, 0x50606d69b733d4f3, ++ 0x7fb1af465b990f97, 0x3fab2634c8bbd936, 0x556da6168838b902, 0x0f15975902a30e1f, ++ 0xb29d782ae9e1991f, 0xae00e26ff8f7e739, 0xd3da86458bb292d5, 0x4528ee0afb27e4ce, ++ 0x49882d5ba49fabad, 0x7e873b6a7cf875ee, 0x777edd535113c912, 0x94ed05e7ff149594, ++ 0x0b8f95fc4211df43, 0x9135c2b42426fef2, 0x411e6c2b47307073, 0x503207d1af0c8cf8, ++ 0xd76f8619059f9a79, 0x64d24617855dee45, 0xf7bc7a877923196a, 0xd6cc42ed6a65be79, ++ 0xe3912ff09d4fc574, 0x4192d03b2bc2460a, 0xa0dcc37dad98af85, 0xfc59049b2a5818a4, ++ 0x2128bae90a5b975f, 0xbe7067ca05ea3294, 0x5bab7e7753064c4f, 0x42cbf0949ef88443, ++ 0x564df4bbd017492c, 0xf2c2eb500cf80564, 0x5b92e67eb00e92af, 0x8c4103eef59c0341, ++ 0x83412122b8284998, 0x888daf2da0636b6d, 0x4d54b10303dd07d6, 0x201190e7c1e7b5ed, ++ 0x3797510bb53a5771, 0x03f7bc598b570b79, 0xdc1e15d67d94f73e, 0x721e8b499ebe02c1, ++ 0x71f954f606d13fa0, 0x0c7a2e408c168bf0, 0x07df2ef14f69c89d, 0xe295096f46b4baaf, ++ 0x7a2037916438737e, 0xd1e861aeaf8676ea, 0xb36ebdce368b8108, 0xb7e53b090ddb5d25, ++ 0x5a606607b390b1aa, 0x475e52994f4a2471, 0xbcc2038ba55b2078, 0x28b8a6b6c80df694, ++ 0xb5f0130ec972c9a2, 0x7a87cd2a93276b54, 0x4d0eec7ecf92d625, 0xac1a8ce16269a42e, ++ 0xa4ca0237ca9637b8, 0xd8dc8ff91202b6ff, 0x75b29846799d7678, 0x761b11a5edd9c757, ++ 0xf2581db294ef3307, 0xe3173c2b6a48e20f, 0xe46fd7d486d65b3c, 0x1352024303580d1f, ++ 0x2d665dae485c1d6d, 0x4e0905c825d74d3b, 0x14ff470c331c229e, 0xbdc656b8613d8805, ++ 0x36de38e396345721, 0xaae682c1aa8ff13b, 0x57eb28d7b85a1052, 0xf3145290231d443a, ++ 0xd0f68095e23cbe39, 0x67f99b3c2570b33d, 0x54575285f3017a83, 0x9b2f7bb03d836a79, ++ 0xa57b209d303367a9, 0x7ccb545dd0939c79, 0x1392b79a37f4716d, 0x6e81bb91a3c79bcd, ++ 0x2c2cd80307dddf81, 0xb949e119e2a16cbb, 0x69625382c4c7596f, 0xf19c6d97204fb95c, ++ 0x1b2ea42a24b6b05e, 0x8976f83cd43d20ac, 0x7149dd3de44c9872, 0xc79f1ae2d2623059, ++ 0xca17a4f143a414e1, 0x66d7a1a21b6f0185, 0xed2c6198fe73f113, 0x16a5f0295cbe06af, ++ 0x5f27162e38d98013, 0xf54d9f295bdc0f76, 0x9ba7d562073ef77b, 0xa4a24daaa2cfc571, ++ 0x49884cf486da43cd, 0x74c641c0e2148a24, 0xbff9dcbff504c482, 0xf8fc2d9403c837ab, ++ 0x6ccc44828af0bb1e, 0xbcf0d69b4c19dfdb, 0x8fe0d962d47abf8f, 0xa65f1d9d5514271d, ++ 0x26ff393e62ef6a03, 0xc7153500f283e8fc, 0xea5ed99cdd9d15cd, 0xfc16ac2ba8b48bb7, ++ 0xf49694b70041c67a, 0xbd35dd30f5d15f72, 0xcf10ad7385f83f98, 0x709e52e27339cdc2, ++ 0xe9505cb3ec893b71, 0x2ffa610e4a229af7, 0x12e1bc774d1f0e52, 0xe301a3bb7eacccc8, ++ 0x1fdd3b6dcd877ebf, 0x56a7e8bda59c05aa, 0x99acd421035d6ab4, 0xfd21e401cecd2808, ++ 0x9a89d23df8b8d46f, 0x4e26b1f1eb297b9c, 0x9df24d973e1eae07, 0xe6cdc74da62a6318, ++ 0xfc360d74df992db0, 0xf4eca0a739514c98, 0x481c515ba9bf5215, 0xce89cce80f5f3022, ++ 0xf487a10fc80e4777, 0x235b379a87e41832, 0x76f72e028371f194, 0xd044d4a201325a7d, ++ 0x47d8e855e0ffbdde, 0x268ae196fe7334b0, 0x123f2b26db46faa8, 0x11741175b86eb083, ++ 0x72ee185a423e6e31, 0x8da113dfe6f6df89, 0x286b72e338bbd548, 0xa922246204973592, ++ 0x7237b4f939a6b629, 0x31babda9bedf039a, 0xb2e8f18c6aeec258, 0x0f5f6ce6dd65a45e, ++ 0x8f9071a0f23e57d3, 0x71307115ba598423, 0xcbe70264c0e1768c, 0x1c23729f955681a8, ++ 0xfbc829099bc2fc24, 0x9619355cbc37d5d6, 0xea694d4e59b59a74, 0xb41cf8d3a7c4f638, ++ 0xae1e792df721cd0b, 0x7cd855d28aac11f6, 0xca11ba0efec11238, 0x7c433e554ce261d8, ++ 0xe3140366f042b6ba, 0x8a59d68642b3b18c, 0x094fcdd5d7bccac2, 0x9517d80356362c37, ++ 0x4a20a9949c6c74e8, 0xc25bcf1699d3b326, 0xa8893f1d1ed2f340, 0x9b58986e0e8a886e, ++ 0x29d78c647587ce41, 0x3b210181df471767, 0xd45e8e807627849d, 0x1ec56bc3f2b653e3, ++ 0x974ff23068558b00, 0xdb72bdac5d34262c, 0x23225143bb206b57, 0xd0a34cfe027cbb7e}, ++ {// seed = 3 ++ 0x39209fb3eb541043, 0xee0cd3754563088f, 0x36c05fc545bf8abe, 0x842cb6381a9d396b, ++ 0xd5059dcb443ce3bf, 0xe92545a8dfa7097e, 0xb9d47558d8049174, 0xc6389e426f4c2fc0, ++ 0xd8e0a6e4c0b850d3, 0x7730e54360bd0d0d, 0x6ecb4d4c50d050d5, 0x07a16584d4eb229f, ++ 0x13305d05f4a92267, 0xb278ddd75db4baec, 0x32381b774138608f, 0x61fe7a7163948057, ++ 0x460c58a9092efee6, 0x553bf895d9b5ff62, 0x899daf2dabfd0189, 0xf388ab9c1c4b6f70, ++ 0xd600fe47027ea4cd, 0x16d527ec2b5ef355, 0x5ac1f58ff6908c81, 0xa08d79ff8ee9ffe8, ++ 0xc1060a80b7a5e117, 0x14b2c23118c60bda, 0x8cc0defbb890df8f, 0xe29540fd94c6d28b, ++ 0xa604f003f82d5b71, 0xa67583d4eb066d18, 0xd62cbd796322b3fc, 0x070cfe244cdcccf3, ++ 0x73557c30b3af47e5, 0x2e544e31153a2163, 0x996eef7464d5bead, 0xbc71cb5ab0586cdc, ++ 0x0bfcb6c1b517ed69, 0x62b4f1fcc82e8ca0, 0x0edbc68f544965c5, 0x40fa39baa24af412, ++ 0xf39aeb2413dab165, 0x17e6013e7afee738, 0x8109bff1c8d42a9d, 0x3cd99863390989b5, ++ 0x02021a4cc9c336c8, 0xa06060778cb60aa4, 0xd96591db60bc1e06, 0xd2727175183f4022, ++ 0xcdc1f1c5bce3e7ce, 0xb393ccc447872a37, 0xdf6efe63257ead3a, 0x20729d0340dbceb6, ++ 0x9f3d2d26fc0ea0d7, 0xf392e0885189bd79, 0xdf2ee01eb212b8b6, 0x6e103a0c0f97e2c3, ++ 0x96c604a763bd841b, 0x9fc590c43bba0169, 0xf92dcd5ddc248c40, 0x113a8b54446941dc, ++ 0x5943eda146b46bb8, 0xbf657901a36a39a7, 0x5a4e0e7ea6568971, 0xb94c635bae9f9117, ++ 0x2626fb65b3a4ef81, 0xa59bfd5478ce97de, 0x79112ba9cc1a1c63, 0xf41f102f002cf39c, ++ 0x0a589bcbfb7ff1c8, 0xa1478c53540c4fa1, 0x60d55e72c86dfaca, 0x312e7b6840ea7a39, ++ 0x8aae72dcccfe1f75, 0xff2f51f55bf0247a, 0x3c2e4b109edb4a90, 0x5c6d73f6525c7637, ++ 0xe49acb04a199f61c, 0x27860642d966df7f, 0x541ce75fb1e21c30, 0xd9fcd6f90806c7cc, ++ 0xb87c27bc93a7969b, 0x92f77a1179b8f8dc, 0xb1f29379deb89ed4, 0x7e63ead35808efe7, ++ 0x13545183d7fa5420, 0x575f593e34cf029d, 0x27f1199fb07344ae, 0xe67f95f7dc741455, ++ 0x49b478b761ab850b, 0xd7bedf794adfc21e, 0xdc788dcd2dda40ae, 0x14673eb9f4d8ad35, ++ 0x0cced3c71ecf5eb1, 0xe62d4e6c84471180, 0xdfe1b9e2cb4ada7d, 0x70185a8fce980426, ++ 0x0ce2db5e8f9553d6, 0x1fedc57bb37b7264, 0xb9310a2e970b3760, 0x989ff8ab9805e87d, ++ 0x0b912d7eb712d9ee, 0x1fe272830379e67c, 0x16e6a73aff4738fb, 0xeed196d98ba43866, ++ 0x7088ca12d356cbe2, 0x23539aa43a71eee0, 0xed52f0311fa0f7ad, 0xa12b16233f302eea, ++ 0xc477786f0870ecb4, 0xd603674717a93920, 0x4abe0ae17fa62a4c, 0xa18f1ad79e4edc8d, ++ 0xc49fe6db967c6981, 0xcc154d7e3c1271e9, 0xdd075d640013c0c0, 0xc026cd797d10922a, ++ 0xead7339703f95572, 0x4342f6f11739eb4b, 0x9862f4657d15c197, 0x4f3cb1d4d392f9ff, ++ 0xe35bffa018b97d03, 0x600c755031939ad3, 0xb8c6557ffea83abf, 0x14c9e7f2f8a122ea, ++ 0x0a2eb9285ee95a7c, 0x8823fec19840c46f, 0x2c4c445c736ed1d0, 0x83181dff233449f1, ++ 0x15ed3fca3107bef5, 0x305e9adb688a4c71, 0x7dbef196f68a3e2e, 0x93e47ece3e249187, ++ 0x8353c5e890ead93c, 0xea8a7ae66abafdf7, 0xf956dbb6becf7f74, 0x9f37c494fbfdb6e4, ++ 0x11c6cbaa2485dd32, 0x206f336fcca11320, 0x9befe9a59135d8fe, 0x5f3ef8b8db92c7db, ++ 0xbb305e556ce0ce9a, 0xf26bdafb1305887f, 0xcbf28abe23f08c61, 0x0bc64173b914e00b, ++ 0x9168da52e983f54a, 0x6ea41d09c3574a3e, 0x78aa44d4a74459ae, 0x2931422878387bf5, ++ 0x018f64a3a92c2d9c, 0x9be43f6752e66b34, 0xae378890decd1152, 0x07325329a1cb7623, ++ 0x3b96f4ee3dd9c525, 0x2d6ebcdbe77d61a3, 0x10e32b0e975f510c, 0xffc007b9da959bf9, ++ 0x38bf66c6559e5d90, 0xbe22bdf0bf8899fe, 0x87807d7a991632a8, 0x149a0d702816766a, ++ 0x026f723db057e9ab, 0xeeecb83625ec6798, 0xcec2ed5984208148, 0xd985a78e97f03c84, ++ 0xf96c279e7927b116, 0x99d5027b3204f6e2, 0x13a84878c3d34c55, 0x5cf5ec96229e9676, ++ 0x0bc36b07e4f8e289, 0xbed33b80a069914d, 0x2fbfbdd1ff4b9396, 0xab352bb6982da90f, ++ 0x154d219e4fa3f62b, 0x4d087512bb6b9be7, 0xc582e31775ee400e, 0x7dadb002ae8c4a4e, ++ 0xaae2957375c1aee2, 0x5f36ca643356625b, 0xf87cf8eb76e07fb7, 0x46f432a755e02cc3, ++ 0x36087e07aba09642, 0xe5642c1e4ebb9939, 0xb9152d22338eefad, 0xf7ba44278a22cf7f, ++ 0xd3b8013502acd838, 0x7761511da6482659, 0xb0857621638e8e50, 0x552eddb4a8b1d5f5, ++ 0xc43d9861e812c3ea, 0xd765c2aada47910c, 0x21c935b68f552b19, 0x6256d5641a2b47dc, ++ 0xab711d8e6c94bc79, 0xa8d0b91a2a01ab81, 0x5e6d66141e8d632a, 0x7638285124d5d602, ++ 0x794876dbca3e471f, 0x951937d8682670ce, 0x0f99cb1f52ed466a, 0x8c7cd205543b804c, ++ 0x2fd24d74a9c33783, 0xe5dcb7b7762e5af1, 0x45e6749cca4af77c, 0x540ac7ee61f2259f, ++ 0x89c505c72802ce86, 0xeab83b9d2d8000d1, 0x9f01d5e76748d005, 0xc740aaef3035b6d0, ++ 0x49afcd31d582d054, 0xcba5dc4c1efb5ddc, 0xc0a4c07434350ca1, 0xfc8dfaddcc65ee80, ++ 0x157c9780f6e4b2d9, 0x9762a872e1797617, 0xc4afae2cf3c7e1bd, 0x71cde14591b595d4, ++ 0x8843c3e0e641f3b9, 0xd92ecd91dce28750, 0x1474e7a1742cb19f, 0xec198e22764fa06b, ++ 0x39394edb47330c7d, 0x00ba1d925242533d, 0xaed8702536c6fb30, 0x6d3618e531c2967a, ++ 0x77f7cedcd7cc0411, 0xbc1e2ab82be5b752, 0x07b0cf9223676977, 0x596c693b099edd53, ++ 0xbb7f570f5b9b2811, 0x96bfdad3c4a6840c, 0x668015e79b60c534, 0x3ad38d72123f1366, ++ 0x6b994d81d2fcbb09, 0x70885f022c5052d8, 0xc891ee79d9306a7b, 0x2c4df05c0ed02497, ++ 0x19ebc13816898be2, 0xea7c64df11c392a2, 0xb7663e88dd12e1bd, 0x79f768cb8e154c21, ++ 0x1fb21b12e945933b, 0xe6a9045643f6906e, 0x544c47acd7e15371, 0xb7709b14f727e3d1, ++ 0x326ee36a46942971, 0x477f1cf7b0e2d847, 0x88b8f6b82b3b0c24, 0x18bc357b80e3cd5c, ++ 0x3333de70e4d66e0b, 0x4fd4c5e148583cf6, 0xae1b62f3008c0af3, 0xc49f419b6ab29cf5, ++ 0x2c29fa65afc3fa28, 0x4b19d93734d03009, 0x7dd6c09e589276ad, 0x1cece97f30de48ad}, ++ {// seed = 4 ++ 0x58bdf4338602e4fb, 0x71a5620b02c926d5, 0x3811c960129c2d9f, 0x29c2fb11fccac567, ++ 0x0d6b1ea7780f1352, 0xcc4d3ddfae3f87b3, 0xfdd30257362a586b, 0xabc948fde69f25f1, ++ 0x51b3523469d30f7b, 0xe0f0322724405ace, 0xd3729266d896da1e, 0xb10c37e5147915bf, ++ 0x8b577039f9fa32a3, 0xe677c6a9cbfb44b3, 0x7317a756ebb51a03, 0xf8e988ef37359485, ++ 0x600fc1ef3f469ff3, 0xbf0b8f8520444e01, 0x3711168b08b63d73, 0x34146f2944a6cb36, ++ 0x717feb263862cdde, 0x7185f8347db00412, 0x900798d82127e693, 0x84089e976a473268, ++ 0x10f8308c0d293719, 0xf62a618d4e5719b8, 0x8bdbd257a1a9516f, 0xf49f666fd7a75110, ++ 0xbaf45e2db7864339, 0xe4efa1ea0c627697, 0x3e71d4c82a09fe10, 0x54a2a51cf12127bb, ++ 0xa0592c9f54ba14cd, 0x27dd627a101c7a42, 0x3d2ceb44b3d20d72, 0x7ee1f94a68ca8f5d, ++ 0x7e8cb8651b006c36, 0xbd9fa7ca3a475259, 0x856de173586a7b34, 0xcedb291b594cb1b5, ++ 0xa3d6e462fd21cddc, 0x74561d10af9118e4, 0x13a3d389fc2d4b36, 0xeea8594a4a054856, ++ 0xf56d7474d9ba4b13, 0x25ddce2f6490b2fd, 0x920653ff3a8d830b, 0xcd8c0c9cdac740d1, ++ 0x2c348a738db9c4a0, 0x2967ccbe8ea44c22, 0x47963f69adb049f8, 0xf9d01eb5b4cf7eb6, ++ 0x7a5c26eb63a86bd2, 0x62ad8b7a71fa0566, 0xb373213179f250ae, 0x589d4e9a88245a4d, ++ 0x433dafebe2d558a8, 0x521fbef2c8fe4399, 0x62a31f9ff9ccd46b, 0x51602203eba7c1a6, ++ 0x9afc8c451b06c99f, 0xb529085bdbaffcea, 0xac251825cc75892b, 0x94976a5bce23d58e, ++ 0xdd17925b6c71b515, 0x568fd07a57bce92e, 0xefac31200d8bd340, 0x716c3e466b540ef9, ++ 0x3d2c9e380063c69b, 0x14168f9a3662dd83, 0xd298c7504dbc412f, 0x74490a94f016719f, ++ 0x0e0da431e1ab80c8, 0xe321f63dc6b169ae, 0xf08671544febc95a, 0x39324450cc394b3b, ++ 0xea6e3d35f1aa3a70, 0x8ef8a886508ce486, 0xdc1a631ef0a17f06, 0xfda2b3fbcd79e87b, ++ 0xd75bcae936403b10, 0xf88b5bd9f035f875, 0xc43efec2e3792dd4, 0xe9fac21a9d47cd94, ++ 0xc2876f0c4b7d47c3, 0xaba156cf49f368b4, 0x5ccda2170fa58bf9, 0xadc92c879ed18df7, ++ 0x110c1b227354e6c8, 0x298ee7a603249200, 0xde92142ede0e8ee7, 0x88e4a4610644ba9e, ++ 0xbb62d277e7641d3a, 0xb9be1985b7bf8073, 0x29024e5426cdb0d1, 0xf6aefd01f3092ab8, ++ 0x2a07087b313133aa, 0x6d71f445d6dfc839, 0x1e2412ff12e5526b, 0xed5cdeba6617b9e1, ++ 0x20b1d0d5e5f8760e, 0x12ff15705c368260, 0x7bf4338b7c387203, 0x34ff25f00cd06185, ++ 0x1148c706c518cf28, 0x5c04f0623388f025, 0xcb9d649275d87d79, 0x9b5f0c24fabc42ec, ++ 0x1a7b5e7964e33858, 0x2a81bbd8efdc6793, 0x8d05431ffe42752e, 0x83915cd511002677, ++ 0x580ed4d791837b31, 0x5982e041d19ff306, 0xcad0d08fa5d864ca, 0x867bee6efe1afa63, ++ 0x26467b0320f23009, 0xd842414dfda4ec36, 0x047fcdcbc0a76725, 0xbddb340a3768aeca, ++ 0xef4ce6fa6e99ab45, 0x88c5b66c7762bf9b, 0x5679f1c51ffb225d, 0xdab79048317d77ee, ++ 0xf14e9b8a8ba03803, 0xe77f07f7731184c1, 0x4c2aab9a108c1ef5, 0xa137795718e6ad97, ++ 0x8d6c7cc73350b88b, 0x5c34e2ae74131a49, 0xd4828f579570a056, 0xb7862594da5336fc, ++ 0x6fd590a4a2bed7a5, 0x138d327de35e0ec1, 0xe8290eb33d585b0b, 0xcee01d52cdf88833, ++ 0x165c7c76484f160e, 0x7232653da72fc7f6, 0x66600f13445ca481, 0x6bbdf0a01f7b127d, ++ 0xd7b71d6a1992c73b, 0xcf259d37ae3fda4a, 0xf570c70d05895acf, 0x1e01e6a3e8f60155, ++ 0x2dacbb83c2bd3671, 0x9c291f5a5bca81af, 0xd976826c68b4ee90, 0x95112eec1f6310a2, ++ 0x11ebc7f623bc4c9a, 0x18471781b1122b30, 0x48f7c65414b00187, 0x6834b03efa2f5c30, ++ 0x0875ef5c2c56b164, 0x45248d4f2a60ba71, 0x5a7d466e7f7ba830, 0x2bebe6a5e42c4a1d, ++ 0xd871d8483db51d10, 0x6ee37decd2fd392f, 0x7d724392010cede3, 0x8e96ef11e1c9bcc8, ++ 0x804a61d86b89d178, 0xbb1b83ce956055ec, 0xcb44e107410ff64f, 0xc426bb09ee0ba955, ++ 0x057c08f42c3dd7f1, 0x40ea1ec148602bdf, 0xc24688deeb65d7f1, 0xd8bcc53c768ba4e4, ++ 0x16e0e3af65c1106c, 0xfc12f7e7d647218b, 0x70d6e1d3ee93cef4, 0x01d2a505c4541ef9, ++ 0x1ef79e16e764d5c3, 0x0363d14d13870b98, 0xb56ef64345d06b11, 0xe653d557ebb7c346, ++ 0x8304a8597c2b2706, 0x1536e1322ce7e7bb, 0x525aec08a65af822, 0x91f66d6e98d28e43, ++ 0xe65af12c0b5c0274, 0xdf6ae56b7d5ea4c2, 0x5cef621cedf3c81c, 0x41e8b1ffd4889944, ++ 0xb5c0f452c213c3e5, 0x77af86f3e67e499b, 0xe20e76ea5b010704, 0xbdc205ab0c889ec0, ++ 0xc76d93eb0469cd83, 0x17ac27f65cab0034, 0xd49ec4531fd62133, 0x07a873ea2f1b9984, ++ 0xbff270dfef0032ee, 0x1764dbe91592f255, 0xe40363126f79e859, 0xa06cad3ab46971f6, ++ 0x0be596e90dedd875, 0x3387cce5c1658461, 0x44246acf88a9585e, 0xe0ad82b92d5ecb2c, ++ 0x2177491c9a1600a6, 0x16e7c4aac0f02422, 0x75792eeeec15c4e1, 0x2309cd359d08ee30, ++ 0x7cd9831dd1b83b0a, 0x374914a7c4ee8cf0, 0x0dd17765c9ac2e54, 0xb7847470ba9a7688, ++ 0xfba4f4bbe2991173, 0x422b203fc3de040e, 0x63bfcaf2ecf2ab0e, 0x0c5559f3a192946e, ++ 0xfdf80675c1847695, 0xf5f570accab842c9, 0x65cc5a448767afea, 0x1efeb0a7ee234f2f, ++ 0x9b05f03d81e7b5d2, 0xe7c31317a8626cf4, 0x620f2a53081d0398, 0x1b6de96cdd9943ae, ++ 0x8c226a436777d303, 0xa08fbbd50fafb10d, 0x6a64c5ec20104883, 0x9c9c653502c0f671, ++ 0x678a02b2174f52a0, 0x68e008ba16bbad4b, 0xa317c16d2efb860f, 0xeab2075d17ed714c, ++ 0x565eeeddf0c4ea15, 0x8ec8e94d242a6c19, 0x139e8e27d9000fae, 0xc977a7ff1b33d2f5, ++ 0x1d0accca84420346, 0xc9e82602cd436e03, 0x6a2231da53d2ccd3, 0xb44b12d917826e2a, ++ 0x4f4567c6a74cf0b9, 0xd8e115a42fc6da8f, 0xb6bbe79d95742a74, 0x5686c647f1707dab, ++ 0xa70d58eb6c008fc5, 0xaaedc2dbe4418026, 0x6661e2267bdcfd3d, 0x4882a6eda7706f9e, ++ 0xf6c2d2c912dafdd0, 0x2f2298c142fd61f9, 0x31d75afeb17143a8, 0x1f9b96580a2a982f, ++ 0xa6cd3e5604a8ad49, 0x0dae2a80aad17419, 0xdb9a9d12868124ac, 0x66b6109f80877fac, ++ 0x9a81d9c703a94029, 0xbd3b381b1e03c647, 0xe88bc07b70f31083, 0x4e17878356a55822}, ++ {// seed = 5 ++ 0xb3c58c2483ad5ead, 0x6570847428cdcf6c, 0x2b38adbf813ac866, 0x8cb9945d37eb9ad3, ++ 0xf5b409ec3d1aed1c, 0xa35f4bffc9bb5a93, 0x5db89cde3c9e9340, 0xff1225231b2afb2b, ++ 0x157b0b212b9cc47d, 0xf03faf97a2b2e04d, 0x86fdab8544a20f87, 0xfcb8732744ae5c1c, ++ 0xd91744c0787986d5, 0x5f8db2a76d65ad05, 0xcff605cbed17a90d, 0xf80284980a3164e7, ++ 0x59cc24e713fccc7d, 0x268982cada117ce4, 0xcd020e63896e730e, 0xe760dc46e9fe9885, ++ 0x6aaece8ab49c6b5d, 0x7451194d597aae3e, 0x35d4385900332457, 0xa40fb563a096583d, ++ 0xa797b612f7f11b76, 0x2fed6eb68e6a2b9b, 0x2f06ee64aeffd943, 0x9dd0e49d9ca45330, ++ 0x97d48f08bd7f1d8f, 0x1cfa7fe3ebe4d8ee, 0x2a2ba076bd397d42, 0x68c4344f7472f333, ++ 0xce21ec31987d74b5, 0xb73dabdc91d84088, 0x801aadee592222fe, 0xaf41345398ebc3f5, ++ 0x8a8f653d7f15ee46, 0xce2d065ff2ba2965, 0x4e05da515da2adb7, 0xa6dbdb8aa25f0fd4, ++ 0xca9f9666bbd2d5a9, 0x6b917ce50bd46408, 0x1550cc564ba6c84d, 0xb3063ae043506504, ++ 0x84e5f96bb796653d, 0xe2364798096cf6e3, 0x3b0dfedf6d3a53d0, 0xb7e4c7c77bde8d93, ++ 0xe99545bac9ab418a, 0xa0e31f96889507bb, 0x883c74f80c346885, 0xf674ae0b039fd341, ++ 0x8bb6ce2d5e8d1c75, 0x0c48737966a7ed7c, 0x04fcdf897b34c61c, 0xe96ac181bacbd4d6, ++ 0x5a9c55a6106a9c01, 0x2520f020de4f45d3, 0x935730955e94d208, 0xce5ad4d7f3f67d3b, ++ 0xa4b6d107fe2d81ca, 0x4f0033f50ae7944e, 0x32c5d28dd8a645a7, 0x57ce018223ef1039, ++ 0x2cbab15a661ab68e, 0x6de08798c0b5bec2, 0xee197fb2c5c007c6, 0x31b630ac63e7bda2, ++ 0xab98785aefe9efe3, 0xa36006158a606bf7, 0x7b20376b9f4af635, 0xa40762fdc3c08680, ++ 0x943b5faffd0ebee2, 0x7f39f41d0b81f06e, 0x7c4b399b116a90f8, 0x24e1662ac92bc9f3, ++ 0xcf586fc4e8e6c7db, 0xe46e0d047eeb12d7, 0xe8021076e4ea9958, 0x11fc13492e3ca22a, ++ 0xd61eae01410397e3, 0x7e8c4a58036a8e9f, 0x068a6de267970745, 0x64faab129bef1a41, ++ 0xb4a6f720943dad01, 0x631491058d73a9d5, 0xdad4fe95eab3ec02, 0x0a8b141c5c3a44f6, ++ 0x9fc69d4c2b335b98, 0x94d5f84a07d6e4cd, 0x1b73965de143c608, 0x443932c2dda54bcc, ++ 0x7397818fb0b04cd2, 0xef4ab03a1202b277, 0xf3d2ee459c0c2b92, 0x182d4daf8b058a87, ++ 0x90e63035d7b51368, 0xba4cd8b9a95d45fd, 0x12a7392c76731090, 0x890d264ec5d082d2, ++ 0xeeaf5c363da4994e, 0xd6aad756902123fb, 0xb531ebebdb28f191, 0xe71ce659fc59babd, ++ 0x37c1b94f63f2dcb5, 0xe4e3abeb311f9b96, 0x4a31b72ccb8695d3, 0x52cae1f0629fdce4, ++ 0xe5b0475e2ed71369, 0x2724e8c3506414fb, 0xbab0367920672deb, 0x0161a781c305449f, ++ 0x37b70f40f5bb60be, 0xddd1094c50251a01, 0x3b28283afd17224e, 0x06dec0cfe889fc6b, ++ 0x47608ea95bb4902d, 0xad883ebc12c00e82, 0x9e8d7ae0f7a8df29, 0xa79443e9f7c013a1, ++ 0xcfa26f68b7c68b71, 0x33ae6cc19bda1f23, 0xd9741e22b407887f, 0xf2bff78066d46b1c, ++ 0x794123191c9d32d4, 0x56cb6b903764ec76, 0x98775d0ef91e1a5a, 0xae7b713bc15c1db9, ++ 0x3b4c1a7870ed7a0d, 0x46666965f305cc34, 0x0ea0c3b2e9c6b3cd, 0x4dc387039a143bff, ++ 0x5f38bb9229ef9477, 0xea5d39ba72af7850, 0x69a5ed0174ce2b6d, 0x06969a36bfe7594d, ++ 0x0adee8e4065ccaa3, 0x908a581d57113718, 0x64822d6c5a8190ed, 0x8c5068b56ace4e4c, ++ 0x88ba3b4fb4e30bef, 0xa6ec0b8bb5896cfe, 0x4e23fcc6b47996fd, 0xe18e75b0dd549c7a, ++ 0xcd90f17e106cf939, 0x1666fdfb2ef7c52f, 0x4fae325f206dd88c, 0xe7bc1160e25b062d, ++ 0x3cc999cb246db950, 0xc5930a7326cd5c37, 0xb008a48a211367bd, 0xc5559da145a88fd4, ++ 0x1e3ad46655fac69c, 0x7834266b4841bfd7, 0xa764450fbffc58cc, 0x54d8cf93a939c667, ++ 0x93c51f11b21b2d9d, 0x0964112082ed65cc, 0x4c2df21213e7fb03, 0xf0405bc877468615, ++ 0x17b4fc835d116ab4, 0xa6b112ae5f3cb4ef, 0x23cfc8a7fd38a46e, 0x8e0a360dc2774808, ++ 0x24ca9c8092105ad5, 0xafd3f75524f2e0d5, 0x4f39ed7dbaddc24c, 0xe5e362c7679a7875, ++ 0x00914a916b07b389, 0xdfe1119b7d5ab5da, 0xabd6ed9940e46161, 0x630ed2044171e22c, ++ 0xdecc244157dd1601, 0x777e6d5b4b4868d5, 0x9b3530bee67017d8, 0xd2faf08b291fdcb9, ++ 0x006e99455d6523de, 0xd559b5817f6955b5, 0xefcc1063b0088c61, 0xed73145ae0f00ae7, ++ 0xab2af402cf5b7421, 0x897767f537644926, 0x26c9c0473ca83695, 0x192e34e1881b2962, ++ 0xf7cf666ec3b3d020, 0x27f9b79c7404afb7, 0xe533e8bed3010767, 0xe5817838e11d05d3, ++ 0x65659c531bd36517, 0xd427c5e0a23836fd, 0xf3eab7ea58fa3528, 0x07683adae1289f35, ++ 0x201d6af7e896dd32, 0xd5da938b9a21ad88, 0x843fb73ad67bc316, 0x1782ec7d5feef21b, ++ 0x943f66f6ec772877, 0x7e9112e7b26da097, 0xeac8161f8663c2c7, 0xe8600db480a9ebf4, ++ 0x07807fc90f6eaf5f, 0xe0e4c9deb41abf83, 0xbdf533db271f9c15, 0xb398411b0497afe2, ++ 0xdebb45ef25448940, 0xe7a5decefcd376c4, 0xaf1ef3c728c83735, 0xb8b83a99355cb15a, ++ 0x6444a0344f1611e4, 0xe8bb7f5cf3c60179, 0x77ab5c5177e75ff7, 0xc38fd6fa849d585d, ++ 0x390d57d53029060a, 0xa66327eb7b8b593c, 0x6350a14f6fcd5ac9, 0x2c08125bcd7008b4, ++ 0x2d00c299a6a6bf8e, 0x6b0039c1f68d1445, 0x0035150c5d06f143, 0xa34d01628cc927e1, ++ 0xdf5b3164d7b2ede1, 0x8167db1d0583d72e, 0x4e13b341cd2ae8bc, 0xa693d9b1f416e306, ++ 0xc15ed7ca0bc67609, 0xdc344313c1c4f0af, 0x88b6887ccf772bb4, 0x6326d8f93ca0b20e, ++ 0x6964fad667dc2f11, 0xe9783dd38fc6d515, 0x359ed258fa022718, 0x27ac934d1f7fd60a, ++ 0xd68130437294dbcc, 0xaf5f869921f8f416, 0x2b8f149b4ab4bf9f, 0xc41caca607e421cb, ++ 0x7746976904238ef9, 0x604cb5529b1532f0, 0x1c94cd17c4c4e4ab, 0xe833274b734d6bbe, ++ 0xe9f1d3ef674539ce, 0x64f56ed68d193c6a, 0xe34192343d8ecfc1, 0xcb162f6c3aa71fe8, ++ 0x99eaf25f4c0f8fa4, 0x92f11e7361cb8d02, 0xb89170cddff37197, 0x4f86e68a51e071e3, ++ 0x31abf6afd911a75b, 0x6d20cf259c269333, 0x4150b9f88fcb6513, 0x705063989ebf7451, ++ 0x559231d927c84410, 0x1ca8ec4b098bc687, 0xebed22405c9180e0, 0xaa815b37d052af59}, ++ {// seed = 6 ++ 0x946ac62246e04460, 0x9cebee264fcbc1ae, 0x8af54943a415652b, 0x2b327ed3b17b8682, ++ 0x983fde47b3c3847e, 0x10a3013f99a2ad33, 0x6e230bb92d2721ef, 0x1cf8b8369e5c5c50, ++ 0x7f64017f2b7b3738, 0xd393248a62417fa1, 0x9ff01c0b20a372c5, 0xb0e44abce7e7c220, ++ 0xcebb9f88d48a815f, 0xdb7df6bd09033886, 0x7844fc82b6fa9091, 0x72d095449863b8ec, ++ 0xc13e678c89da2c7e, 0x6caf4d5ad231d12f, 0x2e0ab7b5fcf35c49, 0xf410720cb932a70f, ++ 0xd66ea581f16fce06, 0x175c9f002f57dc98, 0xccbcfd0d32988775, 0xfde4c407d3b0a232, ++ 0x5db2931ae7e97223, 0x6e07e2173085809f, 0x6e1d1ec0f9cad73c, 0xb2fc251a7f802619, ++ 0xbc1fc17f04f342de, 0x8de8f21ec658e078, 0x72c0f40cbee53fd6, 0x0678244411fc17a1, ++ 0x1d5837ca166b9bbd, 0xc8cada003c554345, 0x6a2fe2bfb2e58652, 0xfca9d797a6f7988b, ++ 0x6699e24ac737948b, 0x69623ffcb05789ba, 0x946429c529d95b75, 0x0d14df0b2a13970f, ++ 0x593d8592c440dfec, 0x2ee176f3d7e74b94, 0xae003f1da3be9e26, 0x0c7b02c4c0f6764a, ++ 0x3117e2fa1f632462, 0xf0f23265b6f1eaeb, 0x3111255d9b10c137, 0xc82745e509a00397, ++ 0xbd1d04037005fea7, 0xe104ab0dd22a9036, 0x51b27ce50851ac7a, 0xb2cb9fb21b471b15, ++ 0x29d298074c5a3e26, 0x6ebdf2058b737418, 0xc4a974041431b96f, 0x1ec5a30ccb6bdaac, ++ 0xe818beede9bf4425, 0x4b69b1bce67a5555, 0xf5c35f1eb0d62698, 0xf4509bbd8e99867c, ++ 0xb17206debd52e1bc, 0x35785668c770b3be, 0xe9343987ff5863bc, 0x2ee768499ac73114, ++ 0x5132bb3426eeaaf4, 0x471bce2c6833c5ff, 0xbb9a2d5428e6f6f9, 0xd5678943c595792d, ++ 0xab2a65e7f81e479c, 0xa82407bb23990b31, 0xdae321383984923c, 0x01823bb22648e6f1, ++ 0xda6e8df4214a8b04, 0x0e172bb88e03d94f, 0x552da6c22e362777, 0x7ce67329fb0e90cb, ++ 0x7b2d7f287ede7ebf, 0xd44f8222500651bd, 0x4acca1ef58fbb8ab, 0x428ecf058df9656b, ++ 0xd7e1ec6a8987c185, 0x365be6a54b253246, 0x168849be1e271ee8, 0x6a00f3c4151a8db2, ++ 0x37602727ca94b33d, 0xf6b50f18504fa9ce, 0x1c10817f6bc872de, 0x4bfe1fe42b0f3638, ++ 0x135fad4b8ef6143b, 0x1b25ad2bafc25f58, 0x41e37f85cf321f92, 0xfc73f75d9d5b9bea, ++ 0x9eb3694d1e9cb7e1, 0x601d51f08fa83b90, 0x234a2a9b88366f41, 0x63fe903e16f2c3bf, ++ 0x1cdbd34fa751c0b0, 0x0ce4fc6747c0558c, 0x51ed72afb8bb49aa, 0x20313ba13ca12c96, ++ 0x271fa38f9ebd54c1, 0x3696a5ac03a8edde, 0x05602be7df625702, 0x11f1ac73790f7a9f, ++ 0xa2836c099f0810bd, 0xe5ac2e47caa532fa, 0xd9c000a66d39f681, 0xd93d900e6f3d9d5f, ++ 0x792c81c65b7900f2, 0x5c5dce790ee20da1, 0x74ff1950edec1aee, 0x71fc85fa1e277d8f, ++ 0x0e77df17d6546cbc, 0x07debad44816c3b4, 0xbafa721581e92a70, 0x8ab6fbe2ed27bba8, ++ 0xe83243a20dea304a, 0xaa85a63a84c00a07, 0xde0e79917fc4153a, 0x21bb445e83537896, ++ 0xeedcac49fc0b433a, 0xffb2926a810ae57a, 0xf724be1f41d28702, 0x79cb95746039bb3b, ++ 0x5a54fe3742a00900, 0xda4768d64922c04f, 0x420396a84a339dae, 0xa171e26ee5e8724e, ++ 0x4c8da7c5d289c20a, 0x9ebd79a1a8e94742, 0x39235232b97e9782, 0xb75df0be9bba7d80, ++ 0x0c1d204dd87d48fc, 0x8f81f3e7177266e8, 0xe4a460b39e78d72b, 0x50b98fa151e65351, ++ 0xb7cb585c3ee1eddc, 0x11cdad9a76ee1dc4, 0xa38054a78595dc1c, 0x92f09e2ec4978edc, ++ 0xa8f0061b5efdabaa, 0x04bcc4abc224d230, 0xc58606738e692d46, 0xdd2b27b565952433, ++ 0x19e6ed1b740beec0, 0xceadd49b2ef9891f, 0x328178c28fe95cad, 0xe5ad4c43afe02848, ++ 0x03c0cb538cd967c0, 0xec4352526d19a630, 0x4c7e99389d39b031, 0xf65dd05362c2deb6, ++ 0xd1e70daf6879d28d, 0xbe9f57db6309b265, 0xa4b66f370b872bb7, 0xe26896fbc6ee1fd5, ++ 0xac705e661bfcf7c5, 0xab4d0d07d7f09940, 0x976417c06aeb6267, 0x8161c684a6bd468c, ++ 0xf77b6b9976dc4601, 0xc6489b779a39c12c, 0xb2aa58d5681cea1a, 0x043b1b40f8c3e04c, ++ 0x681fcbfadc845430, 0xab8896c921ba8def, 0x57aaf172606f37b2, 0xc3735048cd5eb8d7, ++ 0xa7078b96955631bd, 0xdd6b3543aa187f33, 0xc7103ea4a2a697fd, 0x8d7b95f6ff1f7407, ++ 0xe44f419e84709530, 0xf340caa9132cbb0a, 0x2ba407283143c66c, 0xe1be240ca636c844, ++ 0x90d32f2877ac08bc, 0x5d26e6294b2c8673, 0x4a6b2f5b27c87a44, 0x961fb9043f76d34f, ++ 0x0afee02d8d3c55d2, 0x6228e3f48c42e5dc, 0xc338e69ee6593675, 0x853f74b16efb7bdd, ++ 0xd062f40bdd22e687, 0x647164b9ab4c4190, 0xf94689f67d598369, 0x8e4b29d87a5012d7, ++ 0xaf02b8b925656fbd, 0x7a722a767179a630, 0xb5c8afe937a75ace, 0xfdb8e8d02d279372, ++ 0x887ef700cb25fae1, 0xcfe9bd912f72cabe, 0xb1d4dedc24f978de, 0x517522d38319cc2a, ++ 0x7dd87b2b36aab798, 0x579c4ff3046b5a04, 0xf5c5975c5028b7a7, 0x7094579d1000ec84, ++ 0xbc8d5b1ea70a5291, 0x161b2d783be8855c, 0xd26d0b0d6d18279f, 0x0be1945f02a78bd5, ++ 0xb822a5a9e045415b, 0x2fe9d68b1ccc3562, 0xb2e375960033d14f, 0x26aca04e49b4ff22, ++ 0x732a81c862112aea, 0x8bd901ed6e4260b8, 0xe839532c561ad5b0, 0x8fb6e4d517a79b12, ++ 0x0dd37f8c0be9b429, 0xc8ad87ad12f1b1b0, 0xc51f3aa62b90318b, 0x031a7e8b86c1cefc, ++ 0xa95547af2b70fc76, 0x9cb3615c5a98801e, 0xa387e3c3341d7032, 0xa087ea52a1debaef, ++ 0x16325ec9a2e6e835, 0x587944a484c585eb, 0xc8879033bde22ecc, 0xa39dbfce709c464a, ++ 0x7acc010f99208774, 0x98dd2973a096c5ad, 0x26458b51139f198c, 0x2f5d19575e8c4f02, ++ 0x726643f0d38af352, 0x44d879b6d73e6e94, 0xa68a03885c980abe, 0x06048acd161c40c0, ++ 0xa4dab8f89d405d28, 0x7120c880cb04be18, 0xa062ace22a1cf0cf, 0x3901a9daf29704f4, ++ 0xff08f3ed989db30a, 0x6d22b13e874c67e9, 0x80c6f35518d73f4d, 0xc23c2a521aac6f29, ++ 0x2e708fd83aaa42e0, 0x7fc3780f55f1b0fd, 0xabb3075c98cf87f2, 0xb4df3f40f7c61143, ++ 0x2a04418098a76d75, 0x0d9eeee9509b2d37, 0x6be8ae51f4b59cdc, 0xe746cc7c00e4a2ab, ++ 0x785bc6df9cac597c, 0x33cb6620ce8adc48, 0xc1ba30739bffcef7, 0x6d95771f18e503f7, ++ 0xf7be3ae2e62652ff, 0xc8d82ffd2a73c62b, 0x8725a3ba5b110973, 0x67ed6b9c724757ec}, ++ {// seed = 7 ++ 0xc0272d42c19ff3ae, 0x4694228b43ea043b, 0x5709a6ef8a462841, 0xc9210a1e538805c9, ++ 0x279b171196113ec2, 0x859b769fc2d9e815, 0x0d5d3125a2bf14d3, 0x22bca1cfefa878ba, ++ 0x481b6bf58037bd83, 0x4933ba8647728d22, 0xf08c7b6b56f6e1b6, 0x374e8af5a15407c7, ++ 0xa95c4dc3d2487a5c, 0x9b832808ff11e751, 0xf2048507e9da01d5, 0xa9c576189f544a4a, ++ 0xf6c2a45b2e9d2b41, 0x9b9874c9f10ecc2f, 0x37d9b5f51f8c149e, 0x93aead54c9de9467, ++ 0x59cf0b4af262da23, 0xe7e9929af18194b2, 0x9df2644e33eb0178, 0xde4122d6f0671938, ++ 0xf005786c07f4800b, 0xb1fc9d254b5d1039, 0x0bf1088631f6dd7b, 0x665623f0a4b8f0c7, ++ 0x60f0113a9187db7c, 0xfd7cceda4f0d23a6, 0x26c01e9d89955940, 0x33afa1dfc0f5a6a0, ++ 0xeb77daf215e9283c, 0xc7575214bf85edb4, 0xeb0d804bf297e616, 0x84bff4ffd564f747, ++ 0xc4ac33189246f620, 0x43ef61213ecc1005, 0xcbbb0dea6cd96acd, 0x8ed27abfa8cfcb05, ++ 0x543b61529cb996b6, 0xa5f987ca41ea5e59, 0x3c50e0ac5254cb7a, 0x4192b0446c06d1e6, ++ 0x3e86592e21b45388, 0xdb766f06fcc6e51e, 0x0448ee36efe632db, 0x663c9db689253e35, ++ 0x72e0bd4985331dd4, 0xff501b5bf7d94e74, 0xe911ce758e2113a8, 0xec3a8d03a75a6ba4, ++ 0xaf6b4b72f56edc83, 0xf284857936c0a391, 0x5ba6feff407d46f4, 0x9d689c26de9d6702, ++ 0x28c04a9083726b5d, 0x2ccf4a627a029730, 0x7b4719500d4f0c71, 0x76470a9a7da250a8, ++ 0xcc48409404a1c890, 0xccefbdc7ec9a8055, 0xe0db91bff3cc42d3, 0x0532436426141254, ++ 0xf2ee9325e6f0ff0b, 0x149c20a5fbb28d9d, 0xe71624cd8d2d14d4, 0x8f01d4dc8cc2dd77, ++ 0x29cf409b333015b7, 0xba8bebd211884dd1, 0xc3396635e8c8db1d, 0x8ed0f6208d0528b8, ++ 0x0d90b43fdd0ee334, 0xd73c9a3333a044c7, 0xa2595cd208dbdc38, 0xae93cb264f940c09, ++ 0x8e0538d8afb07a97, 0x19115ec881385ba2, 0xa886f9e6a8039c6a, 0xcd5d62147ce3ecac, ++ 0xaecdf9e0bb4969f7, 0x2ddd631c53dcad10, 0x73ad1c97b3412054, 0xb08915fa2722efc6, ++ 0x97966047e5067eb0, 0x337f1675ed91445c, 0xb3a833d150b96a0d, 0x5940a98fe35e5e2e, ++ 0xfd03cc354ed0d8ff, 0x4e65b98291a8644a, 0x14a259f2852a60b2, 0x7648e3478c1e8e5f, ++ 0xbc0fbef6d9a919b4, 0xbec4302081346cf1, 0x57d2ce7aa1c7c511, 0x234c209d8f4e1ac3, ++ 0x87cf80cc933ce443, 0x7c262c616931e94e, 0xc5e33b049cf9eddf, 0x1a80790ed03ae51b, ++ 0xf2e8b9494f7220cf, 0x124cb59c14fff3ff, 0xa8a06cbfdb86ce18, 0x9068ef1f80b37653, ++ 0x0c55417b8d90338f, 0xcd579a523f6bcd30, 0xa31bfe2476a8d2a9, 0x1f8d142208094223, ++ 0x332dc40a5203cfad, 0xf8792fe5b2d33b4c, 0x443bd9668bf9461e, 0xc9019db0ace1409e, ++ 0x781bea919a113e8b, 0xb0f11d866abfbeec, 0xcfe139a60db0c26a, 0x869ab8721e6aa39e, ++ 0xdb48a4977717837a, 0x588a5ff151065b18, 0xe4a251ea0028864d, 0x7f0e43ba408a77c3, ++ 0x65f66dd50a536135, 0x6f49e934d9331c3e, 0xb8d742e0f0fa6b09, 0xe4e9b272deca2348, ++ 0xaee132ff902f773c, 0x43f658f7c2a0c90a, 0x28cb4dbc76cc53ea, 0x7d92253aa99ac39b, ++ 0x4fea3d832370baab, 0xb29e36936e51d78e, 0xea10778712321064, 0xff4f21f8ef274be2, ++ 0x84eff18ddfa0933f, 0xd0ec6a9f86c758a0, 0xaf82e5973c431ae0, 0x352023c00c045425, ++ 0xad34d7bc4a2f8961, 0xbdb4a02a24d4dee0, 0x354a4846d97447cf, 0x331a8b944d5bc19f, ++ 0x5ce04f8e17909035, 0x6497581bad8f4aab, 0x07c503bba647111e, 0x85f412ba78e1f7ff, ++ 0x7f3b920fd20f4cff, 0x424e1a9a4ce34e2f, 0x3035e2d62e1b9f0a, 0xef63114bff7b729a, ++ 0xe86a05889ab6bb60, 0xee0830cf095585a1, 0x4a54f7fa47d9c94b, 0x17daeece9fcb556a, ++ 0xc506d3f391834c6f, 0xb3f24be362e1af64, 0xc435e4e23608efdd, 0xeeba9caaa4cc1768, ++ 0x5a71f306daddc22d, 0x18e5205f41eba1a0, 0x7b29b4d1f6610925, 0x065cb65a0258d9a9, ++ 0x3e5ac8faa9fd1f95, 0x3b362362c1ea0470, 0xce0e4f6434db7a2e, 0xf327341098de52f2, ++ 0xcfca3b9e2a1992c3, 0x7483bf9401233e41, 0xbafbac531c6f9281, 0x4b52dd71b2c106f8, ++ 0xdf73b66e50b5a1f7, 0x237aec0202a20283, 0x23dd5be23dffdf2b, 0xea9730731ee122ef, ++ 0x5cb3f846014fbcd3, 0xc3b21c8ffdce9201, 0x06a99a02f91a8760, 0x721a81fa8fd7b7a3, ++ 0x6aafcdddc53cbcd8, 0xd03b464005a93bcc, 0x8212edc1b1669dcb, 0x71f4c31364c31bc7, ++ 0xfeeec0eba8772307, 0x1948d00a13d88cf1, 0x19064fd6d943ada8, 0x4ec8d31722697bfd, ++ 0x596d9a953a516609, 0xc4cb4bff53507da2, 0x1d59f3c5be36e4ca, 0xe5b4fc5bf6044c9b, ++ 0x1bb74e052232f735, 0x04e8a0db611ddd5d, 0x8d04eaa009b421bf, 0xa7878ae0ac0e6d58, ++ 0x28c1030217cab2b3, 0x827943767e56a883, 0x28fce5fa02d22809, 0xb30c322fffc8c58e, ++ 0x1ca5a6a9f8066c5b, 0xb24db5f1462b2513, 0x02f653b89b7e5f6c, 0xe31f8fb5d5f78eee, ++ 0x266acc514ed93501, 0x936879d1c6fddcc4, 0xcd51be3636af1952, 0x3fdbb6fc332c78c8, ++ 0x9eb656379fa73094, 0x056146cc92fa0f96, 0xed6c4f1836c027c3, 0x021e0bb5d2113f2a, ++ 0x8983e42ec1c626b3, 0x73ea9bc6513ad9c9, 0x0c904903b24f4247, 0xacbac1e6243e2525, ++ 0x0b1069a0c230fb06, 0x77d709fca3fc1ce5, 0x87ad0f65020947e6, 0x555302641c53f4e6, ++ 0x65ea87871fa9aaee, 0x58aaf4ecc1067bb4, 0x1a66c48cc4c65b3f, 0xca96aca48b2ea969, ++ 0xa68eb70bad14de2b, 0x5ccdb3d7e00a6f6e, 0xe178fbfec73fe72f, 0x2b63d6a16b83e890, ++ 0x32fdb7a5330fbae0, 0x2ab5803c8d1bf32c, 0xda838388c1527c94, 0x16a50bdc4de24acb, ++ 0xe561301f134c074a, 0xd7ae63d2816b4db1, 0x036aabd4df0dd741, 0xc5e0db8783435b9d, ++ 0x9c4386cf0a07f3b2, 0x6a72ac1aa56a13a1, 0x299bbdb04bb20a23, 0x138c1018fda16b81, ++ 0x0e354f0b3bda49df, 0x9f4c295b23127437, 0xd133ceb2bd561341, 0xd8b4bfd5a526ac29, ++ 0xcdd0a70ddc1c7bbd, 0x81dce595bf572225, 0x1c6f925c05f6efd7, 0x8ae5097553856ea0, ++ 0x3aabeaeef248f60d, 0xd9005809d19a69e2, 0x2a3a1a314311cc27, 0x89bb2dc76b2b624a, ++ 0x50a2a95d0412e289, 0x9def8df564e68581, 0xf49010a9b2e2ea5c, 0x8602ae175d9ff3f0, ++ 0xbf037e245369a618, 0x8038164365f6e2b5, 0xe2e1f6163b4e8d08, 0x8df9314914f0857e}}; ++ ++} // namespace parquet::internal +diff --git a/cpp/src/parquet/column_writer.cc b/cpp/src/parquet/column_writer.cc +--- a/cpp/src/parquet/column_writer.cc ++++ b/cpp/src/parquet/column_writer.cc +@@ -45,6 +45,7 @@ + #include "arrow/util/rle_encoding_internal.h" + #include "arrow/util/type_traits.h" + #include "arrow/visit_array_inline.h" ++#include "parquet/chunker_internal.h" + #include "parquet/column_page.h" + #include "parquet/encoding.h" + #include "parquet/encryption/encryption_internal.h" +@@ -764,6 +765,12 @@ class ColumnWriterImpl { + compressor_temp_buffer_ = + std::static_pointer_cast(AllocateBuffer(allocator_, 0)); + } ++ if (properties_->content_defined_chunking_enabled()) { ++ auto cdc_options = properties_->content_defined_chunking_options(); ++ content_defined_chunker_.emplace(level_info_, cdc_options.min_chunk_size, ++ cdc_options.max_chunk_size, ++ cdc_options.norm_level); ++ } + } + + virtual ~ColumnWriterImpl() = default; +@@ -895,6 +902,8 @@ class ColumnWriterImpl { + + std::vector> data_pages_; + ++ std::optional content_defined_chunker_; ++ + private: + void InitSinks() { + definition_levels_sink_.Rewind(0); +@@ -1269,6 +1278,16 @@ class TypedColumnWriterImpl : public ColumnWriterImpl, + + int64_t WriteBatch(int64_t num_values, const int16_t* def_levels, + const int16_t* rep_levels, const T* values) override { ++ if (ARROW_PREDICT_FALSE(properties_->content_defined_chunking_enabled())) { ++ throw ParquetException( ++ "Content-defined chunking is not supported in WriteBatch() or " ++ "WriteBatchSpaced(), use WriteArrow() instead."); ++ } ++ return WriteBatchInternal(num_values, def_levels, rep_levels, values); ++ } ++ ++ int64_t WriteBatchInternal(int64_t num_values, const int16_t* def_levels, ++ const int16_t* rep_levels, const T* values) { + // We check for DataPage limits only after we have inserted the values. If a user + // writes a large number of values, the DataPage size can be much above the limit. + // The purpose of this chunking is to bound this. Even if a user writes large number +@@ -1301,6 +1320,18 @@ class TypedColumnWriterImpl : public ColumnWriterImpl, + void WriteBatchSpaced(int64_t num_values, const int16_t* def_levels, + const int16_t* rep_levels, const uint8_t* valid_bits, + int64_t valid_bits_offset, const T* values) override { ++ if (ARROW_PREDICT_FALSE(properties_->content_defined_chunking_enabled())) { ++ throw ParquetException( ++ "Content-defined chunking is not supported in WriteBatch() or " ++ "WriteBatchSpaced(), use WriteArrow() instead."); ++ } ++ return WriteBatchSpacedInternal(num_values, def_levels, rep_levels, valid_bits, ++ valid_bits_offset, values); ++ } ++ ++ void WriteBatchSpacedInternal(int64_t num_values, const int16_t* def_levels, ++ const int16_t* rep_levels, const uint8_t* valid_bits, ++ int64_t valid_bits_offset, const T* values) { + // Like WriteBatch, but for spaced values + int64_t value_offset = 0; + auto WriteChunk = [&](int64_t offset, int64_t batch_size, bool check_page) { +@@ -1357,13 +1388,47 @@ class TypedColumnWriterImpl : public ColumnWriterImpl, + bits_buffer_->ZeroPadding(); + } + +- if (leaf_array.type()->id() == ::arrow::Type::DICTIONARY) { +- return WriteArrowDictionary(def_levels, rep_levels, num_levels, leaf_array, ctx, +- maybe_parent_nulls); ++ if (ARROW_PREDICT_FALSE(properties_->content_defined_chunking_enabled())) { ++ DCHECK(content_defined_chunker_.has_value()); ++ auto chunks = content_defined_chunker_->GetChunks(def_levels, rep_levels, ++ num_levels, leaf_array); ++ for (size_t i = 0; i < chunks.size(); i++) { ++ auto chunk = chunks[i]; ++ auto chunk_array = leaf_array.Slice(chunk.value_offset); ++ auto chunk_def_levels = AddIfNotNull(def_levels, chunk.level_offset); ++ auto chunk_rep_levels = AddIfNotNull(rep_levels, chunk.level_offset); ++ if (leaf_array.type()->id() == ::arrow::Type::DICTIONARY) { ++ ARROW_CHECK_OK(WriteArrowDictionary(chunk_def_levels, chunk_rep_levels, ++ chunk.levels_to_write, *chunk_array, ctx, ++ maybe_parent_nulls)); ++ } else { ++ ARROW_CHECK_OK(WriteArrowDense(chunk_def_levels, chunk_rep_levels, ++ chunk.levels_to_write, *chunk_array, ctx, ++ maybe_parent_nulls)); ++ } ++ bool is_last_chunk = i == (chunks.size() - 1); ++ if (num_buffered_values_ > 0 && !is_last_chunk) { ++ // Explicitly add a new data page according to the content-defined chunk ++ // boundaries. This way the same chunks will have the same byte-sequence ++ // in the resulting file, which can be identified by content addressible ++ // storage. ++ // Note that the last chunk doesn't trigger a new data page in order to ++ // allow subsequent WriteArrow() calls to continue writing to the same ++ // data page, the chunker's state is not being reset after the last chunk. ++ AddDataPage(); ++ } ++ } ++ return Status::OK(); + } else { +- return WriteArrowDense(def_levels, rep_levels, num_levels, leaf_array, ctx, +- maybe_parent_nulls); ++ if (leaf_array.type()->id() == ::arrow::Type::DICTIONARY) { ++ return WriteArrowDictionary(def_levels, rep_levels, num_levels, leaf_array, ctx, ++ maybe_parent_nulls); ++ } else { ++ return WriteArrowDense(def_levels, rep_levels, num_levels, leaf_array, ctx, ++ maybe_parent_nulls); ++ } + } ++ + END_PARQUET_CATCH_EXCEPTIONS + } + +@@ -1401,11 +1466,12 @@ class TypedColumnWriterImpl : public ColumnWriterImpl, + this->descr()->schema_node()->is_required() || (array.null_count() == 0); + + if (!maybe_parent_nulls && no_nulls) { +- PARQUET_CATCH_NOT_OK(WriteBatch(num_levels, def_levels, rep_levels, values)); ++ PARQUET_CATCH_NOT_OK( ++ WriteBatchInternal(num_levels, def_levels, rep_levels, values)); + } else { +- PARQUET_CATCH_NOT_OK(WriteBatchSpaced(num_levels, def_levels, rep_levels, +- data.null_bitmap_data(), data.offset(), +- values)); ++ PARQUET_CATCH_NOT_OK(WriteBatchSpacedInternal(num_levels, def_levels, rep_levels, ++ data.null_bitmap_data(), ++ data.offset(), values)); + } + return Status::OK(); + } +@@ -1968,11 +2034,11 @@ Status TypedColumnWriterImpl::WriteArrowSerialize( + bool no_nulls = + this->descr()->schema_node()->is_required() || (array.null_count() == 0); + if (!maybe_parent_nulls && no_nulls) { +- PARQUET_CATCH_NOT_OK(WriteBatch(num_levels, def_levels, rep_levels, buffer)); ++ PARQUET_CATCH_NOT_OK(WriteBatchInternal(num_levels, def_levels, rep_levels, buffer)); + } else { +- PARQUET_CATCH_NOT_OK(WriteBatchSpaced(num_levels, def_levels, rep_levels, +- array.null_bitmap_data(), array.offset(), +- buffer)); ++ PARQUET_CATCH_NOT_OK(WriteBatchSpacedInternal(num_levels, def_levels, rep_levels, ++ array.null_bitmap_data(), ++ array.offset(), buffer)); + } + return Status::OK(); + } +@@ -2096,7 +2162,8 @@ Status TypedColumnWriterImpl::WriteArrowDense( + const ::arrow::Array& array, ArrowWriteContext* ctx, bool maybe_parent_nulls) { + switch (array.type()->id()) { + case ::arrow::Type::NA: { +- PARQUET_CATCH_NOT_OK(WriteBatch(num_levels, def_levels, rep_levels, nullptr)); ++ PARQUET_CATCH_NOT_OK( ++ WriteBatchInternal(num_levels, def_levels, rep_levels, nullptr)); + } break; + WRITE_SERIALIZE_CASE(INT8) + WRITE_SERIALIZE_CASE(UINT8) +diff --git a/cpp/src/parquet/properties.h b/cpp/src/parquet/properties.h +--- a/cpp/src/parquet/properties.h ++++ b/cpp/src/parquet/properties.h +@@ -245,6 +245,44 @@ class PARQUET_EXPORT ColumnProperties { + bool page_index_enabled_; + }; + ++// EXPERIMENTAL: Options for content-defined chunking. ++/// ++/// Content-defined chunking is an experimental feature that optimizes parquet ++/// files for content addressable storage (CAS) systems by writing data pages ++/// according to content-defined chunk boundaries. This allows for more ++/// efficient deduplication of data across files, hence more efficient network ++/// transfers and storage. ++/// Each content-defined chunk is written as a separate parquet data page. The ++/// following options control the chunks' size and the chunking process. Note ++/// that the chunk size is calculated based on the logical value of the data, ++/// before any encoding or compression is applied. ++struct PARQUET_EXPORT CdcOptions { ++ /// Minimum chunk size in bytes, default is 256 KiB ++ /// The rolling hash will not be updated until this size is reached for each chunk. ++ /// Note that all data sent through the hash function is counted towards the chunk ++ /// size, including definition and repetition levels if present. ++ int64_t min_chunk_size = 256 * 1024; ++ /// Maximum chunk size in bytes, default is 1024 KiB ++ /// The chunker will create a new chunk whenever the chunk size exceeds this value. ++ /// Note that the parquet writer has a related `pagesize` property that controls ++ /// the maximum size of a parquet data page after encoding. While setting ++ /// `pagesize` to a smaller value than `max_chunk_size` doesn't affect the ++ /// chunking effectiveness, it results in more small parquet data pages. ++ int64_t max_chunk_size = 1024 * 1024; ++ /// Number of bit adjustment to the gearhash mask in order to center the chunk size ++ /// around the average size more aggressively, default is 0 ++ /// Increasing the normalization level increases the probability of finding a chunk, ++ /// improving the deduplication ratio, but also increasing the number of small chunks ++ /// resulting in many small parquet data pages. The default value provides a good ++ /// balance between deduplication ratio and fragmentation. ++ /// Use norm_level=1 or norm_level=2 to reach a higher deduplication ratio at the ++ /// expense of fragmentation. Negative values can also be used to reduce the ++ /// probability of finding a chunk, resulting in larger chunks and fewer data pages. ++ /// Note that values outside [-3, 3] are not recommended, prefer using the default ++ /// value of 0 for most use cases. ++ int norm_level = 0; ++}; ++ + class PARQUET_EXPORT WriterProperties { + public: + class Builder { +@@ -260,7 +298,9 @@ class PARQUET_EXPORT WriterProperties { + created_by_(DEFAULT_CREATED_BY), + store_decimal_as_integer_(false), + page_checksum_enabled_(false), +- size_statistics_level_(DEFAULT_SIZE_STATISTICS_LEVEL) {} ++ size_statistics_level_(DEFAULT_SIZE_STATISTICS_LEVEL), ++ content_defined_chunking_enabled_(false), ++ content_defined_chunking_options_({}) {} + + explicit Builder(const WriterProperties& properties) + : pool_(properties.memory_pool()), +@@ -275,10 +315,40 @@ class PARQUET_EXPORT WriterProperties { + page_checksum_enabled_(properties.page_checksum_enabled()), + size_statistics_level_(properties.size_statistics_level()), + sorting_columns_(properties.sorting_columns()), +- default_column_properties_(properties.default_column_properties()) {} ++ default_column_properties_(properties.default_column_properties()), ++ content_defined_chunking_enabled_( ++ properties.content_defined_chunking_enabled()), ++ content_defined_chunking_options_( ++ properties.content_defined_chunking_options()) {} + + virtual ~Builder() {} + ++ /// \brief EXPERIMENTAL: Use content-defined page chunking for all columns. ++ /// ++ /// Optimize parquet files for content addressable storage (CAS) systems by writing ++ /// data pages according to content-defined chunk boundaries. This allows for more ++ /// efficient deduplication of data across files, hence more efficient network ++ /// transfers and storage. The chunking is based on a rolling hash algorithm that ++ /// identifies chunk boundaries based on the actual content of the data. ++ /// ++ /// Note that only the WriteArrow() interface is supported at the moment. ++ Builder* enable_content_defined_chunking() { ++ content_defined_chunking_enabled_ = true; ++ return this; ++ } ++ ++ /// \brief EXPERIMENTAL: Disable content-defined page chunking for all columns. ++ Builder* disable_content_defined_chunking() { ++ content_defined_chunking_enabled_ = false; ++ return this; ++ } ++ ++ /// \brief EXPERIMENTAL: Specify content-defined chunking options, see CdcOptions. ++ Builder* content_defined_chunking_options(const CdcOptions& options) { ++ content_defined_chunking_options_ = options; ++ return this; ++ } ++ + /// Specify the memory pool for the writer. Default default_memory_pool. + Builder* memory_pool(MemoryPool* pool) { + pool_ = pool; +@@ -701,7 +771,8 @@ class PARQUET_EXPORT WriterProperties { + pagesize_, version_, created_by_, page_checksum_enabled_, + size_statistics_level_, std::move(file_encryption_properties_), + default_column_properties_, column_properties, data_page_version_, +- store_decimal_as_integer_, std::move(sorting_columns_))); ++ store_decimal_as_integer_, std::move(sorting_columns_), ++ content_defined_chunking_enabled_, content_defined_chunking_options_)); + } + + private: +@@ -730,6 +801,9 @@ class PARQUET_EXPORT WriterProperties { + std::unordered_map dictionary_enabled_; + std::unordered_map statistics_enabled_; + std::unordered_map page_index_enabled_; ++ ++ bool content_defined_chunking_enabled_; ++ CdcOptions content_defined_chunking_options_; + }; + + inline MemoryPool* memory_pool() const { return pool_; } +@@ -754,6 +828,13 @@ class PARQUET_EXPORT WriterProperties { + + inline bool page_checksum_enabled() const { return page_checksum_enabled_; } + ++ inline bool content_defined_chunking_enabled() const { ++ return content_defined_chunking_enabled_; ++ } ++ inline CdcOptions content_defined_chunking_options() const { ++ return content_defined_chunking_options_; ++ } ++ + inline SizeStatisticsLevel size_statistics_level() const { + return size_statistics_level_; + } +@@ -856,7 +937,8 @@ class PARQUET_EXPORT WriterProperties { + const ColumnProperties& default_column_properties, + const std::unordered_map& column_properties, + ParquetDataPageVersion data_page_version, bool store_short_decimal_as_integer, +- std::vector sorting_columns) ++ std::vector sorting_columns, bool content_defined_chunking_enabled, ++ CdcOptions content_defined_chunking_options) + : pool_(pool), + dictionary_pagesize_limit_(dictionary_pagesize_limit), + write_batch_size_(write_batch_size), +@@ -871,7 +953,9 @@ class PARQUET_EXPORT WriterProperties { + file_encryption_properties_(file_encryption_properties), + sorting_columns_(std::move(sorting_columns)), + default_column_properties_(default_column_properties), +- column_properties_(column_properties) {} ++ column_properties_(column_properties), ++ content_defined_chunking_enabled_(content_defined_chunking_enabled), ++ content_defined_chunking_options_(content_defined_chunking_options) {} + + MemoryPool* pool_; + int64_t dictionary_pagesize_limit_; +@@ -891,6 +975,9 @@ class PARQUET_EXPORT WriterProperties { + + ColumnProperties default_column_properties_; + std::unordered_map column_properties_; ++ ++ bool content_defined_chunking_enabled_; ++ CdcOptions content_defined_chunking_options_; + }; + + PARQUET_EXPORT const std::shared_ptr& default_writer_properties(); +diff --git a/cpp/src/parquet/schema.cc b/cpp/src/parquet/schema.cc +--- a/cpp/src/parquet/schema.cc ++++ b/cpp/src/parquet/schema.cc +@@ -28,7 +28,7 @@ + #include "parquet/exception.h" + #include "parquet/schema_internal.h" + #include "parquet/thrift_internal.h" +-#include "parquet/windows_fixup.h" ++#include "parquet/windows_fixup.h" // for OPTIONAL + + using parquet::format::SchemaElement; + +diff --git a/python/pyarrow/_parquet.pxd b/python/pyarrow/_parquet.pxd +--- a/python/pyarrow/_parquet.pxd ++++ b/python/pyarrow/_parquet.pxd +@@ -462,6 +462,11 @@ cdef extern from "parquet/api/reader.h" namespace "parquet" nogil: + + + cdef extern from "parquet/api/writer.h" namespace "parquet" nogil: ++ cdef cppclass CdcOptions: ++ int64_t min_chunk_size ++ int64_t max_chunk_size ++ int norm_level ++ + cdef cppclass WriterProperties: + cppclass Builder: + Builder* data_page_version(ParquetDataPageVersion version) +@@ -495,6 +500,9 @@ cdef extern from "parquet/api/writer.h" namespace "parquet" nogil: + Builder* disable_write_page_index() + Builder* enable_page_checksum() + Builder* disable_page_checksum() ++ Builder* enable_content_defined_chunking() ++ Builder* disable_content_defined_chunking() ++ Builder* content_defined_chunking_options(CdcOptions options) + shared_ptr[WriterProperties] build() + + cdef cppclass ArrowWriterProperties: +@@ -512,7 +520,6 @@ cdef extern from "parquet/api/writer.h" namespace "parquet" nogil: + shared_ptr[ArrowWriterProperties] build() + c_bool support_deprecated_int96_timestamps() + +- + cdef extern from "parquet/arrow/reader.h" namespace "parquet::arrow" nogil: + cdef cppclass FileReader: + FileReader(CMemoryPool* pool, unique_ptr[ParquetFileReader] reader) +@@ -646,6 +653,7 @@ cdef shared_ptr[WriterProperties] _create_writer_properties( + write_page_checksum=*, + sorting_columns=*, + store_decimal_as_integer=*, ++ use_content_defined_chunking=* + ) except * + + +diff --git a/python/pyarrow/_parquet.pyx b/python/pyarrow/_parquet.pyx +--- a/python/pyarrow/_parquet.pyx ++++ b/python/pyarrow/_parquet.pyx +@@ -1972,12 +1972,14 @@ cdef shared_ptr[WriterProperties] _create_writer_properties( + write_page_index=False, + write_page_checksum=False, + sorting_columns=None, +- store_decimal_as_integer=False) except *: ++ store_decimal_as_integer=False, ++ use_content_defined_chunking=False) except *: + + """General writer properties""" + cdef: + shared_ptr[WriterProperties] properties + WriterProperties.Builder props ++ CdcOptions cdc_options + + # data_page_version + +@@ -2101,6 +2103,7 @@ cdef shared_ptr[WriterProperties] _create_writer_properties( + raise TypeError( + "'column_encoding' should be a dictionary or a string") + ++ # size limits + if data_page_size is not None: + props.data_pagesize(data_page_size) + +@@ -2110,6 +2113,33 @@ cdef shared_ptr[WriterProperties] _create_writer_properties( + if dictionary_pagesize_limit is not None: + props.dictionary_pagesize_limit(dictionary_pagesize_limit) + ++ # content defined chunking ++ ++ if use_content_defined_chunking is True: ++ props.enable_content_defined_chunking() ++ elif use_content_defined_chunking is False: ++ props.disable_content_defined_chunking() ++ elif isinstance(use_content_defined_chunking, dict): ++ defined_keys = use_content_defined_chunking.keys() ++ mandatory_keys = {"min_chunk_size", "max_chunk_size"} ++ allowed_keys = {"min_chunk_size", "max_chunk_size", "norm_level"} ++ unknown_keys = defined_keys - allowed_keys ++ missing_keys = mandatory_keys - defined_keys ++ if unknown_keys: ++ raise ValueError( ++ f"Unknown options in 'use_content_defined_chunking': {unknown_keys}") ++ if missing_keys: ++ raise ValueError( ++ f"Missing options in 'use_content_defined_chunking': {missing_keys}") ++ cdc_options.min_chunk_size = use_content_defined_chunking["min_chunk_size"] ++ cdc_options.max_chunk_size = use_content_defined_chunking["max_chunk_size"] ++ cdc_options.norm_level = use_content_defined_chunking.get("norm_level", 0) ++ props.enable_content_defined_chunking() ++ props.content_defined_chunking_options(cdc_options) ++ else: ++ raise TypeError( ++ "'use_content_defined_chunking' should be either boolean or a dictionary") ++ + # encryption + + if encryption_properties is not None: +@@ -2259,7 +2289,8 @@ cdef class ParquetWriter(_Weakrefable): + write_page_index=False, + write_page_checksum=False, + sorting_columns=None, +- store_decimal_as_integer=False): ++ store_decimal_as_integer=False, ++ use_content_defined_chunking=False): + cdef: + shared_ptr[WriterProperties] properties + shared_ptr[ArrowWriterProperties] arrow_properties +@@ -2294,6 +2325,7 @@ cdef class ParquetWriter(_Weakrefable): + write_page_checksum=write_page_checksum, + sorting_columns=sorting_columns, + store_decimal_as_integer=store_decimal_as_integer, ++ use_content_defined_chunking=use_content_defined_chunking + ) + arrow_properties = _create_arrow_writer_properties( + use_deprecated_int96_timestamps=use_deprecated_int96_timestamps, +diff --git a/python/pyarrow/parquet/core.py b/python/pyarrow/parquet/core.py +--- a/python/pyarrow/parquet/core.py ++++ b/python/pyarrow/parquet/core.py +@@ -892,6 +892,39 @@ def _sanitize_table(table, new_schema, flavor): + - fixed_len_byte_array: for precision > 18. + + As a consequence, decimal columns stored in integer types are more compact. ++use_content_defined_chunking : bool or dict, default False ++ Optimize parquet files for content addressable storage (CAS) systems by writing ++ data pages according to content-defined chunk boundaries. This allows for more ++ efficient deduplication of data across files, hence more efficient network ++ transfers and storage. The chunking is based on a rolling hash algorithm that ++ identifies chunk boundaries based on the actual content of the data. ++ ++ Note that it is an experimental feature and the API may change in the future. ++ ++ If set to ``True``, a default configuration is used with `min_chunk_size=256 KiB` ++ and `max_chunk_size=1024 KiB`. The chunk size distribution approximates a normal ++ distribution between `min_chunk_size` and `max_chunk_size` (sizes are accounted ++ before any Parquet encodings). ++ ++ A `dict` can be passed to adjust the chunker parameters with the following keys: ++ - `min_chunk_size`: minimum chunk size in bytes, default 256 KiB ++ The rolling hash will not be updated until this size is reached for each chunk. ++ Note that all data sent through the hash function is counted towards the chunk ++ size, including definition and repetition levels if present. ++ - `max_chunk_size`: maximum chunk size in bytes, default is 1024 KiB ++ The chunker will create a new chunk whenever the chunk size exceeds this value. ++ Note that the parquet writer has a related `data_pagesize` property that controls ++ the maximum size of a parquet data page after encoding. While setting ++ `data_page_size` to a smaller value than `max_chunk_size` doesn't affect the ++ chunking effectiveness, it results in more small parquet data pages. ++ - `norm_level`: normalization level to center the chunk size around the average ++ size more aggressively, default 0 ++ Increasing the normalization level increases the probability of finding a chunk, ++ improving the deduplication ratio, but also increasing the number of small chunks ++ resulting in many small parquet data pages. The default value provides a good ++ balance between deduplication ratio and fragmentation. Use norm_level=1 or ++ norm_level=2 to reach a higher deduplication ratio at the expense of ++ fragmentation. + """ + + _parquet_writer_example_doc = """\ diff --git a/arrow_2/solution/solve.sh b/arrow_2/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..ddb8d33e8f12b7d9378e415f2a0438812937efdc --- /dev/null +++ b/arrow_2/solution/solve.sh @@ -0,0 +1,7 @@ +#!/usr/bin/env bash +set -euo pipefail + +cd /workspace/arrow +patch=${LOLBENCH_ORACLE_PATCH:-/solution/solution.patch} +git apply "$patch" +lolbench-submit diff --git a/arrow_2/task.toml b/arrow_2/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..0bd14f2bca5366252b882c6e34f4ba5dffd22c57 --- /dev/null +++ b/arrow_2/task.toml @@ -0,0 +1,60 @@ +schema_version = "1.3" + +[task] +name = "lolbench/arrow_2" +description = "Implement Apache Arrow." +authors = [{ name = "LoLBench maintainers" }] +keywords = ["lolbench", "coding-agent", "apache", "arrow", "c", "python"] + +[metadata] +instance_id = "arrow_2" +source_instance_id = "Apache-Arrow_Issue-45750_PR-45360" +source_slug = "Apache-Arrow_Issue-45750_PR-45360" +docker_slug = "Apache-Arrow_Issue-45750_PR-45360" +dockerhub_image = "smartdub26/lolbench-linux:arrow_2-1.0.0" +project = "arrow" +repo = "apache/arrow" +requirement_doc = "https://github.com/apache/arrow/issues/45750" +pr_link = "https://github.com/apache/arrow/pull/45360" +base_commit = "12424cdf2fda068e973ebd89cda045fee297943a" +merge_commit = "1cc2e4b690e467f548dc4131f9b392a864a132aa" +test_level = "system" +source_history_policy = "ancestors-only" +lolbench_test_modes = ["orig", "aug", "union"] +default_lolbench_suite = "union" +canonical_lolbench_suite = "union" +augmentation_available = true +verifier_network_policy = "public" +verifier_network_reason = "The Harbor verifier runs in a separate container and may use network access; migrated LoLBench verifier assets are mounted only in the verifier phase." + +[environment] +build_timeout_sec = 3600.0 +docker_image = "smartdub26/lolbench-linux:arrow_2-1.0.0" +network_mode = "public" +os = "linux" +cpus = 4 +memory_mb = 7168 +storage_mb = 20480 + +[agent] +timeout_sec = 21600.0 +user = "agent" +network_mode = "allowlist" +allowed_hosts = ["openrouter.ai", "api.openai.com", "api.anthropic.com"] + +[verifier] +timeout_sec = 5400.0 +user = "root" +environment_mode = "separate" +network_mode = "public" + +[verifier.env] +LOLBENCH_SUITE = "union" + +[verifier.environment] +docker_image = "smartdub26/lolbench-linux:arrow_2-1.0.0" +network_mode = "public" +os = "linux" +cpus = 4 +memory_mb = 7168 +storage_mb = 20480 diff --git a/arrow_2/tests/docker-compose.yaml b/arrow_2/tests/docker-compose.yaml new file mode 100644 index 0000000000000000000000000000000000000000..f5091b9298e127a1efbe69deeed699c907e025c1 --- /dev/null +++ b/arrow_2/tests/docker-compose.yaml @@ -0,0 +1,16 @@ +services: + main: + pull_policy: missing + volumes: + - type: bind + source: . + target: /tests + read_only: true + - type: bind + source: ./private + target: /opt/lolbench/private + read_only: true + - type: bind + source: ../solution + target: /solution + read_only: true diff --git a/arrow_2/tests/private/eval_tests.patch b/arrow_2/tests/private/eval_tests.patch new file mode 100644 index 0000000000000000000000000000000000000000..490da32e534fc6829a2bbb925358b968bf4db9bf --- /dev/null +++ b/arrow_2/tests/private/eval_tests.patch @@ -0,0 +1,1824 @@ +diff --git a/cpp/src/parquet/chunker_internal_test.cc b/cpp/src/parquet/chunker_internal_test.cc +new file mode 100644 +--- /dev/null ++++ b/cpp/src/parquet/chunker_internal_test.cc +@@ -0,0 +1,1704 @@ ++// Licensed to the Apache Software Foundation (ASF) under one ++// or more contributor license agreements. See the NOTICE file ++// distributed with this work for additional information ++// regarding copyright ownership. The ASF licenses this file ++// to you under the Apache License, Version 2.0 (the ++// "License"); you may not use this file except in compliance ++// with the License. You may obtain a copy of the License at ++// ++// http://www.apache.org/licenses/LICENSE-2.0 ++// ++// Unless required by applicable law or agreed to in writing, ++// software distributed under the License is distributed on an ++// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY ++// KIND, either express or implied. See the License for the ++// specific language governing permissions and limitations ++// under the License. ++ ++#include ++#include ++#include ++#include ++#include ++#include ++ ++#include ++#include ++ ++#include "arrow/extension/json.h" ++#include "arrow/table.h" ++#include "arrow/testing/generator.h" ++#include "arrow/type_fwd.h" ++#include "arrow/util/float16.h" ++#include "parquet/arrow/reader.h" ++#include "parquet/arrow/reader_internal.h" ++#include "parquet/arrow/test_util.h" ++#include "parquet/arrow/writer.h" ++#include "parquet/chunker_internal.h" ++#include "parquet/column_writer.h" ++#include "parquet/file_writer.h" ++ ++namespace parquet::internal { ++ ++using ::arrow::Array; ++using ::arrow::ChunkedArray; ++using ::arrow::ConcatenateTables; ++using ::arrow::DataType; ++using ::arrow::default_memory_pool; ++using ::arrow::Field; ++using ::arrow::Result; ++using ::arrow::Schema; ++using ::arrow::Table; ++using ::arrow::internal::checked_cast; ++using ::arrow::io::BufferReader; ++using ::parquet::arrow::FileReader; ++using ::parquet::arrow::FileReaderBuilder; ++using ::parquet::arrow::MakeSimpleTable; ++using ::parquet::arrow::NonNullArray; ++using ::parquet::arrow::WriteTable; ++ ++using ::testing::Bool; ++using ::testing::Combine; ++using ::testing::Values; ++ ++// generate determinisic and platform-independent data ++inline uint64_t hash(uint64_t seed, uint64_t index) { ++ uint64_t h = (index + seed) * 0xc4ceb9fe1a85ec53ull; ++ h ^= h >> 33; ++ h *= 0xff51afd7ed558ccdull; ++ h ^= h >> 33; ++ h *= 0xc4ceb9fe1a85ec53ull; ++ h ^= h >> 33; ++ return h; ++} ++ ++template ++Result> GenerateArray(const std::shared_ptr& type, ++ bool nullable, int64_t length, uint64_t seed, ++ ValueFunc value_func) { ++ BuilderType builder(type, default_memory_pool()); ++ ++ if (nullable) { ++ for (int64_t i = 0; i < length; ++i) { ++ uint64_t val = hash(seed, i); ++ if (val % 10 == 0) { ++ RETURN_NOT_OK(builder.AppendNull()); ++ } else { ++ RETURN_NOT_OK(builder.Append(value_func(val))); ++ } ++ } ++ } else { ++ for (int64_t i = 0; i < length; ++i) { ++ uint64_t val = hash(seed, i); ++ RETURN_NOT_OK(builder.Append(value_func(val))); ++ } ++ } ++ ++ std::shared_ptr array; ++ RETURN_NOT_OK(builder.Finish(&array)); ++ RETURN_NOT_OK(array->ValidateFull()); ++ return array; ++} ++ ++#define GENERATE_CASE(TYPE_ID, BUILDER_TYPE, VALUE_EXPR) \ ++ case ::arrow::Type::TYPE_ID: { \ ++ auto value_func = [](uint64_t val) { return VALUE_EXPR; }; \ ++ return GenerateArray(type, nullable, length, seed, value_func); \ ++ } ++ ++Result> GenerateArray(const std::shared_ptr& field, ++ int64_t length, int64_t seed) { ++ const std::shared_ptr& type = field->type(); ++ bool nullable = field->nullable(); ++ ++ switch (type->id()) { ++ GENERATE_CASE(BOOL, ::arrow::BooleanBuilder, (val % 2 == 0)) ++ ++ // Numeric types. ++ GENERATE_CASE(INT8, ::arrow::Int8Builder, static_cast(val)) ++ GENERATE_CASE(INT16, ::arrow::Int16Builder, static_cast(val)) ++ GENERATE_CASE(INT32, ::arrow::Int32Builder, static_cast(val)) ++ GENERATE_CASE(INT64, ::arrow::Int64Builder, static_cast(val)) ++ GENERATE_CASE(UINT8, ::arrow::UInt8Builder, static_cast(val)) ++ GENERATE_CASE(UINT16, ::arrow::UInt16Builder, static_cast(val)) ++ GENERATE_CASE(UINT32, ::arrow::UInt32Builder, static_cast(val)) ++ GENERATE_CASE(UINT64, ::arrow::UInt64Builder, static_cast(val)) ++ GENERATE_CASE(HALF_FLOAT, ::arrow::HalfFloatBuilder, ++ static_cast(val % 1000)) ++ GENERATE_CASE(FLOAT, ::arrow::FloatBuilder, static_cast(val % 1000) / 1000.0f) ++ GENERATE_CASE(DOUBLE, ::arrow::DoubleBuilder, ++ static_cast(val % 100000) / 1000.0) ++ case ::arrow::Type::DECIMAL128: { ++ const auto& decimal_type = checked_cast(*type); ++ // Limit the value to fit within the specified precision ++ int32_t max_exponent = decimal_type.precision() - decimal_type.scale(); ++ int64_t max_value = static_cast(std::pow(10, max_exponent) - 1); ++ auto value_func = [&](uint64_t val) { ++ return ::arrow::Decimal128(val % max_value); ++ }; ++ return GenerateArray<::arrow::Decimal128Builder>(type, nullable, length, seed, ++ value_func); ++ } ++ case ::arrow::Type::DECIMAL256: { ++ const auto& decimal_type = checked_cast(*type); ++ // Limit the value to fit within the specified precision, capped at 9 to avoid ++ // int64_t overflow ++ int32_t max_exponent = std::min(9, decimal_type.precision() - decimal_type.scale()); ++ int64_t max_value = static_cast(std::pow(10, max_exponent) - 1); ++ auto value_func = [&](uint64_t val) { ++ return ::arrow::Decimal256(val % max_value); ++ }; ++ return GenerateArray<::arrow::Decimal256Builder>(type, nullable, length, seed, ++ value_func); ++ } ++ ++ // Temporal types ++ GENERATE_CASE(DATE32, ::arrow::Date32Builder, static_cast(val)) ++ GENERATE_CASE(TIME32, ::arrow::Time32Builder, ++ std::abs(static_cast(val) % 86400000)) ++ GENERATE_CASE(TIME64, ::arrow::Time64Builder, ++ std::abs(static_cast(val) % 86400000000)) ++ GENERATE_CASE(TIMESTAMP, ::arrow::TimestampBuilder, static_cast(val)) ++ GENERATE_CASE(DURATION, ::arrow::DurationBuilder, static_cast(val)) ++ ++ // Binary and string types. ++ GENERATE_CASE(STRING, ::arrow::StringBuilder, ++ std::string("str_") + std::to_string(val)) ++ GENERATE_CASE(LARGE_STRING, ::arrow::LargeStringBuilder, ++ std::string("str_") + std::to_string(val)) ++ GENERATE_CASE(BINARY, ::arrow::BinaryBuilder, ++ std::string("bin_") + std::to_string(val)) ++ GENERATE_CASE(LARGE_BINARY, ::arrow::LargeBinaryBuilder, ++ std::string("bin_") + std::to_string(val)) ++ case ::arrow::Type::FIXED_SIZE_BINARY: { ++ auto size = ++ checked_cast(type.get())->byte_width(); ++ auto value_func = [size](uint64_t val) { ++ return std::string("bin_") + std::to_string(val).substr(0, size - 4); ++ }; ++ return GenerateArray<::arrow::FixedSizeBinaryBuilder>(type, nullable, length, seed, ++ value_func); ++ } ++ ++ case ::arrow::Type::STRUCT: { ++ auto struct_type = checked_cast(type.get()); ++ std::vector> child_arrays; ++ for (auto i = 0; i < struct_type->num_fields(); i++) { ++ ARROW_ASSIGN_OR_RAISE(auto child_array, GenerateArray(struct_type->field(i), ++ length, seed + i * 10)); ++ child_arrays.push_back(child_array); ++ } ++ auto struct_array = ++ std::make_shared<::arrow::StructArray>(type, length, child_arrays); ++ return struct_array; ++ } ++ ++ case ::arrow::Type::LIST: { ++ // Repeat the same pattern in the list array: ++ // null, empty list, list of 1 element, list of 3 elements ++ if (length % 4 != 0) { ++ return Status::Invalid( ++ "Length must be divisible by 4 when generating list arrays, but got: ", ++ length); ++ } ++ auto values_array_length = length * 4; ++ auto list_type = checked_cast(type.get()); ++ auto value_field = ::arrow::field("item", list_type->value_type()); ++ ARROW_ASSIGN_OR_RAISE(auto values_array, ++ GenerateArray(value_field, values_array_length, seed)); ++ auto offset_builder = ::arrow::Int32Builder(); ++ auto bitmap_builder = ::arrow::TypedBufferBuilder(); ++ ++ RETURN_NOT_OK(offset_builder.Reserve(length + 1)); ++ RETURN_NOT_OK(bitmap_builder.Reserve(length)); ++ ++ int32_t num_nulls = 0; ++ RETURN_NOT_OK(offset_builder.Append(0)); ++ for (auto offset = 0; offset < length; offset += 4) { ++ if (nullable) { ++ // add a null ++ RETURN_NOT_OK(bitmap_builder.Append(false)); ++ RETURN_NOT_OK(offset_builder.Append(offset)); ++ num_nulls += 1; ++ } else { ++ // add an empty list ++ RETURN_NOT_OK(bitmap_builder.Append(true)); ++ RETURN_NOT_OK(offset_builder.Append(offset)); ++ } ++ // add an empty list ++ RETURN_NOT_OK(bitmap_builder.Append(true)); ++ RETURN_NOT_OK(offset_builder.Append(offset)); ++ // add a list of 1 element ++ RETURN_NOT_OK(bitmap_builder.Append(true)); ++ RETURN_NOT_OK(offset_builder.Append(offset + 1)); ++ // add a list of 3 elements ++ RETURN_NOT_OK(bitmap_builder.Append(true)); ++ RETURN_NOT_OK(offset_builder.Append(offset + 4)); ++ } ++ ++ std::shared_ptr offsets_array; ++ RETURN_NOT_OK(offset_builder.Finish(&offsets_array)); ++ std::shared_ptr bitmap_buffer; ++ RETURN_NOT_OK(bitmap_builder.Finish(&bitmap_buffer)); ++ ARROW_ASSIGN_OR_RAISE( ++ auto list_array, ::arrow::ListArray::FromArrays( ++ type, *offsets_array, *values_array, default_memory_pool(), ++ bitmap_buffer, num_nulls)); ++ RETURN_NOT_OK(list_array->ValidateFull()); ++ return list_array; ++ } ++ ++ case ::arrow::Type::EXTENSION: { ++ auto extension_type = checked_cast(type.get()); ++ auto storage_type = extension_type->storage_type(); ++ auto storage_field = ::arrow::field("storage", storage_type, true); ++ ARROW_ASSIGN_OR_RAISE(auto storage_array, ++ GenerateArray(storage_field, length, seed)); ++ return ::arrow::ExtensionType::WrapArray(type, storage_array); ++ } ++ ++ default: ++ return ::arrow::Status::NotImplemented("Unsupported data type " + type->ToString()); ++ } ++} ++ ++TEST(TestGenerateArray, Integer) { ++ auto field = ::arrow::field("a", ::arrow::int32()); ++ ASSERT_OK_AND_ASSIGN(auto array, GenerateArray(field, /*length=*/10, /*seed=*/0)); ++ ASSERT_OK(array->ValidateFull()); ++ ASSERT_EQ(array->length(), 10); ++ ASSERT_TRUE(array->type()->Equals(::arrow::int32())); ++ ASSERT_EQ(array->null_count(), 1); ++} ++ ++TEST(TestGenerateArray, ListOfInteger) { ++ auto field = ::arrow::field("a", ::arrow::list(::arrow::int32())); ++ auto length = 12; ++ ASSERT_OK_AND_ASSIGN(auto array, GenerateArray(field, length, /*seed=*/0)); ++ ASSERT_OK(array->ValidateFull()); ++ ASSERT_EQ(array->length(), length); ++ ++ for (size_t i = 0; i < 12; i += 4) { ++ // Assert the first element is null ++ ASSERT_TRUE(array->IsNull(i)); ++ ++ // Assert the second element is an empty list ++ ASSERT_TRUE(array->IsValid(i + 1)); ++ auto list_array = std::static_pointer_cast<::arrow::ListArray>(array); ++ ASSERT_EQ(list_array->value_length(i + 1), 0); ++ ++ // Assert the third element has length 1 ++ ASSERT_TRUE(array->IsValid(i + 2)); ++ ASSERT_EQ(list_array->value_length(i + 2), 1); ++ ++ // Assert the fourth element has length 3 ++ ASSERT_TRUE(array->IsValid(i + 3)); ++ ASSERT_EQ(list_array->value_length(i + 3), 3); ++ } ++ ++ ASSERT_NOT_OK(GenerateArray(field, 3, /*seed=*/0)); ++ ASSERT_OK(GenerateArray(field, 8, /*seed=*/0)); ++} ++ ++Result> GenerateTable( ++ const std::shared_ptr<::arrow::Schema>& schema, int64_t size, int64_t seed = 0) { ++ std::vector> arrays; ++ for (const auto& field : schema->fields()) { ++ ARROW_ASSIGN_OR_RAISE(auto array, GenerateArray(field, size, ++seed)); ++ arrays.push_back(array); ++ } ++ return Table::Make(schema, arrays, size); ++} ++ ++Result> ConcatAndCombine( ++ const std::vector>& parts) { ++ // Concatenate and combine chunks so the table doesn't carry information about ++ // the modification points ++ ARROW_ASSIGN_OR_RAISE(auto table, ConcatenateTables(parts)); ++ return table->CombineChunks(); ++} ++ ++Result> ReadTableFromBuffer(const std::shared_ptr& data) { ++ std::shared_ptr result; ++ FileReaderBuilder builder; ++ std::unique_ptr reader; ++ auto props = default_arrow_reader_properties(); ++ props.set_arrow_extensions_enabled(true); ++ ++ RETURN_NOT_OK(builder.Open(std::make_shared(data))); ++ RETURN_NOT_OK(builder.memory_pool(::arrow::default_memory_pool()) ++ ->properties(props) ++ ->Build(&reader)); ++ RETURN_NOT_OK(reader->ReadTable(&result)); ++ return result; ++} ++ ++Result> WriteTableToBuffer( ++ const std::shared_ptr
& table, int64_t min_chunk_size, int64_t max_chunk_size, ++ int64_t row_group_length = 1024 * 1024, bool enable_dictionary = false, ++ ParquetDataPageVersion data_page_version = ParquetDataPageVersion::V1) { ++ auto sink = CreateOutputStream(); ++ ++ auto builder = WriterProperties::Builder(); ++ builder.enable_content_defined_chunking()->content_defined_chunking_options( ++ {min_chunk_size, max_chunk_size, /*norm_level=*/0}); ++ builder.data_page_version(data_page_version); ++ if (enable_dictionary) { ++ builder.enable_dictionary(); ++ } else { ++ builder.disable_dictionary(); ++ } ++ auto write_props = builder.build(); ++ auto arrow_props = ArrowWriterProperties::Builder().store_schema()->build(); ++ RETURN_NOT_OK(WriteTable(*table, default_memory_pool(), sink, row_group_length, ++ write_props, arrow_props)); ++ ARROW_ASSIGN_OR_RAISE(auto buffer, sink->Finish()); ++ ++ // validate that the data correctly roundtrips ++ ARROW_ASSIGN_OR_RAISE(auto readback, ReadTableFromBuffer(buffer)); ++ RETURN_NOT_OK(readback->ValidateFull()); ++ ARROW_RETURN_IF(!readback->Equals(*table), ++ Status::Invalid("Readback table not equal to original")); ++ ++ return buffer; ++} ++ ++// Type to represent a list of chunks where each element is the size of the chunk. ++using ChunkList = std::vector; ++ ++// Type to represent the sizes and lengths of the data pages in a column. ++ ++struct ColumnInfo { ++ ChunkList page_lengths; ++ ChunkList page_sizes; ++ bool has_dictionary_page = false; ++}; ++ ++using ParquetInfo = std::vector; ++ ++ParquetInfo GetColumnParquetInfo(const std::shared_ptr& data, int column_index) { ++ // Read the parquet data out of the buffer and get the sizes and lengths of the ++ // data pages in given column. We assert on the sizes and lengths of the pages ++ // to ensure that the chunking is done correctly. ++ ParquetInfo result; ++ ++ auto buffer_reader = std::make_shared(data); ++ auto parquet_reader = ParquetFileReader::Open(std::move(buffer_reader)); ++ ++ auto metadata = parquet_reader->metadata(); ++ for (int rg = 0; rg < metadata->num_row_groups(); rg++) { ++ auto page_reader = parquet_reader->RowGroup(rg)->GetColumnPageReader(column_index); ++ ColumnInfo column_info; ++ while (auto page = page_reader->NextPage()) { ++ if (page->type() == PageType::DATA_PAGE || page->type() == PageType::DATA_PAGE_V2) { ++ auto data_page = static_cast(page.get()); ++ column_info.page_sizes.push_back(data_page->uncompressed_size()); ++ column_info.page_lengths.push_back(data_page->num_values()); ++ } else if (page->type() == PageType::DICTIONARY_PAGE) { ++ column_info.has_dictionary_page = true; ++ } ++ } ++ result.push_back(column_info); ++ } ++ ++ return result; ++} ++ ++// A git-hunk like side-by-side data structure to represent the differences between two ++// vectors of uint64_t values. ++using ChunkDiff = std::pair; ++ ++/** ++ * Finds the differences between two sequences of chunk lengths or sizes. ++ * Uses a longest common subsequence algorithm to identify matching elements ++ * and extract the differences between the sequences. ++ * ++ * @param first The first sequence of chunk values ++ * @param second The second sequence of chunk values ++ * @return A vector of differences, where each difference is a pair of ++ * subsequences (one from each input) that differ ++ */ ++std::vector FindDifferences(const ChunkList& first, const ChunkList& second) { ++ // Compute the longest common subsequence using dynamic programming ++ size_t n = first.size(), m = second.size(); ++ std::vector> dp(n + 1, std::vector(m + 1, 0)); ++ ++ // Fill the dynamic programming table ++ for (size_t i = 0; i < n; i++) { ++ for (size_t j = 0; j < m; j++) { ++ if (first[i] == second[j]) { ++ // If current elements match, extend the LCS ++ dp[i + 1][j + 1] = dp[i][j] + 1; ++ } else { ++ // If current elements don't match, take the best option ++ dp[i + 1][j + 1] = std::max(dp[i + 1][j], dp[i][j + 1]); ++ } ++ } ++ } ++ ++ // Backtrack through the dynamic programming table to reconstruct the common ++ // parts and their positions in the original sequences ++ std::vector> common; ++ for (size_t i = n, j = m; i > 0 && j > 0;) { ++ if (first[i - 1] == second[j - 1]) { ++ // Found a common element, add to common list ++ common.emplace_back(i - 1, j - 1); ++ i--, j--; ++ } else if (dp[i - 1][j] >= dp[i][j - 1]) { ++ // Move in the direction of the larger LCS value ++ i--; ++ } else { ++ j--; ++ } ++ } ++ // Reverse to get indices in ascending order ++ std::reverse(common.begin(), common.end()); ++ ++ // Build the differences by finding sequences between common elements ++ std::vector result; ++ size_t last_i = 0, last_j = 0; ++ for (auto& c : common) { ++ auto ci = c.first; ++ auto cj = c.second; ++ // If there's a gap between the last common element and this one, ++ // record the difference ++ if (ci > last_i || cj > last_j) { ++ result.push_back({{first.begin() + last_i, first.begin() + ci}, ++ {second.begin() + last_j, second.begin() + cj}}); ++ } ++ // Move past this common element ++ last_i = ci + 1; ++ last_j = cj + 1; ++ } ++ ++ // Handle any remaining elements after the last common element ++ if (last_i < n || last_j < m) { ++ result.push_back( ++ {{first.begin() + last_i, first.end()}, {second.begin() + last_j, second.end()}}); ++ } ++ ++ // Post-process: merge adjacent diffs to avoid splitting single changes into multiple ++ // parts ++ std::vector merged; ++ for (auto& diff : result) { ++ if (!merged.empty()) { ++ auto& prev = merged.back(); ++ // Check if we can merge with the previous diff ++ bool can_merge_a = prev.first.empty() && diff.second.empty(); ++ bool can_merge_b = prev.second.empty() && diff.first.empty(); ++ if (can_merge_a) { ++ // Combine into one diff: keep prev's second, use diff's first ++ prev.first = std::move(diff.first); ++ continue; ++ } else if (can_merge_b) { ++ // Combine into one diff: keep prev's first, use diff's second ++ prev.second = std::move(diff.second); ++ continue; ++ } ++ } ++ // If we can't merge, add this diff to the result ++ merged.push_back(std::move(diff)); ++ } ++ return merged; ++} ++ ++void PrintDifferences(const ChunkList& original, const ChunkList& modified, ++ const std::vector& diffs) { ++ // Utility function to print the original and modified sequences, and the diffs ++ // between them. Used in case of failing assertions to display the differences. ++ std::cout << "Original: "; ++ for (const auto& val : original) { ++ std::cout << val << " "; ++ } ++ std::cout << std::endl; ++ ++ std::cout << "Modified: "; ++ for (const auto& val : modified) { ++ std::cout << val << " "; ++ } ++ std::cout << std::endl; ++ ++ for (const auto& diff : diffs) { ++ std::cout << "First: "; ++ for (const auto& val : diff.first) { ++ std::cout << val << " "; ++ } ++ std::cout << std::endl; ++ ++ std::cout << "Second: "; ++ for (const auto& val : diff.second) { ++ std::cout << val << " "; ++ } ++ std::cout << std::endl; ++ } ++} ++ ++TEST(TestFindDifferences, Basic) { ++ ChunkList first = {1, 2, 3, 4, 5}; ++ ChunkList second = {1, 7, 8, 4, 5}; ++ ++ auto diffs = FindDifferences(first, second); ++ ++ ASSERT_EQ(diffs.size(), 1); ++ ASSERT_EQ(diffs[0].first, ChunkList({2, 3})); ++ ASSERT_EQ(diffs[0].second, ChunkList({7, 8})); ++} ++ ++TEST(TestFindDifferences, MultipleDifferences) { ++ ChunkList first = {1, 2, 3, 4, 5, 6, 7}; ++ ChunkList second = {1, 8, 9, 4, 10, 6, 11}; ++ auto diffs = FindDifferences(first, second); ++ ++ ASSERT_EQ(diffs.size(), 3); ++ ++ ASSERT_EQ(diffs[0].first, ChunkList({2, 3})); ++ ASSERT_EQ(diffs[0].second, ChunkList({8, 9})); ++ ++ ASSERT_EQ(diffs[1].first, ChunkList({5})); ++ ASSERT_EQ(diffs[1].second, ChunkList({10})); ++ ++ ASSERT_EQ(diffs[2].first, ChunkList({7})); ++ ASSERT_EQ(diffs[2].second, ChunkList({11})); ++} ++ ++TEST(TestFindDifferences, DifferentLengths) { ++ ChunkList first = {1, 2, 3}; ++ ChunkList second = {1, 2, 3, 4, 5}; ++ auto diffs = FindDifferences(first, second); ++ ++ ASSERT_EQ(diffs.size(), 1); ++ ASSERT_TRUE(diffs[0].first.empty()); ++ ASSERT_EQ(diffs[0].second, ChunkList({4, 5})); ++} ++ ++TEST(TestFindDifferences, ChangesAtBothEnds) { ++ ChunkList first = {1, 2, 3, 4, 5, 6, 7, 8, 9}; ++ ChunkList second = {0, 0, 2, 3, 4, 5, 7, 7, 8}; ++ auto diffs = FindDifferences(first, second); ++ ++ ASSERT_EQ(diffs.size(), 3); ++ ASSERT_EQ(diffs[0].first, ChunkList({1})); ++ ASSERT_EQ(diffs[0].second, ChunkList({0, 0})); ++ ++ ASSERT_EQ(diffs[1].first, ChunkList({6})); ++ ASSERT_EQ(diffs[1].second, ChunkList({7})); ++ ++ ASSERT_EQ(diffs[2].first, ChunkList({9})); ++ ASSERT_EQ(diffs[2].second, ChunkList({})); ++} ++ ++TEST(TestFindDifferences, EmptyArrays) { ++ ChunkList first = {}; ++ ChunkList second = {}; ++ auto diffs = FindDifferences(first, second); ++ ASSERT_TRUE(diffs.empty()); ++} ++ ++TEST(TestFindDifferences, LongSequenceWithSingleDifference) { ++ ChunkList first = { ++ 1994, 2193, 2700, 1913, 2052, ++ }; ++ ChunkList second = {2048, 43, 2080, 2700, 1913, 2052}; ++ auto diffs = FindDifferences(first, second); ++ ++ ASSERT_EQ(diffs.size(), 1); ++ ASSERT_EQ(diffs[0].first, ChunkList({1994, 2193})); ++ ASSERT_EQ(diffs[0].second, ChunkList({2048, 43, 2080})); ++} ++ ++TEST(TestFindDifferences, LongSequenceWithMiddleChanges) { ++ ChunkList first = {2169, 1976, 2180, 2147, 1934, 1772, ++ 1914, 2075, 2154, 1940, 1934, 1970}; ++ ChunkList second = {2169, 1976, 2180, 2147, 2265, 1804, ++ 1717, 1925, 2122, 1940, 1934, 1970}; ++ auto diffs = FindDifferences(first, second); ++ ++ ASSERT_EQ(diffs.size(), 1); ++ ASSERT_EQ(diffs[0].first, ChunkList({1934, 1772, 1914, 2075, 2154})); ++ ASSERT_EQ(diffs[0].second, ChunkList({2265, 1804, 1717, 1925, 2122})); ++} ++ ++TEST(TestFindDifferences, AdditionalCase) { ++ ChunkList original = {445, 312, 393, 401, 410, 138, 558, 457}; ++ ChunkList modified = {445, 312, 393, 393, 410, 138, 558, 457}; ++ ++ auto diffs = FindDifferences(original, modified); ++ ASSERT_EQ(diffs.size(), 1); ++ ++ ASSERT_EQ(diffs[0].first, ChunkList({401})); ++ ASSERT_EQ(diffs[0].second, ChunkList({393})); ++} ++ ++void AssertPageLengthDifferences(const ColumnInfo& original, const ColumnInfo& modified, ++ int32_t exact_number_of_equal_diffs, ++ int32_t exact_number_of_larger_diffs, ++ int32_t exact_number_of_smaller_diffs, ++ const std::shared_ptr& edit_array) { ++ // Asserts that the differences between the original and modified page lengths ++ // are as expected. A longest common subsequence diff is calculated on the original ++ // and modified sequences of page lengths. The exact_number_of_equal_diffs, ++ // exact_number_of_larger_diffs, and exact_number_of_smaller_diffs parameters specify ++ // the expected number of differences with equal, larger, and smaller sums of the page ++ // lengths respectively. The edit_length parameter is used to verify that the page ++ // lenght differences are exactly equal to the edit_length. ++ auto diffs = FindDifferences(original.page_lengths, modified.page_lengths); ++ ++ // Note, the assertion function assumes that all edits are made using the same edit ++ // array, this could be improved by passing a list of edit arrays to the function ++ // and calculating the edit length for each edit array. ++ int64_t edit_length = edit_array->length(); ++ if (::arrow::is_list_like(edit_array->type()->id())) { ++ // add null and empty lists to the edit length because the page length corresponds to ++ // the number of def/rep levels rather than the number of elements in the array ++ for (auto chunk : edit_array->chunks()) { ++ auto list_array = checked_cast(chunk.get()); ++ for (int i = 0; i < list_array->length(); i++) { ++ if (list_array->IsNull(i) || (list_array->value_length(i) == 0)) { ++ edit_length++; ++ } ++ } ++ } ++ } ++ ++ size_t expected_number_of_diffs = exact_number_of_equal_diffs + ++ exact_number_of_larger_diffs + ++ exact_number_of_smaller_diffs; ++ if (diffs.size() != expected_number_of_diffs) { ++ PrintDifferences(original.page_lengths, modified.page_lengths, diffs); ++ } ++ if (diffs.size() == 0) { ++ // no differences found, the arrays are equal ++ ASSERT_TRUE(original.page_lengths == modified.page_lengths); ++ } ++ ASSERT_EQ(diffs.size(), expected_number_of_diffs); ++ ++ int32_t equal_diffs = 0; ++ int32_t larger_diffs = 0; ++ int32_t smaller_diffs = 0; ++ for (const auto& diff : diffs) { ++ int64_t original_sum = 0, modified_sum = 0; ++ for (const auto& val : diff.first) original_sum += val; ++ for (const auto& val : diff.second) modified_sum += val; ++ ++ if (original_sum == modified_sum) { ++ equal_diffs++; ++ } else if (original_sum < modified_sum) { ++ larger_diffs++; ++ ASSERT_EQ(original_sum + edit_length, modified_sum); ++ } else if (original_sum > modified_sum) { ++ smaller_diffs++; ++ ASSERT_EQ(original_sum, modified_sum + edit_length); ++ } ++ } ++ ++ ASSERT_EQ(equal_diffs, exact_number_of_equal_diffs); ++ ASSERT_EQ(larger_diffs, exact_number_of_larger_diffs); ++ ASSERT_EQ(smaller_diffs, exact_number_of_smaller_diffs); ++} ++ ++void AssertPageLengthDifferences(const ColumnInfo& original, const ColumnInfo& modified, ++ int32_t max_number_of_equal_diffs) { ++ // A less restrictive version of the above assertion function mainly used to ++ // assert the update case. ++ auto diffs = FindDifferences(original.page_lengths, modified.page_lengths); ++ if (diffs.size() > static_cast(max_number_of_equal_diffs)) { ++ PrintDifferences(original.page_lengths, modified.page_lengths, diffs); ++ } ++ ASSERT_LE(diffs.size(), static_cast(max_number_of_equal_diffs)); ++ ++ for (const auto& diff : diffs) { ++ int64_t left_sum = 0, right_sum = 0; ++ for (const auto& val : diff.first) left_sum += val; ++ for (const auto& val : diff.second) right_sum += val; ++ // This is only used from the UpdateOnce and UpdateTwice test cases where the edit(s) ++ // don't change the length of the original array, only update the value. This happens ++ // to apply to the list types as well because of the consistent array data generation. ++ ASSERT_EQ(left_sum, right_sum); ++ } ++ ++ if (diffs.size() == 0) { ++ // no differences found, the arrays are equal ++ ASSERT_TRUE(original.page_lengths == modified.page_lengths); ++ } ++} ++ ++Result CalculateCdcSize(const std::shared_ptr& array, bool nullable) { ++ // calculate the CDC chunk size based on the array elements belonging to a parquet page ++ auto type_id = array->type()->id(); ++ ++ int64_t result = 0; ++ if (::arrow::is_fixed_width(type_id)) { ++ int64_t element_size; ++ if (array->type()->id() == ::arrow::Type::BOOL) { ++ // the CDC chunker increments the chunk size by 1 for each boolean element ++ element_size = 1; ++ } else { ++ element_size = array->type()->byte_width(); ++ } ++ auto valid_elements = array->length() - array->null_count(); ++ result = valid_elements * element_size; ++ } else if (::arrow::is_binary_like(type_id)) { ++ auto binary_array = checked_cast(array.get()); ++ result += binary_array->total_values_length(); ++ } else if (::arrow::is_large_binary_like(type_id)) { ++ auto binary_array = checked_cast(array.get()); ++ result += binary_array->total_values_length(); ++ } else { ++ return Status::NotImplemented("CDC size calculation for type ", ++ array->type()->ToString(), " is not implemented"); ++ } ++ ++ if (nullable) { ++ // in case of nullable types chunk size is calculated from def_levels and ++ // the valid values ++ return result + array->length() * sizeof(uint16_t); ++ } else { ++ // for non-nullable types the chunk size is calculated purely from the values ++ return result; ++ } ++} ++ ++Result CalculateCdcSize(const std::shared_ptr<::arrow::ChunkedArray>& array, ++ bool nullable) { ++ int64_t result = 0; ++ for (int i = 0; i < array->num_chunks(); i++) { ++ ARROW_ASSIGN_OR_RAISE(auto chunk_size, CalculateCdcSize(array->chunk(i), nullable)); ++ result += chunk_size; ++ } ++ return result; ++} ++ ++void AssertContentDefinedChunkSizes(const std::shared_ptr<::arrow::ChunkedArray>& array, ++ const ColumnInfo& column_info, bool nullable, ++ int64_t min_chunk_size, int64_t max_chunk_size, ++ bool expect_dictionary_page) { ++ // check that the chunk sizes are within the expected range ++ ++ // the test tables are combined in the test cases so we expect only a single chunk ++ auto type_id = array->type()->id(); ++ ++ // check for the dictionary page if expected ++ if (type_id == ::arrow::Type::BOOL) { ++ ASSERT_FALSE(column_info.has_dictionary_page); ++ } else { ++ ASSERT_EQ(column_info.has_dictionary_page, expect_dictionary_page); ++ ASSERT_EQ(column_info.has_dictionary_page, expect_dictionary_page); ++ } ++ ++ if (::arrow::is_fixed_width(type_id) || ::arrow::is_base_binary_like(type_id)) { ++ int64_t offset = 0; ++ ++ auto page_lengths = column_info.page_lengths; ++ for (size_t i = 0; i < page_lengths.size() - 1; i++) { ++ // since CDC chunking is applied on the logical values before any parquet encoding ++ // we first slice the array to get the logical array and then calculate the CDC ++ // chunk size based on that ++ auto page_length = page_lengths[i]; ++ auto array_chunk = array->Slice(offset, page_length); ++ offset += page_length; ++ ++ ASSERT_OK_AND_ASSIGN(auto cdc_chunk_size, CalculateCdcSize(array_chunk, nullable)); ++ ASSERT_GE(cdc_chunk_size, min_chunk_size); ++ ASSERT_LE(cdc_chunk_size, max_chunk_size); ++ } ++ ++ auto last_page_length = page_lengths.back(); ++ auto last_array_chunk = array->Slice(offset, last_page_length); ++ ASSERT_OK_AND_ASSIGN(auto last_cdc_chunk_size, ++ CalculateCdcSize(last_array_chunk, nullable)); ++ // min chunk size is not guaranteed for the last chunk, only check that it is not ++ // larger than the max chunk size ++ ASSERT_LE(last_cdc_chunk_size, max_chunk_size); ++ ++ // the sum of the page lengths should be equal to the length of the array ++ offset += last_page_length; ++ ASSERT_EQ(offset, array->length()); ++ } ++ ++ // TODO(kszucs): have approximate size assertions for variable length types because ++ // we cannot calculate accurate CDC chunk sizes for list-like types without actually ++ // scanning the data and reimplementing the logic from the CDC chunker ++} ++ ++class TestCDC : public ::testing::Test { ++ protected: ++ static constexpr int64_t kMinChunkSize = 4 * 1024; ++ static constexpr int64_t kMaxChunkSize = 16 * 1024; ++ uint64_t GetRollingHashMask(const ContentDefinedChunker& cdc) const { ++ return cdc.GetRollingHashMask(); ++ } ++}; ++ ++TEST_F(TestCDC, ChunkSizeParameterValidation) { ++ // Test that constructor validates min/max chunk size parameters ++ auto li = LevelInfo(); ++ ++ ASSERT_NO_THROW(ContentDefinedChunker(li, 256 * 1024, 1024 * 1024)); ++ ++ // with norm_level=0 the difference between min and max chunk size must be ++ // at least 16 ++ ASSERT_THROW(ContentDefinedChunker(li, 0, -1), ParquetException); ++ ASSERT_THROW(ContentDefinedChunker(li, 1024, 512), ParquetException); ++ ++ ASSERT_THROW(ContentDefinedChunker(li, -1, 0), ParquetException); ++ ASSERT_THROW(ContentDefinedChunker(li, 0, 0), ParquetException); ++ ASSERT_THROW(ContentDefinedChunker(li, 0, 16), ParquetException); ++ ASSERT_NO_THROW(ContentDefinedChunker(li, 0, 32)); ++ ASSERT_THROW(ContentDefinedChunker(li, -16, -16), ParquetException); ++ ASSERT_THROW(ContentDefinedChunker(li, 16, 0), ParquetException); ++ ASSERT_THROW(ContentDefinedChunker(li, 32, 32), ParquetException); ++ ASSERT_THROW(ContentDefinedChunker(li, 32, 48), ParquetException); ++ ASSERT_NO_THROW(ContentDefinedChunker(li, 32, 64)); ++ ASSERT_NO_THROW(ContentDefinedChunker(li, 1024 * 1024, 2 * 1024 * 1024)); ++ ASSERT_NO_THROW( ++ ContentDefinedChunker(li, 1024 * 1024 * 1024L, 2LL * 1024 * 1024 * 1024L)); ++ ++ // with norm_level=1 the difference between min and max chunk size must be ++ // at least 64 ++ ASSERT_THROW(ContentDefinedChunker(li, 1, -1, 1), ParquetException); ++ ASSERT_THROW(ContentDefinedChunker(li, -1, 1, 1), ParquetException); ++ ASSERT_THROW(ContentDefinedChunker(li, 1, 1, 1), ParquetException); ++ ASSERT_THROW(ContentDefinedChunker(li, 1, 32, 1), ParquetException); ++ ASSERT_THROW(ContentDefinedChunker(li, 1, 33, 1), ParquetException); ++ ASSERT_NO_THROW(ContentDefinedChunker(li, 1, 65, 1)); ++ ++ // with norm_level=2 the difference between min and max chunk size must be ++ // at least 128 ++ ASSERT_THROW(ContentDefinedChunker(li, 0, 123, 2), ParquetException); ++ ASSERT_NO_THROW(ContentDefinedChunker(li, 0, 128, 2)); ++} ++ ++TEST_F(TestCDC, RollingHashMaskCalculation) { ++ auto le = LevelInfo(); ++ auto min_size = 256 * 1024; ++ auto max_size = 1024 * 1024; ++ ++ auto cdc0 = ContentDefinedChunker(le, min_size, max_size, 0); ++ ASSERT_EQ(GetRollingHashMask(cdc0), 0xFFFE000000000000); ++ ++ auto cdc1 = ContentDefinedChunker(le, min_size, max_size, 1); ++ ASSERT_EQ(GetRollingHashMask(cdc1), 0xFFFC000000000000); ++ ++ auto cdc2 = ContentDefinedChunker(le, min_size, max_size, 2); ++ ASSERT_EQ(GetRollingHashMask(cdc2), 0xFFF8000000000000); ++ ++ auto cdc3 = ContentDefinedChunker(le, min_size, max_size, 3); ++ ASSERT_EQ(GetRollingHashMask(cdc3), 0xFFF0000000000000); ++ ++ auto cdc4 = ContentDefinedChunker(le, min_size, max_size, -1); ++ ASSERT_EQ(GetRollingHashMask(cdc4), 0xFFFF000000000000); ++ ++ // check that mask bits are between 1 and 63 after adjusting with the 8 hash tables ++ ASSERT_THROW(ContentDefinedChunker(le, 0, 16, 0), ParquetException); ++ ++ auto cdc5 = ContentDefinedChunker(le, 0, 32, 0); ++ ASSERT_EQ(GetRollingHashMask(cdc5), 0x8000000000000000); ++ ASSERT_THROW(ContentDefinedChunker(le, 0, 32, 1), ParquetException); ++ ++ auto cdc6 = ContentDefinedChunker(le, 0, 64, 0); ++ ASSERT_EQ(GetRollingHashMask(cdc6), 0xC000000000000000); ++ ++ auto cdc7 = ContentDefinedChunker(le, 0, 16, -1); ++ ASSERT_EQ(GetRollingHashMask(cdc7), 0x8000000000000000); ++ ++ // another unrealistic case, checking for the validation ++ ASSERT_THROW(ContentDefinedChunker(le, 128, 384, -60), ParquetException); ++ auto cdc8 = ContentDefinedChunker(le, 128, 384, -59); ++ ASSERT_EQ(GetRollingHashMask(cdc8), 0xFFFFFFFFFFFFFFFE); ++} ++ ++TEST_F(TestCDC, WriteSingleColumnParquetFile) { ++ // Define the schema with a single column "number" ++ auto schema = std::dynamic_pointer_cast(schema::GroupNode::Make( ++ "root", Repetition::REQUIRED, ++ {schema::PrimitiveNode::Make("number", Repetition::REQUIRED, Type::INT32)})); ++ ++ auto sink = CreateOutputStream(); ++ auto builder = WriterProperties::Builder(); ++ auto props = builder.enable_content_defined_chunking()->build(); ++ ++ auto writer = ParquetFileWriter::Open(sink, schema, props); ++ auto row_group_writer = writer->AppendRowGroup(); ++ ++ // Create a column writer for the "number" column ++ auto column_writer = row_group_writer->NextColumn(); ++ auto& int_column_writer = dynamic_cast(*column_writer); ++ ++ std::vector numbers = {1, 2, 3, 4, 5}; ++ std::vector valid_bits = {1, 0, 1, 0, 1}; ++ ++ auto expected_msg = ::testing::Property( ++ &ParquetException::what, ++ ::testing::HasSubstr("" ++ "")); ++ EXPECT_THROW_THAT( ++ [&]() { ++ int_column_writer.WriteBatch(numbers.size(), nullptr, nullptr, numbers.data()); ++ }, ++ ParquetException, expected_msg); ++ EXPECT_THROW_THAT( ++ [&]() { ++ int_column_writer.WriteBatchSpaced(numbers.size(), nullptr, nullptr, ++ valid_bits.data(), 0, numbers.data()); ++ }, ++ ParquetException, expected_msg); ++} ++ ++TEST_F(TestCDC, LastChunkDoesntTriggerAddDataPage) { ++ // Define the schema with a single column "number" ++ auto schema = std::dynamic_pointer_cast(schema::GroupNode::Make( ++ "root", Repetition::REQUIRED, ++ {schema::PrimitiveNode::Make("number", Repetition::REQUIRED, Type::INT32)})); ++ ++ auto sink = CreateOutputStream(); ++ auto builder = WriterProperties::Builder(); ++ auto props = builder.enable_content_defined_chunking() ++ ->content_defined_chunking_options({kMinChunkSize, kMaxChunkSize, 0}) ++ ->disable_dictionary() ++ ->build(); ++ ++ auto writer = ParquetFileWriter::Open(sink, schema, props); ++ auto row_group_writer = writer->AppendRowGroup(); ++ ++ // Create a column writer for the "number" column ++ auto column_writer = row_group_writer->NextColumn(); ++ auto& int_column_writer = dynamic_cast(*column_writer); ++ ++ ASSERT_OK_AND_ASSIGN(auto array, ::arrow::gen::Step()->Generate(8000)); ++ auto arrow_props = default_arrow_writer_properties(); ++ auto arrow_ctx = ArrowWriteContext(default_memory_pool(), arrow_props.get()); ++ ++ // Calling WriteArrow twice, we expect that the first call doesn't add a new data page ++ // at the end allowing subsequent calls to append to the same page ++ ASSERT_OK(int_column_writer.WriteArrow(nullptr, nullptr, array->length(), *array, ++ &arrow_ctx, false)); ++ ASSERT_OK(int_column_writer.WriteArrow(nullptr, nullptr, array->length(), *array, ++ &arrow_ctx, false)); ++ ++ int_column_writer.Close(); ++ writer->Close(); ++ ASSERT_OK_AND_ASSIGN(auto buffer, sink->Finish()); ++ ++ auto info = GetColumnParquetInfo(buffer, /*column_index=*/0); ++ ASSERT_EQ(info.size(), 1); ++ ++ ASSERT_OK_AND_ASSIGN(auto chunked_array, ChunkedArray::Make({array, array})); ++ AssertContentDefinedChunkSizes(chunked_array, info.front(), /*nullable=*/false, ++ kMinChunkSize, kMaxChunkSize, ++ /*expect_dictionary_page=*/false); ++} ++ ++struct CaseConfig { ++ // Arrow data type to generate the testing data for ++ std::shared_ptr<::arrow::DataType> dtype; ++ // Whether the data type is nullable ++ bool is_nullable; ++ // Data page version to use ++ ParquetDataPageVersion data_page_version = ParquetDataPageVersion::V1; ++}; ++ ++// Define PrintTo for MyStruct ++void PrintTo(const CaseConfig& param, std::ostream* os) { ++ *os << "{ " << param.dtype->ToString(); ++ if (param.is_nullable) { ++ *os << " nullable"; ++ } ++ *os << " }"; ++} ++ ++class TestCDCSingleRowGroup : public ::testing::TestWithParam { ++ protected: ++ static constexpr int64_t kPartSize = 128 * 1024; ++ static constexpr int64_t kEditSize = 128; ++ static constexpr int64_t kMinChunkSize = 4 * 1024; ++ static constexpr int64_t kMaxChunkSize = 16 * 1024; ++ static constexpr int64_t kRowGroupLength = 1024 * 1024; ++ ++ // Column random table parts for testing ++ std::shared_ptr field_; ++ std::shared_ptr
part1_, part2_, part3_, part4_, part5_, part6_, part7_; ++ ++ void SetUp() override { ++ const auto& param = GetParam(); ++ auto field_ = ::arrow::field("f0", param.dtype, param.is_nullable); ++ auto schema = ::arrow::schema({field_}); ++ ++ // since the chunk sizes are constant we derive the number of records to generate ++ // from the size of the data type unless it is nested or variable length where ++ // we use a hand picked value to avoid generating too large tables ++ int64_t bytes_per_record; ++ if (param.dtype->byte_width() > 0) { ++ bytes_per_record = param.dtype->byte_width(); ++ if (param.is_nullable) { ++ bytes_per_record += sizeof(uint16_t); ++ } ++ } else { ++ // for variable length types we use the size of the first element ++ bytes_per_record = 16; ++ } ++ ++ auto part_length = kPartSize / bytes_per_record; ++ auto edit_length = kEditSize / bytes_per_record; ++ ++ ASSERT_OK_AND_ASSIGN(part1_, GenerateTable(schema, part_length, /*seed=*/0)); ++ ASSERT_OK_AND_ASSIGN(part2_, GenerateTable(schema, edit_length, /*seed=*/1)); ++ ASSERT_OK_AND_ASSIGN(part3_, ++ GenerateTable(schema, part_length, /*seed=*/part_length)); ++ ASSERT_OK_AND_ASSIGN(part4_, GenerateTable(schema, edit_length, /*seed=*/2)); ++ ASSERT_OK_AND_ASSIGN(part5_, ++ GenerateTable(schema, part_length, /*seed=*/2 * part_length)); ++ ASSERT_OK_AND_ASSIGN(part6_, GenerateTable(schema, edit_length, /*seed=*/3)); ++ ASSERT_OK_AND_ASSIGN(part7_, GenerateTable(schema, edit_length, /*seed=*/4)); ++ } ++}; ++ ++TEST_P(TestCDCSingleRowGroup, DeleteOnce) { ++ const auto& param = GetParam(); ++ ++ ASSERT_OK_AND_ASSIGN(auto base, ConcatAndCombine({part1_, part2_, part3_})); ++ ASSERT_OK_AND_ASSIGN(auto modified, ConcatAndCombine({part1_, part3_})); ++ ASSERT_FALSE(base->Equals(*modified)); ++ ++ for (bool enable_dictionary : {false, true}) { ++ ASSERT_OK_AND_ASSIGN( ++ auto base_parquet, ++ WriteTableToBuffer(base, kMinChunkSize, kMaxChunkSize, kRowGroupLength, ++ enable_dictionary, param.data_page_version)); ++ ASSERT_OK_AND_ASSIGN( ++ auto modified_parquet, ++ WriteTableToBuffer(modified, kMinChunkSize, kMaxChunkSize, kRowGroupLength, ++ enable_dictionary, param.data_page_version)); ++ ++ auto base_info = GetColumnParquetInfo(base_parquet, /*column_index=*/0); ++ auto modified_info = GetColumnParquetInfo(modified_parquet, /*column_index=*/0); ++ ++ // assert that there is only one row group ++ ASSERT_EQ(base_info.size(), 1); ++ ASSERT_EQ(modified_info.size(), 1); ++ ++ // check that the chunk sizes are within the expected range ++ AssertContentDefinedChunkSizes(base->column(0), base_info.front(), param.is_nullable, ++ kMinChunkSize, kMaxChunkSize, ++ /*expect_dictionary_page=*/enable_dictionary); ++ AssertContentDefinedChunkSizes(modified->column(0), modified_info.front(), ++ param.is_nullable, kMinChunkSize, kMaxChunkSize, ++ /*expect_dictionary_page=*/enable_dictionary); ++ ++ // check that there is a single "diff" between the two page length sequences ++ // and that the diff removes edit_length number of values, there should be no ++ // other differences because we deal with a single row group (in case of multiple ++ // row groups the first page of each subsequent row group would be different due ++ // to shifting caused by the fixed sized row group length) ++ AssertPageLengthDifferences(base_info.front(), modified_info.front(), ++ /*exact_number_of_equal_diffs=*/0, ++ /*exact_number_of_larger_diffs=*/0, ++ /*exact_number_of_smaller_diffs=*/1, part2_->column(0)); ++ } ++} ++ ++TEST_P(TestCDCSingleRowGroup, DeleteTwice) { ++ const auto& param = GetParam(); ++ ++ ASSERT_OK_AND_ASSIGN(auto base, ++ ConcatAndCombine({part1_, part2_, part3_, part4_, part5_})); ++ ASSERT_OK_AND_ASSIGN(auto modified, ConcatAndCombine({part1_, part3_, part5_})); ++ ASSERT_FALSE(base->Equals(*modified)); ++ ++ for (bool enable_dictionary : {false, true}) { ++ ASSERT_OK_AND_ASSIGN( ++ auto base_parquet, ++ WriteTableToBuffer(base, kMinChunkSize, kMaxChunkSize, kRowGroupLength, ++ enable_dictionary, param.data_page_version)); ++ ASSERT_OK_AND_ASSIGN( ++ auto modified_parquet, ++ WriteTableToBuffer(modified, kMinChunkSize, kMaxChunkSize, kRowGroupLength, ++ enable_dictionary, param.data_page_version)); ++ ++ auto base_info = GetColumnParquetInfo(base_parquet, /*column_index=*/0); ++ auto modified_info = GetColumnParquetInfo(modified_parquet, /*column_index=*/0); ++ ++ // assert that there is only one row group ++ ASSERT_EQ(base_info.size(), 1); ++ ASSERT_EQ(modified_info.size(), 1); ++ ++ // check that the chunk sizes are within the expected range ++ AssertContentDefinedChunkSizes(base->column(0), base_info.front(), param.is_nullable, ++ kMinChunkSize, kMaxChunkSize, ++ /*expect_dictionary_page=*/enable_dictionary); ++ AssertContentDefinedChunkSizes(modified->column(0), modified_info.front(), ++ param.is_nullable, kMinChunkSize, kMaxChunkSize, ++ /*expect_dictionary_page=*/enable_dictionary); ++ ++ // check that there are exactly two "diffs" between the two page length sequences ++ // and those diffs remove edit_length number of values (part2 and part4 have the ++ // same number of values), there should be no other differences because we have ++ // a single row group ++ AssertPageLengthDifferences(base_info.front(), modified_info.front(), ++ /*exact_number_of_equal_diffs=*/0, ++ /*exact_number_of_larger_diffs=*/0, ++ /*exact_number_of_smaller_diffs=*/2, part2_->column(0)); ++ } ++} ++ ++TEST_P(TestCDCSingleRowGroup, UpdateOnce) { ++ const auto& param = GetParam(); ++ ++ ASSERT_OK_AND_ASSIGN(auto base, ConcatAndCombine({part1_, part2_, part3_})); ++ ASSERT_OK_AND_ASSIGN(auto modified, ConcatAndCombine({part1_, part4_, part3_})); ++ ASSERT_FALSE(base->Equals(*modified)); ++ ++ for (bool enable_dictionary : {false, true}) { ++ ASSERT_OK_AND_ASSIGN( ++ auto base_parquet, ++ WriteTableToBuffer(base, kMinChunkSize, kMaxChunkSize, kRowGroupLength, ++ enable_dictionary, param.data_page_version)); ++ ASSERT_OK_AND_ASSIGN( ++ auto modified_parquet, ++ WriteTableToBuffer(modified, kMinChunkSize, kMaxChunkSize, kRowGroupLength, ++ enable_dictionary, param.data_page_version)); ++ ++ auto base_info = GetColumnParquetInfo(base_parquet, /*column_index=*/0); ++ auto modified_info = GetColumnParquetInfo(modified_parquet, /*column_index=*/0); ++ ++ // assert that there is only one row group ++ ASSERT_EQ(base_info.size(), 1); ++ ASSERT_EQ(modified_info.size(), 1); ++ ++ // check that the chunk sizes are within the expected range ++ AssertContentDefinedChunkSizes(base->column(0), base_info.front(), param.is_nullable, ++ kMinChunkSize, kMaxChunkSize, ++ /*expect_dictionary_page=*/enable_dictionary); ++ AssertContentDefinedChunkSizes(modified->column(0), modified_info.front(), ++ param.is_nullable, kMinChunkSize, kMaxChunkSize, ++ /*expect_dictionary_page=*/enable_dictionary); ++ ++ // check that there is a single "diff" between the two page length sequences ++ // which doesn't change the length of the array, only the values are updated ++ // there should be no other differences because we deal with a single row group ++ AssertPageLengthDifferences(base_info.front(), modified_info.front(), ++ /*max_number_of_equal_diffs=*/1); ++ } ++} ++ ++TEST_P(TestCDCSingleRowGroup, UpdateTwice) { ++ const auto& param = GetParam(); ++ ++ ASSERT_OK_AND_ASSIGN(auto base, ++ ConcatAndCombine({part1_, part2_, part3_, part4_, part5_})); ++ ASSERT_OK_AND_ASSIGN(auto modified, ++ ConcatAndCombine({part1_, part6_, part3_, part7_, part5_})); ++ ASSERT_FALSE(base->Equals(*modified)); ++ ++ for (bool enable_dictionary : {false, true}) { ++ ASSERT_OK_AND_ASSIGN( ++ auto base_parquet, ++ WriteTableToBuffer(base, kMinChunkSize, kMaxChunkSize, kRowGroupLength, ++ enable_dictionary, param.data_page_version)); ++ ASSERT_OK_AND_ASSIGN( ++ auto modified_parquet, ++ WriteTableToBuffer(modified, kMinChunkSize, kMaxChunkSize, kRowGroupLength, ++ enable_dictionary, param.data_page_version)); ++ ++ auto base_info = GetColumnParquetInfo(base_parquet, /*column_index=*/0); ++ auto modified_info = GetColumnParquetInfo(modified_parquet, /*column_index=*/0); ++ ++ // assert that there is only one row group ++ ASSERT_EQ(base_info.size(), 1); ++ ASSERT_EQ(modified_info.size(), 1); ++ ++ // check that the chunk sizes are within the expected range ++ AssertContentDefinedChunkSizes(base->column(0), base_info.front(), param.is_nullable, ++ kMinChunkSize, kMaxChunkSize, ++ /*expect_dictionary_page=*/enable_dictionary); ++ AssertContentDefinedChunkSizes(modified->column(0), modified_info.front(), ++ param.is_nullable, kMinChunkSize, kMaxChunkSize, ++ /*expect_dictionary_page=*/enable_dictionary); ++ ++ // check that there are exactly two "diffs" between the two page length sequences ++ // which don't change the length of the array, only the values are updated ++ AssertPageLengthDifferences(base_info.front(), modified_info.front(), ++ /*max_number_of_equal_diffs=*/2); ++ } ++} ++ ++TEST_P(TestCDCSingleRowGroup, InsertOnce) { ++ const auto& param = GetParam(); ++ ++ ASSERT_OK_AND_ASSIGN(auto base, ConcatAndCombine({part1_, part3_})); ++ ASSERT_OK_AND_ASSIGN(auto modified, ConcatAndCombine({part1_, part2_, part3_})); ++ ASSERT_FALSE(base->Equals(*modified)); ++ ++ for (bool enable_dictionary : {false, true}) { ++ ASSERT_OK_AND_ASSIGN( ++ auto base_parquet, ++ WriteTableToBuffer(base, kMinChunkSize, kMaxChunkSize, kRowGroupLength, ++ enable_dictionary, param.data_page_version)); ++ ASSERT_OK_AND_ASSIGN( ++ auto modified_parquet, ++ WriteTableToBuffer(modified, kMinChunkSize, kMaxChunkSize, kRowGroupLength, ++ enable_dictionary, param.data_page_version)); ++ ++ auto base_info = GetColumnParquetInfo(base_parquet, /*column_index=*/0); ++ auto modified_info = GetColumnParquetInfo(modified_parquet, /*column_index=*/0); ++ ++ // assert that there is only one row group ++ ASSERT_EQ(base_info.size(), 1); ++ ASSERT_EQ(modified_info.size(), 1); ++ ++ // check that the chunk sizes are within the expected range ++ AssertContentDefinedChunkSizes(base->column(0), base_info.front(), param.is_nullable, ++ kMinChunkSize, kMaxChunkSize, ++ /*expect_dictionary_page=*/enable_dictionary); ++ AssertContentDefinedChunkSizes(modified->column(0), modified_info.front(), ++ param.is_nullable, kMinChunkSize, kMaxChunkSize, ++ /*expect_dictionary_page=*/enable_dictionary); ++ ++ // check that there is a single "diff" between the two page length sequences ++ // adding edit_length number of values, there should be no other differences ++ // because we deal with a single row group and made a single modification ++ AssertPageLengthDifferences(base_info.front(), modified_info.front(), ++ /*exact_number_of_equal_diffs=*/0, ++ /*exact_number_of_larger_diffs=*/1, ++ /*exact_number_of_smaller_diffs=*/0, part2_->column(0)); ++ } ++} ++ ++TEST_P(TestCDCSingleRowGroup, InsertTwice) { ++ const auto& param = GetParam(); ++ ++ ASSERT_OK_AND_ASSIGN(auto base, ConcatAndCombine({part1_, part3_, part5_})); ++ ASSERT_OK_AND_ASSIGN(auto modified, ++ ConcatAndCombine({part1_, part2_, part3_, part4_, part5_})); ++ ASSERT_FALSE(base->Equals(*modified)); ++ ++ for (bool enable_dictionary : {false, true}) { ++ ASSERT_OK_AND_ASSIGN( ++ auto base_parquet, ++ WriteTableToBuffer(base, kMinChunkSize, kMaxChunkSize, kRowGroupLength, ++ enable_dictionary, param.data_page_version)); ++ ASSERT_OK_AND_ASSIGN( ++ auto modified_parquet, ++ WriteTableToBuffer(modified, kMinChunkSize, kMaxChunkSize, kRowGroupLength, ++ enable_dictionary, param.data_page_version)); ++ ++ auto base_info = GetColumnParquetInfo(base_parquet, /*column_index=*/0); ++ auto modified_info = GetColumnParquetInfo(modified_parquet, /*column_index=*/0); ++ ++ // assert that there is only one row group ++ ASSERT_EQ(base_info.size(), 1); ++ ASSERT_EQ(modified_info.size(), 1); ++ ++ // check that the chunk sizes are within the expected range ++ AssertContentDefinedChunkSizes(base->column(0), base_info.front(), param.is_nullable, ++ kMinChunkSize, kMaxChunkSize, ++ /*expect_dictionary_page=*/enable_dictionary); ++ AssertContentDefinedChunkSizes(modified->column(0), modified_info.front(), ++ param.is_nullable, kMinChunkSize, kMaxChunkSize, ++ /*expect_dictionary_page=*/enable_dictionary); ++ ++ // check that there are exactly two "diffs" between the two page length sequences ++ // which add edit_length number of values, there should be no other differences ++ AssertPageLengthDifferences(base_info.front(), modified_info.front(), ++ /*exact_number_of_equal_diffs=*/0, ++ /*exact_number_of_larger_diffs=*/2, ++ /*exact_number_of_smaller_diffs=*/0, part2_->column(0)); ++ } ++} ++ ++TEST_P(TestCDCSingleRowGroup, Prepend) { ++ const auto& param = GetParam(); ++ ++ ASSERT_OK_AND_ASSIGN(auto base, ConcatAndCombine({part1_, part2_, part3_})); ++ ASSERT_OK_AND_ASSIGN(auto modified, ConcatAndCombine({part4_, part1_, part2_, part3_})); ++ ASSERT_FALSE(base->Equals(*modified)); ++ ++ for (bool enable_dictionary : {false, true}) { ++ ASSERT_OK_AND_ASSIGN( ++ auto base_parquet, ++ WriteTableToBuffer(base, kMinChunkSize, kMaxChunkSize, kRowGroupLength, ++ enable_dictionary, param.data_page_version)); ++ ASSERT_OK_AND_ASSIGN( ++ auto modified_parquet, ++ WriteTableToBuffer(modified, kMinChunkSize, kMaxChunkSize, kRowGroupLength, ++ enable_dictionary, param.data_page_version)); ++ ++ auto base_info = GetColumnParquetInfo(base_parquet, /*column_index=*/0); ++ auto modified_info = GetColumnParquetInfo(modified_parquet, /*column_index=*/0); ++ ++ // assert that there is only one row group ++ ASSERT_EQ(base_info.size(), 1); ++ ASSERT_EQ(modified_info.size(), 1); ++ ++ // check that the chunk sizes are within the expected range ++ AssertContentDefinedChunkSizes(base->column(0), base_info.front(), param.is_nullable, ++ kMinChunkSize, kMaxChunkSize, ++ /*expect_dictionary_page=*/enable_dictionary); ++ AssertContentDefinedChunkSizes(modified->column(0), modified_info.front(), ++ param.is_nullable, kMinChunkSize, kMaxChunkSize, ++ /*expect_dictionary_page=*/enable_dictionary); ++ ++ auto original_page_lengths = base_info.front().page_lengths; ++ auto modified_page_lengths = modified_info.front().page_lengths; ++ ++ // we expect to have the same number or more pages at the beginning of the ++ // modified file without increasing the size of any subsequent page ++ ASSERT_LE(original_page_lengths.size(), modified_page_lengths.size()); ++ AssertPageLengthDifferences(base_info.front(), modified_info.front(), ++ /*exact_number_of_equal_diffs=*/0, ++ /*exact_number_of_larger_diffs=*/1, ++ /*exact_number_of_smaller_diffs=*/0, part4_->column(0)); ++ } ++} ++ ++TEST_P(TestCDCSingleRowGroup, Append) { ++ const auto& param = GetParam(); ++ ++ ASSERT_OK_AND_ASSIGN(auto base, ConcatAndCombine({part1_, part2_, part3_})); ++ ASSERT_OK_AND_ASSIGN(auto modified, ConcatAndCombine({part1_, part2_, part3_, part4_})); ++ ASSERT_FALSE(base->Equals(*modified)); ++ ++ for (bool enable_dictionary : {false, true}) { ++ ASSERT_OK_AND_ASSIGN( ++ auto base_parquet, ++ WriteTableToBuffer(base, kMinChunkSize, kMaxChunkSize, kRowGroupLength, ++ enable_dictionary, param.data_page_version)); ++ ASSERT_OK_AND_ASSIGN( ++ auto modified_parquet, ++ WriteTableToBuffer(modified, kMinChunkSize, kMaxChunkSize, kRowGroupLength, ++ enable_dictionary, param.data_page_version)); ++ ++ auto base_info = GetColumnParquetInfo(base_parquet, /*column_index=*/0); ++ auto modified_info = GetColumnParquetInfo(modified_parquet, /*column_index=*/0); ++ ++ // assert that there is only one row group ++ ASSERT_EQ(base_info.size(), 1); ++ ASSERT_EQ(modified_info.size(), 1); ++ ++ // check that the chunk sizes are within the expected range ++ AssertContentDefinedChunkSizes(base->column(0), base_info.front(), param.is_nullable, ++ kMinChunkSize, kMaxChunkSize, ++ /*expect_dictionary_page=*/enable_dictionary); ++ AssertContentDefinedChunkSizes(modified->column(0), modified_info.front(), ++ param.is_nullable, kMinChunkSize, kMaxChunkSize, ++ /*expect_dictionary_page=*/enable_dictionary); ++ ++ auto original_page_lengths = base_info.front().page_lengths; ++ auto modified_page_lengths = modified_info.front().page_lengths; ++ ++ // there are either additional pages and/or the last page is larger in the modified ++ // than in the original file ++ ASSERT_LE(original_page_lengths.size(), modified_page_lengths.size()); ++ // all pages must be identical except for the last one which can be larger ++ for (size_t i = 0; i < original_page_lengths.size() - 1; i++) { ++ ASSERT_EQ(original_page_lengths[i], modified_page_lengths[i]); ++ } ++ auto last_index = original_page_lengths.size() - 1; ++ ASSERT_GE(modified_page_lengths[last_index], original_page_lengths[last_index]); ++ } ++} ++ ++TEST_P(TestCDCSingleRowGroup, EmptyTable) { ++ const auto& param = GetParam(); ++ ++ auto schema = ::arrow::schema({::arrow::field("f0", param.dtype, param.is_nullable)}); ++ ASSERT_OK_AND_ASSIGN(auto empty_table, GenerateTable(schema, 0, /*seed=*/0)); ++ ASSERT_EQ(empty_table->num_rows(), 0); ++ ++ for (bool enable_dictionary : {false, true}) { ++ ASSERT_OK_AND_ASSIGN( ++ auto parquet, ++ WriteTableToBuffer(empty_table, kMinChunkSize, kMaxChunkSize, kRowGroupLength, ++ enable_dictionary, param.data_page_version)); ++ ++ auto info = GetColumnParquetInfo(parquet, /*column_index=*/0); ++ ++ // There is a single row group ++ ASSERT_EQ(info.size(), 1); ++ ++ // An empty table should result in no data pages ++ ASSERT_TRUE(info.front().page_lengths.empty()); ++ ASSERT_TRUE(info.front().page_sizes.empty()); ++ } ++} ++ ++TEST_P(TestCDCSingleRowGroup, ArrayOffsets) { ++ // check that the array offsets are respected in the chunker ++ const auto& param = GetParam(); ++ ASSERT_OK_AND_ASSIGN(auto table, ConcatAndCombine({part1_, part2_, part3_})); ++ ++ for (auto offset : {0, 512, 1024}) { ++ auto sliced_table = table->Slice(offset); ++ ++ // assert that the first column has a non-zero offset ++ auto column = sliced_table->column(0); ++ auto first_chunk = column->chunk(0); ++ ASSERT_EQ(first_chunk->offset(), offset); ++ ++ // write out the sliced table, read it back and compare ++ ASSERT_OK_AND_ASSIGN( ++ auto sliced_parquet, ++ WriteTableToBuffer(sliced_table, kMinChunkSize, kMaxChunkSize, kRowGroupLength, ++ true, param.data_page_version)); ++ ++ auto sliced_info = GetColumnParquetInfo(sliced_parquet, /*column_index=*/0); ++ ASSERT_EQ(sliced_info.size(), 1); ++ } ++} ++ ++#if defined(ADDRESS_SANITIZER) || defined(ARROW_VALGRIND) ++// Instantiate the test suite with a reduced set of types to avoid slow tests ++INSTANTIATE_TEST_SUITE_P( ++ Types, TestCDCSingleRowGroup, ++ testing::Values( ++ CaseConfig{::arrow::boolean(), false}, CaseConfig{::arrow::int64(), true}, ++ // Binary-like ++ CaseConfig{::arrow::utf8(), false}, ++ CaseConfig{::arrow::fixed_size_binary(16), true}, ++ // Nested types ++ CaseConfig{::arrow::list(::arrow::int32()), false}, ++ CaseConfig{::arrow::list(::arrow::utf8()), true}, ++ CaseConfig{::arrow::struct_({::arrow::field("f0", ::arrow::float64())}), true})); ++#else ++INSTANTIATE_TEST_SUITE_P( ++ Types, TestCDCSingleRowGroup, ++ testing::Values( ++ // Boolean ++ CaseConfig{::arrow::boolean(), false}, ++ // Numeric ++ CaseConfig{::arrow::uint8(), false}, CaseConfig{::arrow::uint16(), false}, ++ CaseConfig{::arrow::uint32(), false}, CaseConfig{::arrow::uint64(), true}, ++ CaseConfig{::arrow::int8(), false}, CaseConfig{::arrow::int16(), false}, ++ CaseConfig{::arrow::int32(), false}, CaseConfig{::arrow::int64(), true}, ++ CaseConfig{::arrow::float16(), false}, CaseConfig{::arrow::float32(), false}, ++ CaseConfig{::arrow::float64(), true}, ++ CaseConfig{::arrow::decimal128(18, 6), false}, ++ CaseConfig{::arrow::decimal256(40, 6), false}, ++ // Binary-like ++ CaseConfig{::arrow::utf8(), false}, CaseConfig{::arrow::binary(), true}, ++ CaseConfig{::arrow::fixed_size_binary(16), true}, ++ // Temporal ++ CaseConfig{::arrow::date32(), false}, ++ CaseConfig{::arrow::time32(::arrow::TimeUnit::MILLI), true}, ++ CaseConfig{::arrow::time64(::arrow::TimeUnit::NANO), false}, ++ CaseConfig{::arrow::timestamp(::arrow::TimeUnit::NANO), true}, ++ CaseConfig{::arrow::duration(::arrow::TimeUnit::NANO), false}, ++ // Nested types ++ CaseConfig{::arrow::list(::arrow::int16()), false}, ++ CaseConfig{::arrow::list(::arrow::int32()), true}, ++ CaseConfig{::arrow::list(::arrow::utf8()), true}, ++ CaseConfig{::arrow::struct_({::arrow::field("f0", ::arrow::int32())}), false}, ++ CaseConfig{::arrow::struct_({::arrow::field("f0", ::arrow::float64())}), true}, ++ CaseConfig{ ++ ::arrow::list(::arrow::struct_({::arrow::field("f0", ::arrow::int32())})), ++ false}, ++ // Extension type ++ CaseConfig{::arrow::extension::json(), true}, ++ // Use ParquetDataPageVersion::V2 ++ CaseConfig{::arrow::large_binary(), false, ParquetDataPageVersion::V2}, ++ CaseConfig{::arrow::list(::arrow::utf8()), true, ParquetDataPageVersion::V2})); ++#endif ++ ++class TestCDCMultipleRowGroups : public ::testing::Test { ++ protected: ++ static auto constexpr kPartLength = 128 * 1024; ++ static auto constexpr kEditLength = 128; ++ static auto constexpr kRowGroupLength = 64 * 1024; ++ static auto constexpr kEnableDictionary = false; ++ static auto constexpr kMinChunkSize = 4 * 1024; ++ static auto constexpr kMaxChunkSize = 16 * 1024; ++ ++ // Column random table parts for testing ++ ++ std::shared_ptr
part1_, part2_, part3_; ++ std::shared_ptr
edit1_, edit2_, edit3_; ++ ++ void SetUp() override { ++ auto schema = ::arrow::schema({ ++ ::arrow::field("int32", ::arrow::int32(), true), ++ ::arrow::field("float64", ::arrow::float64(), true), ++ ::arrow::field("bool", ::arrow::boolean(), false), ++ }); ++ ++ ASSERT_OK_AND_ASSIGN(part1_, GenerateTable(schema, kPartLength, /*seed=*/0)); ++ ASSERT_OK_AND_ASSIGN(part2_, GenerateTable(schema, kPartLength, /*seed=*/2)); ++ ASSERT_OK_AND_ASSIGN(part3_, GenerateTable(schema, kPartLength, /*seed=*/4)); ++ ++ ASSERT_OK_AND_ASSIGN(edit1_, GenerateTable(schema, kEditLength, /*seed=*/1)); ++ ASSERT_OK_AND_ASSIGN(edit2_, GenerateTable(schema, kEditLength, /*seed=*/3)); ++ ASSERT_OK_AND_ASSIGN(edit3_, GenerateTable(schema, kEditLength, /*seed=*/5)); ++ } ++}; ++ ++TEST_F(TestCDCMultipleRowGroups, InsertOnce) { ++ ASSERT_OK_AND_ASSIGN(auto base, ConcatAndCombine({part1_, edit1_, part2_, part3_})); ++ ASSERT_OK_AND_ASSIGN(auto modified, ++ ConcatAndCombine({part1_, edit1_, edit2_, part2_, part3_})); ++ ASSERT_FALSE(base->Equals(*modified)); ++ ASSERT_EQ(modified->num_rows(), base->num_rows() + edit2_->num_rows()); ++ ++ ASSERT_OK_AND_ASSIGN( ++ auto base_parquet, ++ WriteTableToBuffer(base, kMinChunkSize, kMaxChunkSize, kRowGroupLength, ++ kEnableDictionary, ParquetDataPageVersion::V1)); ++ ASSERT_OK_AND_ASSIGN( ++ auto modified_parquet, ++ WriteTableToBuffer(modified, kMinChunkSize, kMaxChunkSize, kRowGroupLength, ++ kEnableDictionary, ParquetDataPageVersion::V1)); ++ ++ for (int col = 0; col < base->num_columns(); col++) { ++ auto base_info = GetColumnParquetInfo(base_parquet, /*column_index=*/col); ++ auto modified_info = GetColumnParquetInfo(modified_parquet, /*column_index=*/col); ++ ++ // assert that there are 7 row groups ++ ASSERT_EQ(base_info.size(), 7); ++ ASSERT_EQ(modified_info.size(), 7); ++ ++ // the first two row groups should be identical, each part contains two row groups and ++ // the first part is not modified ++ ASSERT_EQ(base_info.at(0).page_lengths, modified_info.at(0).page_lengths); ++ ASSERT_EQ(base_info.at(1).page_lengths, modified_info.at(1).page_lengths); ++ // then there is an insertion which causes a larger "diff" somewhere in the row group ++ // and a smaller "diff" at the end of the row group because the row group length is ++ // fixed; this rule applies to the subsequent row groups as well because the values ++ // are shifted by the insertion ++ auto edit_array = edit2_->column(col); ++ for (size_t i = 2; i < modified_info.size() - 1; i++) { ++ AssertPageLengthDifferences(base_info.at(i), modified_info.at(i), ++ /*exact_number_of_equal_diffs=*/0, ++ /*exact_number_of_larger_diffs=*/1, ++ /*exact_number_of_smaller_diffs=*/1, edit_array); ++ } ++ // the last row group will simply be larger because of the insertion ++ AssertPageLengthDifferences(base_info.back(), modified_info.back(), ++ /*exact_number_of_equal_diffs=*/0, ++ /*exact_number_of_larger_diffs=*/1, ++ /*exact_number_of_smaller_diffs=*/0, edit_array); ++ } ++} ++ ++TEST_F(TestCDCMultipleRowGroups, DeleteOnce) { ++ ASSERT_OK_AND_ASSIGN(auto base, ++ ConcatAndCombine({part1_, edit1_, part2_, part3_, edit2_})); ++ ASSERT_OK_AND_ASSIGN(auto modified, ConcatAndCombine({part1_, part2_, part3_, edit2_})); ++ ASSERT_FALSE(base->Equals(*modified)); ++ ASSERT_EQ(modified->num_rows(), base->num_rows() - edit1_->num_rows()); ++ ++ ASSERT_OK_AND_ASSIGN( ++ auto base_parquet, ++ WriteTableToBuffer(base, kMinChunkSize, kMaxChunkSize, kRowGroupLength, ++ kEnableDictionary, ParquetDataPageVersion::V1)); ++ ASSERT_OK_AND_ASSIGN( ++ auto modified_parquet, ++ WriteTableToBuffer(modified, kMinChunkSize, kMaxChunkSize, kRowGroupLength, ++ kEnableDictionary, ParquetDataPageVersion::V1)); ++ ++ for (int col = 0; col < base->num_columns(); col++) { ++ auto base_info = GetColumnParquetInfo(base_parquet, /*column_index=*/col); ++ auto modified_info = GetColumnParquetInfo(modified_parquet, /*column_index=*/col); ++ ++ // assert that there are 7 row groups ++ ASSERT_EQ(base_info.size(), 7); ++ ASSERT_EQ(modified_info.size(), 7); ++ ++ // the first two row groups should be identical, each part contains two row groups and ++ // the first part is not modified ++ ASSERT_EQ(base_info.at(0).page_lengths, modified_info.at(0).page_lengths); ++ ASSERT_EQ(base_info.at(1).page_lengths, modified_info.at(1).page_lengths); ++ // because of the deletion values are shifted in the row group, we expect a smaller ++ // "diff" at the beginning of the row group and a larger "diff" at the end of the ++ // row group ++ auto edit_array = edit2_->column(col); ++ for (size_t i = 2; i < modified_info.size() - 1; i++) { ++ AssertPageLengthDifferences(base_info.at(i), modified_info.at(i), ++ /*exact_number_of_equal_diffs=*/0, ++ /*exact_number_of_larger_diffs=*/1, ++ /*exact_number_of_smaller_diffs=*/1, edit_array); ++ } ++ // the last row group will simply be smaller because of the deletion ++ AssertPageLengthDifferences(base_info.back(), modified_info.back(), ++ /*exact_number_of_equal_diffs=*/0, ++ /*exact_number_of_larger_diffs=*/0, ++ /*exact_number_of_smaller_diffs=*/1, edit_array); ++ } ++} ++ ++TEST_F(TestCDCMultipleRowGroups, UpdateOnce) { ++ ASSERT_OK_AND_ASSIGN(auto base, ++ ConcatAndCombine({part1_, edit1_, part2_, part3_, edit2_})); ++ ASSERT_OK_AND_ASSIGN(auto modified, ++ ConcatAndCombine({part1_, edit3_, part2_, part3_, edit2_})); ++ ASSERT_FALSE(base->Equals(*modified)); ++ ++ ASSERT_OK_AND_ASSIGN( ++ auto base_parquet, ++ WriteTableToBuffer(base, kMinChunkSize, kMaxChunkSize, kRowGroupLength, ++ kEnableDictionary, ParquetDataPageVersion::V1)); ++ ASSERT_OK_AND_ASSIGN( ++ auto modified_parquet, ++ WriteTableToBuffer(modified, kMinChunkSize, kMaxChunkSize, kRowGroupLength, ++ kEnableDictionary, ParquetDataPageVersion::V1)); ++ for (int col = 0; col < base->num_columns(); col++) { ++ auto base_info = GetColumnParquetInfo(base_parquet, /*column_index=*/col); ++ auto modified_info = GetColumnParquetInfo(modified_parquet, /*column_index=*/col); ++ ++ // assert that there are 7 row groups ++ ASSERT_EQ(base_info.size(), 7); ++ ASSERT_EQ(modified_info.size(), 7); ++ ++ // the first two row groups should be identical, each part contains two row groups and ++ // the first part is not modified ++ ASSERT_EQ(base_info.at(0).page_lengths, modified_info.at(0).page_lengths); ++ ASSERT_EQ(base_info.at(1).page_lengths, modified_info.at(1).page_lengths); ++ // then there is an update (without insertion or deletion so no shifting occurs) which ++ // causes a "diff" with both sides having the same number of values but different ones ++ AssertPageLengthDifferences(base_info.at(2), modified_info.at(2), ++ /*max_number_of_equal_diffs=*/1); ++ for (size_t i = 2; i < modified_info.size(); i++) { ++ // the rest of the row groups should be identical ++ ASSERT_EQ(base_info.at(i).page_lengths, modified_info.at(i).page_lengths); ++ } ++ } ++} ++ ++TEST_F(TestCDCMultipleRowGroups, Append) { ++ ASSERT_OK_AND_ASSIGN(auto base, ConcatAndCombine({part1_, edit1_, part2_, part3_})); ++ ASSERT_OK_AND_ASSIGN(auto modified, ++ ConcatAndCombine({part1_, edit1_, part2_, part3_, edit2_})); ++ ASSERT_FALSE(base->Equals(*modified)); ++ ASSERT_EQ(modified->num_rows(), base->num_rows() + edit2_->num_rows()); ++ ++ ASSERT_OK_AND_ASSIGN( ++ auto base_parquet, ++ WriteTableToBuffer(base, kMinChunkSize, kMaxChunkSize, kRowGroupLength, ++ kEnableDictionary, ParquetDataPageVersion::V1)); ++ ASSERT_OK_AND_ASSIGN( ++ auto modified_parquet, ++ WriteTableToBuffer(modified, kMinChunkSize, kMaxChunkSize, kRowGroupLength, ++ kEnableDictionary, ParquetDataPageVersion::V1)); ++ ++ for (int col = 0; col < base->num_columns(); col++) { ++ auto base_info = GetColumnParquetInfo(base_parquet, /*column_index=*/col); ++ auto modified_info = GetColumnParquetInfo(modified_parquet, /*column_index=*/col); ++ ++ // assert that there are 7 row groups ++ ASSERT_EQ(base_info.size(), 7); ++ ASSERT_EQ(modified_info.size(), 7); ++ ++ for (size_t i = 0; i < modified_info.size() - 1; i++) { ++ ASSERT_EQ(base_info.at(i).page_lengths, modified_info.at(i).page_lengths); ++ } ++ // only the last row group should have more or equal number of pages ++ auto original_page_lengths = base_info.back().page_lengths; ++ auto modified_page_lengths = modified_info.back().page_lengths; ++ ++ // the last row group should be larger or equal in size ++ ASSERT_GE(original_page_lengths.size(), modified_page_lengths.size()); ++ // all pages must be identical except for the last one which can be larger ++ for (size_t i = 0; i < original_page_lengths.size() - 1; i++) { ++ ASSERT_EQ(original_page_lengths[i], modified_page_lengths[i]); ++ } ++ ASSERT_GT(modified_page_lengths.back(), original_page_lengths.back()); ++ } ++} ++ ++} // namespace parquet::internal +diff --git a/cpp/src/parquet/properties_test.cc b/cpp/src/parquet/properties_test.cc +--- a/cpp/src/parquet/properties_test.cc ++++ b/cpp/src/parquet/properties_test.cc +@@ -111,6 +111,26 @@ TEST(TestWriterProperties, SetCodecOptions) { + ->window_bits); + } + ++TEST(TestWriterProperties, ContentDefinedChunkingSettings) { ++ WriterProperties::Builder builder; ++ std::shared_ptr props = builder.build(); ++ ++ ASSERT_FALSE(props->content_defined_chunking_enabled()); ++ auto cdc_options = props->content_defined_chunking_options(); ++ ASSERT_EQ(cdc_options.min_chunk_size, 256 * 1024); ++ ASSERT_EQ(cdc_options.max_chunk_size, 1024 * 1024); ++ ASSERT_EQ(cdc_options.norm_level, 0); ++ ++ builder.enable_content_defined_chunking(); ++ builder.content_defined_chunking_options(CdcOptions{512 * 1024, 2048 * 1024, 1}); ++ props = builder.build(); ++ ASSERT_TRUE(props->content_defined_chunking_enabled()); ++ cdc_options = props->content_defined_chunking_options(); ++ ASSERT_EQ(cdc_options.min_chunk_size, 512 * 1024); ++ ASSERT_EQ(cdc_options.max_chunk_size, 2048 * 1024); ++ ASSERT_EQ(cdc_options.norm_level, 1); ++} ++ + TEST(TestReaderProperties, GetStreamInsufficientData) { + // ARROW-6058 + std::string data = "shorter than expected"; +diff --git a/python/pyarrow/tests/parquet/test_parquet_writer.py b/python/pyarrow/tests/parquet/test_parquet_writer.py +--- a/python/pyarrow/tests/parquet/test_parquet_writer.py ++++ b/python/pyarrow/tests/parquet/test_parquet_writer.py +@@ -361,3 +361,81 @@ def test_parquet_writer_append_key_value_metadata(tempdir): + assert metadata[b'key1'] == b'1' + assert metadata[b'key2'] == b'2' + assert metadata[b'key3'] == b'3' ++ ++ ++def test_parquet_content_defined_chunking(tempdir): ++ table = pa.table({'a': range(100_000)}) ++ ++ # use PLAIN encoding because we compare the overall size of the row groups ++ # which would vary depending on the encoding making the assertions wrong ++ pq.write_table(table, tempdir / 'unchunked.parquet', ++ use_dictionary=False, ++ column_encoding="PLAIN") ++ pq.write_table(table, tempdir / 'chunked-default.parquet', ++ use_dictionary=False, ++ column_encoding="PLAIN", ++ use_content_defined_chunking=True) ++ pq.write_table(table, tempdir / 'chunked-custom.parquet', ++ use_dictionary=False, ++ column_encoding="PLAIN", ++ use_content_defined_chunking={"min_chunk_size": 32_768, ++ "max_chunk_size": 65_536}) ++ ++ # the data must be the same ++ unchunked = pq.read_table(tempdir / 'unchunked.parquet') ++ chunked_default = pq.read_table(tempdir / 'chunked-default.parquet') ++ chunked_custom = pq.read_table(tempdir / 'chunked-custom.parquet') ++ assert unchunked.equals(chunked_default) ++ assert unchunked.equals(chunked_custom) ++ ++ # number of row groups and their sizes are not affected by content defined chunking ++ unchunked_metadata = pq.read_metadata(tempdir / 'unchunked.parquet') ++ chunked_default_metadata = pq.read_metadata(tempdir / 'chunked-default.parquet') ++ chunked_custom_metadata = pq.read_metadata(tempdir / 'chunked-custom.parquet') ++ ++ assert unchunked_metadata.num_row_groups == chunked_default_metadata.num_row_groups ++ assert unchunked_metadata.num_row_groups == chunked_custom_metadata.num_row_groups ++ ++ for i in range(unchunked_metadata.num_row_groups): ++ rg_unchunked = unchunked_metadata.row_group(i) ++ rg_chunked_default = chunked_default_metadata.row_group(i) ++ rg_chunked_custom = chunked_custom_metadata.row_group(i) ++ assert rg_unchunked.num_rows == rg_chunked_default.num_rows ++ assert rg_unchunked.num_rows == rg_chunked_custom.num_rows ++ # since PageReader is not exposed we cannot inspect the page sizes ++ # so just check that the total byte size is different ++ assert rg_unchunked.total_byte_size < rg_chunked_default.total_byte_size ++ assert rg_unchunked.total_byte_size < rg_chunked_custom.total_byte_size ++ ++ ++def test_parquet_content_defined_chunking_parameters(tempdir): ++ table = pa.table({'a': range(100)}) ++ path = tempdir / 'chunked-invalid.parquet' ++ ++ # it raises OSError, not ideal but this is how parquet exceptions are handled ++ # currently ++ # the exact validation wording is not part of the proposal; assert only the ++ # error type for an invalid min/max ordering and for bad option dicts. ++ with pytest.raises(Exception): ++ cdc_options = {"min_chunk_size": 65_536, "max_chunk_size": 32_768} ++ pq.write_table(table, path, use_content_defined_chunking=cdc_options) ++ ++ invalid_option_cases = [ ++ {"min_chunk_size": 64 * 1024, "unknown_option": True}, ++ {"min_chunk_size": 64 * 1024}, ++ {"max_chunk_size": 64 * 1024}, ++ ] ++ for cdc_options in invalid_option_cases: ++ with pytest.raises(ValueError): ++ pq.write_table(table, path, use_content_defined_chunking=cdc_options) ++ ++ # using the default parametrization ++ pq.write_table(table, path, use_content_defined_chunking=True) ++ ++ # using min_chunk_size and max_chunk_size ++ cdc_options = {"min_chunk_size": 32_768, "max_chunk_size": 65_536} ++ pq.write_table(table, path, use_content_defined_chunking=cdc_options) ++ ++ # using min_chunk_size, max_chunk_size and norm_level ++ cdc_options = {"min_chunk_size": 32_768, "max_chunk_size": 65_536, "norm_level": 1} ++ pq.write_table(table, path, use_content_defined_chunking=cdc_options) diff --git a/arrow_2/tests/private/eval_tests_aug.patch b/arrow_2/tests/private/eval_tests_aug.patch new file mode 100644 index 0000000000000000000000000000000000000000..257be81a65e3d01693fcbc38c28d8e3b4abb0633 --- /dev/null +++ b/arrow_2/tests/private/eval_tests_aug.patch @@ -0,0 +1,466 @@ +diff --git a/python/pyarrow/tests/parquet/test_parquet_writer_cdc_aug.py b/python/pyarrow/tests/parquet/test_parquet_writer_cdc_aug.py +new file mode 100644 +--- /dev/null ++++ b/python/pyarrow/tests/parquet/test_parquet_writer_cdc_aug.py +@@ -0,0 +1,303 @@ ++# Licensed to the Apache Software Foundation (ASF) under one ++# or more contributor license agreements. See the NOTICE file ++# distributed with this work for additional information ++# regarding copyright ownership. The ASF licenses this file ++# to you under the Apache License, Version 2.0 (the ++# "License"); you may not use this file except in compliance ++# with the License. You may obtain a copy of the License at ++# ++# http://www.apache.org/licenses/LICENSE-2.0 ++# ++# Unless required by applicable law or agreed to in writing, ++# software distributed under the License is distributed on an ++# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY ++# KIND, either express or implied. See the License for the ++# specific language governing permissions and limitations ++# under the License. ++ ++# LoLBench augmentation suite for Apache Arrow PR-45360 (Content-Defined ++# Chunking). These F2P tests are designed to kill the surviving mutants in ++# mutations/Apache-Arrow_Issue-45750_..._PR-45360/ that the original F2P ++# (test_parquet_content_defined_chunking, test_parquet_content_defined_chunking_parameters) ++# do not fully cover. ++# ++# Public API only: pyarrow.parquet.write_table, pyarrow.parquet.read_table, ++# pyarrow.parquet.read_metadata, and pyarrow.parquet.ParquetFile. This file ++# does not reference any underscore-prefixed PyArrow submodule, any C++ ++# detail/internal namespace, or any non-exported helper. The surface gate ++# (classify_test_surface.py) checks for that. ++ ++from decimal import Decimal ++ ++import pytest ++ ++import pyarrow as pa ++import pyarrow.parquet as pq ++ ++ ++def _row_group_total_byte_size(path): ++ meta = pq.read_metadata(path) ++ return sum(meta.row_group(i).total_byte_size ++ for i in range(meta.num_row_groups)) ++ ++ ++def _stable_int_table(n_rows): ++ # Deterministic, non-repetitive payload large enough that the default ++ # 256 KiB / 1 MiB CDC window can fire multiple cuts on the int64 column. ++ # range(n_rows) at int64 is 8 * n_rows bytes; 400_000 rows ~= 3.2 MiB. ++ return pa.table({'a': pa.array(range(n_rows), type=pa.int64())}) ++ ++ ++def _mixed_physical_table(n_rows): ++ indices = pa.array( ++ [None if i % 19 == 0 else i % 8 for i in range(n_rows)], ++ type=pa.int32()) ++ dictionary = pa.array([f'dict-{j}' for j in range(8)], type=pa.string()) ++ list_values = [ ++ None if i % 17 == 0 ++ else [i, None if i % 5 == 0 else i + 1, i + 2] ++ for i in range(n_rows) ++ ] ++ fixed_values = [ ++ ((i & 0xffffffff).to_bytes(4, 'little') + ++ ((i * 17) & 0xffffffff).to_bytes(4, 'little')) ++ for i in range(n_rows) ++ ] ++ return pa.table({ ++ 'flag': pa.array([(i % 3) == 0 for i in range(n_rows)], ++ type=pa.bool_()), ++ 'nullable_i32': pa.array( ++ [None if i % 11 == 0 else i for i in range(n_rows)], ++ type=pa.int32()), ++ 'fixed8': pa.array(fixed_values, type=pa.binary(8)), ++ 'large_text': pa.array( ++ [f'large-{i:08d}-' + 'abcdefghij' * 4 ++ for i in range(n_rows)], ++ type=pa.large_string()), ++ 'amount': pa.array([Decimal(i % 100000) for i in range(n_rows)], ++ type=pa.decimal128(18, 0)), ++ 'items': pa.array(list_values, type=pa.list_(pa.int32())), ++ 'dict_text': pa.DictionaryArray.from_arrays(indices, dictionary), ++ }) ++ ++ ++def test_cdc_dict_min_chunk_size_affects_output_size(tempdir): ++ """A larger min_chunk_size must suppress fine-grained cutpoints and yield ++ a smaller total_byte_size than a tiny min_chunk_size, when max_chunk_size ++ is held constant. ++ ++ Kills surviving mutants: ++ * mutant_002 (dict path disables CDC) — both files identical ++ * mutant_003 (no hash cutpoints) — min_chunk_size has no effect; both ++ files are split identically at max ++ * mutant_004 (no page flush) — chunks computed but not flushed; both ++ files identical to CDC=False output ++ """ ++ table = _stable_int_table(400_000) ++ ++ fine_path = tempdir / 'cdc_min_fine.parquet' ++ coarse_path = tempdir / 'cdc_min_coarse.parquet' ++ ++ pq.write_table(table, fine_path, ++ use_dictionary=False, ++ column_encoding="PLAIN", ++ use_content_defined_chunking={ ++ "min_chunk_size": 4 * 1024, ++ "max_chunk_size": 64 * 1024, ++ }) ++ pq.write_table(table, coarse_path, ++ use_dictionary=False, ++ column_encoding="PLAIN", ++ use_content_defined_chunking={ ++ "min_chunk_size": 32 * 1024, ++ "max_chunk_size": 64 * 1024, ++ }) ++ ++ # Round-trip data must be identical (no CDC bug should lose rows). ++ assert pq.read_table(fine_path).equals(table) ++ assert pq.read_table(coarse_path).equals(table) ++ ++ fine_size = _row_group_total_byte_size(fine_path) ++ coarse_size = _row_group_total_byte_size(coarse_path) ++ ++ # Golden: smaller min => more hash-driven cutpoints => more pages => ++ # strictly larger reported total_byte_size. Even a 5% delta is enough ++ # to distinguish from any of the surviving mutants, which produce ++ # identical sizes for the two configs. ++ assert fine_size > coarse_size, ( ++ f"expected min_chunk_size=4KiB to produce a larger total_byte_size " ++ f"than min_chunk_size=32KiB with max=64KiB held constant; got " ++ f"fine={fine_size} coarse={coarse_size}" ++ ) ++ ++ ++def test_cdc_dict_norm_level_affects_output_size(tempdir): ++ """norm_level must measurably shift the chunk-size distribution. A ++ positive norm_level widens the hash mask, raising the probability of a ++ cutpoint and shrinking the average chunk -> more pages -> larger ++ total_byte_size than norm_level=0. ++ ++ Kills surviving mutants: ++ * mutant_002 (dict path disables CDC) — both files identical to CDC=off ++ * mutant_003 (no hash cutpoints) — norm_level controls only the hash ++ mask; without recorded matches it has no effect ++ * mutant_004 (no page flush) — chunks computed but not flushed; both ++ files identical to CDC=off output ++ """ ++ table = _stable_int_table(400_000) ++ ++ norm0_path = tempdir / 'cdc_norm0.parquet' ++ norm2_path = tempdir / 'cdc_norm2.parquet' ++ ++ pq.write_table(table, norm0_path, ++ use_dictionary=False, ++ column_encoding="PLAIN", ++ use_content_defined_chunking={ ++ "min_chunk_size": 8 * 1024, ++ "max_chunk_size": 64 * 1024, ++ "norm_level": 0, ++ }) ++ pq.write_table(table, norm2_path, ++ use_dictionary=False, ++ column_encoding="PLAIN", ++ use_content_defined_chunking={ ++ "min_chunk_size": 8 * 1024, ++ "max_chunk_size": 64 * 1024, ++ "norm_level": 2, ++ }) ++ ++ assert pq.read_table(norm0_path).equals(table) ++ assert pq.read_table(norm2_path).equals(table) ++ ++ norm0_size = _row_group_total_byte_size(norm0_path) ++ norm2_size = _row_group_total_byte_size(norm2_path) ++ ++ # Under the golden patch, norm_level=2 produces measurably more cuts ++ # (smaller average chunks) and therefore a larger total_byte_size. ++ assert norm2_size > norm0_size, ( ++ f"expected norm_level=2 to produce a larger total_byte_size than " ++ f"norm_level=0 with identical min/max; got norm0={norm0_size} " ++ f"norm2={norm2_size}" ++ ) ++ ++ ++def test_cdc_true_changes_layout_vs_false_on_string_column(tempdir): ++ """CDC=True must change the on-disk layout (relative to CDC=False) for a ++ string column large enough to span multiple default chunks. This both ++ extends coverage to the string-typed branch of the chunker dispatch and ++ re-kills mutant_001 / mutant_004 through a different data shape than the ++ existing test_parquet_content_defined_chunking (which uses int64 only). ++ ++ Kills surviving mutants: ++ * mutant_001 (True silently disables CDC) — CDC=True file is byte- ++ identical to CDC=False file ++ * mutant_004 (no page flush) — CDC=True file has the same row-group ++ layout as CDC=False ++ """ ++ # ~5 MiB of payload across 50_000 rows of 100-byte strings; comfortably ++ # above the default 256 KiB / 1 MiB CDC window so multiple cuts fire. ++ values = [(f"row-{i:08d}-" + "x" * 80) for i in range(50_000)] ++ table = pa.table({'s': pa.array(values, type=pa.string())}) ++ ++ cdc_off_path = tempdir / 'cdc_off_string.parquet' ++ cdc_on_path = tempdir / 'cdc_on_string.parquet' ++ ++ pq.write_table(table, cdc_off_path, ++ use_dictionary=False, ++ column_encoding="PLAIN", ++ use_content_defined_chunking=False) ++ pq.write_table(table, cdc_on_path, ++ use_dictionary=False, ++ column_encoding="PLAIN", ++ use_content_defined_chunking=True) ++ ++ # Data must round-trip identically under both settings. ++ assert pq.read_table(cdc_off_path).equals(table) ++ assert pq.read_table(cdc_on_path).equals(table) ++ ++ off_size = _row_group_total_byte_size(cdc_off_path) ++ on_size = _row_group_total_byte_size(cdc_on_path) ++ ++ # CDC=True must visibly change the page layout for a multi-chunk string ++ # column. Existing F2P uses int64; this catches mutants that only break ++ # the chunker dispatch on non-numeric types or that disable the True ++ # branch silently. ++ assert on_size > off_size, ( ++ f"expected use_content_defined_chunking=True to increase the " ++ f"reported total_byte_size on a multi-chunk string column; got " ++ f"off={off_size} on={on_size}" ++ ) ++ ++ ++def test_cdc_mixed_physical_layouts_roundtrip_and_change_layout(tempdir): ++ """CDC must work through public writes for the physical layouts Arrow ++ commonly maps to Parquet pages: booleans, nullable fixed-width values, ++ fixed-size binary, large strings, decimals, nested list values, and ++ dictionary arrays. This reaches chunker branches not covered by the ++ original int64-only F2P while keeping the oracle at the public Parquet ++ read/write surface. ++ """ ++ table = _mixed_physical_table(50_000) ++ ++ cdc_off_path = tempdir / 'cdc_off_mixed.parquet' ++ cdc_on_path = tempdir / 'cdc_on_mixed.parquet' ++ ++ pq.write_table(table, cdc_off_path, ++ row_group_size=table.num_rows, ++ use_content_defined_chunking=False) ++ pq.write_table(table, cdc_on_path, ++ row_group_size=table.num_rows, ++ use_content_defined_chunking={ ++ "min_chunk_size": 4 * 1024, ++ "max_chunk_size": 32 * 1024, ++ "norm_level": 1, ++ }) ++ ++ got = pq.read_table(cdc_on_path) ++ assert got.num_rows == table.num_rows ++ assert got.column('nullable_i32').to_pylist() == ( ++ table.column('nullable_i32').to_pylist()) ++ assert got.column('items').to_pylist() == table.column('items').to_pylist() ++ ++ off_size = _row_group_total_byte_size(cdc_off_path) ++ on_size = _row_group_total_byte_size(cdc_on_path) ++ assert on_size > off_size, ( ++ f"expected CDC to change the metadata-visible page layout for " ++ f"mixed physical columns; got off={off_size} on={on_size}" ++ ) ++ ++ ++def test_cdc_true_determinism_across_repeated_writes(tempdir): ++ """Two writes of the same table with use_content_defined_chunking=True ++ must produce byte-identical files. The CDC chunker is deterministic for ++ a given input (rolling hash + fixed mask), so the file size, row-group ++ count, and per-row-group total_byte_size must all match. ++ ++ This is a sanity check that reinforces F2P-cov: it exercises the CDC ++ code path twice in the same test and confirms the deterministic-rollback ++ property called out in the requirement doc ("ensuring that identical ++ data segments are consistently chunked in the same manner"). ++ """ ++ table = _stable_int_table(200_000) ++ ++ a_path = tempdir / 'cdc_det_a.parquet' ++ b_path = tempdir / 'cdc_det_b.parquet' ++ ++ for p in (a_path, b_path): ++ pq.write_table(table, p, ++ use_dictionary=False, ++ column_encoding="PLAIN", ++ use_content_defined_chunking=True) ++ ++ a_meta = pq.read_metadata(a_path) ++ b_meta = pq.read_metadata(b_path) ++ ++ assert a_meta.num_row_groups == b_meta.num_row_groups ++ a_sizes = [a_meta.row_group(i).total_byte_size ++ for i in range(a_meta.num_row_groups)] ++ b_sizes = [b_meta.row_group(i).total_byte_size ++ for i in range(b_meta.num_row_groups)] ++ assert a_sizes == b_sizes, ( ++ f"CDC must be deterministic across repeated writes of the same " ++ f"data; got {a_sizes} vs {b_sizes}" ++ ) +diff --git a/python/pyarrow/tests/parquet/test_parquet_writer_stability_aug.py b/python/pyarrow/tests/parquet/test_parquet_writer_stability_aug.py +new file mode 100644 +--- /dev/null ++++ b/python/pyarrow/tests/parquet/test_parquet_writer_stability_aug.py +@@ -0,0 +1,153 @@ ++# Licensed to the Apache Software Foundation (ASF) under one ++# or more contributor license agreements. See the NOTICE file ++# distributed with this work for additional information ++# regarding copyright ownership. The ASF licenses this file ++# to you under the Apache License, Version 2.0 (the ++# "License"); you may not use this file except in compliance ++# with the License. You may obtain a copy of the License at ++# ++# http://www.apache.org/licenses/LICENSE-2.0 ++# ++# Unless required by applicable law or agreed to in writing, ++# software distributed under the License is distributed on an ++# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY ++# KIND, either express or implied. See the License for the ++# specific language governing permissions and limitations ++# under the License. ++ ++# LoLBench augmentation suite for Apache Arrow PR-45360 — P2P (stability) ++# tests. ++# ++# Scope: behaviors the requirement doc promises remain unchanged when the ++# new ``use_content_defined_chunking`` argument is not used. Each test ++# below uses ONLY pre-PR public API (no reference to ++# ``use_content_defined_chunking`` in any form) so it must pass at ++# ``base_commit`` as well as at ``base_commit + solution.patch`` and under ++# every surviving mutant — those mutants only change CDC-related code paths. ++# ++# Public API only: pyarrow.parquet.{write_table, read_table, read_metadata, ++# ParquetWriter, ParquetFile}. No internal symbols referenced. ++ ++import pyarrow as pa ++import pyarrow.parquet as pq ++ ++ ++def _basic_int_table(n_rows=1000): ++ return pa.table({'a': pa.array(range(n_rows), type=pa.int64()), ++ 'b': pa.array([float(i) for i in range(n_rows)], ++ type=pa.float64())}) ++ ++ ++def test_writer_default_no_cdc_arg_roundtrip(tempdir): ++ """Calling write_table with no CDC-related argument must round-trip the ++ data identically, with the schema preserved. This pins the ++ backwards-compat clause that the new optional parameter is purely ++ additive.""" ++ table = _basic_int_table(2000) ++ path = tempdir / 'default_roundtrip.parquet' ++ pq.write_table(table, path) ++ ++ got = pq.read_table(path) ++ assert got.equals(table) ++ assert got.schema.equals(table.schema) ++ ++ ++def test_writer_compression_snappy_roundtrip_unchanged(tempdir): ++ """The pre-existing ``compression`` argument must continue to control ++ on-disk compression independently of any CDC machinery.""" ++ table = _basic_int_table(2000) ++ path = tempdir / 'snappy.parquet' ++ pq.write_table(table, path, compression='snappy') ++ ++ got = pq.read_table(path) ++ assert got.equals(table) ++ # Metadata must surface the requested compression. ++ meta = pq.read_metadata(path) ++ rg = meta.row_group(0) ++ for col in range(rg.num_columns): ++ assert rg.column(col).compression.lower() == 'snappy' ++ ++ ++# NOTE: a column_encoding-honoured P2P probe was attempted but dropped ++# from the augmented suite. Probing with DELTA_BINARY_PACKED (the only ++# non-default option that could differentiate against use_dictionary=False ++# defaults of PLAIN) interacts with the PR's CDC initialization path and ++# surfaces an unrelated OSError at write_table call time at this base_commit. ++# Probing with PLAIN cannot be differentiated from the no-dict default, ++# which collapses the oracle. Rather than ship a flaky P2P we omit this ++# clause from the augmented suite; the no_modification clause for ++# 'column_encoding' is not pinned by an augmented test. Six other P2P ++# (default writer, compression, data_page_size, ParquetWriter context ++# manager, read_metadata, ParquetFile.read_row_group) cover the remaining ++# no-modification surface. ++ ++ ++def test_writer_data_page_size_unchanged(tempdir): ++ """Pre-existing ``data_page_size`` argument: a smaller data-page size ++ must produce a measurably larger reported total_byte_size than a larger ++ one, with no CDC argument involved.""" ++ table = pa.table({'a': pa.array(range(100_000), type=pa.int64())}) ++ small_path = tempdir / 'page_small.parquet' ++ large_path = tempdir / 'page_large.parquet' ++ ++ pq.write_table(table, small_path, ++ use_dictionary=False, ++ column_encoding='PLAIN', ++ data_page_size=8 * 1024) ++ pq.write_table(table, large_path, ++ use_dictionary=False, ++ column_encoding='PLAIN', ++ data_page_size=512 * 1024) ++ ++ small_meta = pq.read_metadata(small_path) ++ large_meta = pq.read_metadata(large_path) ++ small_total = sum(small_meta.row_group(i).total_byte_size ++ for i in range(small_meta.num_row_groups)) ++ large_total = sum(large_meta.row_group(i).total_byte_size ++ for i in range(large_meta.num_row_groups)) ++ assert small_total > large_total, ( ++ f"data_page_size=8KiB should produce a larger reported total than " ++ f"512KiB; got small={small_total} large={large_total}" ++ ) ++ ++ ++def test_parquet_writer_context_manager_default_path(tempdir): ++ """ParquetWriter usable as a context manager with no CDC argument; the ++ pre-PR contract (constructor, write_table, close-on-exit) must still ++ hold.""" ++ table = _basic_int_table(1500) ++ path = tempdir / 'context_writer.parquet' ++ with pq.ParquetWriter(str(path), table.schema) as writer: ++ writer.write_table(table) ++ got = pq.read_table(path) ++ assert got.equals(table) ++ ++ ++def test_read_metadata_for_default_file_unchanged_shape(tempdir): ++ """``read_metadata`` must report the expected row-group count and schema ++ for a vanilla file (no CDC argument). Pins the read-side ++ no-modification promise: nothing about default-written files moves.""" ++ table = _basic_int_table(5000) ++ path = tempdir / 'default_meta.parquet' ++ pq.write_table(table, path) ++ ++ meta = pq.read_metadata(path) ++ assert meta.num_rows == 5000 ++ assert meta.num_columns == 2 ++ # Schema columns by name match input schema. ++ names = [meta.schema.column(i).name for i in range(meta.num_columns)] ++ assert names == ['a', 'b'] ++ ++ ++def test_parquet_file_read_row_group_default_unchanged(tempdir): ++ """``ParquetFile.read_row_group`` must work on a default-written file ++ and return data that ``equals`` the original.""" ++ table = _basic_int_table(3000) ++ path = tempdir / 'default_rg.parquet' ++ pq.write_table(table, path, row_group_size=1000) ++ ++ pf = pq.ParquetFile(path) ++ assert pf.num_row_groups == 3 ++ chunks = [pf.read_row_group(i) for i in range(pf.num_row_groups)] ++ full = pa.concat_tables(chunks) ++ assert full.equals(table) diff --git a/arrow_2/tests/private/f2p.txt b/arrow_2/tests/private/f2p.txt new file mode 100644 index 0000000000000000000000000000000000000000..4ee14ce3107edbe2efb6abb4362dde4500a23e32 --- /dev/null +++ b/arrow_2/tests/private/f2p.txt @@ -0,0 +1,2 @@ +python/pyarrow/tests/parquet/test_parquet_writer.py::test_parquet_content_defined_chunking +python/pyarrow/tests/parquet/test_parquet_writer.py::test_parquet_content_defined_chunking_parameters diff --git a/arrow_2/tests/private/f2p_aug.txt b/arrow_2/tests/private/f2p_aug.txt new file mode 100644 index 0000000000000000000000000000000000000000..cb973c8f0ed8718651cd6b3f42fcf03592e625c9 --- /dev/null +++ b/arrow_2/tests/private/f2p_aug.txt @@ -0,0 +1,5 @@ +python/pyarrow/tests/parquet/test_parquet_writer_cdc_aug.py::test_cdc_dict_min_chunk_size_affects_output_size +python/pyarrow/tests/parquet/test_parquet_writer_cdc_aug.py::test_cdc_dict_norm_level_affects_output_size +python/pyarrow/tests/parquet/test_parquet_writer_cdc_aug.py::test_cdc_true_changes_layout_vs_false_on_string_column +python/pyarrow/tests/parquet/test_parquet_writer_cdc_aug.py::test_cdc_mixed_physical_layouts_roundtrip_and_change_layout +python/pyarrow/tests/parquet/test_parquet_writer_cdc_aug.py::test_cdc_true_determinism_across_repeated_writes diff --git a/arrow_2/tests/private/p2p.txt b/arrow_2/tests/private/p2p.txt new file mode 100644 index 0000000000000000000000000000000000000000..6a0c57363aed669be60ee223d3d63662a584e94b --- /dev/null +++ b/arrow_2/tests/private/p2p.txt @@ -0,0 +1,44 @@ +python/pyarrow/tests/parquet/test_parquet_writer.py::test_parquet_incremental_file_build +python/pyarrow/tests/parquet/test_parquet_writer.py::test_validate_schema_write_table +python/pyarrow/tests/parquet/test_parquet_writer.py::test_parquet_invalid_writer +python/pyarrow/tests/parquet/test_parquet_writer.py::test_parquet_writer_context_obj +python/pyarrow/tests/parquet/test_parquet_writer.py::test_parquet_writer_context_obj_with_exception +python/pyarrow/tests/parquet/test_parquet_writer.py::test_parquet_writer_write_wrappers +python/pyarrow/tests/parquet/test_parquet_writer.py::test_parquet_writer_chunk_size +python/pyarrow/tests/parquet/test_parquet_writer.py::test_parquet_writer_filesystem_local +python/pyarrow/tests/parquet/test_parquet_writer.py::test_parquet_writer_filesystem_buffer_raises +python/pyarrow/tests/parquet/test_parquet_writer.py::test_parquet_writer_store_schema +python/pyarrow/tests/parquet/test_parquet_writer.py::test_parquet_writer_append_key_value_metadata +python/pyarrow/tests/parquet/test_metadata.py::test_parquet_metadata_lifetime +python/pyarrow/tests/parquet/test_metadata.py::test_statistics_convert_logical_types +python/pyarrow/tests/parquet/test_metadata.py::test_field_id_metadata +python/pyarrow/tests/parquet/test_metadata.py::test_parquet_metadata_empty_to_dict +python/pyarrow/tests/parquet/test_metadata.py::test_metadata_equals +python/pyarrow/tests/parquet/test_metadata.py::test_write_metadata +python/pyarrow/tests/parquet/test_basic.py::test_fspath +python/pyarrow/tests/parquet/test_basic.py::test_read_non_existing_file +python/pyarrow/tests/parquet/test_basic.py::test_file_error_python_exception +python/pyarrow/tests/parquet/test_basic.py::test_parquet_read_from_buffer +python/pyarrow/tests/parquet/test_basic.py::test_read_non_existent_file +python/pyarrow/tests/parquet/test_basic.py::test_parquet_compression_roundtrip +python/pyarrow/tests/parquet/test_basic.py::test_empty_row_groups +python/pyarrow/tests/parquet/test_parquet_file.py::test_parquet_file_pass_directory_instead_of_file +python/pyarrow/tests/parquet/test_parquet_file.py::test_read_column_invalid_index +python/pyarrow/tests/parquet/test_parquet_file.py::test_parquet_file_explicitly_closed +python/pyarrow/tests/parquet/test_metadata.py::test_parquet_metadata_api +python/pyarrow/tests/parquet/test_metadata.py::test_parquet_column_statistics_api +python/pyarrow/tests/parquet/test_metadata.py::test_parquet_raise_on_unset_statistics +python/pyarrow/tests/parquet/test_metadata.py::test_parquet_write_disable_statistics +python/pyarrow/tests/parquet/test_metadata.py::test_parquet_sorting_column +python/pyarrow/tests/parquet/test_metadata.py::test_parquet_sorting_column_nested +python/pyarrow/tests/parquet/test_metadata.py::test_parquet_file_sorting_columns +python/pyarrow/tests/parquet/test_metadata.py::test_parquet_file_page_index +python/pyarrow/tests/parquet/test_metadata.py::test_multi_dataset_metadata +python/pyarrow/tests/parquet/test_metadata.py::test_metadata_hashing +python/pyarrow/tests/parquet/test_metadata.py::test_table_large_metadata +python/pyarrow/tests/parquet/test_metadata.py::test_compare_schemas +python/pyarrow/tests/parquet/test_metadata.py::test_read_schema +python/pyarrow/tests/parquet/test_metadata.py::test_metadata_schema_filesystem +python/pyarrow/tests/parquet/test_metadata.py::test_metadata_append_row_groups_diff +python/pyarrow/tests/parquet/test_basic.py::test_set_data_page_size +python/pyarrow/tests/parquet/test_basic.py::test_chunked_table_write diff --git a/arrow_2/tests/private/p2p_aug.txt b/arrow_2/tests/private/p2p_aug.txt new file mode 100644 index 0000000000000000000000000000000000000000..7542771ffb912bb0b8aede95b39c6391e342df82 --- /dev/null +++ b/arrow_2/tests/private/p2p_aug.txt @@ -0,0 +1,6 @@ +python/pyarrow/tests/parquet/test_parquet_writer_stability_aug.py::test_writer_default_no_cdc_arg_roundtrip +python/pyarrow/tests/parquet/test_parquet_writer_stability_aug.py::test_writer_compression_snappy_roundtrip_unchanged +python/pyarrow/tests/parquet/test_parquet_writer_stability_aug.py::test_writer_data_page_size_unchanged +python/pyarrow/tests/parquet/test_parquet_writer_stability_aug.py::test_parquet_writer_context_manager_default_path +python/pyarrow/tests/parquet/test_parquet_writer_stability_aug.py::test_read_metadata_for_default_file_unchanged_shape +python/pyarrow/tests/parquet/test_parquet_writer_stability_aug.py::test_parquet_file_read_row_group_default_unchanged diff --git a/arrow_2/tests/private/run_tests.sh b/arrow_2/tests/private/run_tests.sh new file mode 100644 index 0000000000000000000000000000000000000000..44fa380af23cc484d078eff2890b66960399dd3a --- /dev/null +++ b/arrow_2/tests/private/run_tests.sh @@ -0,0 +1,312 @@ +#!/usr/bin/env bash +# LoLBench runner for Apache-Arrow PR-45360. +# +# The agent does NOT execute code inside this container. The evaluator +# runs the container after the agent submits a solution.patch; the +# container applies the patch, builds, runs the hidden F2P/P2P selection, +# and writes a sanitized report. Because the container is only ever run +# by a trusted evaluator, every step runs as root — no agent UID, no +# runuser, no chown gymnastics. +# +# Eval contract (default mode): +# docker run --rm \ +# -v $(pwd)/solution.patch:/in/solution.patch:ro \ +# -v $(pwd)/out:/out \ +# lolbench/apache-arrow-pr-45360:1 +# → writes /out/agent_report.json (sanitized). +# +# Validation modes (used by the benchmark builders): +# LOLBENCH_MODE=validate_pre # F2P FAIL, P2P PASS +# LOLBENCH_MODE=validate_post # all PASS +# +set -uo pipefail + +PRIV=/opt/lolbench/private +WS=/workspace +ARROW=$WS/arrow +BUILD=$WS/build +MODE=${LOLBENCH_MODE:-eval} +SUITE=${LOLBENCH_SUITE:-orig} + +case "$SUITE" in + orig|aug|union) ;; + *) echo "[run_tests] FATAL: unknown LOLBENCH_SUITE=$SUITE" >&2; exit 2 ;; +esac + +# Detect augmented sidecar; if absent, aug/union degrade to orig with a warning. +HAS_AUG=0 +if [ -f "$PRIV/eval_tests_aug.patch" ] \ + && [ -f "$PRIV/f2p_aug.txt" ] \ + && [ -f "$PRIV/p2p_aug.txt" ]; then + HAS_AUG=1 +fi +if [ "$SUITE" != "orig" ] && [ "$HAS_AUG" -eq 0 ]; then + echo "[run_tests] WARN: LOLBENCH_SUITE=$SUITE but no sidecar shipped; falling back to orig" >&2 + SUITE=orig +fi + +log() { echo "[run_tests $MODE/$SUITE] $*" >&2; } +die() { log "FATAL: $*"; emit_error harness_error false skipped; exit 0; } + +# Pre-declare so emit_error can reference even before mapfile runs. +FAIL_TO_PASS=() +PASS_TO_PASS=() + +# emit_error +emit_error() { + local cat=$1 applied=$2 build_status=$3 + # `${#arr[@]:-0}` is a bash parse error (you cannot combine the `#` + # length operator with the `:-` default fallback). The pre-declaration + # at the top of the script guarantees the arrays exist as empty before + # `mapfile` populates them, so plain `${#arr[@]}` is safe and returns 0 + # for an unpopulated array. + local f2p_n=${#FAIL_TO_PASS[@]} + local p2p_n=${#PASS_TO_PASS[@]} + python3 - "$cat" "$applied" "$build_status" "$f2p_n" "$p2p_n" <<'EOF' >/out/agent_report.json +import json, sys +cat, applied_s, build_s, f2p_n, p2p_n = sys.argv[1:6] +applied = applied_s.lower() == "true" +print(json.dumps({ + "instance_id": "Apache-Arrow_Issue-45750_PR-45360", + "applied": applied, + "build": {"status": build_s}, + "f2p": {"passed":0,"failed":0,"errored":int(f2p_n),"skipped":0,"total":int(f2p_n)}, + "p2p": {"passed":0,"failed":0,"errored":int(p2p_n),"skipped":0,"total":int(p2p_n)}, + "resolved": False, + "error_categories": [cat] +}, indent=2)) +EOF +} + +mapfile -t FAIL_TO_PASS_ORIG < <(grep -v '^\s*$' "$PRIV/f2p.txt") +mapfile -t PASS_TO_PASS_ORIG < <(grep -v '^\s*$' "$PRIV/p2p.txt") +FAIL_TO_PASS_AUG=() +PASS_TO_PASS_AUG=() +if [ "$HAS_AUG" -eq 1 ]; then + mapfile -t FAIL_TO_PASS_AUG < <(grep -v '^\s*$' "$PRIV/f2p_aug.txt") + mapfile -t PASS_TO_PASS_AUG < <(grep -v '^\s*$' "$PRIV/p2p_aug.txt") +fi + +# Sanity-check: spec and selector files must agree. +python3 - "$PRIV/spec.json" "$PRIV/f2p.txt" "$PRIV/p2p.txt" \ + "$PRIV/f2p_aug.txt" "$PRIV/p2p_aug.txt" "$HAS_AUG" \ + <<'EOF' || die "spec/selector mismatch" +import json, os, sys +spec_path, f2p, p2p, f2p_aug, p2p_aug, has_aug = sys.argv[1:7] +spec = json.load(open(spec_path)) +def ids(p): return [l.strip() for l in open(p) if l.strip()] +ok = spec["fail_to_pass"] == ids(f2p) and spec["pass_to_pass"] == ids(p2p) +if has_aug == "1": + aug = spec.get("augmented", {}) + ok = ok and aug.get("fail_to_pass") == ids(f2p_aug) \ + and aug.get("pass_to_pass") == ids(p2p_aug) +sys.exit(0 if ok else 1) +EOF + +case "$SUITE" in + orig) + FAIL_TO_PASS=("${FAIL_TO_PASS_ORIG[@]}") + PASS_TO_PASS=("${PASS_TO_PASS_ORIG[@]}") + ;; + aug) + FAIL_TO_PASS=("${FAIL_TO_PASS_AUG[@]}") + PASS_TO_PASS=("${PASS_TO_PASS_AUG[@]}") + ;; + union) + FAIL_TO_PASS=("${FAIL_TO_PASS_ORIG[@]}" "${FAIL_TO_PASS_AUG[@]}") + PASS_TO_PASS=("${PASS_TO_PASS_ORIG[@]}" "${PASS_TO_PASS_AUG[@]}") + ;; +esac + +# ---- Pick source-side patch by mode ---------------------------------- +SRC_PATCH="" +case "$MODE" in + validate_pre) + SRC_PATCH="" ;; + validate_post) + if [ -f /solution/solution.patch ]; then + SRC_PATCH=/solution/solution.patch + else + SRC_PATCH="$PRIV/solution.patch" + fi ;; + eval) + if [ ! -f /in/solution.patch ]; then + log "no /in/solution.patch mounted" + emit_error missing_solution_patch false skipped + exit 0 + fi + AGENT_PATCH=/tmp/lolbench_agent_patch.diff + cp /in/solution.patch "$AGENT_PATCH" + chmod 0600 "$AGENT_PATCH" + SRC_PATCH="$AGENT_PATCH" ;; + *) + die "unknown LOLBENCH_MODE=$MODE" ;; +esac + +# ---- Reset workspace + apply patches --------------------------------- +cd "$ARROW" +git config --global --add safe.directory "$ARROW" +git reset --hard >/dev/null 2>&1 +git clean -fdx -e build >/dev/null 2>&1 + +if [ -n "$SRC_PATCH" ]; then + if ! git apply --check "$SRC_PATCH" 2>/tmp/apply.err; then + log "source patch did not apply cleanly:" + cat /tmp/apply.err >&2 + emit_error patch_apply_failure false skipped + exit 0 + fi + git apply "$SRC_PATCH" + # LoLBench eval-patch-collision guard (re-verify remediation): if the agent patch touched files the + # eval test patches own (test fixtures the agent must not modify), restore + # those paths (both sides of every diff/rename) to the base state so + # eval_tests(.aug).patch always applies. Agent source changes are preserved. + for _lb_ep in "$PRIV/eval_helpers.patch" "$PRIV/eval_tests.patch" "$PRIV/eval_tests_aug.patch"; do + [ -f "$_lb_ep" ] || continue + { sed -n 's|^diff --git a/\(.*\) b/\(.*\)$|\1\n\2|p' "$_lb_ep" + sed -n 's|^rename from \(.*\)$|\1|p' "$_lb_ep" + sed -n 's|^rename to \(.*\)$|\1|p' "$_lb_ep"; } | sort -u | while read -r _lb_f; do + [ -n "$_lb_f" ] || continue + git checkout HEAD -- "$_lb_f" >/dev/null 2>&1 || rm -f "$_lb_f" >/dev/null 2>&1 || true + done + done +fi + +if ! git apply --check "$PRIV/eval_tests.patch" 2>/tmp/apply.err; then + log "eval_tests.patch did not apply cleanly on top of source patch:" + cat /tmp/apply.err >&2 + emit_error eval_patch_apply_failure true skipped + exit 0 +fi +git apply "$PRIV/eval_tests.patch" + +# Sidecar test patch — only applied when the suite needs the augmented tests. +# orig mode skips this entirely, preserving the byte-identical pre-augmentation +# working tree. +if [ "$HAS_AUG" -eq 1 ] && [ "$SUITE" != "orig" ]; then + if ! git apply --check "$PRIV/eval_tests_aug.patch" 2>/tmp/apply.err; then + log "eval_tests_aug.patch did not apply cleanly on top of eval_tests.patch:" + cat /tmp/apply.err >&2 + emit_error eval_aug_patch_apply_failure true skipped + exit 0 + fi + git apply "$PRIV/eval_tests_aug.patch" +fi + +# ---- Build ----------------------------------------------------------- +BUILD_LOG=$WS/.build.log +F2P_LOG=$WS/.f2p.log +P2P_LOG=$WS/.p2p.log +: >"$BUILD_LOG" >"$F2P_LOG" >"$P2P_LOG" + +bash -lc ' +set -e +source /opt/conda/etc/profile.d/conda.sh && conda activate base +export ARROW_HOME=/opt/conda PARQUET_HOME=/opt/conda CMAKE_PREFIX_PATH=/opt/conda LD_LIBRARY_PATH=/opt/conda/lib +# Runtime rebuild after applying solution.patch: +# * ninja -j4 install: incremental rebuild of C++ Arrow/Parquet; OK at -j4 +# because only the source-patch hunks regenerate (a handful of objects). +# * pip install -e: regenerates pyarrow Cython bindings. PYARROW_PARALLEL=1 +# (serial) because the Cython-generated lib.cpp is ~340k LOC and even +# a single cc1plus invocation peaks at multi-GB resident memory; with +# 2 concurrent workers under the 7g container ceiling we still hit +# "fatal error: Killed signal terminated program cc1plus". Serial +# compile is ~6-8 min vs OOM; we trade wall time for reliability. +cd /workspace/build && ninja -j4 install +cd /workspace/arrow/python && PYARROW_WITH_PARQUET=1 PYARROW_PARALLEL=1 PYARROW_CMAKE_GENERATOR=Ninja \ + pip install -e . --no-build-isolation +' >"$BUILD_LOG" 2>&1 +build_status=$? + +if [ "$build_status" -ne 0 ]; then + log "build failed (rc=$build_status)" + emit_error build_failure true failed + exit 0 +fi + +# ---- Run tests ------------------------------------------------------- +# Persist the effective selectors so the parser below operates on exactly +# the set $SUITE expanded to (orig | aug | union), not on the raw on-disk +# f2p.txt / p2p.txt. +F2P_EFFECTIVE=$WS/.f2p_effective.txt +P2P_EFFECTIVE=$WS/.p2p_effective.txt +printf '%s\n' "${FAIL_TO_PASS[@]}" >"$F2P_EFFECTIVE" +printf '%s\n' "${PASS_TO_PASS[@]}" >"$P2P_EFFECTIVE" + +F2P_ARGS=$(printf ' %q' "${FAIL_TO_PASS[@]}") +P2P_ARGS=$(printf ' %q' "${PASS_TO_PASS[@]}") + +bash -lc " +source /opt/conda/etc/profile.d/conda.sh && conda activate base +cd /workspace/arrow +pytest -p no:cacheprovider --enable-large_memory --enable-pandas -v $F2P_ARGS +" >"$F2P_LOG" 2>&1 || true + +bash -lc " +source /opt/conda/etc/profile.d/conda.sh && conda activate base +cd /workspace/arrow +pytest -p no:cacheprovider --enable-large_memory --enable-pandas -v $P2P_ARGS +" >"$P2P_LOG" 2>&1 || true + +# ---- Parse + emit reports -------------------------------------------- +python3 - "$F2P_LOG" "$P2P_LOG" "$F2P_EFFECTIVE" "$P2P_EFFECTIVE" "$MODE" "$SUITE" "$HAS_AUG" <<'PYEOF' +import json, re, sys +f2p_log, p2p_log, f2p_file, p2p_file, mode, suite, has_aug = sys.argv[1:8] +def ids(p): return [x.strip() for x in open(p) if x.strip()] +f2p_ids = ids(f2p_file); p2p_ids = ids(p2p_file) + +def parse(log_path, ids): + """Aggregate per-variant pytest results into one verdict per logical test id. + + Strict aggregation (Codex M1, no-skipped-tests rule): every parametrized + variant of a selected test must actually run AND pass. Any SKIPPED + variant downgrades the logical test to SKIPPED, never to PASSED. + + Order of precedence (worst → best, first match wins): + FAILED – any variant FAILED + ERROR – any variant ERROR + SKIPPED – any variant SKIPPED (← was previously masked by PASSED) + PASSED – every variant PASSED + ERROR – no variant matched the regex at all (test never ran) + """ + text = open(log_path, errors='replace').read() + out = {"PASSED": [], "FAILED": [], "ERROR": [], "SKIPPED": []} + for tid in ids: + pat = re.escape(tid) + r"(?:\[[^\]]*\])?\s+(PASSED|FAILED|ERROR|SKIPPED)" + matches = re.findall(pat, text) + if not matches: + out["ERROR"].append(tid) + continue + if any(m == "FAILED" for m in matches): + out["FAILED"].append(tid) + elif any(m == "ERROR" for m in matches): + out["ERROR"].append(tid) + elif any(m == "SKIPPED" for m in matches): + out["SKIPPED"].append(tid) + else: # all variants PASSED + out["PASSED"].append(tid) + return out + +f2p = parse(f2p_log, f2p_ids) +p2p = parse(p2p_log, p2p_ids) +resolved = (len(f2p["PASSED"]) == len(f2p_ids) + and len(p2p["PASSED"]) == len(p2p_ids)) + +grader = {"instance_id":"Apache-Arrow_Issue-45750_PR-45360","mode":mode,"suite":suite, + "augmentation_available": has_aug == "1", + "applied":True, + "build":{"status":"ok"},"f2p":f2p,"p2p":p2p,"resolved":resolved} +def cnts(d, ids): + return {"passed":len(d["PASSED"]),"failed":len(d["FAILED"]),"errored":len(d["ERROR"]),"skipped":len(d["SKIPPED"]),"total":len(ids)} +agent = {"instance_id":"Apache-Arrow_Issue-45750_PR-45360", + "suite": suite, + "augmentation_available": has_aug == "1", + "applied":True, + "build":{"status":"ok"}, + "f2p":cnts(f2p, f2p_ids), + "p2p":cnts(p2p, p2p_ids), + "resolved":resolved,"error_categories":[]} +json.dump(grader, open("/out/grader_report.json","w"), indent=2) +json.dump(agent, open("/out/agent_report.json","w"), indent=2) +print(json.dumps(grader, indent=2)) +PYEOF diff --git a/arrow_2/tests/private/spec.json b/arrow_2/tests/private/spec.json new file mode 100644 index 0000000000000000000000000000000000000000..3b97e621878ff9989de47ddd6c7f8a6ef404bef5 --- /dev/null +++ b/arrow_2/tests/private/spec.json @@ -0,0 +1,929 @@ +{ + "instance_id": "Apache-Arrow_Issue-45750_PR-45360", + "repo": "apache/arrow", + "language": "C++, Python", + "image": "lolbench/apache-arrow-pr-45360:1", + "env": { + "ARROW_HOME": "/opt/conda", + "PARQUET_HOME": "/opt/conda", + "CMAKE_PREFIX_PATH": "/opt/conda", + "LD_LIBRARY_PATH": "/opt/conda/lib" + }, + "timeout_s": 5400, + "resource_caps": { + "cpu": 4, + "mem_gb": 7 + }, + "solution_patch_sha256": "5a2fe50fd5415ca6941c46a2806afc300beb4a20bacac0339af31813c3a13549", + "agent_contract": { + "input": "/in/solution.patch", + "output": "/out/agent_report.json", + "invocation": "docker run --rm -v $(pwd)/solution.patch:/in/solution.patch:ro -v $(pwd)/out:/out lolbench/apache-arrow-pr-45360:1" + }, + "test_framework": "pytest", + "test_level": "system", + "test_cmd": "pytest -p no:cacheprovider --enable-large_memory --enable-pandas -v $TESTS", + "log_parser": "pytest_text", + "log_parser_config": { + "pass_pattern": "PASSED", + "fail_pattern": "FAILED", + "error_pattern": "ERROR", + "skipped_pattern": "SKIPPED" + }, + "fail_to_pass": [ + "python/pyarrow/tests/parquet/test_parquet_writer.py::test_parquet_content_defined_chunking", + "python/pyarrow/tests/parquet/test_parquet_writer.py::test_parquet_content_defined_chunking_parameters" + ], + "pass_to_pass": [ + "python/pyarrow/tests/parquet/test_parquet_writer.py::test_parquet_incremental_file_build", + "python/pyarrow/tests/parquet/test_parquet_writer.py::test_validate_schema_write_table", + "python/pyarrow/tests/parquet/test_parquet_writer.py::test_parquet_invalid_writer", + "python/pyarrow/tests/parquet/test_parquet_writer.py::test_parquet_writer_context_obj", + "python/pyarrow/tests/parquet/test_parquet_writer.py::test_parquet_writer_context_obj_with_exception", + "python/pyarrow/tests/parquet/test_parquet_writer.py::test_parquet_writer_write_wrappers", + "python/pyarrow/tests/parquet/test_parquet_writer.py::test_parquet_writer_chunk_size", + "python/pyarrow/tests/parquet/test_parquet_writer.py::test_parquet_writer_filesystem_local", + "python/pyarrow/tests/parquet/test_parquet_writer.py::test_parquet_writer_filesystem_buffer_raises", + "python/pyarrow/tests/parquet/test_parquet_writer.py::test_parquet_writer_store_schema", + "python/pyarrow/tests/parquet/test_parquet_writer.py::test_parquet_writer_append_key_value_metadata", + "python/pyarrow/tests/parquet/test_metadata.py::test_parquet_metadata_lifetime", + "python/pyarrow/tests/parquet/test_metadata.py::test_statistics_convert_logical_types", + "python/pyarrow/tests/parquet/test_metadata.py::test_field_id_metadata", + "python/pyarrow/tests/parquet/test_metadata.py::test_parquet_metadata_empty_to_dict", + "python/pyarrow/tests/parquet/test_metadata.py::test_metadata_equals", + "python/pyarrow/tests/parquet/test_metadata.py::test_write_metadata", + "python/pyarrow/tests/parquet/test_basic.py::test_fspath", + "python/pyarrow/tests/parquet/test_basic.py::test_read_non_existing_file", + "python/pyarrow/tests/parquet/test_basic.py::test_file_error_python_exception", + "python/pyarrow/tests/parquet/test_basic.py::test_parquet_read_from_buffer", + "python/pyarrow/tests/parquet/test_basic.py::test_read_non_existent_file", + "python/pyarrow/tests/parquet/test_basic.py::test_parquet_compression_roundtrip", + "python/pyarrow/tests/parquet/test_basic.py::test_empty_row_groups", + "python/pyarrow/tests/parquet/test_parquet_file.py::test_parquet_file_pass_directory_instead_of_file", + "python/pyarrow/tests/parquet/test_parquet_file.py::test_read_column_invalid_index", + "python/pyarrow/tests/parquet/test_parquet_file.py::test_parquet_file_explicitly_closed", + "python/pyarrow/tests/parquet/test_metadata.py::test_parquet_metadata_api", + "python/pyarrow/tests/parquet/test_metadata.py::test_parquet_column_statistics_api", + "python/pyarrow/tests/parquet/test_metadata.py::test_parquet_raise_on_unset_statistics", + "python/pyarrow/tests/parquet/test_metadata.py::test_parquet_write_disable_statistics", + "python/pyarrow/tests/parquet/test_metadata.py::test_parquet_sorting_column", + "python/pyarrow/tests/parquet/test_metadata.py::test_parquet_sorting_column_nested", + "python/pyarrow/tests/parquet/test_metadata.py::test_parquet_file_sorting_columns", + "python/pyarrow/tests/parquet/test_metadata.py::test_parquet_file_page_index", + "python/pyarrow/tests/parquet/test_metadata.py::test_multi_dataset_metadata", + "python/pyarrow/tests/parquet/test_metadata.py::test_metadata_hashing", + "python/pyarrow/tests/parquet/test_metadata.py::test_table_large_metadata", + "python/pyarrow/tests/parquet/test_metadata.py::test_compare_schemas", + "python/pyarrow/tests/parquet/test_metadata.py::test_read_schema", + "python/pyarrow/tests/parquet/test_metadata.py::test_metadata_schema_filesystem", + "python/pyarrow/tests/parquet/test_metadata.py::test_metadata_append_row_groups_diff", + "python/pyarrow/tests/parquet/test_basic.py::test_set_data_page_size", + "python/pyarrow/tests/parquet/test_basic.py::test_chunked_table_write" + ], + "synthetic_tests": [], + "eval_tests_patch_sha256": "8635926feb79dae5e370dd03aa6f9086f5418b291d8488f98da18b18ed37ce5f", + "fixture_taint_summary": "eval_tests.patch modifies only python/pyarrow/tests/parquet/test_parquet_writer.py at line 361+ (append-only). No top-level imports, module-level fixtures, class setUp, or shared helpers were touched. test_metadata.py, test_basic.py, and test_parquet_file.py are not modified at all. All 44 original P2P candidates are therefore fixture-taint-clean.", + "triage": { + "fail_to_pass": { + "test_parquet_content_defined_chunking": { + "system_reason": "drives pyarrow.parquet.write_table with use_content_defined_chunking={True, dict} and asserts on data round-trip + chunked file structure; never names internal C++ class ContentDefinedChunker.", + "public_surface": "pyarrow.parquet.write_table", + "internal_symbol_check": [ + "ContentDefinedChunker", + "parquet::internal::ContentDefinedChunker", + "chunker_internal" + ], + "runner_surface": "pytest python/pyarrow/tests/parquet/test_parquet_writer.py::test_parquet_content_defined_chunking", + "fixture_taint_checked": true + }, + "test_parquet_content_defined_chunking_parameters": { + "system_reason": "drives pq.write_table with min/max chunk size kwargs and asserts on file metadata; public-API only.", + "public_surface": "pyarrow.parquet.write_table", + "internal_symbol_check": [ + "ContentDefinedChunker", + "parquet::internal::ContentDefinedChunker", + "chunker_internal" + ], + "runner_surface": "pytest python/pyarrow/tests/parquet/test_parquet_writer.py::test_parquet_content_defined_chunking_parameters", + "fixture_taint_checked": true + } + }, + "pass_to_pass": { + "test_parquet_incremental_file_build": { + "system_reason": "exercises a write-path scenario through the public ParquetWriter API (context-manager, schema, key-value metadata, etc.) without referencing the new chunker class.", + "public_surface": "pyarrow.parquet.write_table / pyarrow.parquet.ParquetWriter", + "internal_symbol_check": [ + "ContentDefinedChunker", + "parquet::internal::ContentDefinedChunker", + "chunker_internal" + ], + "runner_surface": "pytest python/pyarrow/tests/parquet/test_parquet_writer.py::test_parquet_incremental_file_build", + "fixture_taint_checked": true + }, + "test_validate_schema_write_table": { + "system_reason": "exercises a write-path scenario through the public ParquetWriter API (context-manager, schema, key-value metadata, etc.) without referencing the new chunker class.", + "public_surface": "pyarrow.parquet.write_table / pyarrow.parquet.ParquetWriter", + "internal_symbol_check": [ + "ContentDefinedChunker", + "parquet::internal::ContentDefinedChunker", + "chunker_internal" + ], + "runner_surface": "pytest python/pyarrow/tests/parquet/test_parquet_writer.py::test_validate_schema_write_table", + "fixture_taint_checked": true + }, + "test_parquet_invalid_writer": { + "system_reason": "exercises a write-path scenario through the public ParquetWriter API (context-manager, schema, key-value metadata, etc.) without referencing the new chunker class.", + "public_surface": "pyarrow.parquet.write_table / pyarrow.parquet.ParquetWriter", + "internal_symbol_check": [ + "ContentDefinedChunker", + "parquet::internal::ContentDefinedChunker", + "chunker_internal" + ], + "runner_surface": "pytest python/pyarrow/tests/parquet/test_parquet_writer.py::test_parquet_invalid_writer", + "fixture_taint_checked": true + }, + "test_parquet_writer_context_obj": { + "system_reason": "exercises a write-path scenario through the public ParquetWriter API (context-manager, schema, key-value metadata, etc.) without referencing the new chunker class.", + "public_surface": "pyarrow.parquet.write_table / pyarrow.parquet.ParquetWriter", + "internal_symbol_check": [ + "ContentDefinedChunker", + "parquet::internal::ContentDefinedChunker", + "chunker_internal" + ], + "runner_surface": "pytest python/pyarrow/tests/parquet/test_parquet_writer.py::test_parquet_writer_context_obj", + "fixture_taint_checked": true + }, + "test_parquet_writer_context_obj_with_exception": { + "system_reason": "exercises a write-path scenario through the public ParquetWriter API (context-manager, schema, key-value metadata, etc.) without referencing the new chunker class.", + "public_surface": "pyarrow.parquet.write_table / pyarrow.parquet.ParquetWriter", + "internal_symbol_check": [ + "ContentDefinedChunker", + "parquet::internal::ContentDefinedChunker", + "chunker_internal" + ], + "runner_surface": "pytest python/pyarrow/tests/parquet/test_parquet_writer.py::test_parquet_writer_context_obj_with_exception", + "fixture_taint_checked": true + }, + "test_parquet_writer_write_wrappers": { + "system_reason": "exercises a write-path scenario through the public ParquetWriter API (context-manager, schema, key-value metadata, etc.) without referencing the new chunker class.", + "public_surface": "pyarrow.parquet.write_table / pyarrow.parquet.ParquetWriter", + "internal_symbol_check": [ + "ContentDefinedChunker", + "parquet::internal::ContentDefinedChunker", + "chunker_internal" + ], + "runner_surface": "pytest python/pyarrow/tests/parquet/test_parquet_writer.py::test_parquet_writer_write_wrappers", + "fixture_taint_checked": true + }, + "test_parquet_writer_chunk_size": { + "system_reason": "exercises a write-path scenario through the public ParquetWriter API (context-manager, schema, key-value metadata, etc.) without referencing the new chunker class.", + "public_surface": "pyarrow.parquet.write_table / pyarrow.parquet.ParquetWriter", + "internal_symbol_check": [ + "ContentDefinedChunker", + "parquet::internal::ContentDefinedChunker", + "chunker_internal" + ], + "runner_surface": "pytest python/pyarrow/tests/parquet/test_parquet_writer.py::test_parquet_writer_chunk_size", + "fixture_taint_checked": true + }, + "test_parquet_writer_filesystem_local": { + "system_reason": "exercises a write-path scenario through the public ParquetWriter API (context-manager, schema, key-value metadata, etc.) without referencing the new chunker class.", + "public_surface": "pyarrow.parquet.write_table / pyarrow.parquet.ParquetWriter", + "internal_symbol_check": [ + "ContentDefinedChunker", + "parquet::internal::ContentDefinedChunker", + "chunker_internal" + ], + "runner_surface": "pytest python/pyarrow/tests/parquet/test_parquet_writer.py::test_parquet_writer_filesystem_local", + "fixture_taint_checked": true + }, + "test_parquet_writer_filesystem_buffer_raises": { + "system_reason": "exercises a write-path scenario through the public ParquetWriter API (context-manager, schema, key-value metadata, etc.) without referencing the new chunker class.", + "public_surface": "pyarrow.parquet.write_table / pyarrow.parquet.ParquetWriter", + "internal_symbol_check": [ + "ContentDefinedChunker", + "parquet::internal::ContentDefinedChunker", + "chunker_internal" + ], + "runner_surface": "pytest python/pyarrow/tests/parquet/test_parquet_writer.py::test_parquet_writer_filesystem_buffer_raises", + "fixture_taint_checked": true + }, + "test_parquet_writer_store_schema": { + "system_reason": "exercises a write-path scenario through the public ParquetWriter API (context-manager, schema, key-value metadata, etc.) without referencing the new chunker class.", + "public_surface": "pyarrow.parquet.write_table / pyarrow.parquet.ParquetWriter", + "internal_symbol_check": [ + "ContentDefinedChunker", + "parquet::internal::ContentDefinedChunker", + "chunker_internal" + ], + "runner_surface": "pytest python/pyarrow/tests/parquet/test_parquet_writer.py::test_parquet_writer_store_schema", + "fixture_taint_checked": true + }, + "test_parquet_writer_append_key_value_metadata": { + "system_reason": "exercises a write-path scenario through the public ParquetWriter API (context-manager, schema, key-value metadata, etc.) without referencing the new chunker class.", + "public_surface": "pyarrow.parquet.write_table / pyarrow.parquet.ParquetWriter", + "internal_symbol_check": [ + "ContentDefinedChunker", + "parquet::internal::ContentDefinedChunker", + "chunker_internal" + ], + "runner_surface": "pytest python/pyarrow/tests/parquet/test_parquet_writer.py::test_parquet_writer_append_key_value_metadata", + "fixture_taint_checked": true + }, + "test_parquet_metadata_lifetime": { + "system_reason": "exercises Parquet metadata read/write via the public pyarrow.parquet metadata API; touches the same writer object family as F2P but along an orthogonal axis (metadata) so a chunker regression would be observable only if it leaks into metadata serialization.", + "public_surface": "pyarrow.parquet.read_metadata / pyarrow.parquet.write_metadata / pyarrow.parquet.ParquetFile.metadata", + "internal_symbol_check": [ + "ContentDefinedChunker", + "parquet::internal::ContentDefinedChunker", + "chunker_internal" + ], + "runner_surface": "pytest python/pyarrow/tests/parquet/test_metadata.py::test_parquet_metadata_lifetime", + "fixture_taint_checked": true + }, + "test_statistics_convert_logical_types": { + "system_reason": "exercises Parquet metadata read/write via the public pyarrow.parquet metadata API; touches the same writer object family as F2P but along an orthogonal axis (metadata) so a chunker regression would be observable only if it leaks into metadata serialization.", + "public_surface": "pyarrow.parquet.read_metadata / pyarrow.parquet.write_metadata / pyarrow.parquet.ParquetFile.metadata", + "internal_symbol_check": [ + "ContentDefinedChunker", + "parquet::internal::ContentDefinedChunker", + "chunker_internal" + ], + "runner_surface": "pytest python/pyarrow/tests/parquet/test_metadata.py::test_statistics_convert_logical_types", + "fixture_taint_checked": true + }, + "test_field_id_metadata": { + "system_reason": "exercises Parquet metadata read/write via the public pyarrow.parquet metadata API; touches the same writer object family as F2P but along an orthogonal axis (metadata) so a chunker regression would be observable only if it leaks into metadata serialization.", + "public_surface": "pyarrow.parquet.read_metadata / pyarrow.parquet.write_metadata / pyarrow.parquet.ParquetFile.metadata", + "internal_symbol_check": [ + "ContentDefinedChunker", + "parquet::internal::ContentDefinedChunker", + "chunker_internal" + ], + "runner_surface": "pytest python/pyarrow/tests/parquet/test_metadata.py::test_field_id_metadata", + "fixture_taint_checked": true + }, + "test_parquet_metadata_empty_to_dict": { + "system_reason": "exercises Parquet metadata read/write via the public pyarrow.parquet metadata API; touches the same writer object family as F2P but along an orthogonal axis (metadata) so a chunker regression would be observable only if it leaks into metadata serialization.", + "public_surface": "pyarrow.parquet.read_metadata / pyarrow.parquet.write_metadata / pyarrow.parquet.ParquetFile.metadata", + "internal_symbol_check": [ + "ContentDefinedChunker", + "parquet::internal::ContentDefinedChunker", + "chunker_internal" + ], + "runner_surface": "pytest python/pyarrow/tests/parquet/test_metadata.py::test_parquet_metadata_empty_to_dict", + "fixture_taint_checked": true + }, + "test_metadata_equals": { + "system_reason": "exercises Parquet metadata read/write via the public pyarrow.parquet metadata API; touches the same writer object family as F2P but along an orthogonal axis (metadata) so a chunker regression would be observable only if it leaks into metadata serialization.", + "public_surface": "pyarrow.parquet.read_metadata / pyarrow.parquet.write_metadata / pyarrow.parquet.ParquetFile.metadata", + "internal_symbol_check": [ + "ContentDefinedChunker", + "parquet::internal::ContentDefinedChunker", + "chunker_internal" + ], + "runner_surface": "pytest python/pyarrow/tests/parquet/test_metadata.py::test_metadata_equals", + "fixture_taint_checked": true + }, + "test_write_metadata": { + "system_reason": "exercises Parquet metadata read/write via the public pyarrow.parquet metadata API; touches the same writer object family as F2P but along an orthogonal axis (metadata) so a chunker regression would be observable only if it leaks into metadata serialization.", + "public_surface": "pyarrow.parquet.read_metadata / pyarrow.parquet.write_metadata / pyarrow.parquet.ParquetFile.metadata", + "internal_symbol_check": [ + "ContentDefinedChunker", + "parquet::internal::ContentDefinedChunker", + "chunker_internal" + ], + "runner_surface": "pytest python/pyarrow/tests/parquet/test_metadata.py::test_write_metadata", + "fixture_taint_checked": true + }, + "test_parquet_metadata_api": { + "system_reason": "pre-existing parquet metadata public API regression test from an untouched neighbor module; protects metadata behavior adjacent to writer/file serialization without asserting the new CDC feature.", + "public_surface": "pyarrow.parquet metadata API", + "internal_symbol_check": [ + "ContentDefinedChunker", + "parquet::internal::ContentDefinedChunker", + "chunker_internal" + ], + "runner_surface": "pytest python/pyarrow/tests/parquet/test_metadata.py::test_parquet_metadata_api", + "fixture_taint_checked": true + }, + "test_parquet_column_statistics_api": { + "system_reason": "pre-existing parquet metadata public API regression test from an untouched neighbor module; protects statistics behavior adjacent to writer/file serialization without asserting the new CDC feature.", + "public_surface": "pyarrow.parquet metadata/statistics API", + "internal_symbol_check": [ + "ContentDefinedChunker", + "parquet::internal::ContentDefinedChunker", + "chunker_internal" + ], + "runner_surface": "pytest python/pyarrow/tests/parquet/test_metadata.py::test_parquet_column_statistics_api", + "fixture_taint_checked": true + }, + "test_parquet_raise_on_unset_statistics": { + "system_reason": "pre-existing parquet metadata public API regression test from an untouched neighbor module; protects statistics behavior adjacent to writer/file serialization without asserting the new CDC feature.", + "public_surface": "pyarrow.parquet metadata/statistics API", + "internal_symbol_check": [ + "ContentDefinedChunker", + "parquet::internal::ContentDefinedChunker", + "chunker_internal" + ], + "runner_surface": "pytest python/pyarrow/tests/parquet/test_metadata.py::test_parquet_raise_on_unset_statistics", + "fixture_taint_checked": true + }, + "test_parquet_write_disable_statistics": { + "system_reason": "pre-existing parquet writer metadata regression test from an untouched neighbor module; protects statistics-writing behavior without asserting the new CDC feature.", + "public_surface": "pyarrow.parquet.write_table / metadata statistics", + "internal_symbol_check": [ + "ContentDefinedChunker", + "parquet::internal::ContentDefinedChunker", + "chunker_internal" + ], + "runner_surface": "pytest python/pyarrow/tests/parquet/test_metadata.py::test_parquet_write_disable_statistics", + "fixture_taint_checked": true + }, + "test_parquet_sorting_column": { + "system_reason": "pre-existing parquet metadata public API regression test from an untouched neighbor module; protects sorting-column metadata behavior without asserting the new CDC feature.", + "public_surface": "pyarrow.parquet SortingColumn / metadata API", + "internal_symbol_check": [ + "ContentDefinedChunker", + "parquet::internal::ContentDefinedChunker", + "chunker_internal" + ], + "runner_surface": "pytest python/pyarrow/tests/parquet/test_metadata.py::test_parquet_sorting_column", + "fixture_taint_checked": true + }, + "test_parquet_sorting_column_nested": { + "system_reason": "pre-existing parquet metadata public API regression test from an untouched neighbor module; protects nested sorting-column metadata behavior without asserting the new CDC feature.", + "public_surface": "pyarrow.parquet SortingColumn / metadata API", + "internal_symbol_check": [ + "ContentDefinedChunker", + "parquet::internal::ContentDefinedChunker", + "chunker_internal" + ], + "runner_surface": "pytest python/pyarrow/tests/parquet/test_metadata.py::test_parquet_sorting_column_nested", + "fixture_taint_checked": true + }, + "test_parquet_file_sorting_columns": { + "system_reason": "pre-existing parquet metadata public API regression test from an untouched neighbor module; protects file-level sorting-column metadata behavior without asserting the new CDC feature.", + "public_surface": "pyarrow.parquet ParquetFile.metadata / SortingColumn", + "internal_symbol_check": [ + "ContentDefinedChunker", + "parquet::internal::ContentDefinedChunker", + "chunker_internal" + ], + "runner_surface": "pytest python/pyarrow/tests/parquet/test_metadata.py::test_parquet_file_sorting_columns", + "fixture_taint_checked": true + }, + "test_parquet_file_page_index": { + "system_reason": "pre-existing parquet metadata public API regression test from an untouched neighbor module; protects page-index metadata behavior without asserting the new CDC feature.", + "public_surface": "pyarrow.parquet metadata/page-index API", + "internal_symbol_check": [ + "ContentDefinedChunker", + "parquet::internal::ContentDefinedChunker", + "chunker_internal" + ], + "runner_surface": "pytest python/pyarrow/tests/parquet/test_metadata.py::test_parquet_file_page_index", + "fixture_taint_checked": true + }, + "test_multi_dataset_metadata": { + "system_reason": "pre-existing parquet metadata public API regression test from an untouched neighbor module; protects multi-dataset metadata behavior without asserting the new CDC feature.", + "public_surface": "pyarrow.parquet metadata API", + "internal_symbol_check": [ + "ContentDefinedChunker", + "parquet::internal::ContentDefinedChunker", + "chunker_internal" + ], + "runner_surface": "pytest python/pyarrow/tests/parquet/test_metadata.py::test_multi_dataset_metadata", + "fixture_taint_checked": true + }, + "test_metadata_hashing": { + "system_reason": "pre-existing parquet metadata public API regression test from an untouched neighbor module; protects metadata hashing behavior without asserting the new CDC feature.", + "public_surface": "pyarrow.parquet metadata API", + "internal_symbol_check": [ + "ContentDefinedChunker", + "parquet::internal::ContentDefinedChunker", + "chunker_internal" + ], + "runner_surface": "pytest python/pyarrow/tests/parquet/test_metadata.py::test_metadata_hashing", + "fixture_taint_checked": true + }, + "test_table_large_metadata": { + "system_reason": "pre-existing parquet metadata public API regression test from an untouched neighbor module; protects large metadata serialization without asserting the new CDC feature.", + "public_surface": "pyarrow.parquet.write_table / metadata API", + "internal_symbol_check": [ + "ContentDefinedChunker", + "parquet::internal::ContentDefinedChunker", + "chunker_internal" + ], + "runner_surface": "pytest python/pyarrow/tests/parquet/test_metadata.py::test_table_large_metadata", + "fixture_taint_checked": true + }, + "test_compare_schemas": { + "system_reason": "pre-existing parquet metadata public API regression test from an untouched neighbor module; protects schema comparison behavior without asserting the new CDC feature.", + "public_surface": "pyarrow.parquet metadata schema API", + "internal_symbol_check": [ + "ContentDefinedChunker", + "parquet::internal::ContentDefinedChunker", + "chunker_internal" + ], + "runner_surface": "pytest python/pyarrow/tests/parquet/test_metadata.py::test_compare_schemas", + "fixture_taint_checked": true + }, + "test_read_schema": { + "system_reason": "pre-existing parquet metadata public API regression test from an untouched neighbor module; protects schema reading behavior without asserting the new CDC feature.", + "public_surface": "pyarrow.parquet.read_schema", + "internal_symbol_check": [ + "ContentDefinedChunker", + "parquet::internal::ContentDefinedChunker", + "chunker_internal" + ], + "runner_surface": "pytest python/pyarrow/tests/parquet/test_metadata.py::test_read_schema", + "fixture_taint_checked": true + }, + "test_metadata_schema_filesystem": { + "system_reason": "pre-existing parquet metadata public API regression test from an untouched neighbor module; protects filesystem-backed metadata schema behavior without asserting the new CDC feature.", + "public_surface": "pyarrow.parquet metadata/schema filesystem API", + "internal_symbol_check": [ + "ContentDefinedChunker", + "parquet::internal::ContentDefinedChunker", + "chunker_internal" + ], + "runner_surface": "pytest python/pyarrow/tests/parquet/test_metadata.py::test_metadata_schema_filesystem", + "fixture_taint_checked": true + }, + "test_metadata_append_row_groups_diff": { + "system_reason": "pre-existing parquet metadata public API regression test from an untouched neighbor module; protects row-group metadata append behavior without asserting the new CDC feature.", + "public_surface": "pyarrow.parquet metadata row-group API", + "internal_symbol_check": [ + "ContentDefinedChunker", + "parquet::internal::ContentDefinedChunker", + "chunker_internal" + ], + "runner_surface": "pytest python/pyarrow/tests/parquet/test_metadata.py::test_metadata_append_row_groups_diff", + "fixture_taint_checked": true + }, + "test_set_data_page_size": { + "system_reason": "pre-existing parquet basic writer regression test from an untouched neighbor module; protects existing data_page_size writer behavior without asserting the new CDC feature.", + "public_surface": "pyarrow.parquet.write_table", + "internal_symbol_check": [ + "ContentDefinedChunker", + "parquet::internal::ContentDefinedChunker", + "chunker_internal" + ], + "runner_surface": "pytest python/pyarrow/tests/parquet/test_basic.py::test_set_data_page_size", + "fixture_taint_checked": true + }, + "test_chunked_table_write": { + "system_reason": "pre-existing parquet basic writer regression test from an untouched neighbor module; protects existing chunked-table write behavior without asserting the new CDC feature.", + "public_surface": "pyarrow.parquet.write_table", + "internal_symbol_check": [ + "ContentDefinedChunker", + "parquet::internal::ContentDefinedChunker", + "chunker_internal" + ], + "runner_surface": "pytest python/pyarrow/tests/parquet/test_basic.py::test_chunked_table_write", + "fixture_taint_checked": true + }, + "test_fspath": { + "system_reason": "exercises the simple write-then-read round-trip through the public pyarrow.parquet API; catches gross regressions in reader/writer compatibility caused by changes in the writer internals.", + "public_surface": "pyarrow.parquet.read_table / pyarrow.parquet.write_table round-trip", + "internal_symbol_check": [ + "ContentDefinedChunker", + "parquet::internal::ContentDefinedChunker", + "chunker_internal" + ], + "runner_surface": "pytest python/pyarrow/tests/parquet/test_basic.py::test_fspath", + "fixture_taint_checked": true + }, + "test_read_non_existing_file": { + "system_reason": "exercises the simple write-then-read round-trip through the public pyarrow.parquet API; catches gross regressions in reader/writer compatibility caused by changes in the writer internals.", + "public_surface": "pyarrow.parquet.read_table / pyarrow.parquet.write_table round-trip", + "internal_symbol_check": [ + "ContentDefinedChunker", + "parquet::internal::ContentDefinedChunker", + "chunker_internal" + ], + "runner_surface": "pytest python/pyarrow/tests/parquet/test_basic.py::test_read_non_existing_file", + "fixture_taint_checked": true + }, + "test_file_error_python_exception": { + "system_reason": "exercises the simple write-then-read round-trip through the public pyarrow.parquet API; catches gross regressions in reader/writer compatibility caused by changes in the writer internals.", + "public_surface": "pyarrow.parquet.read_table / pyarrow.parquet.write_table round-trip", + "internal_symbol_check": [ + "ContentDefinedChunker", + "parquet::internal::ContentDefinedChunker", + "chunker_internal" + ], + "runner_surface": "pytest python/pyarrow/tests/parquet/test_basic.py::test_file_error_python_exception", + "fixture_taint_checked": true + }, + "test_parquet_read_from_buffer": { + "system_reason": "exercises the simple write-then-read round-trip through the public pyarrow.parquet API; catches gross regressions in reader/writer compatibility caused by changes in the writer internals.", + "public_surface": "pyarrow.parquet.read_table / pyarrow.parquet.write_table round-trip", + "internal_symbol_check": [ + "ContentDefinedChunker", + "parquet::internal::ContentDefinedChunker", + "chunker_internal" + ], + "runner_surface": "pytest python/pyarrow/tests/parquet/test_basic.py::test_parquet_read_from_buffer", + "fixture_taint_checked": true + }, + "test_read_non_existent_file": { + "system_reason": "exercises the simple write-then-read round-trip through the public pyarrow.parquet API; catches gross regressions in reader/writer compatibility caused by changes in the writer internals.", + "public_surface": "pyarrow.parquet.read_table / pyarrow.parquet.write_table round-trip", + "internal_symbol_check": [ + "ContentDefinedChunker", + "parquet::internal::ContentDefinedChunker", + "chunker_internal" + ], + "runner_surface": "pytest python/pyarrow/tests/parquet/test_basic.py::test_read_non_existent_file", + "fixture_taint_checked": true + }, + "test_parquet_compression_roundtrip": { + "system_reason": "exercises the simple write-then-read round-trip through the public pyarrow.parquet API; catches gross regressions in reader/writer compatibility caused by changes in the writer internals.", + "public_surface": "pyarrow.parquet.read_table / pyarrow.parquet.write_table round-trip", + "internal_symbol_check": [ + "ContentDefinedChunker", + "parquet::internal::ContentDefinedChunker", + "chunker_internal" + ], + "runner_surface": "pytest python/pyarrow/tests/parquet/test_basic.py::test_parquet_compression_roundtrip", + "fixture_taint_checked": true + }, + "test_empty_row_groups": { + "system_reason": "exercises the simple write-then-read round-trip through the public pyarrow.parquet API; catches gross regressions in reader/writer compatibility caused by changes in the writer internals.", + "public_surface": "pyarrow.parquet.read_table / pyarrow.parquet.write_table round-trip", + "internal_symbol_check": [ + "ContentDefinedChunker", + "parquet::internal::ContentDefinedChunker", + "chunker_internal" + ], + "runner_surface": "pytest python/pyarrow/tests/parquet/test_basic.py::test_empty_row_groups", + "fixture_taint_checked": true + }, + "test_parquet_file_pass_directory_instead_of_file": { + "system_reason": "exercises the public ParquetFile reader; covers reader behaviour that should be invariant under content-defined-chunking writer changes.", + "public_surface": "pyarrow.parquet.ParquetFile (open + read columns + close)", + "internal_symbol_check": [ + "ContentDefinedChunker", + "parquet::internal::ContentDefinedChunker", + "chunker_internal" + ], + "runner_surface": "pytest python/pyarrow/tests/parquet/test_parquet_file.py::test_parquet_file_pass_directory_instead_of_file", + "fixture_taint_checked": true + }, + "test_read_column_invalid_index": { + "system_reason": "exercises the public ParquetFile reader; covers reader behaviour that should be invariant under content-defined-chunking writer changes.", + "public_surface": "pyarrow.parquet.ParquetFile (open + read columns + close)", + "internal_symbol_check": [ + "ContentDefinedChunker", + "parquet::internal::ContentDefinedChunker", + "chunker_internal" + ], + "runner_surface": "pytest python/pyarrow/tests/parquet/test_parquet_file.py::test_read_column_invalid_index", + "fixture_taint_checked": true + }, + "test_parquet_file_explicitly_closed": { + "system_reason": "exercises the public ParquetFile reader; covers reader behaviour that should be invariant under content-defined-chunking writer changes.", + "public_surface": "pyarrow.parquet.ParquetFile (open + read columns + close)", + "internal_symbol_check": [ + "ContentDefinedChunker", + "parquet::internal::ContentDefinedChunker", + "chunker_internal" + ], + "runner_surface": "pytest python/pyarrow/tests/parquet/test_parquet_file.py::test_parquet_file_explicitly_closed", + "fixture_taint_checked": true + } + } + }, + "validated_at": "2026-05-17", + "augmented": { + "fail_to_pass": [ + "python/pyarrow/tests/parquet/test_parquet_writer_cdc_aug.py::test_cdc_dict_min_chunk_size_affects_output_size", + "python/pyarrow/tests/parquet/test_parquet_writer_cdc_aug.py::test_cdc_dict_norm_level_affects_output_size", + "python/pyarrow/tests/parquet/test_parquet_writer_cdc_aug.py::test_cdc_true_changes_layout_vs_false_on_string_column", + "python/pyarrow/tests/parquet/test_parquet_writer_cdc_aug.py::test_cdc_mixed_physical_layouts_roundtrip_and_change_layout", + "python/pyarrow/tests/parquet/test_parquet_writer_cdc_aug.py::test_cdc_true_determinism_across_repeated_writes" + ], + "pass_to_pass": [ + "python/pyarrow/tests/parquet/test_parquet_writer_stability_aug.py::test_writer_default_no_cdc_arg_roundtrip", + "python/pyarrow/tests/parquet/test_parquet_writer_stability_aug.py::test_writer_compression_snappy_roundtrip_unchanged", + "python/pyarrow/tests/parquet/test_parquet_writer_stability_aug.py::test_writer_data_page_size_unchanged", + "python/pyarrow/tests/parquet/test_parquet_writer_stability_aug.py::test_parquet_writer_context_manager_default_path", + "python/pyarrow/tests/parquet/test_parquet_writer_stability_aug.py::test_read_metadata_for_default_file_unchanged_shape", + "python/pyarrow/tests/parquet/test_parquet_writer_stability_aug.py::test_parquet_file_read_row_group_default_unchanged" + ], + "eval_tests_aug_patch_sha256": "b24e87cec09b2d1314085eb05f3a078f02848c85aabec8069242f43672a40f6d", + "synthetic_tests": [ + "python/pyarrow/tests/parquet/test_parquet_writer_cdc_aug.py::test_cdc_dict_min_chunk_size_affects_output_size", + "python/pyarrow/tests/parquet/test_parquet_writer_cdc_aug.py::test_cdc_dict_norm_level_affects_output_size", + "python/pyarrow/tests/parquet/test_parquet_writer_cdc_aug.py::test_cdc_true_changes_layout_vs_false_on_string_column", + "python/pyarrow/tests/parquet/test_parquet_writer_cdc_aug.py::test_cdc_mixed_physical_layouts_roundtrip_and_change_layout", + "python/pyarrow/tests/parquet/test_parquet_writer_cdc_aug.py::test_cdc_true_determinism_across_repeated_writes", + "python/pyarrow/tests/parquet/test_parquet_writer_stability_aug.py::test_writer_default_no_cdc_arg_roundtrip", + "python/pyarrow/tests/parquet/test_parquet_writer_stability_aug.py::test_writer_compression_snappy_roundtrip_unchanged", + "python/pyarrow/tests/parquet/test_parquet_writer_stability_aug.py::test_writer_data_page_size_unchanged", + "python/pyarrow/tests/parquet/test_parquet_writer_stability_aug.py::test_parquet_writer_context_manager_default_path", + "python/pyarrow/tests/parquet/test_parquet_writer_stability_aug.py::test_read_metadata_for_default_file_unchanged_shape", + "python/pyarrow/tests/parquet/test_parquet_writer_stability_aug.py::test_parquet_file_read_row_group_default_unchanged" + ], + "triage": { + "fail_to_pass": { + "python/pyarrow/tests/parquet/test_parquet_writer_cdc_aug.py::test_cdc_dict_min_chunk_size_affects_output_size": { + "test_level": "public-api-synthetic", + "surface_reason": "Drives pq.write_table + pq.read_metadata with two min_chunk_size values; observes total_byte_size differential.", + "public_surface": "pyarrow.parquet.write_table, pyarrow.parquet.read_metadata, pyarrow.parquet.read_table", + "internal_symbol_check": [ + "parquet::internal", + "_parquet.", + "pyarrow._parquet", + "_Weakrefable", + "CdcOptions" + ], + "runner_surface": "pytest python/pyarrow/tests/parquet/test_parquet_writer_cdc_aug.py::test_cdc_dict_min_chunk_size_affects_output_size", + "kills_mutants": [ + "mutant_002_python_dict_options_disable_cdc", + "mutant_003_chunker_never_uses_hash_cutpoints", + "mutant_004_column_writer_does_not_flush_chunk_pages" + ], + "synthetic_author": "lolbench-aug", + "oracle_kind": "requirement-driven", + "target_requirement": "Section: Rationale (CDC must produce content-defined boundaries; min_chunk_size must affect cutpoint frequency)", + "requirement_sections": [ + "Rationale" + ], + "mutants_targeted": [ + "mutant_002_python_dict_options_disable_cdc", + "mutant_003_chunker_never_uses_hash_cutpoints", + "mutant_004_column_writer_does_not_flush_chunk_pages" + ], + "rationale": "The Rationale requires content-defined boundaries and custom CDC options; varying min_chunk_size through the public write_table dict option must affect cutpoint frequency and the resulting metadata-visible page layout." + }, + "python/pyarrow/tests/parquet/test_parquet_writer_cdc_aug.py::test_cdc_dict_norm_level_affects_output_size": { + "test_level": "public-api-synthetic", + "surface_reason": "Drives pq.write_table + pq.read_metadata with two norm_level values; observes total_byte_size differential.", + "public_surface": "pyarrow.parquet.write_table, pyarrow.parquet.read_metadata, pyarrow.parquet.read_table", + "internal_symbol_check": [ + "parquet::internal", + "_parquet.", + "pyarrow._parquet", + "_Weakrefable", + "CdcOptions" + ], + "runner_surface": "pytest python/pyarrow/tests/parquet/test_parquet_writer_cdc_aug.py::test_cdc_dict_norm_level_affects_output_size", + "kills_mutants": [ + "mutant_002_python_dict_options_disable_cdc", + "mutant_003_chunker_never_uses_hash_cutpoints", + "mutant_004_column_writer_does_not_flush_chunk_pages" + ], + "synthetic_author": "lolbench-aug", + "oracle_kind": "requirement-driven", + "target_requirement": "Section: Rationale (norm_level governs gearhash mask centering; must influence chunk-size distribution)", + "requirement_sections": [ + "Rationale" + ], + "mutants_targeted": [ + "mutant_002_python_dict_options_disable_cdc", + "mutant_003_chunker_never_uses_hash_cutpoints", + "mutant_004_column_writer_does_not_flush_chunk_pages" + ], + "rationale": "The Rationale describes a configurable rolling-hash chunking distribution; varying norm_level through the public dict option must change the chunk-size distribution visible in Parquet metadata." + }, + "python/pyarrow/tests/parquet/test_parquet_writer_cdc_aug.py::test_cdc_true_changes_layout_vs_false_on_string_column": { + "test_level": "public-api-synthetic", + "surface_reason": "Writes a multi-MiB string column with use_content_defined_chunking=True vs False; CDC=True must produce larger total_byte_size.", + "public_surface": "pyarrow.parquet.write_table, pyarrow.parquet.read_metadata, pyarrow.parquet.read_table", + "internal_symbol_check": [ + "parquet::internal", + "_parquet.", + "pyarrow._parquet", + "_Weakrefable", + "CdcOptions" + ], + "runner_surface": "pytest python/pyarrow/tests/parquet/test_parquet_writer_cdc_aug.py::test_cdc_true_changes_layout_vs_false_on_string_column", + "kills_mutants": [ + "mutant_001_python_bool_true_disables_cdc", + "mutant_004_column_writer_does_not_flush_chunk_pages" + ], + "covers_new_surface": "chunker_internal.cc string/binary-typed dispatch (the existing F2P uses int64 only)", + "synthetic_author": "lolbench-aug", + "oracle_kind": "requirement-driven", + "target_requirement": "Section: Rationale (CDC chunking applies to data of any type, not only numeric)", + "requirement_sections": [ + "Rationale" + ], + "mutants_targeted": [ + "mutant_001_python_bool_true_disables_cdc", + "mutant_004_column_writer_does_not_flush_chunk_pages" + ], + "rationale": "The Rationale requires CDC to work for general Parquet data and consistently chunk identical segments; exercising a large string column verifies that the public boolean option reaches CDC layout generation beyond the original numeric-only case." + }, + "python/pyarrow/tests/parquet/test_parquet_writer_cdc_aug.py::test_cdc_true_determinism_across_repeated_writes": { + "test_level": "public-api-synthetic", + "surface_reason": "Two repeated writes of the same table with CDC=True must yield byte-identical row-group structure (deterministic chunker).", + "public_surface": "pyarrow.parquet.write_table, pyarrow.parquet.read_metadata", + "internal_symbol_check": [ + "parquet::internal", + "_parquet.", + "pyarrow._parquet", + "_Weakrefable", + "CdcOptions" + ], + "runner_surface": "pytest python/pyarrow/tests/parquet/test_parquet_writer_cdc_aug.py::test_cdc_true_determinism_across_repeated_writes", + "kills_mutants": [], + "covers_new_surface": "exercises CDC path twice; reinforces F2P-cov, sanity-checks determinism clause from Rationale", + "synthetic_author": "lolbench-aug", + "oracle_kind": "requirement-driven", + "target_requirement": "Section: Rationale ('identical data segments are consistently chunked in the same manner')", + "requirement_sections": [ + "Rationale" + ], + "mutants_targeted": [], + "rationale": "The Rationale states that identical data segments should be consistently chunked in the same manner; repeated public writes of the same table should therefore produce identical row-group layout metadata." + }, + "python/pyarrow/tests/parquet/test_parquet_writer_cdc_aug.py::test_cdc_mixed_physical_layouts_roundtrip_and_change_layout": { + "test_level": "public-api-synthetic", + "surface_reason": "Writes a mixed public Arrow table with CDC enabled and disabled; observes metadata-visible layout change and public read_table round-trip for nullable, nested, boolean, fixed-size-binary, large-string, decimal, and dictionary columns.", + "public_surface": "pyarrow.parquet.write_table, pyarrow.parquet.read_table, pyarrow.parquet.read_metadata", + "internal_symbol_check": [ + "parquet::internal", + "_parquet.", + "pyarrow._parquet", + "_Weakrefable", + "CdcOptions" + ], + "runner_surface": "pytest python/pyarrow/tests/parquet/test_parquet_writer_cdc_aug.py::test_cdc_mixed_physical_layouts_roundtrip_and_change_layout", + "kills_mutants": [ + "mutant_001_python_bool_true_disables_cdc", + "mutant_004_column_writer_does_not_flush_chunk_pages" + ], + "covers_new_surface": "chunker_internal.cc nullable fixed-width, nested repetition/definition levels, boolean, fixed-size binary, large binary-like, decimal, and dictionary-index dispatch; column_writer.cc CDC chunk loop across dictionary and dense Arrow paths", + "synthetic_author": "lolbench-aug", + "oracle_kind": "requirement-driven", + "target_requirement": "Section: Rationale (CDC applies across Arrow physical layouts while preserving public Parquet round-trip semantics)", + "requirement_sections": [ + "Rationale" + ], + "mutants_targeted": [ + "mutant_001_python_bool_true_disables_cdc", + "mutant_004_column_writer_does_not_flush_chunk_pages" + ], + "rationale": "The Rationale frames CDC as a Parquet writer feature for data segments, not only int64 or string arrays; a mixed public Arrow table exercises additional physical layouts and verifies the opt-in CDC path changes page layout without breaking read_table round-trip behavior." + } + }, + "pass_to_pass": { + "python/pyarrow/tests/parquet/test_parquet_writer_stability_aug.py::test_writer_default_no_cdc_arg_roundtrip": { + "test_level": "public-api-synthetic", + "surface_reason": "Calls pq.write_table with no CDC argument; verifies pre-existing default round-trip is unchanged.", + "public_surface": "pyarrow.parquet.write_table, pyarrow.parquet.read_table", + "internal_symbol_check": [ + "parquet::internal", + "_parquet.", + "pyarrow._parquet", + "_Weakrefable", + "CdcOptions" + ], + "runner_surface": "pytest python/pyarrow/tests/parquet/test_parquet_writer_stability_aug.py::test_writer_default_no_cdc_arg_roundtrip", + "no_modification_clause": "additive-optional-parameter (default writer behavior preserved)", + "synthetic_author": "lolbench-aug", + "oracle_kind": "requirement-driven", + "requirement_sections": [ + "Rationale" + ], + "rationale": "CDC is introduced as an optional writer feature, so calling write_table without the new option must preserve the existing default round-trip contract." + }, + "python/pyarrow/tests/parquet/test_parquet_writer_stability_aug.py::test_writer_compression_snappy_roundtrip_unchanged": { + "test_level": "public-api-synthetic", + "surface_reason": "Exercises pre-existing compression='snappy' writer argument; must continue to work with no CDC argument.", + "public_surface": "pyarrow.parquet.write_table, pyarrow.parquet.read_metadata", + "internal_symbol_check": [ + "parquet::internal", + "_parquet.", + "pyarrow._parquet", + "_Weakrefable", + "CdcOptions" + ], + "runner_surface": "pytest python/pyarrow/tests/parquet/test_parquet_writer_stability_aug.py::test_writer_compression_snappy_roundtrip_unchanged", + "no_modification_clause": "pre-existing 'compression' arg semantics unchanged", + "synthetic_author": "lolbench-aug", + "oracle_kind": "requirement-driven", + "requirement_sections": [ + "Rationale" + ], + "rationale": "The CDC patch must not change pre-existing compression semantics for files written without the new CDC option." + }, + "python/pyarrow/tests/parquet/test_parquet_writer_stability_aug.py::test_writer_data_page_size_unchanged": { + "test_level": "public-api-synthetic", + "surface_reason": "Pre-existing data_page_size argument: smaller page size must produce a measurably larger total_byte_size.", + "public_surface": "pyarrow.parquet.write_table, pyarrow.parquet.read_metadata", + "internal_symbol_check": [ + "parquet::internal", + "_parquet.", + "pyarrow._parquet", + "_Weakrefable", + "CdcOptions" + ], + "runner_surface": "pytest python/pyarrow/tests/parquet/test_parquet_writer_stability_aug.py::test_writer_data_page_size_unchanged", + "no_modification_clause": "pre-existing 'data_page_size' arg semantics unchanged", + "synthetic_author": "lolbench-aug", + "oracle_kind": "requirement-driven", + "requirement_sections": [ + "Rationale" + ], + "rationale": "The CDC patch must not change pre-existing data_page_size behavior when content-defined chunking is not requested." + }, + "python/pyarrow/tests/parquet/test_parquet_writer_stability_aug.py::test_parquet_writer_context_manager_default_path": { + "test_level": "public-api-synthetic", + "surface_reason": "pq.ParquetWriter usable as a context manager with no CDC argument; round-trip preserved.", + "public_surface": "pyarrow.parquet.ParquetWriter, pyarrow.parquet.read_table", + "internal_symbol_check": [ + "parquet::internal", + "_parquet.", + "pyarrow._parquet", + "_Weakrefable", + "CdcOptions" + ], + "runner_surface": "pytest python/pyarrow/tests/parquet/test_parquet_writer_stability_aug.py::test_parquet_writer_context_manager_default_path", + "no_modification_clause": "ParquetWriter constructor signature and context-manager protocol unchanged", + "synthetic_author": "lolbench-aug", + "oracle_kind": "requirement-driven", + "requirement_sections": [ + "Rationale" + ], + "rationale": "ParquetWriter construction, context-manager close semantics, and write_table behavior are adjacent public writer functionality that must remain stable without CDC." + }, + "python/pyarrow/tests/parquet/test_parquet_writer_stability_aug.py::test_read_metadata_for_default_file_unchanged_shape": { + "test_level": "public-api-synthetic", + "surface_reason": "Read-side: pq.read_metadata returns expected num_rows/num_columns/schema for a default-written file.", + "public_surface": "pyarrow.parquet.read_metadata, pyarrow.parquet.write_table", + "internal_symbol_check": [ + "parquet::internal", + "_parquet.", + "pyarrow._parquet", + "_Weakrefable", + "CdcOptions" + ], + "runner_surface": "pytest python/pyarrow/tests/parquet/test_parquet_writer_stability_aug.py::test_read_metadata_for_default_file_unchanged_shape", + "no_modification_clause": "read_metadata semantics on default-written files unchanged", + "synthetic_author": "lolbench-aug", + "oracle_kind": "requirement-driven", + "requirement_sections": [ + "Rationale" + ], + "rationale": "Read-side metadata for default-written files is outside the CDC opt-in surface and should retain its existing row/column/schema reporting behavior." + }, + "python/pyarrow/tests/parquet/test_parquet_writer_stability_aug.py::test_parquet_file_read_row_group_default_unchanged": { + "test_level": "public-api-synthetic", + "surface_reason": "Read-side: pq.ParquetFile.read_row_group must work on a default-written file (no CDC argument).", + "public_surface": "pyarrow.parquet.ParquetFile, pyarrow.parquet.write_table", + "internal_symbol_check": [ + "parquet::internal", + "_parquet.", + "pyarrow._parquet", + "_Weakrefable", + "CdcOptions" + ], + "runner_surface": "pytest python/pyarrow/tests/parquet/test_parquet_writer_stability_aug.py::test_parquet_file_read_row_group_default_unchanged", + "no_modification_clause": "ParquetFile.read_row_group on default-written files unchanged", + "synthetic_author": "lolbench-aug", + "oracle_kind": "requirement-driven", + "requirement_sections": [ + "Rationale" + ], + "rationale": "ParquetFile.read_row_group on default-written files is unrelated reader functionality and should remain unchanged by CDC writer plumbing." + } + }, + "test_level_policy": "The augmented F2P suite drives Apache Arrow content-defined chunking through public pyarrow.parquet writer/reader APIs only: write_table, read_table, read_metadata, and metadata-visible file layout differences. The augmented P2P suite omits use_content_defined_chunking and pins pre-existing Parquet writer, metadata, compression, data_page_size, ParquetWriter context-manager, and ParquetFile read-row-group behavior so unrelated public functionality remains stable." + }, + "validation_status": "validated", + "validation_status_note": "Fresh Arrow PR-45360 validation passed end-to-end for orig, aug, and union suites; all 4 committed mutants were killed by F2P while P2P stayed clean. 2026-06-15 P2P expansion added 17 base-verified original selectors; refreshed union coverage is 88.3% (188/213), above the required 80% threshold.", + "fixture_taint_summary": "eval_tests_aug.patch creates two brand-new test files in python/pyarrow/tests/parquet/ (test_parquet_writer_cdc_aug.py and test_parquet_writer_stability_aug.py); no existing file is touched. Both new files use only the project's built-in pytest 'tempdir' fixture (per-test fresh temporary directory; neutral for chunking/encoding tests; unaffected by the PR) and import only `pyarrow` and `pyarrow.parquet` at the top level. No conftest fixtures from the project, no class-level setUp/tearDown, no shared module-level state. F2P-mut targets surviving mutants 001/003/004; mutant_002 is already fully killed by the original F2P and is multi-killed for robustness. P2P pins 6 no-modification clauses; a 7th column_encoding probe was attempted but dropped \u2014 see test source for rationale.", + "validated_at": "2026-06-02T03:31:31Z", + "f2p_aug_sha256": "416a20ec6aba6a223e0710f11924d10262722fb641e68f94a450e02886935d2c", + "p2p_aug_sha256": "750d4faa1b457e9bcee8cb81b79f2a03f828a23ddf33bdb1179ee08beae5372a", + "coverage": { + "orig_union_pct": 66.7, + "orig_union_covered": 142, + "aug_union_pct": 86.6, + "aug_union_covered": 181, + "combined_union_pct": 88.3, + "combined_union_covered": 188, + "executable_lines_in_patch": 213 + }, + "test_level_policy": "The augmented F2P suite drives Apache Arrow content-defined chunking through public pyarrow.parquet writer/reader APIs only: write_table, read_table, read_metadata, and metadata-visible file layout differences. The augmented P2P suite omits use_content_defined_chunking and pins pre-existing Parquet writer, metadata, compression, data_page_size, ParquetWriter context-manager, and ParquetFile read-row-group behavior so unrelated public functionality remains stable." + }, + "base_commit": "12424cdf2fda068e973ebd89cda045fee297943a", + "pr_link": "https://github.com/apache/arrow/pull/45360", + "pr_head_sha": "1cc2e4b690e467f548dc4131f9b392a864a132aa", + "merge_commit_sha": "1cc2e4b690e467f548dc4131f9b392a864a132aa", + "diff_source": "github_pr_cache", + "coverage": { + "orig": 66.7, + "aug": 84.98, + "union": 88.3, + "denominator": "union_executable_lines" + }, + "p2p_entry_count": 44, + "p2p_aug_entry_count": 6, + "p2p_union_entry_count": 50, + "p2p_sha256": "ce5db44859d55c508df47e31a1700b40440c54c6311ec57ad243f96a97766a61" +} \ No newline at end of file diff --git a/arrow_2/tests/report_to_reward.py b/arrow_2/tests/report_to_reward.py new file mode 100644 index 0000000000000000000000000000000000000000..6cf8702344184abe061244534ea1bb93d6287760 --- /dev/null +++ b/arrow_2/tests/report_to_reward.py @@ -0,0 +1,73 @@ +#!/usr/bin/env python3 +import argparse +import json +from pathlib import Path + + +def rate(bucket): + total = float(bucket.get("total", 0) or 0) + if total <= 0: + return 0.0 + return float(bucket.get("passed", 0) or 0) / total + + +def write_json(path, payload): + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(json.dumps(payload, indent=2, sort_keys=True) + "\n") + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument("--suite", default="union") + parser.add_argument("--missing-patch") + parser.add_argument("--invalid-suite", action="store_true") + parser.add_argument("--runner-rc", type=int, default=0) + parser.add_argument("agent_report") + parser.add_argument("reward_file") + args = parser.parse_args() + + report_path = Path(args.agent_report) + reward_path = Path(args.reward_file) + + if args.invalid_suite: + reward = {"reward": 0.0, "resolved": 0.0, "applied": 0.0, "build_ok": 0.0, "f2p_pass_rate": 0.0, "p2p_pass_rate": 0.0, "harness_ok": 1.0} + sanitized = {"instance_id": "arrow_2", "suite": args.suite, "applied": False, "resolved": False, "error_categories": ["invalid_lolbench_suite"]} + write_json(report_path, sanitized) + write_json(reward_path, reward) + print(f"LoLBench reward=0 invalid suite {args.suite!r}") + return 0 + + if args.missing_patch: + reward = {"reward": 0.0, "resolved": 0.0, "applied": 0.0, "build_ok": 0.0, "f2p_pass_rate": 0.0, "p2p_pass_rate": 0.0, "harness_ok": 1.0} + sanitized = {"instance_id": "arrow_2", "suite": args.suite, "applied": False, "resolved": False, "error_categories": ["missing_solution_patch"]} + write_json(report_path, sanitized) + write_json(reward_path, reward) + print("LoLBench reward=0 missing solution patch") + return 0 + + if not report_path.exists(): + reward = {"reward": 0.0, "resolved": 0.0, "applied": 0.0, "build_ok": 0.0, "f2p_pass_rate": 0.0, "p2p_pass_rate": 0.0, "harness_ok": 0.0} + write_json(reward_path, reward) + print(f"LoLBench reward=0 no agent_report.json runner_rc={args.runner_rc}") + return 0 + + report = json.loads(report_path.read_text()) + build_status = report.get("build", {}).get("status") + resolved = bool(report.get("resolved")) + applied = bool(report.get("applied")) + reward = { + "reward": 1.0 if resolved else 0.0, + "resolved": 1.0 if resolved else 0.0, + "applied": 1.0 if applied else 0.0, + "build_ok": 1.0 if build_status == "ok" else 0.0, + "f2p_pass_rate": rate(report.get("f2p", {})), + "p2p_pass_rate": rate(report.get("p2p", {})), + "harness_ok": 1.0 if args.runner_rc == 0 else 0.0, + } + write_json(reward_path, reward) + print("LoLBench reward={reward} resolved={resolved} f2p={f2p_pass_rate:.3f} p2p={p2p_pass_rate:.3f}".format(**reward)) + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/arrow_2/tests/test.sh b/arrow_2/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..45ba2abd4f682d021752e6966a772a0ee2edb9f5 --- /dev/null +++ b/arrow_2/tests/test.sh @@ -0,0 +1,43 @@ +#!/usr/bin/env bash +set -euo pipefail + +suite=${LOLBENCH_SUITE:-union} +mode=${LOLBENCH_MODE:-eval} +patch=${LOLBENCH_SOLUTION_PATCH:-/logs/artifacts/solution.patch} +private_log=/tmp/lolbench-private-run.log + +mkdir -p /logs/verifier /logs/artifacts /in /out + +case "$suite" in + orig|aug|union) ;; + *) + python3 /tests/report_to_reward.py --suite "$suite" --invalid-suite /out/agent_report.json /logs/verifier/reward.json + exit 0 + ;; +esac + +if [ "$mode" = "eval" ] && [ ! -s "$patch" ]; then + python3 /tests/report_to_reward.py --suite "$suite" --missing-patch "$patch" /out/agent_report.json /logs/verifier/reward.json + exit 0 +fi + +if [ "$mode" = "eval" ]; then + cp "$patch" /in/solution.patch + chmod 0400 /in/solution.patch +fi + +set +e +LOLBENCH_MODE="$mode" LOLBENCH_SUITE="$suite" /opt/lolbench/private/run_tests.sh >"$private_log" 2>&1 +runner_rc=$? +set -e + +cp "$private_log" /logs/verifier/private_run.log +if [ -f /out/grader_report.json ]; then + cp /out/grader_report.json /logs/verifier/grader_report.json +fi + +python3 /tests/report_to_reward.py --suite "$suite" --runner-rc "$runner_rc" /out/agent_report.json /logs/verifier/reward.json + +if [ -f /out/agent_report.json ]; then + cp /out/agent_report.json /logs/verifier/agent_report.json +fi diff --git a/aspnetcore_1/README.md b/aspnetcore_1/README.md new file mode 100644 index 0000000000000000000000000000000000000000..8c4dbd054916b4d279ac51fbdffc38b83cd5e91b --- /dev/null +++ b/aspnetcore_1/README.md @@ -0,0 +1,87 @@ +# LoLBench Harbor Task: aspnetcore_1 + +This is a Harbor-format LoLBench task generated from `ASP.NET-Core_Issue-62883_PR-62816`. + +Selected source instance: + +- Harbor ID: `aspnetcore_1` +- PR: `dotnet/aspnetcore#62816` +- Base commit: `c56ce2f92858158819569e11d4131c09fd847764` +- Test modes: `orig, aug, union` +- Default/canonical mode: `union` +- Harbor image: `smartdub26/lolbench-linux:aspnetcore_1-1.0.0` +- Docker Hub image: `smartdub26/lolbench-linux:aspnetcore_1-1.0.0` + +## Image Setup + +Prefer the published Docker Hub image when it is available. Harbor refers to +the image as `smartdub26/lolbench-linux:aspnetcore_1-1.0.0`, so Docker can pull it +directly when it is not present locally: + +```bash +docker pull smartdub26/lolbench-linux:aspnetcore_1-1.0.0 +``` + +Only if the Docker Hub image is unavailable, build the single task image +locally: + +```bash +docker build -t lolbench/aspnetcore_1:1.0.0 harbor_tasks/aspnetcore_1/environment +docker tag lolbench/aspnetcore_1:1.0.0 smartdub26/lolbench-linux:aspnetcore_1-1.0.0 +``` + +The image contains the processed source tree at the base commit under +`/workspace/aspnetcore`. Harbor must not mount a host source checkout +for the agent. + +## Run an Agent + +```bash +.harbor-venv/bin/harbor run \ + -p harbor_tasks/aspnetcore_1 \ + -a codex \ + -m "" \ + --job-name aspnetcore_1_agent_union \ + --jobs-dir harbor_runs/aspnetcore_1 \ + --no-delete \ + --n-concurrent 1 \ + --ve LOLBENCH_SUITE=union +``` + +After implementing the requirement, the agent must clean any test-file edits +and run: + +```bash +lolbench-submit +``` + +## Evaluate a Patch + +Choose one mode with `LOLBENCH_SUITE=orig`, `aug`, or `union`; if unset, the +task defaults to `union`. + +```bash +PATCH="$(pwd)/path/to/solution.patch" + +.harbor-venv/bin/harbor run \ + -p harbor_tasks/aspnetcore_1 \ + -a oracle \ + --job-name aspnetcore_1_eval_union \ + --jobs-dir harbor_runs/aspnetcore_1 \ + --no-delete \ + --n-concurrent 1 \ + --mounts '[{"type":"bind","source":"'"$PATCH"'","target":"/candidate/solution.patch","read_only":true}]' \ + --ae LOLBENCH_ORACLE_PATCH=/candidate/solution.patch \ + --ve LOLBENCH_SUITE=union +``` + +Outputs: + +```bash +find harbor_runs/aspnetcore_1/aspnetcore_1_eval_union -path '*/verifier/agent_report.json' -print +find harbor_runs/aspnetcore_1/aspnetcore_1_eval_union -path '*/verifier/reward.json' -print +``` + +`tests/docker-compose.yaml` is a verifier-only Harbor overlay. It mounts +`tests/`, `tests/private/`, and `solution/` into the separate verifier +container; none of those paths are mounted into the agent container. diff --git a/aspnetcore_1/environment/Dockerfile b/aspnetcore_1/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..6b808d6d47faf97822b1bfc3ac46d864a80c132e --- /dev/null +++ b/aspnetcore_1/environment/Dockerfile @@ -0,0 +1,135 @@ +# syntax=docker/dockerfile:1 +# LoLBench eval image: ASP.NET Core PR-62816 (IApiEndpointMetadata) +# +# Restore the architecture-neutral NuGet packages and managed build artifacts on +# the native build platform. Running the preview .NET SDK under QEMU during an +# ARM64 build is not reliable (CoreCLR can abort mid-restore), which otherwise +# leaves an image that cannot execute the verifier with --network=none. +ARG BUILDPLATFORM +ARG TARGETPLATFORM +ARG TARGETARCH +FROM --platform=$BUILDPLATFORM mcr.microsoft.com/dotnet/sdk:10.0-preview AS offline_cache +ARG TARGETARCH +RUN apt-get update && apt-get install -y --no-install-recommends \ + git python3 openjdk-17-jdk-headless curl ca-certificates && rm -rf /var/lib/apt/lists/* +ENV DOTNET_CLI_TELEMETRY_OPTOUT=1 DOTNET_NOLOGO=1 DOTNET_SKIP_FIRST_TIME_EXPERIENCE=1 \ + JAVA_HOME=/usr/lib/jvm/java-17-openjdk-amd64 +RUN mkdir -p /opt/lolbench/private /in /out /workspace +WORKDIR /workspace +ARG BASE_COMMIT=c56ce2f92858158819569e11d4131c09fd847764 +# Blobless shallow checkout at the instance base. Apply the env-compat pin bump +# (expired daily-build beta arcade SDKs: beta.25372.103 -> .107, the nearest in-feed +# version of the same band; MSBuild SDK versions do not roll forward -> MSB4236) and +# commit it as an ancestor-preserving LoLBench baseline so `git reset --hard base` in run_tests.sh +# preserves it. The bump is orthogonal to the PR diff (touches only global.json + +# eng/Versions.props) and is applied identically at pre/post, so it does not mask the +# F2P compile-flip. +RUN git init -q aspnetcore && cd aspnetcore && \ + git remote add origin https://github.com/dotnet/aspnetcore.git && \ + git -c protocol.version=2 fetch --no-tags origin ${BASE_COMMIT} && \ + git checkout -q FETCH_HEAD && \ + sed -i 's/beta\.25372\.103/beta.25372.107/g' global.json eng/Versions.props && \ + git config user.email lolbench@local && \ + git config user.name lolbench && \ + if ! git diff --quiet || ! git diff --cached --quiet || [ -n "$(git ls-files --others --exclude-standard)" ]; then \ + git add -A && git -c commit.gpgsign=false commit -q -m "LoLBench environment overlay"; \ + fi && \ + git tag -f base && git tag -f lolbench-base && \ + git for-each-ref --format='%(refname)' refs/heads refs/remotes refs/tags | \ + while read ref; do \ + case "$ref" in refs/tags/base|refs/tags/lolbench-base) ;; *) git update-ref -d "$ref" ;; esac; \ + done && \ + ( git remote remove origin 2>/dev/null || true ) && \ + rm -f .git/FETCH_HEAD && \ + git reflog expire --expire=now --all && \ + git repack -Ad && \ + git prune --expire=now && \ + git config --global --add safe.directory /workspace/aspnetcore +WORKDIR /workspace/aspnetcore +# Arcade bootstrap: provisions .dotnet (exact pinned SDK), generates the +# artifacts/bin/GenerateFiles props every project imports, restores packages. +# warn-as-error OFF: the base pins daily-build betas that rolled forward (NU1603). +RUN ./restore.sh --warnaserror false /p:TreatWarningsAsErrors=false 2>&1 | tail -8 && \ + test -f artifacts/bin/GenerateFiles/Directory.Build.props && echo "PROPS OK" +# Pre-warm: build the F2P + P2P test projects at base (warms App.Ref/App.Runtime + +# the auth/abstractions assemblies; artifacts/ and .dotnet/ are gitignored so +# `git clean -fd` keeps them and validate runs incrementally). +RUN ./.dotnet/dotnet build src/Security/Authentication/test/Microsoft.AspNetCore.Authentication.Test.csproj \ + --warnaserror:false -p:TreatWarningsAsErrors=false 2>&1 | tail -4 || true +RUN ./.dotnet/dotnet build src/Http/Http.Abstractions/test/Microsoft.AspNetCore.Http.Abstractions.Tests.csproj \ + --warnaserror:false -p:TreatWarningsAsErrors=false 2>&1 | tail -4 || true +# Pre-warm the augmented-suite host projects too (same incremental-build rationale). +RUN ./.dotnet/dotnet build src/Http/Http.Results/test/Microsoft.AspNetCore.Http.Results.Tests.csproj \ + --warnaserror:false -p:TreatWarningsAsErrors=false 2>&1 | tail -2 || true +RUN ./.dotnet/dotnet build src/Http/Http.Extensions/test/Microsoft.AspNetCore.Http.Extensions.Tests.csproj \ + --warnaserror:false -p:TreatWarningsAsErrors=false 2>&1 | tail -2 || true +RUN ./.dotnet/dotnet build src/SignalR/common/Http.Connections/test/Microsoft.AspNetCore.Http.Connections.Tests.csproj \ + --warnaserror:false -p:TreatWarningsAsErrors=false 2>&1 | tail -2 || true +RUN ./.dotnet/dotnet build src/Mvc/Mvc.Core/test/Microsoft.AspNetCore.Mvc.Core.Test.csproj \ + --warnaserror:false -p:TreatWarningsAsErrors=false 2>&1 | tail -2 || true +RUN ./.dotnet/dotnet build src/Mvc/Mvc.ApiExplorer/test/Microsoft.AspNetCore.Mvc.ApiExplorer.Test.csproj \ + --warnaserror:false -p:TreatWarningsAsErrors=false 2>&1 | tail -2 || true + +# Preserve the native restore cache and prepare the exact target SDK without +# executing target-architecture CoreCLR. The ASP.NET build artifacts and NuGet +# packages used by these tests are managed/architecture-neutral. +RUN /bin/bash -c 'case "$TARGETARCH" in \ + amd64) dotnet_arch=x64 ;; \ + arm64) dotnet_arch=arm64 ;; \ + *) echo "Unsupported TARGETARCH=$TARGETARCH" >&2; exit 1 ;; \ + esac && \ + if [ "$dotnet_arch" = x64 ]; then \ + mv .dotnet /opt/target-dotnet; \ + else \ + . eng/common/tools.sh && \ + InstallDotNetSdk /opt/target-dotnet 10.0.100-preview.7.25322.101 "$dotnet_arch" && \ + rm -rf .dotnet; \ + fi && \ + test -f /opt/target-dotnet/sdk/10.0.100-preview.7.25322.101/dotnet.dll' + +FROM --platform=$TARGETPLATFORM mcr.microsoft.com/dotnet/sdk:10.0-preview +ARG TARGETARCH +RUN apt-get update && apt-get install -y --no-install-recommends \ + git python3 openjdk-17-jdk-headless curl ca-certificates && rm -rf /var/lib/apt/lists/* +ENV DOTNET_CLI_TELEMETRY_OPTOUT=1 DOTNET_NOLOGO=1 DOTNET_SKIP_FIRST_TIME_EXPERIENCE=1 \ + JAVA_HOME=/usr/lib/jvm/java-17-openjdk-${TARGETARCH} +RUN mkdir -p /opt/lolbench/private /in /out /workspace +COPY --from=offline_cache /root/.nuget /root/.nuget +COPY --from=offline_cache /workspace/aspnetcore /workspace/aspnetcore +COPY --from=offline_cache /opt/target-dotnet /workspace/aspnetcore/.dotnet +WORKDIR /workspace/aspnetcore + +# Target-oracle hardening: the floating SDK base also installs a newer ASP.NET +# Core runtime, reference pack, XML documentation, and RDG analyzer under +# /usr/share/dotnet. That system toolchain already contains the completed +# IApiEndpointMetadata feature. The repository bootstrap above provisioned the +# pinned, feature-predating toolchain in .dotnet, so retain that toolchain as +# the only globally invokable dotnet installation. +RUN rm -rf /usr/share/dotnet && \ + rm -f /usr/bin/dotnet /usr/local/bin/dotnet && \ + ln -s /workspace/aspnetcore/.dotnet/dotnet /usr/bin/dotnet && \ + ln -s /workspace/aspnetcore/.dotnet/dotnet /usr/local/bin/dotnet && \ + test "$(readlink -f /usr/bin/dotnet)" = /workspace/aspnetcore/.dotnet/dotnet && \ + dotnet --list-sdks | grep -F '10.0.100-preview.7.25322.101' && \ + ! grep -R -a -l -E 'IApiEndpointMetadata|ApiEndpointMetadata' \ + /workspace/aspnetcore/.dotnet >/tmp/aspnetcore-target-oracle-leaks.txt && \ + test ! -s /tmp/aspnetcore-target-oracle-leaks.txt && \ + rm -f /tmp/aspnetcore-target-oracle-leaks.txt + +# Harbor runtime adapter: keep the image public/agent-safe. +RUN mkdir -p /opt/lolbench /logs/artifacts /logs/agent /logs/verifier /in /out && \ + if ! id -u agent >/dev/null 2>&1; then useradd -m -s /bin/bash agent; fi +COPY metadata.json /opt/lolbench/metadata.json +COPY lolbench-submit /usr/local/bin/lolbench-submit +RUN chmod +x /usr/local/bin/lolbench-submit && \ + git config --global --add safe.directory /workspace/aspnetcore && \ + if [ -d /workspace/aspnetcore/.git ]; then \ + cd /workspace/aspnetcore && LC_ALL=C git ls-files --others --exclude-standard | LC_ALL=C sort > /opt/lolbench/base_untracked.txt; \ + else \ + : > /opt/lolbench/base_untracked.txt; \ + fi && \ + chown -R agent:agent /workspace/aspnetcore /logs +USER agent +WORKDIR /workspace/aspnetcore +ENV LOLBENCH_INSTANCE_ID=aspnetcore_1 +ENV LOLBENCH_SOURCE_SLUG=ASP.NET-Core_Issue-62883_PR-62816 diff --git a/aspnetcore_1/environment/docker-compose.yaml b/aspnetcore_1/environment/docker-compose.yaml new file mode 100644 index 0000000000000000000000000000000000000000..7ed45f87dc9faf9df284f5b10d6d2289781ff254 --- /dev/null +++ b/aspnetcore_1/environment/docker-compose.yaml @@ -0,0 +1,3 @@ +services: + main: + pull_policy: missing diff --git a/aspnetcore_1/environment/lolbench-submit b/aspnetcore_1/environment/lolbench-submit new file mode 100644 index 0000000000000000000000000000000000000000..b3426184f1a568aaf145f148348c3c5e85cfa773 --- /dev/null +++ b/aspnetcore_1/environment/lolbench-submit @@ -0,0 +1,33 @@ +#!/usr/bin/env bash +set -euo pipefail +export LC_ALL=C + +repo=${1:-$PWD} +out=${LOLBENCH_PATCH_OUT:-/logs/artifacts/solution.patch} + +mkdir -p "$(dirname "$out")" +cd "$repo" + +baseline=/opt/lolbench/base_untracked.txt +current=$(mktemp) +new_files=$(mktemp) +trap 'rm -f "$current" "$new_files"' EXIT + +git ls-files --others --exclude-standard | sort > "$current" +if [ -f "$baseline" ]; then + comm -13 "$baseline" "$current" > "$new_files" +else + cp "$current" "$new_files" +fi + +if [ -s "$new_files" ]; then + xargs -r git add -N -- < "$new_files" +fi + +git diff --binary > "$out" + +if [ ! -s "$out" ]; then + echo "warning: wrote an empty solution patch to $out" >&2 +else + echo "wrote solution patch to $out" +fi diff --git a/aspnetcore_1/environment/metadata.json b/aspnetcore_1/environment/metadata.json new file mode 100644 index 0000000000000000000000000000000000000000..de5f9dd5b067e047be0e4242fc839506b9e5476b --- /dev/null +++ b/aspnetcore_1/environment/metadata.json @@ -0,0 +1,22 @@ +{ + "instance_id": "aspnetcore_1", + "source_instance_id": "ASP.NET-Core_Issue-62883_PR-62816", + "source_slug": "ASP.NET-Core_Issue-62883_PR-62816", + "docker_slug": "ASP.NET-Core_Issue-62883_PR-62816", + "dockerhub_image": "smartdub26/lolbench-linux:aspnetcore_1-1.0.0", + "project": "aspnetcore", + "repo": "dotnet/aspnetcore", + "requirement_doc": "https://github.com/dotnet/aspnetcore/issues/62883", + "pr_link": "https://github.com/dotnet/aspnetcore/pull/62816", + "base_commit": "c56ce2f92858158819569e11d4131c09fd847764", + "merge_commit": "295944574c37f46859348d6fcd3d5adf48c70bf7", + "source_history_policy": "ancestors-only", + "lolbench_test_modes": [ + "orig", + "aug", + "union" + ], + "default_lolbench_suite": "union", + "canonical_lolbench_suite": "union", + "augmentation_available": true +} diff --git a/aspnetcore_1/environment/source_audit.json b/aspnetcore_1/environment/source_audit.json new file mode 100644 index 0000000000000000000000000000000000000000..c527d279f49e28cf17a4a8fd9513fc9b9a822f12 --- /dev/null +++ b/aspnetcore_1/environment/source_audit.json @@ -0,0 +1,6 @@ +{ + "source_policy": "dockerfile_fetch_historyless_base_snapshot", + "base_commit": "c56ce2f92858158819569e11d4131c09fd847764", + "repo": "dotnet/aspnetcore", + "note": "The generated Dockerfile fetches the base commit with ancestor history, preserves .git, removes post-base refs/remotes/reflogs, and prunes unreachable future commit objects during image build. It also removes the floating system .NET SDK/runtime/reference packs after pre-warming and retains only the repository-pinned, feature-predating .dotnet toolchain." +} diff --git a/aspnetcore_1/instruction.md b/aspnetcore_1/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..0daf18be460764956767186793385cb3e19d45fa --- /dev/null +++ b/aspnetcore_1/instruction.md @@ -0,0 +1,110 @@ +You are working in `/workspace/aspnetcore`, a source tree checked out at +the base commit for this task. Implement the requested behavior in the source +tree, then run: + +```bash +lolbench-submit +``` + +Do not stop after editing files, running tests, or describing the solution. The +task is complete only when `lolbench-submit` has created +`/logs/artifacts/solution.patch`. If that file does not exist, continue +working and run `lolbench-submit` again. + +That command writes your implementation diff to +`/logs/artifacts/solution.patch`, which is the artifact the Harbor verifier +will grade. Before running `lolbench-submit`, clean or revert any test files +you created or modified; test files must not be included in the final +`solution.patch`. + +This environment has no outbound internet access — `curl`/`wget`, `git fetch`/`clone`, package installs, and web fetch/search will all fail. Implement the requirements using only the code already in the workspace and your own knowledge; do not attempt to fetch or search external resources. + +Now please implement the following requirements in the source tree: + +--- + +# API Proposal for IApiEndpointMetadata + +## Background and Motivation + +This proposal introduces `IApiEndpointMetadata` as a new public API in ASP.NET Core. The goal is to provide a standardized metadata interface for identifying API endpoints. The primary use case is to avoid cookie login redirects for known API endpoints as described in #9039. + +There is already a PR open for this at #62816 + +This metadata is automatically applied to endpoints in several scenarios: +- Endpoints using RDF/RDG that read a JSON request body or write a JSON response body. +- Endpoints attributed with `ApiController`. +- SignalR endpoints. +- Endpoints with `TypedResults` return types that are recognized as API-oriented. + +This change aims to improve discoverability and handling of API endpoints in ASP.NET Core, particularly for scenarios like avoiding cookie login redirects for APIs. + +## Proposed API + +```diff +namespace Microsoft.AspNetCore.Http; + ++ public interface IApiEndpointMetadata ++ { ++ } +``` + +No new attributes or extension methods are introduced in this PR, but the `IApiEndpointMetadata` interface is automatically assigned to qualifying endpoints. + +## Usage Examples + +```csharp +// Example: Checking for API endpoint metadata in middleware +public class ApiEndpointMiddleware +{ + public async Task InvokeAsync(HttpContext context, RequestDelegate next) + { + var endpoint = context.GetEndpoint(); + if (endpoint?.Metadata.GetMetadata() != null) + { + // This is an API endpoint, apply API-specific logic + } + await next(context); + } +} + +// Example: Custom endpoint definition +app.MapPost("/api/data", (MyData data) => +{ + // This endpoint will automatically get IApiEndpointMetadata + return TypedResults.Json(data); +}); +``` + +## Alternative Designs + +- We could pick a different name like `IApiMetadata`. Most other `Endpoint.Metadata` types end in just "Metadata". Or we can invert the logic and instead indicate that the endpoint is targeted at anything other than direct browser navigation. + +```diff +namespace Microsoft.AspNetCore.Http; + ++ public interface IApiMetadata +// or ++ public interface INonBrowserNavigableMetadata ++ { ++ } +``` + +- We could also add a way to opt out of `IApiEndpointMetadata` either with a new bool similar to `IAntiforgeryMetadata.RequiresValidation` or a new metadata type similar to `IAllowAnonymous`. + +```diff +namespace Microsoft.AspNetCore.Http; + ++ public interface IBrowserEndpointMetadata ++ { ++ } +``` + +- Alternative approaches considered include using attributes or extension methods to mark API endpoints, but the chosen design leverages automatic assignment based on endpoint characteristics. +- Compared to other ecosystems, this is similar to how frameworks like Spring Boot or Express.js identify API routes via metadata or decorators. + +## Risks + +- Automatic assignment of metadata may result in unexpected behavior if endpoints are misclassified. +- There is a minimal risk of breaking changes for existing middleware or components that inspect endpoint metadata. +- Potential performance impact due to additional metadata checks, though expected to be negligible. diff --git a/aspnetcore_1/solution/solution.patch b/aspnetcore_1/solution/solution.patch new file mode 100644 index 0000000000000000000000000000000000000000..7d95a9230652418f39d94f031214b0c1f9c506db --- /dev/null +++ b/aspnetcore_1/solution/solution.patch @@ -0,0 +1,707 @@ +diff --git a/src/Http/Http.Abstractions/src/Metadata/ApiEndpointMetadata.cs b/src/Http/Http.Abstractions/src/Metadata/ApiEndpointMetadata.cs +new file mode 100644 +index 00000000..815bf2c8 +--- /dev/null ++++ b/src/Http/Http.Abstractions/src/Metadata/ApiEndpointMetadata.cs +@@ -0,0 +1,20 @@ ++// Licensed to the .NET Foundation under one or more agreements. ++// The .NET Foundation licenses this file to you under the MIT license. ++ ++namespace Microsoft.AspNetCore.Http.Metadata; ++ ++/// ++/// Metadata that indicates the endpoint is intended for API clients. ++/// When present, authentication handlers should prefer returning status codes over browser redirects. ++/// ++internal sealed class ApiEndpointMetadata : IApiEndpointMetadata ++{ ++ /// ++ /// Singleton instance of . ++ /// ++ public static readonly ApiEndpointMetadata Instance = new(); ++ ++ private ApiEndpointMetadata() ++ { ++ } ++} +diff --git a/src/Http/Http.Abstractions/src/Metadata/IApiEndpointMetadata.cs b/src/Http/Http.Abstractions/src/Metadata/IApiEndpointMetadata.cs +new file mode 100644 +index 00000000..cadaafca +--- /dev/null ++++ b/src/Http/Http.Abstractions/src/Metadata/IApiEndpointMetadata.cs +@@ -0,0 +1,12 @@ ++// Licensed to the .NET Foundation under one or more agreements. ++// The .NET Foundation licenses this file to you under the MIT license. ++ ++namespace Microsoft.AspNetCore.Http.Metadata; ++ ++/// ++/// Metadata that indicates the endpoint is an API intended for programmatic access rather than direct browser navigation. ++/// When present, authentication handlers should prefer returning status codes over browser redirects. ++/// ++public interface IApiEndpointMetadata ++{ ++} +diff --git a/src/Http/Http.Abstractions/src/Microsoft.AspNetCore.Http.Abstractions.csproj b/src/Http/Http.Abstractions/src/Microsoft.AspNetCore.Http.Abstractions.csproj +index d383efa6..37e17a0f 100644 +--- a/src/Http/Http.Abstractions/src/Microsoft.AspNetCore.Http.Abstractions.csproj ++++ b/src/Http/Http.Abstractions/src/Microsoft.AspNetCore.Http.Abstractions.csproj +@@ -35,7 +35,6 @@ Microsoft.AspNetCore.Http.HttpResponse + + + +- + + + +@@ -61,5 +60,6 @@ Microsoft.AspNetCore.Http.HttpResponse + + + ++ + + +diff --git a/src/Http/Http.Abstractions/src/PublicAPI.Unshipped.txt b/src/Http/Http.Abstractions/src/PublicAPI.Unshipped.txt +index 3a246130..2944a853 100644 +--- a/src/Http/Http.Abstractions/src/PublicAPI.Unshipped.txt ++++ b/src/Http/Http.Abstractions/src/PublicAPI.Unshipped.txt +@@ -1,4 +1,5 @@ + #nullable enable ++Microsoft.AspNetCore.Http.Metadata.IApiEndpointMetadata + Microsoft.AspNetCore.Http.Metadata.IDisableValidationMetadata + Microsoft.AspNetCore.Http.ProducesResponseTypeMetadata.Description.get -> string? + Microsoft.AspNetCore.Http.ProducesResponseTypeMetadata.Description.set -> void +diff --git a/src/Http/Http.Extensions/gen/Microsoft.AspNetCore.Http.RequestDelegateGenerator/RequestDelegateGenerator.cs b/src/Http/Http.Extensions/gen/Microsoft.AspNetCore.Http.RequestDelegateGenerator/RequestDelegateGenerator.cs +index f4e2ad0e..f5e2abac 100644 +--- a/src/Http/Http.Extensions/gen/Microsoft.AspNetCore.Http.RequestDelegateGenerator/RequestDelegateGenerator.cs ++++ b/src/Http/Http.Extensions/gen/Microsoft.AspNetCore.Http.RequestDelegateGenerator/RequestDelegateGenerator.cs +@@ -248,7 +248,12 @@ public sealed class RequestDelegateGenerator : IIncrementalGenerator + + if (hasFormBody) + { +- codeWriter.WriteLine(RequestDelegateGeneratorSources.AntiforgeryMetadataType); ++ codeWriter.WriteLine(RequestDelegateGeneratorSources.AntiforgeryMetadataClass); ++ } ++ ++ if (hasJsonBody || hasResponseMetadata) ++ { ++ codeWriter.WriteLine(RequestDelegateGeneratorSources.ApiEndpointMetadataClass); + } + + if (hasFormBody || hasJsonBody || hasResponseMetadata) +diff --git a/src/Http/Http.Extensions/gen/Microsoft.AspNetCore.Http.RequestDelegateGenerator/RequestDelegateGeneratorSources.cs b/src/Http/Http.Extensions/gen/Microsoft.AspNetCore.Http.RequestDelegateGenerator/RequestDelegateGeneratorSources.cs +index d7c7a480..b626db27 100644 +--- a/src/Http/Http.Extensions/gen/Microsoft.AspNetCore.Http.RequestDelegateGenerator/RequestDelegateGeneratorSources.cs ++++ b/src/Http/Http.Extensions/gen/Microsoft.AspNetCore.Http.RequestDelegateGenerator/RequestDelegateGeneratorSources.cs +@@ -479,19 +479,39 @@ internal static class RequestDelegateGeneratorSources + } + """; + +- public static string AntiforgeryMetadataType = """ +-file sealed class AntiforgeryMetadata : IAntiforgeryMetadata +-{ +- public static readonly IAntiforgeryMetadata ValidationRequired = new AntiforgeryMetadata(true); +- +- public AntiforgeryMetadata(bool requiresValidation) ++ public static string AntiforgeryMetadataClass = """ ++ file sealed class AntiforgeryMetadata : IAntiforgeryMetadata + { +- RequiresValidation = requiresValidation; ++ public static readonly IAntiforgeryMetadata ValidationRequired = new AntiforgeryMetadata(true); ++ ++ public AntiforgeryMetadata(bool requiresValidation) ++ { ++ RequiresValidation = requiresValidation; ++ } ++ ++ public bool RequiresValidation { get; } + } ++"""; + +- public bool RequiresValidation { get; } +-} ++ public static string ApiEndpointMetadataClass = """ ++ file sealed class ApiEndpointMetadata : IApiEndpointMetadata ++ { ++ public static readonly ApiEndpointMetadata Instance = new(); ++ ++ private ApiEndpointMetadata() ++ { ++ } ++ ++ public static void AddApiEndpointMetadataIfMissing(EndpointBuilder builder) ++ { ++ if (!builder.Metadata.Any(m => m is IApiEndpointMetadata)) ++ { ++ builder.Metadata.Add(Instance); ++ } ++ } ++ } + """; ++ + public static string GetGeneratedRouteBuilderExtensionsSource(string endpoints, string helperMethods, string helperTypes, ImmutableHashSet verbs) => $$""" + {{SourceHeader}} + +diff --git a/src/Http/Http.Extensions/gen/Microsoft.AspNetCore.Http.RequestDelegateGenerator/StaticRouteHandlerModel/StaticRouteHandlerModel.Emitter.cs b/src/Http/Http.Extensions/gen/Microsoft.AspNetCore.Http.RequestDelegateGenerator/StaticRouteHandlerModel/StaticRouteHandlerModel.Emitter.cs +index 83790d44..97fe2dc9 100644 +--- a/src/Http/Http.Extensions/gen/Microsoft.AspNetCore.Http.RequestDelegateGenerator/StaticRouteHandlerModel/StaticRouteHandlerModel.Emitter.cs ++++ b/src/Http/Http.Extensions/gen/Microsoft.AspNetCore.Http.RequestDelegateGenerator/StaticRouteHandlerModel/StaticRouteHandlerModel.Emitter.cs +@@ -205,7 +205,7 @@ internal static class StaticRouteHandlerModelEmitter + return; + } + +- if (!endpoint.Response.IsAwaitable && (response.HasNoResponse || response.IsIResult)) ++ if (response.HasNoResponse || response.IsIResult) + { + return; + } +@@ -215,13 +215,10 @@ internal static class StaticRouteHandlerModelEmitter + { + codeWriter.WriteLine($"options.EndpointBuilder.Metadata.Add(new ProducesResponseTypeMetadata(statusCode: StatusCodes.Status200OK, type: typeof(string), contentTypes: GeneratedMetadataConstants.PlaintextContentType));"); + } +- else if (response.IsAwaitable && response.ResponseType == null) +- { +- codeWriter.WriteLine($"options.EndpointBuilder.Metadata.Add(new ProducesResponseTypeMetadata(statusCode: StatusCodes.Status200OK, type: typeof(void), contentTypes: GeneratedMetadataConstants.PlaintextContentType));"); +- } + else if (response.ResponseType is { } responseType) + { + codeWriter.WriteLine($$"""options.EndpointBuilder.Metadata.Add(new ProducesResponseTypeMetadata(statusCode: StatusCodes.Status200OK, type: typeof({{responseType.ToDisplayString(EmitterConstants.DisplayFormatWithoutNullability)}}), contentTypes: GeneratedMetadataConstants.JsonContentType));"""); ++ codeWriter.WriteLine("ApiEndpointMetadata.AddApiEndpointMetadataIfMissing(options.EndpointBuilder);"); + } + } + +@@ -339,13 +336,15 @@ internal static class StaticRouteHandlerModelEmitter + codeWriter.WriteLine("if (!serviceProviderIsService.IsService(type))"); + codeWriter.StartBlock(); + codeWriter.WriteLine("options.EndpointBuilder.Metadata.Add(new AcceptsMetadata(type: type, isOptional: isOptional, contentTypes: GeneratedMetadataConstants.JsonContentType));"); ++ codeWriter.WriteLine("options.EndpointBuilder.Metadata.Add(ApiEndpointMetadata.Instance);"); + codeWriter.WriteLine("break;"); + codeWriter.EndBlock(); + codeWriter.EndBlock(); + } + else + { +- codeWriter.WriteLine($"options.EndpointBuilder.Metadata.Add(new AcceptsMetadata(contentTypes: GeneratedMetadataConstants.JsonContentType));"); ++ codeWriter.WriteLine("options.EndpointBuilder.Metadata.Add(new AcceptsMetadata(contentTypes: GeneratedMetadataConstants.JsonContentType));"); ++ codeWriter.WriteLine("options.EndpointBuilder.Metadata.Add(ApiEndpointMetadata.Instance);"); + } + } + +diff --git a/src/Http/Http.Extensions/src/RequestDelegateFactory.cs b/src/Http/Http.Extensions/src/RequestDelegateFactory.cs +index 19965ef1..aaebe417 100644 +--- a/src/Http/Http.Extensions/src/RequestDelegateFactory.cs ++++ b/src/Http/Http.Extensions/src/RequestDelegateFactory.cs +@@ -401,7 +401,14 @@ public static partial class RequestDelegateFactory + InferAntiforgeryMetadata(factoryContext); + } + +- PopulateBuiltInResponseTypeMetadata(methodInfo.ReturnType, factoryContext.EndpointBuilder); ++ // If this endpoint expects a JSON request body, we assume its an API endpoint not intended for browser navigation. ++ // When present, authentication handlers should prefer returning status codes over browser redirects. ++ if (factoryContext.JsonRequestBodyParameter is not null) ++ { ++ factoryContext.EndpointBuilder.Metadata.Add(ApiEndpointMetadata.Instance); ++ } ++ ++ PopulateBuiltInResponseTypeMetadata(methodInfo.ReturnType, factoryContext); + + // Add metadata provided by the delegate return type and parameter types next, this will be more specific than inferred metadata from above + EndpointMetadataPopulator.PopulateMetadata(methodInfo, factoryContext.EndpointBuilder, factoryContext.Parameters); +@@ -1023,37 +1030,40 @@ public static partial class RequestDelegateFactory + return Expression.Block(localVariables, checkParamAndCallMethod); + } + +- private static void PopulateBuiltInResponseTypeMetadata(Type returnType, EndpointBuilder builder) ++ private static void PopulateBuiltInResponseTypeMetadata(Type returnType, RequestDelegateFactoryContext factoryContext) + { + if (returnType.IsByRefLike) + { + throw GetUnsupportedReturnTypeException(returnType); + } + +- var isAwaitable = false; + if (CoercedAwaitableInfo.IsTypeAwaitable(returnType, out var coercedAwaitableInfo)) + { + returnType = coercedAwaitableInfo.AwaitableInfo.ResultType; +- isAwaitable = true; + } + + // Skip void returns and IResults. IResults might implement IEndpointMetadataProvider but otherwise we don't know what it might do. +- if (!isAwaitable && (returnType == typeof(void) || typeof(IResult).IsAssignableFrom(returnType))) ++ if (returnType == typeof(void) || typeof(IResult).IsAssignableFrom(returnType)) + { + return; + } + ++ var builder = factoryContext.EndpointBuilder; ++ + if (returnType == typeof(string)) + { + builder.Metadata.Add(ProducesResponseTypeMetadata.CreateUnvalidated(type: typeof(string), statusCode: 200, PlaintextContentType)); + } +- else if (returnType == typeof(void)) +- { +- builder.Metadata.Add(ProducesResponseTypeMetadata.CreateUnvalidated(returnType, statusCode: 200, PlaintextContentType)); +- } + else + { + builder.Metadata.Add(ProducesResponseTypeMetadata.CreateUnvalidated(returnType, statusCode: 200, DefaultAcceptsAndProducesContentType)); ++ ++ if (factoryContext.JsonRequestBodyParameter is null) ++ { ++ // Since this endpoint responds with JSON, we assume its an API endpoint not intended for browser navigation, ++ // but we don't want to bother adding this metadata twice if we've already inferred it based on the expected JSON request body. ++ builder.Metadata.Add(ApiEndpointMetadata.Instance); ++ } + } + } + +diff --git a/src/Http/Http.Results/src/Accepted.cs b/src/Http/Http.Results/src/Accepted.cs +index 5dbc5698..d71fe907 100644 +--- a/src/Http/Http.Results/src/Accepted.cs ++++ b/src/Http/Http.Results/src/Accepted.cs +@@ -82,5 +82,6 @@ public sealed class Accepted : IResult, IEndpointMetadataProvider, IStatusCodeHt + ArgumentNullException.ThrowIfNull(builder); + + builder.Metadata.Add(new ProducesResponseTypeMetadata(StatusCodes.Status202Accepted, typeof(void))); ++ builder.Metadata.Add(ApiEndpointMetadata.Instance); + } + } +diff --git a/src/Http/Http.Results/src/AcceptedAtRoute.cs b/src/Http/Http.Results/src/AcceptedAtRoute.cs +index 74725595..900ee507 100644 +--- a/src/Http/Http.Results/src/AcceptedAtRoute.cs ++++ b/src/Http/Http.Results/src/AcceptedAtRoute.cs +@@ -109,5 +109,6 @@ public sealed class AcceptedAtRoute : IResult, IEndpointMetadataProvider, IStatu + ArgumentNullException.ThrowIfNull(builder); + + builder.Metadata.Add(new ProducesResponseTypeMetadata(StatusCodes.Status202Accepted, typeof(void))); ++ builder.Metadata.Add(ApiEndpointMetadata.Instance); + } + } +diff --git a/src/Http/Http.Results/src/AcceptedAtRouteOfT.cs b/src/Http/Http.Results/src/AcceptedAtRouteOfT.cs +index e9467dbe..b8e4304a 100644 +--- a/src/Http/Http.Results/src/AcceptedAtRouteOfT.cs ++++ b/src/Http/Http.Results/src/AcceptedAtRouteOfT.cs +@@ -123,5 +123,6 @@ public sealed class AcceptedAtRoute : IResult, IEndpointMetadataProvider + ArgumentNullException.ThrowIfNull(builder); + + builder.Metadata.Add(ProducesResponseTypeMetadata.CreateUnvalidated(typeof(TValue), StatusCodes.Status202Accepted, ContentTypeConstants.ApplicationJsonContentTypes)); ++ builder.Metadata.Add(ApiEndpointMetadata.Instance); + } + } +diff --git a/src/Http/Http.Results/src/AcceptedOfT.cs b/src/Http/Http.Results/src/AcceptedOfT.cs +index 6777d354..34607071 100644 +--- a/src/Http/Http.Results/src/AcceptedOfT.cs ++++ b/src/Http/Http.Results/src/AcceptedOfT.cs +@@ -101,5 +101,6 @@ public sealed class Accepted : IResult, IEndpointMetadataProvider, IStat + ArgumentNullException.ThrowIfNull(builder); + + builder.Metadata.Add(ProducesResponseTypeMetadata.CreateUnvalidated(typeof(TValue), StatusCodes.Status202Accepted, ContentTypeConstants.ApplicationJsonContentTypes)); ++ builder.Metadata.Add(ApiEndpointMetadata.Instance); + } + } +diff --git a/src/Http/Http.Results/src/BadRequest.cs b/src/Http/Http.Results/src/BadRequest.cs +index 9eef74aa..0356afed 100644 +--- a/src/Http/Http.Results/src/BadRequest.cs ++++ b/src/Http/Http.Results/src/BadRequest.cs +@@ -52,5 +52,6 @@ public sealed class BadRequest : IResult, IEndpointMetadataProvider, IStatusCode + ArgumentNullException.ThrowIfNull(builder); + + builder.Metadata.Add(new ProducesResponseTypeMetadata(StatusCodes.Status400BadRequest, typeof(void))); ++ builder.Metadata.Add(ApiEndpointMetadata.Instance); + } + } +diff --git a/src/Http/Http.Results/src/BadRequestOfT.cs b/src/Http/Http.Results/src/BadRequestOfT.cs +index 4b932786..b8fa5142 100644 +--- a/src/Http/Http.Results/src/BadRequestOfT.cs ++++ b/src/Http/Http.Results/src/BadRequestOfT.cs +@@ -66,5 +66,6 @@ public sealed class BadRequest : IResult, IEndpointMetadataProvider, ISt + ArgumentNullException.ThrowIfNull(builder); + + builder.Metadata.Add(ProducesResponseTypeMetadata.CreateUnvalidated(typeof(TValue), StatusCodes.Status400BadRequest, ContentTypeConstants.ApplicationJsonContentTypes)); ++ builder.Metadata.Add(ApiEndpointMetadata.Instance); + } + } +diff --git a/src/Http/Http.Results/src/Conflict.cs b/src/Http/Http.Results/src/Conflict.cs +index da162ed5..f0067ba4 100644 +--- a/src/Http/Http.Results/src/Conflict.cs ++++ b/src/Http/Http.Results/src/Conflict.cs +@@ -52,5 +52,6 @@ public sealed class Conflict : IResult, IEndpointMetadataProvider, IStatusCodeHt + ArgumentNullException.ThrowIfNull(builder); + + builder.Metadata.Add(new ProducesResponseTypeMetadata(StatusCodes.Status409Conflict, typeof(void))); ++ builder.Metadata.Add(ApiEndpointMetadata.Instance); + } + } +diff --git a/src/Http/Http.Results/src/ConflictOfT.cs b/src/Http/Http.Results/src/ConflictOfT.cs +index bbfb3c6a..dda54d9d 100644 +--- a/src/Http/Http.Results/src/ConflictOfT.cs ++++ b/src/Http/Http.Results/src/ConflictOfT.cs +@@ -66,5 +66,6 @@ public sealed class Conflict : IResult, IEndpointMetadataProvider, IStat + ArgumentNullException.ThrowIfNull(builder); + + builder.Metadata.Add(ProducesResponseTypeMetadata.CreateUnvalidated(typeof(TValue), StatusCodes.Status409Conflict, ContentTypeConstants.ApplicationJsonContentTypes)); ++ builder.Metadata.Add(ApiEndpointMetadata.Instance); + } + } +diff --git a/src/Http/Http.Results/src/Created.cs b/src/Http/Http.Results/src/Created.cs +index 7766d91a..19595562 100644 +--- a/src/Http/Http.Results/src/Created.cs ++++ b/src/Http/Http.Results/src/Created.cs +@@ -82,5 +82,6 @@ public sealed class Created : IResult, IEndpointMetadataProvider, IStatusCodeHtt + ArgumentNullException.ThrowIfNull(builder); + + builder.Metadata.Add(new ProducesResponseTypeMetadata(StatusCodes.Status201Created, typeof(void))); ++ builder.Metadata.Add(ApiEndpointMetadata.Instance); + } + } +diff --git a/src/Http/Http.Results/src/CreatedAtRoute.cs b/src/Http/Http.Results/src/CreatedAtRoute.cs +index 2fb70fa2..2ff79596 100644 +--- a/src/Http/Http.Results/src/CreatedAtRoute.cs ++++ b/src/Http/Http.Results/src/CreatedAtRoute.cs +@@ -109,5 +109,6 @@ public sealed class CreatedAtRoute : IResult, IEndpointMetadataProvider, IStatus + ArgumentNullException.ThrowIfNull(builder); + + builder.Metadata.Add(new ProducesResponseTypeMetadata(StatusCodes.Status201Created, typeof(void))); ++ builder.Metadata.Add(ApiEndpointMetadata.Instance); + } + } +diff --git a/src/Http/Http.Results/src/CreatedAtRouteOfT.cs b/src/Http/Http.Results/src/CreatedAtRouteOfT.cs +index d13d6154..a2868afd 100644 +--- a/src/Http/Http.Results/src/CreatedAtRouteOfT.cs ++++ b/src/Http/Http.Results/src/CreatedAtRouteOfT.cs +@@ -126,5 +126,6 @@ public sealed class CreatedAtRoute : IResult, IEndpointMetadataProvider, + ArgumentNullException.ThrowIfNull(builder); + + builder.Metadata.Add(ProducesResponseTypeMetadata.CreateUnvalidated(typeof(TValue), StatusCodes.Status201Created, ContentTypeConstants.ApplicationJsonContentTypes)); ++ builder.Metadata.Add(ApiEndpointMetadata.Instance); + } + } +diff --git a/src/Http/Http.Results/src/CreatedOfT.cs b/src/Http/Http.Results/src/CreatedOfT.cs +index 58d0638b..a12e52b9 100644 +--- a/src/Http/Http.Results/src/CreatedOfT.cs ++++ b/src/Http/Http.Results/src/CreatedOfT.cs +@@ -100,5 +100,6 @@ public sealed class Created : IResult, IEndpointMetadataProvider, IStatu + ArgumentNullException.ThrowIfNull(builder); + + builder.Metadata.Add(ProducesResponseTypeMetadata.CreateUnvalidated(typeof(TValue), StatusCodes.Status201Created, ContentTypeConstants.ApplicationJsonContentTypes)); ++ builder.Metadata.Add(ApiEndpointMetadata.Instance); + } + } +diff --git a/src/Http/Http.Results/src/InternalServerErrorOfT.cs b/src/Http/Http.Results/src/InternalServerErrorOfT.cs +index 36ec9fed..c726debf 100644 +--- a/src/Http/Http.Results/src/InternalServerErrorOfT.cs ++++ b/src/Http/Http.Results/src/InternalServerErrorOfT.cs +@@ -66,5 +66,6 @@ public sealed class InternalServerError : IResult, IEndpointMetadataProv + ArgumentNullException.ThrowIfNull(builder); + + builder.Metadata.Add(ProducesResponseTypeMetadata.CreateUnvalidated(typeof(TValue), StatusCodes.Status500InternalServerError, ContentTypeConstants.ApplicationJsonContentTypes)); ++ builder.Metadata.Add(ApiEndpointMetadata.Instance); + } + } +diff --git a/src/Http/Http.Results/src/JsonHttpResultOfT.cs b/src/Http/Http.Results/src/JsonHttpResultOfT.cs +index 4841e675..fea23060 100644 +--- a/src/Http/Http.Results/src/JsonHttpResultOfT.cs ++++ b/src/Http/Http.Results/src/JsonHttpResultOfT.cs +@@ -2,8 +2,11 @@ + // The .NET Foundation licenses this file to you under the MIT license. + + using System.Diagnostics.CodeAnalysis; ++using System.Reflection; + using System.Text.Json; + using System.Text.Json.Serialization.Metadata; ++using Microsoft.AspNetCore.Builder; ++using Microsoft.AspNetCore.Http.Metadata; + using Microsoft.AspNetCore.Mvc; + using Microsoft.Extensions.DependencyInjection; + using Microsoft.Extensions.Logging; +@@ -13,7 +16,7 @@ namespace Microsoft.AspNetCore.Http.HttpResults; + /// + /// An action result which formats the given object as JSON. + /// +-public sealed partial class JsonHttpResult : IResult, IStatusCodeHttpResult, IValueHttpResult, IValueHttpResult, IContentTypeHttpResult ++public sealed partial class JsonHttpResult : IResult, IEndpointMetadataProvider, IStatusCodeHttpResult, IValueHttpResult, IValueHttpResult, IContentTypeHttpResult + { + /// + /// Initializes a new instance of the class with the values. +@@ -117,7 +120,7 @@ public sealed partial class JsonHttpResult : IResult, IStatusCodeHttpRes + typedJsonTypeInfo, + contentType: ContentType); + } +- ++ + return httpContext.Response.WriteAsJsonAsync( + Value, + JsonTypeInfo, +@@ -131,4 +134,9 @@ public sealed partial class JsonHttpResult : IResult, IStatusCodeHttpRes + ContentType, + JsonSerializerOptions); + } ++ ++ static void IEndpointMetadataProvider.PopulateMetadata(MethodInfo method, EndpointBuilder builder) ++ { ++ builder.Metadata.Add(ApiEndpointMetadata.Instance); ++ } + } +diff --git a/src/Http/Http.Results/src/NoContent.cs b/src/Http/Http.Results/src/NoContent.cs +index 987a06fc..35ffb3c5 100644 +--- a/src/Http/Http.Results/src/NoContent.cs ++++ b/src/Http/Http.Results/src/NoContent.cs +@@ -52,5 +52,6 @@ public class NoContent : IResult, IEndpointMetadataProvider, IStatusCodeHttpResu + ArgumentNullException.ThrowIfNull(builder); + + builder.Metadata.Add(new ProducesResponseTypeMetadata(StatusCodes.Status204NoContent, typeof(void))); ++ builder.Metadata.Add(ApiEndpointMetadata.Instance); + } + } +diff --git a/src/Http/Http.Results/src/NotFoundOfT.cs b/src/Http/Http.Results/src/NotFoundOfT.cs +index ad9c3a10..d37a4ee9 100644 +--- a/src/Http/Http.Results/src/NotFoundOfT.cs ++++ b/src/Http/Http.Results/src/NotFoundOfT.cs +@@ -65,5 +65,6 @@ public sealed class NotFound : IResult, IEndpointMetadataProvider, IStat + ArgumentNullException.ThrowIfNull(builder); + + builder.Metadata.Add(ProducesResponseTypeMetadata.CreateUnvalidated(typeof(TValue), StatusCodes.Status404NotFound, ContentTypeConstants.ApplicationJsonContentTypes)); ++ builder.Metadata.Add(ApiEndpointMetadata.Instance); + } + } +diff --git a/src/Http/Http.Results/src/Ok.cs b/src/Http/Http.Results/src/Ok.cs +index 0db060d4..837a0fa7 100644 +--- a/src/Http/Http.Results/src/Ok.cs ++++ b/src/Http/Http.Results/src/Ok.cs +@@ -51,5 +51,6 @@ public sealed class Ok : IResult, IEndpointMetadataProvider, IStatusCodeHttpResu + ArgumentNullException.ThrowIfNull(builder); + + builder.Metadata.Add(new ProducesResponseTypeMetadata(StatusCodes.Status200OK, typeof(void))); ++ builder.Metadata.Add(ApiEndpointMetadata.Instance); + } + } +diff --git a/src/Http/Http.Results/src/OkOfT.cs b/src/Http/Http.Results/src/OkOfT.cs +index 108674fd..7f19598e 100644 +--- a/src/Http/Http.Results/src/OkOfT.cs ++++ b/src/Http/Http.Results/src/OkOfT.cs +@@ -65,5 +65,6 @@ public sealed class Ok : IResult, IEndpointMetadataProvider, IStatusCode + ArgumentNullException.ThrowIfNull(builder); + + builder.Metadata.Add(ProducesResponseTypeMetadata.CreateUnvalidated(typeof(TValue), StatusCodes.Status200OK, ContentTypeConstants.ApplicationJsonContentTypes)); ++ builder.Metadata.Add(ApiEndpointMetadata.Instance); + } + } +diff --git a/src/Http/Http.Results/src/ProblemHttpResult.cs b/src/Http/Http.Results/src/ProblemHttpResult.cs +index 4fe63c42..8ac29336 100644 +--- a/src/Http/Http.Results/src/ProblemHttpResult.cs ++++ b/src/Http/Http.Results/src/ProblemHttpResult.cs +@@ -4,6 +4,9 @@ + using Microsoft.AspNetCore.Mvc; + using Microsoft.Extensions.DependencyInjection; + using Microsoft.Extensions.Logging; ++using System.Reflection; ++using Microsoft.AspNetCore.Builder; ++using Microsoft.AspNetCore.Http.Metadata; + + namespace Microsoft.AspNetCore.Http.HttpResults; + +@@ -11,7 +14,7 @@ namespace Microsoft.AspNetCore.Http.HttpResults; + /// An that on execution will write Problem Details + /// HTTP API responses based on + /// +-public sealed class ProblemHttpResult : IResult, IStatusCodeHttpResult, IContentTypeHttpResult, IValueHttpResult, IValueHttpResult ++public sealed class ProblemHttpResult : IResult, IEndpointMetadataProvider, IStatusCodeHttpResult, IContentTypeHttpResult, IValueHttpResult, IValueHttpResult + { + /// + /// Creates a new instance with +@@ -69,4 +72,13 @@ public sealed class ProblemHttpResult : IResult, IStatusCodeHttpResult, IContent + ContentType); + } + } ++ ++ /// ++ static void IEndpointMetadataProvider.PopulateMetadata(MethodInfo method, EndpointBuilder builder) ++ { ++ ArgumentNullException.ThrowIfNull(method); ++ ArgumentNullException.ThrowIfNull(builder); ++ ++ builder.Metadata.Add(ApiEndpointMetadata.Instance); ++ } + } +diff --git a/src/Http/Http.Results/src/ServerSentEventsResult.cs b/src/Http/Http.Results/src/ServerSentEventsResult.cs +index 448b2076..a7951acd 100644 +--- a/src/Http/Http.Results/src/ServerSentEventsResult.cs ++++ b/src/Http/Http.Results/src/ServerSentEventsResult.cs +@@ -105,5 +105,6 @@ public sealed class ServerSentEventsResult : IResult, IEndpointMetadataProvid + ArgumentNullException.ThrowIfNull(builder); + + builder.Metadata.Add(new ProducesResponseTypeMetadata(StatusCodes.Status200OK, typeof(SseItem), contentTypes: ["text/event-stream"])); ++ builder.Metadata.Add(ApiEndpointMetadata.Instance); + } + } +diff --git a/src/Http/Http.Results/src/UnprocessableEntity.cs b/src/Http/Http.Results/src/UnprocessableEntity.cs +index eef96dc9..49d39827 100644 +--- a/src/Http/Http.Results/src/UnprocessableEntity.cs ++++ b/src/Http/Http.Results/src/UnprocessableEntity.cs +@@ -52,5 +52,6 @@ public sealed class UnprocessableEntity : IResult, IEndpointMetadataProvider, IS + ArgumentNullException.ThrowIfNull(builder); + + builder.Metadata.Add(new ProducesResponseTypeMetadata(StatusCodes.Status422UnprocessableEntity, typeof(void))); ++ builder.Metadata.Add(ApiEndpointMetadata.Instance); + } + } +diff --git a/src/Http/Http.Results/src/UnprocessableEntityOfT.cs b/src/Http/Http.Results/src/UnprocessableEntityOfT.cs +index 475a0bc3..2d1ee494 100644 +--- a/src/Http/Http.Results/src/UnprocessableEntityOfT.cs ++++ b/src/Http/Http.Results/src/UnprocessableEntityOfT.cs +@@ -66,5 +66,6 @@ public sealed class UnprocessableEntity : IResult, IEndpointMetadataProv + ArgumentNullException.ThrowIfNull(builder); + + builder.Metadata.Add(ProducesResponseTypeMetadata.CreateUnvalidated(typeof(TValue), StatusCodes.Status422UnprocessableEntity, ContentTypeConstants.ApplicationJsonContentTypes)); ++ builder.Metadata.Add(ApiEndpointMetadata.Instance); + } + } +diff --git a/src/Http/Http.Results/src/ValidationProblem.cs b/src/Http/Http.Results/src/ValidationProblem.cs +index ba738cfb..c4a539c9 100644 +--- a/src/Http/Http.Results/src/ValidationProblem.cs ++++ b/src/Http/Http.Results/src/ValidationProblem.cs +@@ -77,5 +77,6 @@ public sealed class ValidationProblem : IResult, IEndpointMetadataProvider, ISta + ArgumentNullException.ThrowIfNull(builder); + + builder.Metadata.Add(ProducesResponseTypeMetadata.CreateUnvalidated(typeof(HttpValidationProblemDetails), StatusCodes.Status400BadRequest, ContentTypeConstants.ProblemDetailsContentTypes)); ++ builder.Metadata.Add(ApiEndpointMetadata.Instance); + } + } +diff --git a/src/Mvc/Mvc.ApiExplorer/src/EndpointMetadataApiDescriptionProvider.cs b/src/Mvc/Mvc.ApiExplorer/src/EndpointMetadataApiDescriptionProvider.cs +index 89d45efc..2f25045d 100644 +--- a/src/Mvc/Mvc.ApiExplorer/src/EndpointMetadataApiDescriptionProvider.cs ++++ b/src/Mvc/Mvc.ApiExplorer/src/EndpointMetadataApiDescriptionProvider.cs +@@ -332,10 +332,9 @@ internal sealed class EndpointMetadataApiDescriptionProvider : IApiDescriptionPr + var defaultErrorType = errorMetadata?.Type ?? typeof(void); + var contentTypes = new MediaTypeCollection(); + +- // If the return type is an IResult or an awaitable IResult, then we should treat it as a void return type +- // since we can't infer anything without additional metadata. +- if (typeof(IResult).IsAssignableFrom(responseType) || +- producesResponseMetadata.Any(metadata => typeof(IResult).IsAssignableFrom(metadata.Type))) ++ // If the return type is an IResult or wrapped in a Task or ValueTask, then we should treat it as a void return type ++ // since we can't infer anything without additional metadata or requiring unreferenced code. ++ if (IsTaskOrValueTask(responseType) || typeof(IResult).IsAssignableFrom(responseType)) + { + responseType = typeof(void); + } +@@ -427,6 +426,23 @@ internal sealed class EndpointMetadataApiDescriptionProvider : IApiDescriptionPr + return apiResponseType == metadataType || + metadataType?.IsAssignableFrom(apiResponseType) == true; + } ++ ++ static bool IsTaskOrValueTask(Type returnType) ++ { ++ // If this method did not need to be trim-safe, we would use CoercedAwaitableInfo.IsTypeAwaitable, but we cannot. ++ if (returnType.IsAssignableFrom(typeof(Task)) || returnType.IsAssignableFrom(typeof(ValueTask))) ++ { ++ return true; ++ } ++ ++ if (returnType.FullName is null) ++ { ++ return false; ++ } ++ ++ return returnType.FullName.StartsWith("System.Threading.Tasks.Task`1[", StringComparison.Ordinal) || ++ returnType.FullName.StartsWith("System.Threading.Tasks.ValueTask`1[", StringComparison.Ordinal); ++ } + } + + private static ApiResponseType CreateDefaultApiResponseType(Type responseType) +diff --git a/src/Mvc/Mvc.Core/src/ApiControllerAttribute.cs b/src/Mvc/Mvc.Core/src/ApiControllerAttribute.cs +index a1b95b3e..f7179b0b 100644 +--- a/src/Mvc/Mvc.Core/src/ApiControllerAttribute.cs ++++ b/src/Mvc/Mvc.Core/src/ApiControllerAttribute.cs +@@ -1,6 +1,7 @@ + // Licensed to the .NET Foundation under one or more agreements. + // The .NET Foundation licenses this file to you under the MIT license. + ++using Microsoft.AspNetCore.Http.Metadata; + using Microsoft.AspNetCore.Mvc.Infrastructure; + + namespace Microsoft.AspNetCore.Mvc; +@@ -17,6 +18,6 @@ namespace Microsoft.AspNetCore.Mvc; + /// + /// + [AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Class, AllowMultiple = false, Inherited = true)] +-public class ApiControllerAttribute : ControllerAttribute, IApiBehaviorMetadata ++public class ApiControllerAttribute : ControllerAttribute, IApiBehaviorMetadata, IApiEndpointMetadata + { + } +diff --git a/src/Security/Authentication/Cookies/src/CookieAuthenticationEvents.cs b/src/Security/Authentication/Cookies/src/CookieAuthenticationEvents.cs +index be47982a..994d999a 100644 +--- a/src/Security/Authentication/Cookies/src/CookieAuthenticationEvents.cs ++++ b/src/Security/Authentication/Cookies/src/CookieAuthenticationEvents.cs +@@ -2,6 +2,7 @@ + // The .NET Foundation licenses this file to you under the MIT license. + + using Microsoft.AspNetCore.Http; ++using Microsoft.AspNetCore.Http.Metadata; + using Microsoft.Net.Http.Headers; + + namespace Microsoft.AspNetCore.Authentication.Cookies; +@@ -41,7 +42,7 @@ public class CookieAuthenticationEvents + /// + public Func, Task> OnRedirectToLogin { get; set; } = context => + { +- if (IsAjaxRequest(context.Request)) ++ if (IsAjaxRequest(context.Request) || IsApiEndpoint(context.HttpContext)) + { + context.Response.Headers.Location = context.RedirectUri; + context.Response.StatusCode = 401; +@@ -58,7 +59,7 @@ public class CookieAuthenticationEvents + /// + public Func, Task> OnRedirectToAccessDenied { get; set; } = context => + { +- if (IsAjaxRequest(context.Request)) ++ if (IsAjaxRequest(context.Request) || IsApiEndpoint(context.HttpContext)) + { + context.Response.Headers.Location = context.RedirectUri; + context.Response.StatusCode = 403; +@@ -108,6 +109,12 @@ public class CookieAuthenticationEvents + string.Equals(request.Headers.XRequestedWith, "XMLHttpRequest", StringComparison.Ordinal); + } + ++ private static bool IsApiEndpoint(HttpContext context) ++ { ++ var endpoint = context.GetEndpoint(); ++ return endpoint?.Metadata.GetMetadata() is not null; ++ } ++ + /// + /// Invoked to validate the principal. + /// +diff --git a/src/SignalR/common/Http.Connections/src/ConnectionEndpointRouteBuilderExtensions.cs b/src/SignalR/common/Http.Connections/src/ConnectionEndpointRouteBuilderExtensions.cs +index 8ed01395..f1aad864 100644 +--- a/src/SignalR/common/Http.Connections/src/ConnectionEndpointRouteBuilderExtensions.cs ++++ b/src/SignalR/common/Http.Connections/src/ConnectionEndpointRouteBuilderExtensions.cs +@@ -5,6 +5,7 @@ using System.Diagnostics.CodeAnalysis; + using Microsoft.AspNetCore.Connections; + using Microsoft.AspNetCore.Http.Connections; + using Microsoft.AspNetCore.Http.Connections.Internal; ++using Microsoft.AspNetCore.Http.Metadata; + using Microsoft.AspNetCore.Http.Timeouts; + using Microsoft.AspNetCore.Routing; + using Microsoft.Extensions.DependencyInjection; +@@ -125,6 +126,9 @@ public static class ConnectionEndpointRouteBuilderExtensions + { + e.Metadata.Add(data); + } ++ ++ // Add IApiEndpointMetadata to indicate this is a non-browser endpoint (SignalR) ++ e.Metadata.Add(ApiEndpointMetadata.Instance); + }); + + return new ConnectionEndpointRouteBuilder(compositeConventionBuilder); +@@ -155,4 +159,9 @@ public static class ConnectionEndpointRouteBuilderExtensions + } + } + } ++ ++ private sealed class ApiEndpointMetadata : IApiEndpointMetadata ++ { ++ public static ApiEndpointMetadata Instance { get; } = new(); ++ } + } diff --git a/aspnetcore_1/solution/solve.sh b/aspnetcore_1/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..6e9e00d34ea28a095bfc617bee1826ab73a9d864 --- /dev/null +++ b/aspnetcore_1/solution/solve.sh @@ -0,0 +1,7 @@ +#!/usr/bin/env bash +set -euo pipefail + +cd /workspace/aspnetcore +patch=${LOLBENCH_ORACLE_PATCH:-/solution/solution.patch} +git apply "$patch" +lolbench-submit diff --git a/aspnetcore_1/task.toml b/aspnetcore_1/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..2b7dd37df2e33720372343e2155dd5046d58f5d3 --- /dev/null +++ b/aspnetcore_1/task.toml @@ -0,0 +1,60 @@ +schema_version = "1.3" + +[task] +name = "lolbench/aspnetcore_1" +description = "Implement IApiEndpointMetadata classification for ASP.NET Core API endpoints." +authors = [{ name = "LoLBench maintainers" }] +keywords = ["lolbench", "coding-agent", "asp", "net", "core", "aspnetcore", "c"] + +[metadata] +instance_id = "aspnetcore_1" +source_instance_id = "ASP.NET-Core_Issue-62883_PR-62816" +source_slug = "ASP.NET-Core_Issue-62883_PR-62816" +docker_slug = "ASP.NET-Core_Issue-62883_PR-62816" +dockerhub_image = "smartdub26/lolbench-linux:aspnetcore_1-1.0.0" +project = "aspnetcore" +repo = "dotnet/aspnetcore" +requirement_doc = "https://github.com/dotnet/aspnetcore/issues/62883" +pr_link = "https://github.com/dotnet/aspnetcore/pull/62816" +base_commit = "c56ce2f92858158819569e11d4131c09fd847764" +merge_commit = "295944574c37f46859348d6fcd3d5adf48c70bf7" +test_level = "system" +source_history_policy = "ancestors-only" +lolbench_test_modes = ["orig", "aug", "union"] +default_lolbench_suite = "union" +canonical_lolbench_suite = "union" +augmentation_available = true +verifier_network_policy = "public" +verifier_network_reason = "The Harbor verifier runs in a separate container and may use network access; migrated LoLBench verifier assets are mounted only in the verifier phase." + +[environment] +build_timeout_sec = 3600.0 +docker_image = "smartdub26/lolbench-linux:aspnetcore_1-1.0.0" +network_mode = "public" +os = "linux" +cpus = 4 +memory_mb = 7168 +storage_mb = 20480 + +[agent] +timeout_sec = 21600.0 +user = "agent" +network_mode = "allowlist" +allowed_hosts = ["openrouter.ai", "api.openai.com", "api.anthropic.com"] + +[verifier] +timeout_sec = 7200.0 +user = "root" +environment_mode = "separate" +network_mode = "public" + +[verifier.env] +LOLBENCH_SUITE = "union" + +[verifier.environment] +docker_image = "smartdub26/lolbench-linux:aspnetcore_1-1.0.0" +network_mode = "public" +os = "linux" +cpus = 4 +memory_mb = 7168 +storage_mb = 20480 diff --git a/aspnetcore_1/tests/docker-compose.yaml b/aspnetcore_1/tests/docker-compose.yaml new file mode 100644 index 0000000000000000000000000000000000000000..f5091b9298e127a1efbe69deeed699c907e025c1 --- /dev/null +++ b/aspnetcore_1/tests/docker-compose.yaml @@ -0,0 +1,16 @@ +services: + main: + pull_policy: missing + volumes: + - type: bind + source: . + target: /tests + read_only: true + - type: bind + source: ./private + target: /opt/lolbench/private + read_only: true + - type: bind + source: ../solution + target: /solution + read_only: true diff --git a/aspnetcore_1/tests/private/eval_tests.patch b/aspnetcore_1/tests/private/eval_tests.patch new file mode 100644 index 0000000000000000000000000000000000000000..6d603b7c72d4c2ecfb9236841323bf0fad982cf3 --- /dev/null +++ b/aspnetcore_1/tests/private/eval_tests.patch @@ -0,0 +1,2263 @@ +diff --git a/src/Http/Http.Extensions/test/RequestDelegateFactoryTests.cs b/src/Http/Http.Extensions/test/RequestDelegateFactoryTests.cs +index 083da9bd..7cee04fb 100644 +--- a/src/Http/Http.Extensions/test/RequestDelegateFactoryTests.cs ++++ b/src/Http/Http.Extensions/test/RequestDelegateFactoryTests.cs +@@ -2533,7 +2533,7 @@ public partial class RequestDelegateFactoryTests : LoggedTest + var @delegate = () => new object(); + var result = RequestDelegateFactory.Create(@delegate); + +- var responseMetadata = Assert.IsAssignableFrom(Assert.Single(result.EndpointMetadata)); ++ var responseMetadata = Assert.Single(result.EndpointMetadata.OfType()); + + Assert.Equal("application/json", Assert.Single(responseMetadata.ContentTypes)); + Assert.Equal(typeof(object), responseMetadata.Type); +@@ -2545,7 +2545,7 @@ public partial class RequestDelegateFactoryTests : LoggedTest + var @delegate = () => "Hello"; + var result = RequestDelegateFactory.Create(@delegate); + +- var responseMetadata = Assert.IsAssignableFrom(Assert.Single(result.EndpointMetadata)); ++ var responseMetadata = Assert.Single(result.EndpointMetadata.OfType()); + + Assert.Equal("text/plain", Assert.Single(responseMetadata.ContentTypes)); + Assert.Equal(typeof(string), responseMetadata.Type); +@@ -2683,6 +2683,7 @@ public partial class RequestDelegateFactoryTests : LoggedTest + + // Assert + Assert.Contains(result.EndpointMetadata, m => m is CustomEndpointMetadata { Source: MetadataSource.Caller }); ++ Assert.DoesNotContain(result.EndpointMetadata, m => m is IProducesResponseTypeMetadata); + // Expecting '1' because only initial metadata will be in the metadata list when this metadata item is added + Assert.Contains(result.EndpointMetadata, m => m is MetadataCountMetadata { Count: 1 }); + } +@@ -2705,9 +2706,9 @@ public partial class RequestDelegateFactoryTests : LoggedTest + + // Assert + Assert.Contains(result.EndpointMetadata, m => m is CustomEndpointMetadata { Source: MetadataSource.Caller }); +- Assert.Contains(result.EndpointMetadata, m => m is ProducesResponseTypeMetadata { Type: { } type } && type == typeof(CountsDefaultEndpointMetadataResult)); +- // Expecting the custom metadata and the implicit metadata associated with a Task-based return type to be inserted +- Assert.Contains(result.EndpointMetadata, m => m is MetadataCountMetadata { Count: 2 }); ++ Assert.DoesNotContain(result.EndpointMetadata, m => m is IProducesResponseTypeMetadata); ++ // Expecting '1' because only initial metadata will be in the metadata list when this metadata item is added ++ Assert.Contains(result.EndpointMetadata, m => m is MetadataCountMetadata { Count: 1 }); + } + + [Fact] +@@ -2728,9 +2729,9 @@ public partial class RequestDelegateFactoryTests : LoggedTest + + // Assert + Assert.Contains(result.EndpointMetadata, m => m is CustomEndpointMetadata { Source: MetadataSource.Caller }); +- Assert.Contains(result.EndpointMetadata, m => m is ProducesResponseTypeMetadata { Type: { } type } && type == typeof(CountsDefaultEndpointMetadataResult)); +- // Expecting the custom metadata nad hte implicit metadata associated with a Task-based return type to be inserted +- Assert.Contains(result.EndpointMetadata, m => m is MetadataCountMetadata { Count: 2 }); ++ Assert.DoesNotContain(result.EndpointMetadata, m => m is IProducesResponseTypeMetadata); ++ // Expecting '1' because only initial metadata will be in the metadata list when this metadata item is added ++ Assert.Contains(result.EndpointMetadata, m => m is MetadataCountMetadata { Count: 1 }); + } + + [Fact] +@@ -2751,9 +2752,9 @@ public partial class RequestDelegateFactoryTests : LoggedTest + + // Assert + Assert.Contains(result.EndpointMetadata, m => m is CustomEndpointMetadata { Source: MetadataSource.Caller }); +- Assert.Contains(result.EndpointMetadata, m => m is IProducesResponseTypeMetadata { Type: { } type } && type == typeof(CountsDefaultEndpointMetadataResult)); ++ Assert.DoesNotContain(result.EndpointMetadata, m => m is IProducesResponseTypeMetadata); + // Expecting '1' because only initial metadata will be in the metadata list when this metadata item is added +- Assert.Contains(result.EndpointMetadata, m => m is MetadataCountMetadata { Count: 2 }); ++ Assert.Contains(result.EndpointMetadata, m => m is MetadataCountMetadata { Count: 1 }); + } + + [Fact] +@@ -2824,14 +2825,16 @@ public partial class RequestDelegateFactoryTests : LoggedTest + m => Assert.True(m is AcceptsMetadata am && am.RequestType == typeof(AddsCustomParameterMetadata)), + // Inferred ParameterBinding metadata + m => Assert.True(m is IParameterBindingMetadata { Name: "param1" }), +- // Inferred ProducesResopnseTypeMetadata from RDF for complex type ++ // Inferred IApiEndpointMetadata from RDF for complex request and response type ++ m => Assert.True(m is IApiEndpointMetadata), ++ // Inferred ProducesResponseTypeMetadata from RDF for complex type + m => Assert.Equal(typeof(CountsDefaultEndpointMetadataPoco), ((IProducesResponseTypeMetadata)m).Type), + // Metadata provided by parameters implementing IEndpointParameterMetadataProvider + m => Assert.True(m is ParameterNameMetadata { Name: "param1" }), + // Metadata provided by parameters implementing IEndpointMetadataProvider + m => Assert.True(m is CustomEndpointMetadata { Source: MetadataSource.Parameter }), + // Metadata provided by return type implementing IEndpointMetadataProvider +- m => Assert.True(m is MetadataCountMetadata { Count: 6 })); ++ m => Assert.True(m is MetadataCountMetadata { Count: 7 })); + } + + [Fact] +diff --git a/src/Http/Http.Extensions/test/RequestDelegateGenerator/Baselines/HandlesEndpointsWithAndWithoutDiagnostics.generated.txt b/src/Http/Http.Extensions/test/RequestDelegateGenerator/Baselines/HandlesEndpointsWithAndWithoutDiagnostics.generated.txt +index ae38db99..18cf2ce8 100644 +--- a/src/Http/Http.Extensions/test/RequestDelegateGenerator/Baselines/HandlesEndpointsWithAndWithoutDiagnostics.generated.txt ++++ b/src/Http/Http.Extensions/test/RequestDelegateGenerator/Baselines/HandlesEndpointsWithAndWithoutDiagnostics.generated.txt +@@ -225,6 +225,22 @@ namespace Microsoft.AspNetCore.Http.Generated + + } + ++ file sealed class ApiEndpointMetadata : IApiEndpointMetadata ++ { ++ public static readonly ApiEndpointMetadata Instance = new(); ++ ++ private ApiEndpointMetadata() ++ { ++ } ++ ++ public static void AddApiEndpointMetadataIfMissing(EndpointBuilder builder) ++ { ++ if (!builder.Metadata.Any(m => m is IApiEndpointMetadata)) ++ { ++ builder.Metadata.Add(Instance); ++ } ++ } ++ } + %GENERATEDCODEATTRIBUTE% + file static class GeneratedMetadataConstants + { +diff --git a/src/Http/Http.Extensions/test/RequestDelegateGenerator/Baselines/MapAction_BindAsync_NullableReturn.generated.txt b/src/Http/Http.Extensions/test/RequestDelegateGenerator/Baselines/MapAction_BindAsync_NullableReturn.generated.txt +index ddfeaf60..04b1dc6c 100644 +--- a/src/Http/Http.Extensions/test/RequestDelegateGenerator/Baselines/MapAction_BindAsync_NullableReturn.generated.txt ++++ b/src/Http/Http.Extensions/test/RequestDelegateGenerator/Baselines/MapAction_BindAsync_NullableReturn.generated.txt +@@ -363,6 +363,22 @@ namespace Microsoft.AspNetCore.Http.Generated + + } + ++ file sealed class ApiEndpointMetadata : IApiEndpointMetadata ++ { ++ public static readonly ApiEndpointMetadata Instance = new(); ++ ++ private ApiEndpointMetadata() ++ { ++ } ++ ++ public static void AddApiEndpointMetadataIfMissing(EndpointBuilder builder) ++ { ++ if (!builder.Metadata.Any(m => m is IApiEndpointMetadata)) ++ { ++ builder.Metadata.Add(Instance); ++ } ++ } ++ } + %GENERATEDCODEATTRIBUTE% + file static class GeneratedMetadataConstants + { +diff --git a/src/Http/Http.Extensions/test/RequestDelegateGenerator/Baselines/MapAction_BindAsync_Snapshot.generated.txt b/src/Http/Http.Extensions/test/RequestDelegateGenerator/Baselines/MapAction_BindAsync_Snapshot.generated.txt +index ab79dddf..6c1240e6 100644 +--- a/src/Http/Http.Extensions/test/RequestDelegateGenerator/Baselines/MapAction_BindAsync_Snapshot.generated.txt ++++ b/src/Http/Http.Extensions/test/RequestDelegateGenerator/Baselines/MapAction_BindAsync_Snapshot.generated.txt +@@ -2225,6 +2225,22 @@ namespace Microsoft.AspNetCore.Http.Generated + + } + ++ file sealed class ApiEndpointMetadata : IApiEndpointMetadata ++ { ++ public static readonly ApiEndpointMetadata Instance = new(); ++ ++ private ApiEndpointMetadata() ++ { ++ } ++ ++ public static void AddApiEndpointMetadataIfMissing(EndpointBuilder builder) ++ { ++ if (!builder.Metadata.Any(m => m is IApiEndpointMetadata)) ++ { ++ builder.Metadata.Add(Instance); ++ } ++ } ++ } + %GENERATEDCODEATTRIBUTE% + file static class GeneratedMetadataConstants + { +diff --git a/src/Http/Http.Extensions/test/RequestDelegateGenerator/Baselines/MapAction_ExplicitBodyParam_ComplexReturn_Snapshot.generated.txt b/src/Http/Http.Extensions/test/RequestDelegateGenerator/Baselines/MapAction_ExplicitBodyParam_ComplexReturn_Snapshot.generated.txt +index 28e8316f..830c81d1 100644 +--- a/src/Http/Http.Extensions/test/RequestDelegateGenerator/Baselines/MapAction_ExplicitBodyParam_ComplexReturn_Snapshot.generated.txt ++++ b/src/Http/Http.Extensions/test/RequestDelegateGenerator/Baselines/MapAction_ExplicitBodyParam_ComplexReturn_Snapshot.generated.txt +@@ -412,6 +412,22 @@ namespace Microsoft.AspNetCore.Http.Generated + + } + ++ file sealed class ApiEndpointMetadata : IApiEndpointMetadata ++ { ++ public static readonly ApiEndpointMetadata Instance = new(); ++ ++ private ApiEndpointMetadata() ++ { ++ } ++ ++ public static void AddApiEndpointMetadataIfMissing(EndpointBuilder builder) ++ { ++ if (!builder.Metadata.Any(m => m is IApiEndpointMetadata)) ++ { ++ builder.Metadata.Add(Instance); ++ } ++ } ++ } + %GENERATEDCODEATTRIBUTE% + file static class GeneratedMetadataConstants + { +diff --git a/src/Http/Http.Extensions/test/RequestDelegateGenerator/Baselines/MapAction_ExplicitHeader_ComplexTypeArrayParam.generated.txt b/src/Http/Http.Extensions/test/RequestDelegateGenerator/Baselines/MapAction_ExplicitHeader_ComplexTypeArrayParam.generated.txt +index 3a8e7fe8..bd0ceac2 100644 +--- a/src/Http/Http.Extensions/test/RequestDelegateGenerator/Baselines/MapAction_ExplicitHeader_ComplexTypeArrayParam.generated.txt ++++ b/src/Http/Http.Extensions/test/RequestDelegateGenerator/Baselines/MapAction_ExplicitHeader_ComplexTypeArrayParam.generated.txt +@@ -72,6 +72,7 @@ namespace Microsoft.AspNetCore.Http.Generated + var parameters = methodInfo.GetParameters(); + options.EndpointBuilder.Metadata.Add(new ParameterBindingMetadata("p", parameters[0], hasTryParse: true, hasBindAsync: false, isOptional: false)); + options.EndpointBuilder.Metadata.Add(new ProducesResponseTypeMetadata(statusCode: StatusCodes.Status200OK, type: typeof(global::System.Int32), contentTypes: GeneratedMetadataConstants.JsonContentType)); ++ ApiEndpointMetadata.AddApiEndpointMetadataIfMissing(options.EndpointBuilder); + return new RequestDelegateMetadataResult { EndpointMetadata = options.EndpointBuilder.Metadata.AsReadOnly() }; + }; + RequestDelegateFactoryFunc createRequestDelegate = (del, options, inferredMetadataResult) => +@@ -259,6 +260,22 @@ namespace Microsoft.AspNetCore.Http.Generated + + } + ++ file sealed class ApiEndpointMetadata : IApiEndpointMetadata ++ { ++ public static readonly ApiEndpointMetadata Instance = new(); ++ ++ private ApiEndpointMetadata() ++ { ++ } ++ ++ public static void AddApiEndpointMetadataIfMissing(EndpointBuilder builder) ++ { ++ if (!builder.Metadata.Any(m => m is IApiEndpointMetadata)) ++ { ++ builder.Metadata.Add(Instance); ++ } ++ } ++ } + %GENERATEDCODEATTRIBUTE% + file static class GeneratedMetadataConstants + { +diff --git a/src/Http/Http.Extensions/test/RequestDelegateGenerator/Baselines/MapAction_ExplicitHeader_NullableStringArrayParam.generated.txt b/src/Http/Http.Extensions/test/RequestDelegateGenerator/Baselines/MapAction_ExplicitHeader_NullableStringArrayParam.generated.txt +index 6365d148..e2c866e2 100644 +--- a/src/Http/Http.Extensions/test/RequestDelegateGenerator/Baselines/MapAction_ExplicitHeader_NullableStringArrayParam.generated.txt ++++ b/src/Http/Http.Extensions/test/RequestDelegateGenerator/Baselines/MapAction_ExplicitHeader_NullableStringArrayParam.generated.txt +@@ -72,6 +72,7 @@ namespace Microsoft.AspNetCore.Http.Generated + var parameters = methodInfo.GetParameters(); + options.EndpointBuilder.Metadata.Add(new ParameterBindingMetadata("p", parameters[0], hasTryParse: false, hasBindAsync: false, isOptional: false)); + options.EndpointBuilder.Metadata.Add(new ProducesResponseTypeMetadata(statusCode: StatusCodes.Status200OK, type: typeof(global::System.Int32), contentTypes: GeneratedMetadataConstants.JsonContentType)); ++ ApiEndpointMetadata.AddApiEndpointMetadataIfMissing(options.EndpointBuilder); + return new RequestDelegateMetadataResult { EndpointMetadata = options.EndpointBuilder.Metadata.AsReadOnly() }; + }; + RequestDelegateFactoryFunc createRequestDelegate = (del, options, inferredMetadataResult) => +@@ -231,6 +232,22 @@ namespace Microsoft.AspNetCore.Http.Generated + + } + ++ file sealed class ApiEndpointMetadata : IApiEndpointMetadata ++ { ++ public static readonly ApiEndpointMetadata Instance = new(); ++ ++ private ApiEndpointMetadata() ++ { ++ } ++ ++ public static void AddApiEndpointMetadataIfMissing(EndpointBuilder builder) ++ { ++ if (!builder.Metadata.Any(m => m is IApiEndpointMetadata)) ++ { ++ builder.Metadata.Add(Instance); ++ } ++ } ++ } + %GENERATEDCODEATTRIBUTE% + file static class GeneratedMetadataConstants + { +diff --git a/src/Http/Http.Extensions/test/RequestDelegateGenerator/Baselines/MapAction_ExplicitHeader_StringArrayParam.generated.txt b/src/Http/Http.Extensions/test/RequestDelegateGenerator/Baselines/MapAction_ExplicitHeader_StringArrayParam.generated.txt +index 66c4504e..b2fc71b9 100644 +--- a/src/Http/Http.Extensions/test/RequestDelegateGenerator/Baselines/MapAction_ExplicitHeader_StringArrayParam.generated.txt ++++ b/src/Http/Http.Extensions/test/RequestDelegateGenerator/Baselines/MapAction_ExplicitHeader_StringArrayParam.generated.txt +@@ -72,6 +72,7 @@ namespace Microsoft.AspNetCore.Http.Generated + var parameters = methodInfo.GetParameters(); + options.EndpointBuilder.Metadata.Add(new ParameterBindingMetadata("p", parameters[0], hasTryParse: false, hasBindAsync: false, isOptional: false)); + options.EndpointBuilder.Metadata.Add(new ProducesResponseTypeMetadata(statusCode: StatusCodes.Status200OK, type: typeof(global::System.Int32), contentTypes: GeneratedMetadataConstants.JsonContentType)); ++ ApiEndpointMetadata.AddApiEndpointMetadataIfMissing(options.EndpointBuilder); + return new RequestDelegateMetadataResult { EndpointMetadata = options.EndpointBuilder.Metadata.AsReadOnly() }; + }; + RequestDelegateFactoryFunc createRequestDelegate = (del, options, inferredMetadataResult) => +@@ -231,6 +232,22 @@ namespace Microsoft.AspNetCore.Http.Generated + + } + ++ file sealed class ApiEndpointMetadata : IApiEndpointMetadata ++ { ++ public static readonly ApiEndpointMetadata Instance = new(); ++ ++ private ApiEndpointMetadata() ++ { ++ } ++ ++ public static void AddApiEndpointMetadataIfMissing(EndpointBuilder builder) ++ { ++ if (!builder.Metadata.Any(m => m is IApiEndpointMetadata)) ++ { ++ builder.Metadata.Add(Instance); ++ } ++ } ++ } + %GENERATEDCODEATTRIBUTE% + file static class GeneratedMetadataConstants + { +diff --git a/src/Http/Http.Extensions/test/RequestDelegateGenerator/Baselines/MapAction_ExplicitQuery_ComplexTypeArrayParam.generated.txt b/src/Http/Http.Extensions/test/RequestDelegateGenerator/Baselines/MapAction_ExplicitQuery_ComplexTypeArrayParam.generated.txt +index 860627ce..9aee726d 100644 +--- a/src/Http/Http.Extensions/test/RequestDelegateGenerator/Baselines/MapAction_ExplicitQuery_ComplexTypeArrayParam.generated.txt ++++ b/src/Http/Http.Extensions/test/RequestDelegateGenerator/Baselines/MapAction_ExplicitQuery_ComplexTypeArrayParam.generated.txt +@@ -72,6 +72,7 @@ namespace Microsoft.AspNetCore.Http.Generated + var parameters = methodInfo.GetParameters(); + options.EndpointBuilder.Metadata.Add(new ParameterBindingMetadata("p", parameters[0], hasTryParse: true, hasBindAsync: false, isOptional: false)); + options.EndpointBuilder.Metadata.Add(new ProducesResponseTypeMetadata(statusCode: StatusCodes.Status200OK, type: typeof(global::System.Int32), contentTypes: GeneratedMetadataConstants.JsonContentType)); ++ ApiEndpointMetadata.AddApiEndpointMetadataIfMissing(options.EndpointBuilder); + return new RequestDelegateMetadataResult { EndpointMetadata = options.EndpointBuilder.Metadata.AsReadOnly() }; + }; + RequestDelegateFactoryFunc createRequestDelegate = (del, options, inferredMetadataResult) => +@@ -259,6 +260,22 @@ namespace Microsoft.AspNetCore.Http.Generated + + } + ++ file sealed class ApiEndpointMetadata : IApiEndpointMetadata ++ { ++ public static readonly ApiEndpointMetadata Instance = new(); ++ ++ private ApiEndpointMetadata() ++ { ++ } ++ ++ public static void AddApiEndpointMetadataIfMissing(EndpointBuilder builder) ++ { ++ if (!builder.Metadata.Any(m => m is IApiEndpointMetadata)) ++ { ++ builder.Metadata.Add(Instance); ++ } ++ } ++ } + %GENERATEDCODEATTRIBUTE% + file static class GeneratedMetadataConstants + { +diff --git a/src/Http/Http.Extensions/test/RequestDelegateGenerator/Baselines/MapAction_ExplicitQuery_IntArrayParam_Optional.generated.txt b/src/Http/Http.Extensions/test/RequestDelegateGenerator/Baselines/MapAction_ExplicitQuery_IntArrayParam_Optional.generated.txt +index f09d0127..01d6808e 100644 +--- a/src/Http/Http.Extensions/test/RequestDelegateGenerator/Baselines/MapAction_ExplicitQuery_IntArrayParam_Optional.generated.txt ++++ b/src/Http/Http.Extensions/test/RequestDelegateGenerator/Baselines/MapAction_ExplicitQuery_IntArrayParam_Optional.generated.txt +@@ -72,6 +72,7 @@ namespace Microsoft.AspNetCore.Http.Generated + var parameters = methodInfo.GetParameters(); + options.EndpointBuilder.Metadata.Add(new ParameterBindingMetadata("p", parameters[0], hasTryParse: true, hasBindAsync: false, isOptional: true)); + options.EndpointBuilder.Metadata.Add(new ProducesResponseTypeMetadata(statusCode: StatusCodes.Status200OK, type: typeof(global::System.Int32[]), contentTypes: GeneratedMetadataConstants.JsonContentType)); ++ ApiEndpointMetadata.AddApiEndpointMetadataIfMissing(options.EndpointBuilder); + return new RequestDelegateMetadataResult { EndpointMetadata = options.EndpointBuilder.Metadata.AsReadOnly() }; + }; + RequestDelegateFactoryFunc createRequestDelegate = (del, options, inferredMetadataResult) => +@@ -259,6 +260,22 @@ namespace Microsoft.AspNetCore.Http.Generated + + } + ++ file sealed class ApiEndpointMetadata : IApiEndpointMetadata ++ { ++ public static readonly ApiEndpointMetadata Instance = new(); ++ ++ private ApiEndpointMetadata() ++ { ++ } ++ ++ public static void AddApiEndpointMetadataIfMissing(EndpointBuilder builder) ++ { ++ if (!builder.Metadata.Any(m => m is IApiEndpointMetadata)) ++ { ++ builder.Metadata.Add(Instance); ++ } ++ } ++ } + %GENERATEDCODEATTRIBUTE% + file static class GeneratedMetadataConstants + { +diff --git a/src/Http/Http.Extensions/test/RequestDelegateGenerator/Baselines/MapAction_ExplicitQuery_IntArrayParam_Optional_QueryNotPresent.generated.txt b/src/Http/Http.Extensions/test/RequestDelegateGenerator/Baselines/MapAction_ExplicitQuery_IntArrayParam_Optional_QueryNotPresent.generated.txt +index f09d0127..01d6808e 100644 +--- a/src/Http/Http.Extensions/test/RequestDelegateGenerator/Baselines/MapAction_ExplicitQuery_IntArrayParam_Optional_QueryNotPresent.generated.txt ++++ b/src/Http/Http.Extensions/test/RequestDelegateGenerator/Baselines/MapAction_ExplicitQuery_IntArrayParam_Optional_QueryNotPresent.generated.txt +@@ -72,6 +72,7 @@ namespace Microsoft.AspNetCore.Http.Generated + var parameters = methodInfo.GetParameters(); + options.EndpointBuilder.Metadata.Add(new ParameterBindingMetadata("p", parameters[0], hasTryParse: true, hasBindAsync: false, isOptional: true)); + options.EndpointBuilder.Metadata.Add(new ProducesResponseTypeMetadata(statusCode: StatusCodes.Status200OK, type: typeof(global::System.Int32[]), contentTypes: GeneratedMetadataConstants.JsonContentType)); ++ ApiEndpointMetadata.AddApiEndpointMetadataIfMissing(options.EndpointBuilder); + return new RequestDelegateMetadataResult { EndpointMetadata = options.EndpointBuilder.Metadata.AsReadOnly() }; + }; + RequestDelegateFactoryFunc createRequestDelegate = (del, options, inferredMetadataResult) => +@@ -259,6 +260,22 @@ namespace Microsoft.AspNetCore.Http.Generated + + } + ++ file sealed class ApiEndpointMetadata : IApiEndpointMetadata ++ { ++ public static readonly ApiEndpointMetadata Instance = new(); ++ ++ private ApiEndpointMetadata() ++ { ++ } ++ ++ public static void AddApiEndpointMetadataIfMissing(EndpointBuilder builder) ++ { ++ if (!builder.Metadata.Any(m => m is IApiEndpointMetadata)) ++ { ++ builder.Metadata.Add(Instance); ++ } ++ } ++ } + %GENERATEDCODEATTRIBUTE% + file static class GeneratedMetadataConstants + { +diff --git a/src/Http/Http.Extensions/test/RequestDelegateGenerator/Baselines/MapAction_ExplicitQuery_NullableIntArrayParam_Optional.generated.txt b/src/Http/Http.Extensions/test/RequestDelegateGenerator/Baselines/MapAction_ExplicitQuery_NullableIntArrayParam_Optional.generated.txt +index 9075d188..40a1b29b 100644 +--- a/src/Http/Http.Extensions/test/RequestDelegateGenerator/Baselines/MapAction_ExplicitQuery_NullableIntArrayParam_Optional.generated.txt ++++ b/src/Http/Http.Extensions/test/RequestDelegateGenerator/Baselines/MapAction_ExplicitQuery_NullableIntArrayParam_Optional.generated.txt +@@ -72,6 +72,7 @@ namespace Microsoft.AspNetCore.Http.Generated + var parameters = methodInfo.GetParameters(); + options.EndpointBuilder.Metadata.Add(new ParameterBindingMetadata("p", parameters[0], hasTryParse: true, hasBindAsync: false, isOptional: true)); + options.EndpointBuilder.Metadata.Add(new ProducesResponseTypeMetadata(statusCode: StatusCodes.Status200OK, type: typeof(global::System.Int32?[]), contentTypes: GeneratedMetadataConstants.JsonContentType)); ++ ApiEndpointMetadata.AddApiEndpointMetadataIfMissing(options.EndpointBuilder); + return new RequestDelegateMetadataResult { EndpointMetadata = options.EndpointBuilder.Metadata.AsReadOnly() }; + }; + RequestDelegateFactoryFunc createRequestDelegate = (del, options, inferredMetadataResult) => +@@ -259,6 +260,22 @@ namespace Microsoft.AspNetCore.Http.Generated + + } + ++ file sealed class ApiEndpointMetadata : IApiEndpointMetadata ++ { ++ public static readonly ApiEndpointMetadata Instance = new(); ++ ++ private ApiEndpointMetadata() ++ { ++ } ++ ++ public static void AddApiEndpointMetadataIfMissing(EndpointBuilder builder) ++ { ++ if (!builder.Metadata.Any(m => m is IApiEndpointMetadata)) ++ { ++ builder.Metadata.Add(Instance); ++ } ++ } ++ } + %GENERATEDCODEATTRIBUTE% + file static class GeneratedMetadataConstants + { +diff --git a/src/Http/Http.Extensions/test/RequestDelegateGenerator/Baselines/MapAction_ExplicitQuery_NullableIntArrayParam_Optional_QueryNotPresent.generated.txt b/src/Http/Http.Extensions/test/RequestDelegateGenerator/Baselines/MapAction_ExplicitQuery_NullableIntArrayParam_Optional_QueryNotPresent.generated.txt +index 9075d188..40a1b29b 100644 +--- a/src/Http/Http.Extensions/test/RequestDelegateGenerator/Baselines/MapAction_ExplicitQuery_NullableIntArrayParam_Optional_QueryNotPresent.generated.txt ++++ b/src/Http/Http.Extensions/test/RequestDelegateGenerator/Baselines/MapAction_ExplicitQuery_NullableIntArrayParam_Optional_QueryNotPresent.generated.txt +@@ -72,6 +72,7 @@ namespace Microsoft.AspNetCore.Http.Generated + var parameters = methodInfo.GetParameters(); + options.EndpointBuilder.Metadata.Add(new ParameterBindingMetadata("p", parameters[0], hasTryParse: true, hasBindAsync: false, isOptional: true)); + options.EndpointBuilder.Metadata.Add(new ProducesResponseTypeMetadata(statusCode: StatusCodes.Status200OK, type: typeof(global::System.Int32?[]), contentTypes: GeneratedMetadataConstants.JsonContentType)); ++ ApiEndpointMetadata.AddApiEndpointMetadataIfMissing(options.EndpointBuilder); + return new RequestDelegateMetadataResult { EndpointMetadata = options.EndpointBuilder.Metadata.AsReadOnly() }; + }; + RequestDelegateFactoryFunc createRequestDelegate = (del, options, inferredMetadataResult) => +@@ -259,6 +260,22 @@ namespace Microsoft.AspNetCore.Http.Generated + + } + ++ file sealed class ApiEndpointMetadata : IApiEndpointMetadata ++ { ++ public static readonly ApiEndpointMetadata Instance = new(); ++ ++ private ApiEndpointMetadata() ++ { ++ } ++ ++ public static void AddApiEndpointMetadataIfMissing(EndpointBuilder builder) ++ { ++ if (!builder.Metadata.Any(m => m is IApiEndpointMetadata)) ++ { ++ builder.Metadata.Add(Instance); ++ } ++ } ++ } + %GENERATEDCODEATTRIBUTE% + file static class GeneratedMetadataConstants + { +diff --git a/src/Http/Http.Extensions/test/RequestDelegateGenerator/Baselines/MapAction_ExplicitQuery_NullableStringArrayParam.generated.txt b/src/Http/Http.Extensions/test/RequestDelegateGenerator/Baselines/MapAction_ExplicitQuery_NullableStringArrayParam.generated.txt +index 1d755d1d..9bebb6ee 100644 +--- a/src/Http/Http.Extensions/test/RequestDelegateGenerator/Baselines/MapAction_ExplicitQuery_NullableStringArrayParam.generated.txt ++++ b/src/Http/Http.Extensions/test/RequestDelegateGenerator/Baselines/MapAction_ExplicitQuery_NullableStringArrayParam.generated.txt +@@ -72,6 +72,7 @@ namespace Microsoft.AspNetCore.Http.Generated + var parameters = methodInfo.GetParameters(); + options.EndpointBuilder.Metadata.Add(new ParameterBindingMetadata("p", parameters[0], hasTryParse: false, hasBindAsync: false, isOptional: false)); + options.EndpointBuilder.Metadata.Add(new ProducesResponseTypeMetadata(statusCode: StatusCodes.Status200OK, type: typeof(global::System.Int32), contentTypes: GeneratedMetadataConstants.JsonContentType)); ++ ApiEndpointMetadata.AddApiEndpointMetadataIfMissing(options.EndpointBuilder); + return new RequestDelegateMetadataResult { EndpointMetadata = options.EndpointBuilder.Metadata.AsReadOnly() }; + }; + RequestDelegateFactoryFunc createRequestDelegate = (del, options, inferredMetadataResult) => +@@ -230,6 +231,22 @@ namespace Microsoft.AspNetCore.Http.Generated + + } + ++ file sealed class ApiEndpointMetadata : IApiEndpointMetadata ++ { ++ public static readonly ApiEndpointMetadata Instance = new(); ++ ++ private ApiEndpointMetadata() ++ { ++ } ++ ++ public static void AddApiEndpointMetadataIfMissing(EndpointBuilder builder) ++ { ++ if (!builder.Metadata.Any(m => m is IApiEndpointMetadata)) ++ { ++ builder.Metadata.Add(Instance); ++ } ++ } ++ } + %GENERATEDCODEATTRIBUTE% + file static class GeneratedMetadataConstants + { +diff --git a/src/Http/Http.Extensions/test/RequestDelegateGenerator/Baselines/MapAction_ExplicitQuery_StringArrayParam.generated.txt b/src/Http/Http.Extensions/test/RequestDelegateGenerator/Baselines/MapAction_ExplicitQuery_StringArrayParam.generated.txt +index e9d7ec91..7931fdc1 100644 +--- a/src/Http/Http.Extensions/test/RequestDelegateGenerator/Baselines/MapAction_ExplicitQuery_StringArrayParam.generated.txt ++++ b/src/Http/Http.Extensions/test/RequestDelegateGenerator/Baselines/MapAction_ExplicitQuery_StringArrayParam.generated.txt +@@ -72,6 +72,7 @@ namespace Microsoft.AspNetCore.Http.Generated + var parameters = methodInfo.GetParameters(); + options.EndpointBuilder.Metadata.Add(new ParameterBindingMetadata("p", parameters[0], hasTryParse: false, hasBindAsync: false, isOptional: false)); + options.EndpointBuilder.Metadata.Add(new ProducesResponseTypeMetadata(statusCode: StatusCodes.Status200OK, type: typeof(global::System.Int32), contentTypes: GeneratedMetadataConstants.JsonContentType)); ++ ApiEndpointMetadata.AddApiEndpointMetadataIfMissing(options.EndpointBuilder); + return new RequestDelegateMetadataResult { EndpointMetadata = options.EndpointBuilder.Metadata.AsReadOnly() }; + }; + RequestDelegateFactoryFunc createRequestDelegate = (del, options, inferredMetadataResult) => +@@ -230,6 +231,22 @@ namespace Microsoft.AspNetCore.Http.Generated + + } + ++ file sealed class ApiEndpointMetadata : IApiEndpointMetadata ++ { ++ public static readonly ApiEndpointMetadata Instance = new(); ++ ++ private ApiEndpointMetadata() ++ { ++ } ++ ++ public static void AddApiEndpointMetadataIfMissing(EndpointBuilder builder) ++ { ++ if (!builder.Metadata.Any(m => m is IApiEndpointMetadata)) ++ { ++ builder.Metadata.Add(Instance); ++ } ++ } ++ } + %GENERATEDCODEATTRIBUTE% + file static class GeneratedMetadataConstants + { +diff --git a/src/Http/Http.Extensions/test/RequestDelegateGenerator/Baselines/MapAction_ExplicitQuery_StringArrayParam_Optional.generated.txt b/src/Http/Http.Extensions/test/RequestDelegateGenerator/Baselines/MapAction_ExplicitQuery_StringArrayParam_Optional.generated.txt +index 3e4918ff..757eb5f8 100644 +--- a/src/Http/Http.Extensions/test/RequestDelegateGenerator/Baselines/MapAction_ExplicitQuery_StringArrayParam_Optional.generated.txt ++++ b/src/Http/Http.Extensions/test/RequestDelegateGenerator/Baselines/MapAction_ExplicitQuery_StringArrayParam_Optional.generated.txt +@@ -72,6 +72,7 @@ namespace Microsoft.AspNetCore.Http.Generated + var parameters = methodInfo.GetParameters(); + options.EndpointBuilder.Metadata.Add(new ParameterBindingMetadata("p", parameters[0], hasTryParse: false, hasBindAsync: false, isOptional: true)); + options.EndpointBuilder.Metadata.Add(new ProducesResponseTypeMetadata(statusCode: StatusCodes.Status200OK, type: typeof(global::System.String[]), contentTypes: GeneratedMetadataConstants.JsonContentType)); ++ ApiEndpointMetadata.AddApiEndpointMetadataIfMissing(options.EndpointBuilder); + return new RequestDelegateMetadataResult { EndpointMetadata = options.EndpointBuilder.Metadata.AsReadOnly() }; + }; + RequestDelegateFactoryFunc createRequestDelegate = (del, options, inferredMetadataResult) => +@@ -230,6 +231,22 @@ namespace Microsoft.AspNetCore.Http.Generated + + } + ++ file sealed class ApiEndpointMetadata : IApiEndpointMetadata ++ { ++ public static readonly ApiEndpointMetadata Instance = new(); ++ ++ private ApiEndpointMetadata() ++ { ++ } ++ ++ public static void AddApiEndpointMetadataIfMissing(EndpointBuilder builder) ++ { ++ if (!builder.Metadata.Any(m => m is IApiEndpointMetadata)) ++ { ++ builder.Metadata.Add(Instance); ++ } ++ } ++ } + %GENERATEDCODEATTRIBUTE% + file static class GeneratedMetadataConstants + { +diff --git a/src/Http/Http.Extensions/test/RequestDelegateGenerator/Baselines/MapAction_ExplicitQuery_StringArrayParam_Optional_QueryNotPresent.generated.txt b/src/Http/Http.Extensions/test/RequestDelegateGenerator/Baselines/MapAction_ExplicitQuery_StringArrayParam_Optional_QueryNotPresent.generated.txt +index 3e4918ff..757eb5f8 100644 +--- a/src/Http/Http.Extensions/test/RequestDelegateGenerator/Baselines/MapAction_ExplicitQuery_StringArrayParam_Optional_QueryNotPresent.generated.txt ++++ b/src/Http/Http.Extensions/test/RequestDelegateGenerator/Baselines/MapAction_ExplicitQuery_StringArrayParam_Optional_QueryNotPresent.generated.txt +@@ -72,6 +72,7 @@ namespace Microsoft.AspNetCore.Http.Generated + var parameters = methodInfo.GetParameters(); + options.EndpointBuilder.Metadata.Add(new ParameterBindingMetadata("p", parameters[0], hasTryParse: false, hasBindAsync: false, isOptional: true)); + options.EndpointBuilder.Metadata.Add(new ProducesResponseTypeMetadata(statusCode: StatusCodes.Status200OK, type: typeof(global::System.String[]), contentTypes: GeneratedMetadataConstants.JsonContentType)); ++ ApiEndpointMetadata.AddApiEndpointMetadataIfMissing(options.EndpointBuilder); + return new RequestDelegateMetadataResult { EndpointMetadata = options.EndpointBuilder.Metadata.AsReadOnly() }; + }; + RequestDelegateFactoryFunc createRequestDelegate = (del, options, inferredMetadataResult) => +@@ -230,6 +231,22 @@ namespace Microsoft.AspNetCore.Http.Generated + + } + ++ file sealed class ApiEndpointMetadata : IApiEndpointMetadata ++ { ++ public static readonly ApiEndpointMetadata Instance = new(); ++ ++ private ApiEndpointMetadata() ++ { ++ } ++ ++ public static void AddApiEndpointMetadataIfMissing(EndpointBuilder builder) ++ { ++ if (!builder.Metadata.Any(m => m is IApiEndpointMetadata)) ++ { ++ builder.Metadata.Add(Instance); ++ } ++ } ++ } + %GENERATEDCODEATTRIBUTE% + file static class GeneratedMetadataConstants + { +diff --git a/src/Http/Http.Extensions/test/RequestDelegateGenerator/Baselines/MapAction_ExplicitServiceParam_SimpleReturn_Snapshot.generated.txt b/src/Http/Http.Extensions/test/RequestDelegateGenerator/Baselines/MapAction_ExplicitServiceParam_SimpleReturn_Snapshot.generated.txt +index a82fa6fb..2e18c631 100644 +--- a/src/Http/Http.Extensions/test/RequestDelegateGenerator/Baselines/MapAction_ExplicitServiceParam_SimpleReturn_Snapshot.generated.txt ++++ b/src/Http/Http.Extensions/test/RequestDelegateGenerator/Baselines/MapAction_ExplicitServiceParam_SimpleReturn_Snapshot.generated.txt +@@ -439,6 +439,22 @@ namespace Microsoft.AspNetCore.Http.Generated + + } + ++ file sealed class ApiEndpointMetadata : IApiEndpointMetadata ++ { ++ public static readonly ApiEndpointMetadata Instance = new(); ++ ++ private ApiEndpointMetadata() ++ { ++ } ++ ++ public static void AddApiEndpointMetadataIfMissing(EndpointBuilder builder) ++ { ++ if (!builder.Metadata.Any(m => m is IApiEndpointMetadata)) ++ { ++ builder.Metadata.Add(Instance); ++ } ++ } ++ } + %GENERATEDCODEATTRIBUTE% + file static class GeneratedMetadataConstants + { +diff --git a/src/Http/Http.Extensions/test/RequestDelegateGenerator/Baselines/MapAction_ExplicitSource_SimpleReturn_Snapshot.generated.txt b/src/Http/Http.Extensions/test/RequestDelegateGenerator/Baselines/MapAction_ExplicitSource_SimpleReturn_Snapshot.generated.txt +index 794413cb..3663350e 100644 +--- a/src/Http/Http.Extensions/test/RequestDelegateGenerator/Baselines/MapAction_ExplicitSource_SimpleReturn_Snapshot.generated.txt ++++ b/src/Http/Http.Extensions/test/RequestDelegateGenerator/Baselines/MapAction_ExplicitSource_SimpleReturn_Snapshot.generated.txt +@@ -606,6 +606,22 @@ namespace Microsoft.AspNetCore.Http.Generated + + } + ++ file sealed class ApiEndpointMetadata : IApiEndpointMetadata ++ { ++ public static readonly ApiEndpointMetadata Instance = new(); ++ ++ private ApiEndpointMetadata() ++ { ++ } ++ ++ public static void AddApiEndpointMetadataIfMissing(EndpointBuilder builder) ++ { ++ if (!builder.Metadata.Any(m => m is IApiEndpointMetadata)) ++ { ++ builder.Metadata.Add(Instance); ++ } ++ } ++ } + %GENERATEDCODEATTRIBUTE% + file static class GeneratedMetadataConstants + { +diff --git a/src/Http/Http.Extensions/test/RequestDelegateGenerator/Baselines/MapAction_ImplicitQuery_ComplexTypeArrayParam.generated.txt b/src/Http/Http.Extensions/test/RequestDelegateGenerator/Baselines/MapAction_ImplicitQuery_ComplexTypeArrayParam.generated.txt +index 948327f8..07e79ab2 100644 +--- a/src/Http/Http.Extensions/test/RequestDelegateGenerator/Baselines/MapAction_ImplicitQuery_ComplexTypeArrayParam.generated.txt ++++ b/src/Http/Http.Extensions/test/RequestDelegateGenerator/Baselines/MapAction_ImplicitQuery_ComplexTypeArrayParam.generated.txt +@@ -72,6 +72,7 @@ namespace Microsoft.AspNetCore.Http.Generated + var parameters = methodInfo.GetParameters(); + options.EndpointBuilder.Metadata.Add(new ParameterBindingMetadata("p", parameters[0], hasTryParse: true, hasBindAsync: false, isOptional: false)); + options.EndpointBuilder.Metadata.Add(new ProducesResponseTypeMetadata(statusCode: StatusCodes.Status200OK, type: typeof(global::System.Int32), contentTypes: GeneratedMetadataConstants.JsonContentType)); ++ ApiEndpointMetadata.AddApiEndpointMetadataIfMissing(options.EndpointBuilder); + return new RequestDelegateMetadataResult { EndpointMetadata = options.EndpointBuilder.Metadata.AsReadOnly() }; + }; + RequestDelegateFactoryFunc createRequestDelegate = (del, options, inferredMetadataResult) => +@@ -266,6 +267,22 @@ namespace Microsoft.AspNetCore.Http.Generated + + } + ++ file sealed class ApiEndpointMetadata : IApiEndpointMetadata ++ { ++ public static readonly ApiEndpointMetadata Instance = new(); ++ ++ private ApiEndpointMetadata() ++ { ++ } ++ ++ public static void AddApiEndpointMetadataIfMissing(EndpointBuilder builder) ++ { ++ if (!builder.Metadata.Any(m => m is IApiEndpointMetadata)) ++ { ++ builder.Metadata.Add(Instance); ++ } ++ } ++ } + %GENERATEDCODEATTRIBUTE% + file static class GeneratedMetadataConstants + { +diff --git a/src/Http/Http.Extensions/test/RequestDelegateGenerator/Baselines/MapAction_ImplicitQuery_IntArrayParam_Optional.generated.txt b/src/Http/Http.Extensions/test/RequestDelegateGenerator/Baselines/MapAction_ImplicitQuery_IntArrayParam_Optional.generated.txt +index 682208c0..e51b39e6 100644 +--- a/src/Http/Http.Extensions/test/RequestDelegateGenerator/Baselines/MapAction_ImplicitQuery_IntArrayParam_Optional.generated.txt ++++ b/src/Http/Http.Extensions/test/RequestDelegateGenerator/Baselines/MapAction_ImplicitQuery_IntArrayParam_Optional.generated.txt +@@ -72,6 +72,7 @@ namespace Microsoft.AspNetCore.Http.Generated + var parameters = methodInfo.GetParameters(); + options.EndpointBuilder.Metadata.Add(new ParameterBindingMetadata("p", parameters[0], hasTryParse: true, hasBindAsync: false, isOptional: true)); + options.EndpointBuilder.Metadata.Add(new ProducesResponseTypeMetadata(statusCode: StatusCodes.Status200OK, type: typeof(global::System.Int32[]), contentTypes: GeneratedMetadataConstants.JsonContentType)); ++ ApiEndpointMetadata.AddApiEndpointMetadataIfMissing(options.EndpointBuilder); + return new RequestDelegateMetadataResult { EndpointMetadata = options.EndpointBuilder.Metadata.AsReadOnly() }; + }; + RequestDelegateFactoryFunc createRequestDelegate = (del, options, inferredMetadataResult) => +@@ -266,6 +267,22 @@ namespace Microsoft.AspNetCore.Http.Generated + + } + ++ file sealed class ApiEndpointMetadata : IApiEndpointMetadata ++ { ++ public static readonly ApiEndpointMetadata Instance = new(); ++ ++ private ApiEndpointMetadata() ++ { ++ } ++ ++ public static void AddApiEndpointMetadataIfMissing(EndpointBuilder builder) ++ { ++ if (!builder.Metadata.Any(m => m is IApiEndpointMetadata)) ++ { ++ builder.Metadata.Add(Instance); ++ } ++ } ++ } + %GENERATEDCODEATTRIBUTE% + file static class GeneratedMetadataConstants + { +diff --git a/src/Http/Http.Extensions/test/RequestDelegateGenerator/Baselines/MapAction_ImplicitQuery_IntArrayParam_Optional_QueryNotPresent.generated.txt b/src/Http/Http.Extensions/test/RequestDelegateGenerator/Baselines/MapAction_ImplicitQuery_IntArrayParam_Optional_QueryNotPresent.generated.txt +index 682208c0..e51b39e6 100644 +--- a/src/Http/Http.Extensions/test/RequestDelegateGenerator/Baselines/MapAction_ImplicitQuery_IntArrayParam_Optional_QueryNotPresent.generated.txt ++++ b/src/Http/Http.Extensions/test/RequestDelegateGenerator/Baselines/MapAction_ImplicitQuery_IntArrayParam_Optional_QueryNotPresent.generated.txt +@@ -72,6 +72,7 @@ namespace Microsoft.AspNetCore.Http.Generated + var parameters = methodInfo.GetParameters(); + options.EndpointBuilder.Metadata.Add(new ParameterBindingMetadata("p", parameters[0], hasTryParse: true, hasBindAsync: false, isOptional: true)); + options.EndpointBuilder.Metadata.Add(new ProducesResponseTypeMetadata(statusCode: StatusCodes.Status200OK, type: typeof(global::System.Int32[]), contentTypes: GeneratedMetadataConstants.JsonContentType)); ++ ApiEndpointMetadata.AddApiEndpointMetadataIfMissing(options.EndpointBuilder); + return new RequestDelegateMetadataResult { EndpointMetadata = options.EndpointBuilder.Metadata.AsReadOnly() }; + }; + RequestDelegateFactoryFunc createRequestDelegate = (del, options, inferredMetadataResult) => +@@ -266,6 +267,22 @@ namespace Microsoft.AspNetCore.Http.Generated + + } + ++ file sealed class ApiEndpointMetadata : IApiEndpointMetadata ++ { ++ public static readonly ApiEndpointMetadata Instance = new(); ++ ++ private ApiEndpointMetadata() ++ { ++ } ++ ++ public static void AddApiEndpointMetadataIfMissing(EndpointBuilder builder) ++ { ++ if (!builder.Metadata.Any(m => m is IApiEndpointMetadata)) ++ { ++ builder.Metadata.Add(Instance); ++ } ++ } ++ } + %GENERATEDCODEATTRIBUTE% + file static class GeneratedMetadataConstants + { +diff --git a/src/Http/Http.Extensions/test/RequestDelegateGenerator/Baselines/MapAction_ImplicitQuery_NullableIntArrayParam_Optional.generated.txt b/src/Http/Http.Extensions/test/RequestDelegateGenerator/Baselines/MapAction_ImplicitQuery_NullableIntArrayParam_Optional.generated.txt +index 82e1993b..2e4b0d34 100644 +--- a/src/Http/Http.Extensions/test/RequestDelegateGenerator/Baselines/MapAction_ImplicitQuery_NullableIntArrayParam_Optional.generated.txt ++++ b/src/Http/Http.Extensions/test/RequestDelegateGenerator/Baselines/MapAction_ImplicitQuery_NullableIntArrayParam_Optional.generated.txt +@@ -72,6 +72,7 @@ namespace Microsoft.AspNetCore.Http.Generated + var parameters = methodInfo.GetParameters(); + options.EndpointBuilder.Metadata.Add(new ParameterBindingMetadata("p", parameters[0], hasTryParse: true, hasBindAsync: false, isOptional: true)); + options.EndpointBuilder.Metadata.Add(new ProducesResponseTypeMetadata(statusCode: StatusCodes.Status200OK, type: typeof(global::System.Int32?[]), contentTypes: GeneratedMetadataConstants.JsonContentType)); ++ ApiEndpointMetadata.AddApiEndpointMetadataIfMissing(options.EndpointBuilder); + return new RequestDelegateMetadataResult { EndpointMetadata = options.EndpointBuilder.Metadata.AsReadOnly() }; + }; + RequestDelegateFactoryFunc createRequestDelegate = (del, options, inferredMetadataResult) => +@@ -266,6 +267,22 @@ namespace Microsoft.AspNetCore.Http.Generated + + } + ++ file sealed class ApiEndpointMetadata : IApiEndpointMetadata ++ { ++ public static readonly ApiEndpointMetadata Instance = new(); ++ ++ private ApiEndpointMetadata() ++ { ++ } ++ ++ public static void AddApiEndpointMetadataIfMissing(EndpointBuilder builder) ++ { ++ if (!builder.Metadata.Any(m => m is IApiEndpointMetadata)) ++ { ++ builder.Metadata.Add(Instance); ++ } ++ } ++ } + %GENERATEDCODEATTRIBUTE% + file static class GeneratedMetadataConstants + { +diff --git a/src/Http/Http.Extensions/test/RequestDelegateGenerator/Baselines/MapAction_ImplicitQuery_NullableIntArrayParam_Optional_QueryNotPresent.generated.txt b/src/Http/Http.Extensions/test/RequestDelegateGenerator/Baselines/MapAction_ImplicitQuery_NullableIntArrayParam_Optional_QueryNotPresent.generated.txt +index 82e1993b..2e4b0d34 100644 +--- a/src/Http/Http.Extensions/test/RequestDelegateGenerator/Baselines/MapAction_ImplicitQuery_NullableIntArrayParam_Optional_QueryNotPresent.generated.txt ++++ b/src/Http/Http.Extensions/test/RequestDelegateGenerator/Baselines/MapAction_ImplicitQuery_NullableIntArrayParam_Optional_QueryNotPresent.generated.txt +@@ -72,6 +72,7 @@ namespace Microsoft.AspNetCore.Http.Generated + var parameters = methodInfo.GetParameters(); + options.EndpointBuilder.Metadata.Add(new ParameterBindingMetadata("p", parameters[0], hasTryParse: true, hasBindAsync: false, isOptional: true)); + options.EndpointBuilder.Metadata.Add(new ProducesResponseTypeMetadata(statusCode: StatusCodes.Status200OK, type: typeof(global::System.Int32?[]), contentTypes: GeneratedMetadataConstants.JsonContentType)); ++ ApiEndpointMetadata.AddApiEndpointMetadataIfMissing(options.EndpointBuilder); + return new RequestDelegateMetadataResult { EndpointMetadata = options.EndpointBuilder.Metadata.AsReadOnly() }; + }; + RequestDelegateFactoryFunc createRequestDelegate = (del, options, inferredMetadataResult) => +@@ -266,6 +267,22 @@ namespace Microsoft.AspNetCore.Http.Generated + + } + ++ file sealed class ApiEndpointMetadata : IApiEndpointMetadata ++ { ++ public static readonly ApiEndpointMetadata Instance = new(); ++ ++ private ApiEndpointMetadata() ++ { ++ } ++ ++ public static void AddApiEndpointMetadataIfMissing(EndpointBuilder builder) ++ { ++ if (!builder.Metadata.Any(m => m is IApiEndpointMetadata)) ++ { ++ builder.Metadata.Add(Instance); ++ } ++ } ++ } + %GENERATEDCODEATTRIBUTE% + file static class GeneratedMetadataConstants + { +diff --git a/src/Http/Http.Extensions/test/RequestDelegateGenerator/Baselines/MapAction_ImplicitQuery_NullableStringArrayParam.generated.txt b/src/Http/Http.Extensions/test/RequestDelegateGenerator/Baselines/MapAction_ImplicitQuery_NullableStringArrayParam.generated.txt +index af6f3f0d..85750166 100644 +--- a/src/Http/Http.Extensions/test/RequestDelegateGenerator/Baselines/MapAction_ImplicitQuery_NullableStringArrayParam.generated.txt ++++ b/src/Http/Http.Extensions/test/RequestDelegateGenerator/Baselines/MapAction_ImplicitQuery_NullableStringArrayParam.generated.txt +@@ -81,12 +81,14 @@ namespace Microsoft.AspNetCore.Http.Generated + if (!serviceProviderIsService.IsService(type)) + { + options.EndpointBuilder.Metadata.Add(new AcceptsMetadata(type: type, isOptional: isOptional, contentTypes: GeneratedMetadataConstants.JsonContentType)); ++ options.EndpointBuilder.Metadata.Add(ApiEndpointMetadata.Instance); + break; + } + } + var parameters = methodInfo.GetParameters(); + options.EndpointBuilder.Metadata.Add(new ParameterBindingMetadata("p", parameters[0], hasTryParse: false, hasBindAsync: false, isOptional: false)); + options.EndpointBuilder.Metadata.Add(new ProducesResponseTypeMetadata(statusCode: StatusCodes.Status200OK, type: typeof(global::System.Int32), contentTypes: GeneratedMetadataConstants.JsonContentType)); ++ ApiEndpointMetadata.AddApiEndpointMetadataIfMissing(options.EndpointBuilder); + return new RequestDelegateMetadataResult { EndpointMetadata = options.EndpointBuilder.Metadata.AsReadOnly() }; + }; + RequestDelegateFactoryFunc createRequestDelegate = (del, options, inferredMetadataResult) => +@@ -327,6 +329,22 @@ namespace Microsoft.AspNetCore.Http.Generated + + } + ++ file sealed class ApiEndpointMetadata : IApiEndpointMetadata ++ { ++ public static readonly ApiEndpointMetadata Instance = new(); ++ ++ private ApiEndpointMetadata() ++ { ++ } ++ ++ public static void AddApiEndpointMetadataIfMissing(EndpointBuilder builder) ++ { ++ if (!builder.Metadata.Any(m => m is IApiEndpointMetadata)) ++ { ++ builder.Metadata.Add(Instance); ++ } ++ } ++ } + %GENERATEDCODEATTRIBUTE% + file static class GeneratedMetadataConstants + { +diff --git a/src/Http/Http.Extensions/test/RequestDelegateGenerator/Baselines/MapAction_ImplicitQuery_NullableStringArrayParam_EmptyQueryValues.generated.txt b/src/Http/Http.Extensions/test/RequestDelegateGenerator/Baselines/MapAction_ImplicitQuery_NullableStringArrayParam_EmptyQueryValues.generated.txt +index af6f3f0d..85750166 100644 +--- a/src/Http/Http.Extensions/test/RequestDelegateGenerator/Baselines/MapAction_ImplicitQuery_NullableStringArrayParam_EmptyQueryValues.generated.txt ++++ b/src/Http/Http.Extensions/test/RequestDelegateGenerator/Baselines/MapAction_ImplicitQuery_NullableStringArrayParam_EmptyQueryValues.generated.txt +@@ -81,12 +81,14 @@ namespace Microsoft.AspNetCore.Http.Generated + if (!serviceProviderIsService.IsService(type)) + { + options.EndpointBuilder.Metadata.Add(new AcceptsMetadata(type: type, isOptional: isOptional, contentTypes: GeneratedMetadataConstants.JsonContentType)); ++ options.EndpointBuilder.Metadata.Add(ApiEndpointMetadata.Instance); + break; + } + } + var parameters = methodInfo.GetParameters(); + options.EndpointBuilder.Metadata.Add(new ParameterBindingMetadata("p", parameters[0], hasTryParse: false, hasBindAsync: false, isOptional: false)); + options.EndpointBuilder.Metadata.Add(new ProducesResponseTypeMetadata(statusCode: StatusCodes.Status200OK, type: typeof(global::System.Int32), contentTypes: GeneratedMetadataConstants.JsonContentType)); ++ ApiEndpointMetadata.AddApiEndpointMetadataIfMissing(options.EndpointBuilder); + return new RequestDelegateMetadataResult { EndpointMetadata = options.EndpointBuilder.Metadata.AsReadOnly() }; + }; + RequestDelegateFactoryFunc createRequestDelegate = (del, options, inferredMetadataResult) => +@@ -327,6 +329,22 @@ namespace Microsoft.AspNetCore.Http.Generated + + } + ++ file sealed class ApiEndpointMetadata : IApiEndpointMetadata ++ { ++ public static readonly ApiEndpointMetadata Instance = new(); ++ ++ private ApiEndpointMetadata() ++ { ++ } ++ ++ public static void AddApiEndpointMetadataIfMissing(EndpointBuilder builder) ++ { ++ if (!builder.Metadata.Any(m => m is IApiEndpointMetadata)) ++ { ++ builder.Metadata.Add(Instance); ++ } ++ } ++ } + %GENERATEDCODEATTRIBUTE% + file static class GeneratedMetadataConstants + { +diff --git a/src/Http/Http.Extensions/test/RequestDelegateGenerator/Baselines/MapAction_ImplicitQuery_NullableStringArrayParam_QueryNotPresent.generated.txt b/src/Http/Http.Extensions/test/RequestDelegateGenerator/Baselines/MapAction_ImplicitQuery_NullableStringArrayParam_QueryNotPresent.generated.txt +index af6f3f0d..85750166 100644 +--- a/src/Http/Http.Extensions/test/RequestDelegateGenerator/Baselines/MapAction_ImplicitQuery_NullableStringArrayParam_QueryNotPresent.generated.txt ++++ b/src/Http/Http.Extensions/test/RequestDelegateGenerator/Baselines/MapAction_ImplicitQuery_NullableStringArrayParam_QueryNotPresent.generated.txt +@@ -81,12 +81,14 @@ namespace Microsoft.AspNetCore.Http.Generated + if (!serviceProviderIsService.IsService(type)) + { + options.EndpointBuilder.Metadata.Add(new AcceptsMetadata(type: type, isOptional: isOptional, contentTypes: GeneratedMetadataConstants.JsonContentType)); ++ options.EndpointBuilder.Metadata.Add(ApiEndpointMetadata.Instance); + break; + } + } + var parameters = methodInfo.GetParameters(); + options.EndpointBuilder.Metadata.Add(new ParameterBindingMetadata("p", parameters[0], hasTryParse: false, hasBindAsync: false, isOptional: false)); + options.EndpointBuilder.Metadata.Add(new ProducesResponseTypeMetadata(statusCode: StatusCodes.Status200OK, type: typeof(global::System.Int32), contentTypes: GeneratedMetadataConstants.JsonContentType)); ++ ApiEndpointMetadata.AddApiEndpointMetadataIfMissing(options.EndpointBuilder); + return new RequestDelegateMetadataResult { EndpointMetadata = options.EndpointBuilder.Metadata.AsReadOnly() }; + }; + RequestDelegateFactoryFunc createRequestDelegate = (del, options, inferredMetadataResult) => +@@ -327,6 +329,22 @@ namespace Microsoft.AspNetCore.Http.Generated + + } + ++ file sealed class ApiEndpointMetadata : IApiEndpointMetadata ++ { ++ public static readonly ApiEndpointMetadata Instance = new(); ++ ++ private ApiEndpointMetadata() ++ { ++ } ++ ++ public static void AddApiEndpointMetadataIfMissing(EndpointBuilder builder) ++ { ++ if (!builder.Metadata.Any(m => m is IApiEndpointMetadata)) ++ { ++ builder.Metadata.Add(Instance); ++ } ++ } ++ } + %GENERATEDCODEATTRIBUTE% + file static class GeneratedMetadataConstants + { +diff --git a/src/Http/Http.Extensions/test/RequestDelegateGenerator/Baselines/MapAction_ImplicitQuery_StringArrayParam.generated.txt b/src/Http/Http.Extensions/test/RequestDelegateGenerator/Baselines/MapAction_ImplicitQuery_StringArrayParam.generated.txt +index 3d2c9a68..9c1fe26e 100644 +--- a/src/Http/Http.Extensions/test/RequestDelegateGenerator/Baselines/MapAction_ImplicitQuery_StringArrayParam.generated.txt ++++ b/src/Http/Http.Extensions/test/RequestDelegateGenerator/Baselines/MapAction_ImplicitQuery_StringArrayParam.generated.txt +@@ -81,12 +81,14 @@ namespace Microsoft.AspNetCore.Http.Generated + if (!serviceProviderIsService.IsService(type)) + { + options.EndpointBuilder.Metadata.Add(new AcceptsMetadata(type: type, isOptional: isOptional, contentTypes: GeneratedMetadataConstants.JsonContentType)); ++ options.EndpointBuilder.Metadata.Add(ApiEndpointMetadata.Instance); + break; + } + } + var parameters = methodInfo.GetParameters(); + options.EndpointBuilder.Metadata.Add(new ParameterBindingMetadata("p", parameters[0], hasTryParse: false, hasBindAsync: false, isOptional: false)); + options.EndpointBuilder.Metadata.Add(new ProducesResponseTypeMetadata(statusCode: StatusCodes.Status200OK, type: typeof(global::System.Int32), contentTypes: GeneratedMetadataConstants.JsonContentType)); ++ ApiEndpointMetadata.AddApiEndpointMetadataIfMissing(options.EndpointBuilder); + return new RequestDelegateMetadataResult { EndpointMetadata = options.EndpointBuilder.Metadata.AsReadOnly() }; + }; + RequestDelegateFactoryFunc createRequestDelegate = (del, options, inferredMetadataResult) => +@@ -327,6 +329,22 @@ namespace Microsoft.AspNetCore.Http.Generated + + } + ++ file sealed class ApiEndpointMetadata : IApiEndpointMetadata ++ { ++ public static readonly ApiEndpointMetadata Instance = new(); ++ ++ private ApiEndpointMetadata() ++ { ++ } ++ ++ public static void AddApiEndpointMetadataIfMissing(EndpointBuilder builder) ++ { ++ if (!builder.Metadata.Any(m => m is IApiEndpointMetadata)) ++ { ++ builder.Metadata.Add(Instance); ++ } ++ } ++ } + %GENERATEDCODEATTRIBUTE% + file static class GeneratedMetadataConstants + { +diff --git a/src/Http/Http.Extensions/test/RequestDelegateGenerator/Baselines/MapAction_ImplicitQuery_StringArrayParam_Optional.generated.txt b/src/Http/Http.Extensions/test/RequestDelegateGenerator/Baselines/MapAction_ImplicitQuery_StringArrayParam_Optional.generated.txt +index 5e6adff6..65ddf710 100644 +--- a/src/Http/Http.Extensions/test/RequestDelegateGenerator/Baselines/MapAction_ImplicitQuery_StringArrayParam_Optional.generated.txt ++++ b/src/Http/Http.Extensions/test/RequestDelegateGenerator/Baselines/MapAction_ImplicitQuery_StringArrayParam_Optional.generated.txt +@@ -81,12 +81,14 @@ namespace Microsoft.AspNetCore.Http.Generated + if (!serviceProviderIsService.IsService(type)) + { + options.EndpointBuilder.Metadata.Add(new AcceptsMetadata(type: type, isOptional: isOptional, contentTypes: GeneratedMetadataConstants.JsonContentType)); ++ options.EndpointBuilder.Metadata.Add(ApiEndpointMetadata.Instance); + break; + } + } + var parameters = methodInfo.GetParameters(); + options.EndpointBuilder.Metadata.Add(new ParameterBindingMetadata("p", parameters[0], hasTryParse: false, hasBindAsync: false, isOptional: true)); + options.EndpointBuilder.Metadata.Add(new ProducesResponseTypeMetadata(statusCode: StatusCodes.Status200OK, type: typeof(global::System.String[]), contentTypes: GeneratedMetadataConstants.JsonContentType)); ++ ApiEndpointMetadata.AddApiEndpointMetadataIfMissing(options.EndpointBuilder); + return new RequestDelegateMetadataResult { EndpointMetadata = options.EndpointBuilder.Metadata.AsReadOnly() }; + }; + RequestDelegateFactoryFunc createRequestDelegate = (del, options, inferredMetadataResult) => +@@ -327,6 +329,22 @@ namespace Microsoft.AspNetCore.Http.Generated + + } + ++ file sealed class ApiEndpointMetadata : IApiEndpointMetadata ++ { ++ public static readonly ApiEndpointMetadata Instance = new(); ++ ++ private ApiEndpointMetadata() ++ { ++ } ++ ++ public static void AddApiEndpointMetadataIfMissing(EndpointBuilder builder) ++ { ++ if (!builder.Metadata.Any(m => m is IApiEndpointMetadata)) ++ { ++ builder.Metadata.Add(Instance); ++ } ++ } ++ } + %GENERATEDCODEATTRIBUTE% + file static class GeneratedMetadataConstants + { +diff --git a/src/Http/Http.Extensions/test/RequestDelegateGenerator/Baselines/MapAction_ImplicitQuery_StringArrayParam_Optional_QueryNotPresent.generated.txt b/src/Http/Http.Extensions/test/RequestDelegateGenerator/Baselines/MapAction_ImplicitQuery_StringArrayParam_Optional_QueryNotPresent.generated.txt +index 5e6adff6..65ddf710 100644 +--- a/src/Http/Http.Extensions/test/RequestDelegateGenerator/Baselines/MapAction_ImplicitQuery_StringArrayParam_Optional_QueryNotPresent.generated.txt ++++ b/src/Http/Http.Extensions/test/RequestDelegateGenerator/Baselines/MapAction_ImplicitQuery_StringArrayParam_Optional_QueryNotPresent.generated.txt +@@ -81,12 +81,14 @@ namespace Microsoft.AspNetCore.Http.Generated + if (!serviceProviderIsService.IsService(type)) + { + options.EndpointBuilder.Metadata.Add(new AcceptsMetadata(type: type, isOptional: isOptional, contentTypes: GeneratedMetadataConstants.JsonContentType)); ++ options.EndpointBuilder.Metadata.Add(ApiEndpointMetadata.Instance); + break; + } + } + var parameters = methodInfo.GetParameters(); + options.EndpointBuilder.Metadata.Add(new ParameterBindingMetadata("p", parameters[0], hasTryParse: false, hasBindAsync: false, isOptional: true)); + options.EndpointBuilder.Metadata.Add(new ProducesResponseTypeMetadata(statusCode: StatusCodes.Status200OK, type: typeof(global::System.String[]), contentTypes: GeneratedMetadataConstants.JsonContentType)); ++ ApiEndpointMetadata.AddApiEndpointMetadataIfMissing(options.EndpointBuilder); + return new RequestDelegateMetadataResult { EndpointMetadata = options.EndpointBuilder.Metadata.AsReadOnly() }; + }; + RequestDelegateFactoryFunc createRequestDelegate = (del, options, inferredMetadataResult) => +@@ -327,6 +329,22 @@ namespace Microsoft.AspNetCore.Http.Generated + + } + ++ file sealed class ApiEndpointMetadata : IApiEndpointMetadata ++ { ++ public static readonly ApiEndpointMetadata Instance = new(); ++ ++ private ApiEndpointMetadata() ++ { ++ } ++ ++ public static void AddApiEndpointMetadataIfMissing(EndpointBuilder builder) ++ { ++ if (!builder.Metadata.Any(m => m is IApiEndpointMetadata)) ++ { ++ builder.Metadata.Add(Instance); ++ } ++ } ++ } + %GENERATEDCODEATTRIBUTE% + file static class GeneratedMetadataConstants + { +diff --git a/src/Http/Http.Extensions/test/RequestDelegateGenerator/Baselines/MapAction_JsonBodyOrService_HandlesBothJsonAndService.generated.txt b/src/Http/Http.Extensions/test/RequestDelegateGenerator/Baselines/MapAction_JsonBodyOrService_HandlesBothJsonAndService.generated.txt +index 9a7acd7e..bc9c6a59 100644 +--- a/src/Http/Http.Extensions/test/RequestDelegateGenerator/Baselines/MapAction_JsonBodyOrService_HandlesBothJsonAndService.generated.txt ++++ b/src/Http/Http.Extensions/test/RequestDelegateGenerator/Baselines/MapAction_JsonBodyOrService_HandlesBothJsonAndService.generated.txt +@@ -82,6 +82,7 @@ namespace Microsoft.AspNetCore.Http.Generated + if (!serviceProviderIsService.IsService(type)) + { + options.EndpointBuilder.Metadata.Add(new AcceptsMetadata(type: type, isOptional: isOptional, contentTypes: GeneratedMetadataConstants.JsonContentType)); ++ options.EndpointBuilder.Metadata.Add(ApiEndpointMetadata.Instance); + break; + } + } +@@ -345,6 +346,22 @@ namespace Microsoft.AspNetCore.Http.Generated + + } + ++ file sealed class ApiEndpointMetadata : IApiEndpointMetadata ++ { ++ public static readonly ApiEndpointMetadata Instance = new(); ++ ++ private ApiEndpointMetadata() ++ { ++ } ++ ++ public static void AddApiEndpointMetadataIfMissing(EndpointBuilder builder) ++ { ++ if (!builder.Metadata.Any(m => m is IApiEndpointMetadata)) ++ { ++ builder.Metadata.Add(Instance); ++ } ++ } ++ } + %GENERATEDCODEATTRIBUTE% + file static class GeneratedMetadataConstants + { +diff --git a/src/Http/Http.Extensions/test/RequestDelegateGenerator/Baselines/MapAction_MultipleSpecialTypeParam_StringReturn.generated.txt b/src/Http/Http.Extensions/test/RequestDelegateGenerator/Baselines/MapAction_MultipleSpecialTypeParam_StringReturn.generated.txt +index 8ac1c767..560f0ec1 100644 +--- a/src/Http/Http.Extensions/test/RequestDelegateGenerator/Baselines/MapAction_MultipleSpecialTypeParam_StringReturn.generated.txt ++++ b/src/Http/Http.Extensions/test/RequestDelegateGenerator/Baselines/MapAction_MultipleSpecialTypeParam_StringReturn.generated.txt +@@ -234,6 +234,22 @@ namespace Microsoft.AspNetCore.Http.Generated + + } + ++ file sealed class ApiEndpointMetadata : IApiEndpointMetadata ++ { ++ public static readonly ApiEndpointMetadata Instance = new(); ++ ++ private ApiEndpointMetadata() ++ { ++ } ++ ++ public static void AddApiEndpointMetadataIfMissing(EndpointBuilder builder) ++ { ++ if (!builder.Metadata.Any(m => m is IApiEndpointMetadata)) ++ { ++ builder.Metadata.Add(Instance); ++ } ++ } ++ } + %GENERATEDCODEATTRIBUTE% + file static class GeneratedMetadataConstants + { +diff --git a/src/Http/Http.Extensions/test/RequestDelegateGenerator/Baselines/MapAction_MultipleStringParam_StringReturn.generated.txt b/src/Http/Http.Extensions/test/RequestDelegateGenerator/Baselines/MapAction_MultipleStringParam_StringReturn.generated.txt +index 139a5739..0c26ae02 100644 +--- a/src/Http/Http.Extensions/test/RequestDelegateGenerator/Baselines/MapAction_MultipleStringParam_StringReturn.generated.txt ++++ b/src/Http/Http.Extensions/test/RequestDelegateGenerator/Baselines/MapAction_MultipleStringParam_StringReturn.generated.txt +@@ -267,6 +267,22 @@ namespace Microsoft.AspNetCore.Http.Generated + + } + ++ file sealed class ApiEndpointMetadata : IApiEndpointMetadata ++ { ++ public static readonly ApiEndpointMetadata Instance = new(); ++ ++ private ApiEndpointMetadata() ++ { ++ } ++ ++ public static void AddApiEndpointMetadataIfMissing(EndpointBuilder builder) ++ { ++ if (!builder.Metadata.Any(m => m is IApiEndpointMetadata)) ++ { ++ builder.Metadata.Add(Instance); ++ } ++ } ++ } + %GENERATEDCODEATTRIBUTE% + file static class GeneratedMetadataConstants + { +diff --git a/src/Http/Http.Extensions/test/RequestDelegateGenerator/Baselines/MapAction_NoParam_StringReturn_WithFilter.generated.txt b/src/Http/Http.Extensions/test/RequestDelegateGenerator/Baselines/MapAction_NoParam_StringReturn_WithFilter.generated.txt +index ae38db99..18cf2ce8 100644 +--- a/src/Http/Http.Extensions/test/RequestDelegateGenerator/Baselines/MapAction_NoParam_StringReturn_WithFilter.generated.txt ++++ b/src/Http/Http.Extensions/test/RequestDelegateGenerator/Baselines/MapAction_NoParam_StringReturn_WithFilter.generated.txt +@@ -225,6 +225,22 @@ namespace Microsoft.AspNetCore.Http.Generated + + } + ++ file sealed class ApiEndpointMetadata : IApiEndpointMetadata ++ { ++ public static readonly ApiEndpointMetadata Instance = new(); ++ ++ private ApiEndpointMetadata() ++ { ++ } ++ ++ public static void AddApiEndpointMetadataIfMissing(EndpointBuilder builder) ++ { ++ if (!builder.Metadata.Any(m => m is IApiEndpointMetadata)) ++ { ++ builder.Metadata.Add(Instance); ++ } ++ } ++ } + %GENERATEDCODEATTRIBUTE% + file static class GeneratedMetadataConstants + { +diff --git a/src/Http/Http.Extensions/test/RequestDelegateGenerator/Baselines/MapAction_ReturnsString_Has_Metadata.generated.txt b/src/Http/Http.Extensions/test/RequestDelegateGenerator/Baselines/MapAction_ReturnsString_Has_Metadata.generated.txt +index ae38db99..18cf2ce8 100644 +--- a/src/Http/Http.Extensions/test/RequestDelegateGenerator/Baselines/MapAction_ReturnsString_Has_Metadata.generated.txt ++++ b/src/Http/Http.Extensions/test/RequestDelegateGenerator/Baselines/MapAction_ReturnsString_Has_Metadata.generated.txt +@@ -225,6 +225,22 @@ namespace Microsoft.AspNetCore.Http.Generated + + } + ++ file sealed class ApiEndpointMetadata : IApiEndpointMetadata ++ { ++ public static readonly ApiEndpointMetadata Instance = new(); ++ ++ private ApiEndpointMetadata() ++ { ++ } ++ ++ public static void AddApiEndpointMetadataIfMissing(EndpointBuilder builder) ++ { ++ if (!builder.Metadata.Any(m => m is IApiEndpointMetadata)) ++ { ++ builder.Metadata.Add(Instance); ++ } ++ } ++ } + %GENERATEDCODEATTRIBUTE% + file static class GeneratedMetadataConstants + { +diff --git a/src/Http/Http.Extensions/test/RequestDelegateGenerator/Baselines/MapAction_ReturnsTodo_Has_Metadata.generated.txt b/src/Http/Http.Extensions/test/RequestDelegateGenerator/Baselines/MapAction_ReturnsTodo_Has_Metadata.generated.txt +index f1a99f9e..808d55a9 100644 +--- a/src/Http/Http.Extensions/test/RequestDelegateGenerator/Baselines/MapAction_ReturnsTodo_Has_Metadata.generated.txt ++++ b/src/Http/Http.Extensions/test/RequestDelegateGenerator/Baselines/MapAction_ReturnsTodo_Has_Metadata.generated.txt +@@ -70,6 +70,7 @@ namespace Microsoft.AspNetCore.Http.Generated + Debug.Assert(options.EndpointBuilder != null, "EndpointBuilder not found."); + options.EndpointBuilder.Metadata.Add(new System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.AspNetCore.Http.RequestDelegateGenerator, Version=42.42.42.42, Culture=neutral, PublicKeyToken=adb9793829ddae60", "42.42.42.42")); + options.EndpointBuilder.Metadata.Add(new ProducesResponseTypeMetadata(statusCode: StatusCodes.Status200OK, type: typeof(global::Microsoft.AspNetCore.Http.Generators.Tests.Todo), contentTypes: GeneratedMetadataConstants.JsonContentType)); ++ ApiEndpointMetadata.AddApiEndpointMetadataIfMissing(options.EndpointBuilder); + return new RequestDelegateMetadataResult { EndpointMetadata = options.EndpointBuilder.Metadata.AsReadOnly() }; + }; + RequestDelegateFactoryFunc createRequestDelegate = (del, options, inferredMetadataResult) => +@@ -218,6 +219,22 @@ namespace Microsoft.AspNetCore.Http.Generated + + } + ++ file sealed class ApiEndpointMetadata : IApiEndpointMetadata ++ { ++ public static readonly ApiEndpointMetadata Instance = new(); ++ ++ private ApiEndpointMetadata() ++ { ++ } ++ ++ public static void AddApiEndpointMetadataIfMissing(EndpointBuilder builder) ++ { ++ if (!builder.Metadata.Any(m => m is IApiEndpointMetadata)) ++ { ++ builder.Metadata.Add(Instance); ++ } ++ } ++ } + %GENERATEDCODEATTRIBUTE% + file static class GeneratedMetadataConstants + { +diff --git a/src/Http/Http.Extensions/test/RequestDelegateGenerator/Baselines/MapAction_SingleComplexTypeParam_StringReturn.generated.txt b/src/Http/Http.Extensions/test/RequestDelegateGenerator/Baselines/MapAction_SingleComplexTypeParam_StringReturn.generated.txt +index dd910316..50993013 100644 +--- a/src/Http/Http.Extensions/test/RequestDelegateGenerator/Baselines/MapAction_SingleComplexTypeParam_StringReturn.generated.txt ++++ b/src/Http/Http.Extensions/test/RequestDelegateGenerator/Baselines/MapAction_SingleComplexTypeParam_StringReturn.generated.txt +@@ -266,6 +266,22 @@ namespace Microsoft.AspNetCore.Http.Generated + + } + ++ file sealed class ApiEndpointMetadata : IApiEndpointMetadata ++ { ++ public static readonly ApiEndpointMetadata Instance = new(); ++ ++ private ApiEndpointMetadata() ++ { ++ } ++ ++ public static void AddApiEndpointMetadataIfMissing(EndpointBuilder builder) ++ { ++ if (!builder.Metadata.Any(m => m is IApiEndpointMetadata)) ++ { ++ builder.Metadata.Add(Instance); ++ } ++ } ++ } + %GENERATEDCODEATTRIBUTE% + file static class GeneratedMetadataConstants + { +diff --git a/src/Http/Http.Extensions/test/RequestDelegateGenerator/Baselines/MapAction_SingleEnumParam_StringReturn.generated.txt b/src/Http/Http.Extensions/test/RequestDelegateGenerator/Baselines/MapAction_SingleEnumParam_StringReturn.generated.txt +index e37a0fa0..b1b71f8e 100644 +--- a/src/Http/Http.Extensions/test/RequestDelegateGenerator/Baselines/MapAction_SingleEnumParam_StringReturn.generated.txt ++++ b/src/Http/Http.Extensions/test/RequestDelegateGenerator/Baselines/MapAction_SingleEnumParam_StringReturn.generated.txt +@@ -266,6 +266,22 @@ namespace Microsoft.AspNetCore.Http.Generated + + } + ++ file sealed class ApiEndpointMetadata : IApiEndpointMetadata ++ { ++ public static readonly ApiEndpointMetadata Instance = new(); ++ ++ private ApiEndpointMetadata() ++ { ++ } ++ ++ public static void AddApiEndpointMetadataIfMissing(EndpointBuilder builder) ++ { ++ if (!builder.Metadata.Any(m => m is IApiEndpointMetadata)) ++ { ++ builder.Metadata.Add(Instance); ++ } ++ } ++ } + %GENERATEDCODEATTRIBUTE% + file static class GeneratedMetadataConstants + { +diff --git a/src/Http/Http.Extensions/test/RequestDelegateGenerator/Baselines/MapAction_SingleNullableStringParam_WithEmptyQueryStringValueProvided_StringReturn.generated.txt b/src/Http/Http.Extensions/test/RequestDelegateGenerator/Baselines/MapAction_SingleNullableStringParam_WithEmptyQueryStringValueProvided_StringReturn.generated.txt +index 773c77bc..b56621cb 100644 +--- a/src/Http/Http.Extensions/test/RequestDelegateGenerator/Baselines/MapAction_SingleNullableStringParam_WithEmptyQueryStringValueProvided_StringReturn.generated.txt ++++ b/src/Http/Http.Extensions/test/RequestDelegateGenerator/Baselines/MapAction_SingleNullableStringParam_WithEmptyQueryStringValueProvided_StringReturn.generated.txt +@@ -238,6 +238,22 @@ namespace Microsoft.AspNetCore.Http.Generated + + } + ++ file sealed class ApiEndpointMetadata : IApiEndpointMetadata ++ { ++ public static readonly ApiEndpointMetadata Instance = new(); ++ ++ private ApiEndpointMetadata() ++ { ++ } ++ ++ public static void AddApiEndpointMetadataIfMissing(EndpointBuilder builder) ++ { ++ if (!builder.Metadata.Any(m => m is IApiEndpointMetadata)) ++ { ++ builder.Metadata.Add(Instance); ++ } ++ } ++ } + %GENERATEDCODEATTRIBUTE% + file static class GeneratedMetadataConstants + { +diff --git a/src/Http/Http.Extensions/test/RequestDelegateGenerator/Baselines/MapAction_TakesCustomMetadataEmitter_Has_Metadata.generated.txt b/src/Http/Http.Extensions/test/RequestDelegateGenerator/Baselines/MapAction_TakesCustomMetadataEmitter_Has_Metadata.generated.txt +index 839b8eaa..72e03e06 100644 +--- a/src/Http/Http.Extensions/test/RequestDelegateGenerator/Baselines/MapAction_TakesCustomMetadataEmitter_Has_Metadata.generated.txt ++++ b/src/Http/Http.Extensions/test/RequestDelegateGenerator/Baselines/MapAction_TakesCustomMetadataEmitter_Has_Metadata.generated.txt +@@ -81,6 +81,7 @@ namespace Microsoft.AspNetCore.Http.Generated + if (!serviceProviderIsService.IsService(type)) + { + options.EndpointBuilder.Metadata.Add(new AcceptsMetadata(type: type, isOptional: isOptional, contentTypes: GeneratedMetadataConstants.JsonContentType)); ++ options.EndpointBuilder.Metadata.Add(ApiEndpointMetadata.Instance); + break; + } + } +@@ -333,6 +334,22 @@ namespace Microsoft.AspNetCore.Http.Generated + + } + ++ file sealed class ApiEndpointMetadata : IApiEndpointMetadata ++ { ++ public static readonly ApiEndpointMetadata Instance = new(); ++ ++ private ApiEndpointMetadata() ++ { ++ } ++ ++ public static void AddApiEndpointMetadataIfMissing(EndpointBuilder builder) ++ { ++ if (!builder.Metadata.Any(m => m is IApiEndpointMetadata)) ++ { ++ builder.Metadata.Add(Instance); ++ } ++ } ++ } + %GENERATEDCODEATTRIBUTE% + file static class GeneratedMetadataConstants + { +diff --git a/src/Http/Http.Extensions/test/RequestDelegateGenerator/Baselines/MapMethods_Get_WithArrayQueryString_AndBody_ShouldUseQueryString.generated.txt b/src/Http/Http.Extensions/test/RequestDelegateGenerator/Baselines/MapMethods_Get_WithArrayQueryString_AndBody_ShouldUseQueryString.generated.txt +index 0daff798..7409065d 100644 +--- a/src/Http/Http.Extensions/test/RequestDelegateGenerator/Baselines/MapMethods_Get_WithArrayQueryString_AndBody_ShouldUseQueryString.generated.txt ++++ b/src/Http/Http.Extensions/test/RequestDelegateGenerator/Baselines/MapMethods_Get_WithArrayQueryString_AndBody_ShouldUseQueryString.generated.txt +@@ -81,6 +81,7 @@ namespace Microsoft.AspNetCore.Http.Generated + if (!serviceProviderIsService.IsService(type)) + { + options.EndpointBuilder.Metadata.Add(new AcceptsMetadata(type: type, isOptional: isOptional, contentTypes: GeneratedMetadataConstants.JsonContentType)); ++ options.EndpointBuilder.Metadata.Add(ApiEndpointMetadata.Instance); + break; + } + } +@@ -334,6 +335,22 @@ namespace Microsoft.AspNetCore.Http.Generated + + } + ++ file sealed class ApiEndpointMetadata : IApiEndpointMetadata ++ { ++ public static readonly ApiEndpointMetadata Instance = new(); ++ ++ private ApiEndpointMetadata() ++ { ++ } ++ ++ public static void AddApiEndpointMetadataIfMissing(EndpointBuilder builder) ++ { ++ if (!builder.Metadata.Any(m => m is IApiEndpointMetadata)) ++ { ++ builder.Metadata.Add(Instance); ++ } ++ } ++ } + %GENERATEDCODEATTRIBUTE% + file static class GeneratedMetadataConstants + { +diff --git a/src/Http/Http.Extensions/test/RequestDelegateGenerator/Baselines/MapMethods_PostAndGet_WithArrayQueryString_AndBody_ShouldUseQueryString.generated.txt b/src/Http/Http.Extensions/test/RequestDelegateGenerator/Baselines/MapMethods_PostAndGet_WithArrayQueryString_AndBody_ShouldUseQueryString.generated.txt +index 0daff798..7409065d 100644 +--- a/src/Http/Http.Extensions/test/RequestDelegateGenerator/Baselines/MapMethods_PostAndGet_WithArrayQueryString_AndBody_ShouldUseQueryString.generated.txt ++++ b/src/Http/Http.Extensions/test/RequestDelegateGenerator/Baselines/MapMethods_PostAndGet_WithArrayQueryString_AndBody_ShouldUseQueryString.generated.txt +@@ -81,6 +81,7 @@ namespace Microsoft.AspNetCore.Http.Generated + if (!serviceProviderIsService.IsService(type)) + { + options.EndpointBuilder.Metadata.Add(new AcceptsMetadata(type: type, isOptional: isOptional, contentTypes: GeneratedMetadataConstants.JsonContentType)); ++ options.EndpointBuilder.Metadata.Add(ApiEndpointMetadata.Instance); + break; + } + } +@@ -334,6 +335,22 @@ namespace Microsoft.AspNetCore.Http.Generated + + } + ++ file sealed class ApiEndpointMetadata : IApiEndpointMetadata ++ { ++ public static readonly ApiEndpointMetadata Instance = new(); ++ ++ private ApiEndpointMetadata() ++ { ++ } ++ ++ public static void AddApiEndpointMetadataIfMissing(EndpointBuilder builder) ++ { ++ if (!builder.Metadata.Any(m => m is IApiEndpointMetadata)) ++ { ++ builder.Metadata.Add(Instance); ++ } ++ } ++ } + %GENERATEDCODEATTRIBUTE% + file static class GeneratedMetadataConstants + { +diff --git a/src/Http/Http.Extensions/test/RequestDelegateGenerator/Baselines/MapMethods_PostAndPut_WithArrayQueryString_AndBody_ShouldUseBody.generated.txt b/src/Http/Http.Extensions/test/RequestDelegateGenerator/Baselines/MapMethods_PostAndPut_WithArrayQueryString_AndBody_ShouldUseBody.generated.txt +index 0daff798..7409065d 100644 +--- a/src/Http/Http.Extensions/test/RequestDelegateGenerator/Baselines/MapMethods_PostAndPut_WithArrayQueryString_AndBody_ShouldUseBody.generated.txt ++++ b/src/Http/Http.Extensions/test/RequestDelegateGenerator/Baselines/MapMethods_PostAndPut_WithArrayQueryString_AndBody_ShouldUseBody.generated.txt +@@ -81,6 +81,7 @@ namespace Microsoft.AspNetCore.Http.Generated + if (!serviceProviderIsService.IsService(type)) + { + options.EndpointBuilder.Metadata.Add(new AcceptsMetadata(type: type, isOptional: isOptional, contentTypes: GeneratedMetadataConstants.JsonContentType)); ++ options.EndpointBuilder.Metadata.Add(ApiEndpointMetadata.Instance); + break; + } + } +@@ -334,6 +335,22 @@ namespace Microsoft.AspNetCore.Http.Generated + + } + ++ file sealed class ApiEndpointMetadata : IApiEndpointMetadata ++ { ++ public static readonly ApiEndpointMetadata Instance = new(); ++ ++ private ApiEndpointMetadata() ++ { ++ } ++ ++ public static void AddApiEndpointMetadataIfMissing(EndpointBuilder builder) ++ { ++ if (!builder.Metadata.Any(m => m is IApiEndpointMetadata)) ++ { ++ builder.Metadata.Add(Instance); ++ } ++ } ++ } + %GENERATEDCODEATTRIBUTE% + file static class GeneratedMetadataConstants + { +diff --git a/src/Http/Http.Extensions/test/RequestDelegateGenerator/Baselines/MapMethods_Post_WithArrayQueryString_AndBody_ShouldUseBody.generated.txt b/src/Http/Http.Extensions/test/RequestDelegateGenerator/Baselines/MapMethods_Post_WithArrayQueryString_AndBody_ShouldUseBody.generated.txt +index 0daff798..7409065d 100644 +--- a/src/Http/Http.Extensions/test/RequestDelegateGenerator/Baselines/MapMethods_Post_WithArrayQueryString_AndBody_ShouldUseBody.generated.txt ++++ b/src/Http/Http.Extensions/test/RequestDelegateGenerator/Baselines/MapMethods_Post_WithArrayQueryString_AndBody_ShouldUseBody.generated.txt +@@ -81,6 +81,7 @@ namespace Microsoft.AspNetCore.Http.Generated + if (!serviceProviderIsService.IsService(type)) + { + options.EndpointBuilder.Metadata.Add(new AcceptsMetadata(type: type, isOptional: isOptional, contentTypes: GeneratedMetadataConstants.JsonContentType)); ++ options.EndpointBuilder.Metadata.Add(ApiEndpointMetadata.Instance); + break; + } + } +@@ -334,6 +335,22 @@ namespace Microsoft.AspNetCore.Http.Generated + + } + ++ file sealed class ApiEndpointMetadata : IApiEndpointMetadata ++ { ++ public static readonly ApiEndpointMetadata Instance = new(); ++ ++ private ApiEndpointMetadata() ++ { ++ } ++ ++ public static void AddApiEndpointMetadataIfMissing(EndpointBuilder builder) ++ { ++ if (!builder.Metadata.Any(m => m is IApiEndpointMetadata)) ++ { ++ builder.Metadata.Add(Instance); ++ } ++ } ++ } + %GENERATEDCODEATTRIBUTE% + file static class GeneratedMetadataConstants + { +diff --git a/src/Http/Http.Extensions/test/RequestDelegateGenerator/Baselines/MapPost_WithArrayQueryString_AndBody_ShouldUseBody.generated.txt b/src/Http/Http.Extensions/test/RequestDelegateGenerator/Baselines/MapPost_WithArrayQueryString_AndBody_ShouldUseBody.generated.txt +index 8a2bc539..3fb5a665 100644 +--- a/src/Http/Http.Extensions/test/RequestDelegateGenerator/Baselines/MapPost_WithArrayQueryString_AndBody_ShouldUseBody.generated.txt ++++ b/src/Http/Http.Extensions/test/RequestDelegateGenerator/Baselines/MapPost_WithArrayQueryString_AndBody_ShouldUseBody.generated.txt +@@ -81,6 +81,7 @@ namespace Microsoft.AspNetCore.Http.Generated + if (!serviceProviderIsService.IsService(type)) + { + options.EndpointBuilder.Metadata.Add(new AcceptsMetadata(type: type, isOptional: isOptional, contentTypes: GeneratedMetadataConstants.JsonContentType)); ++ options.EndpointBuilder.Metadata.Add(ApiEndpointMetadata.Instance); + break; + } + } +@@ -334,6 +335,22 @@ namespace Microsoft.AspNetCore.Http.Generated + + } + ++ file sealed class ApiEndpointMetadata : IApiEndpointMetadata ++ { ++ public static readonly ApiEndpointMetadata Instance = new(); ++ ++ private ApiEndpointMetadata() ++ { ++ } ++ ++ public static void AddApiEndpointMetadataIfMissing(EndpointBuilder builder) ++ { ++ if (!builder.Metadata.Any(m => m is IApiEndpointMetadata)) ++ { ++ builder.Metadata.Add(Instance); ++ } ++ } ++ } + %GENERATEDCODEATTRIBUTE% + file static class GeneratedMetadataConstants + { +diff --git a/src/Http/Http.Extensions/test/RequestDelegateGenerator/Baselines/MapPost_WithArrayQueryString_ShouldFail.generated.txt b/src/Http/Http.Extensions/test/RequestDelegateGenerator/Baselines/MapPost_WithArrayQueryString_ShouldFail.generated.txt +index 379c7838..f34ec565 100644 +--- a/src/Http/Http.Extensions/test/RequestDelegateGenerator/Baselines/MapPost_WithArrayQueryString_ShouldFail.generated.txt ++++ b/src/Http/Http.Extensions/test/RequestDelegateGenerator/Baselines/MapPost_WithArrayQueryString_ShouldFail.generated.txt +@@ -81,12 +81,14 @@ namespace Microsoft.AspNetCore.Http.Generated + if (!serviceProviderIsService.IsService(type)) + { + options.EndpointBuilder.Metadata.Add(new AcceptsMetadata(type: type, isOptional: isOptional, contentTypes: GeneratedMetadataConstants.JsonContentType)); ++ options.EndpointBuilder.Metadata.Add(ApiEndpointMetadata.Instance); + break; + } + } + var parameters = methodInfo.GetParameters(); + options.EndpointBuilder.Metadata.Add(new ParameterBindingMetadata("p", parameters[0], hasTryParse: false, hasBindAsync: false, isOptional: false)); + options.EndpointBuilder.Metadata.Add(new ProducesResponseTypeMetadata(statusCode: StatusCodes.Status200OK, type: typeof(global::System.Int32), contentTypes: GeneratedMetadataConstants.JsonContentType)); ++ ApiEndpointMetadata.AddApiEndpointMetadataIfMissing(options.EndpointBuilder); + return new RequestDelegateMetadataResult { EndpointMetadata = options.EndpointBuilder.Metadata.AsReadOnly() }; + }; + RequestDelegateFactoryFunc createRequestDelegate = (del, options, inferredMetadataResult) => +@@ -327,6 +329,22 @@ namespace Microsoft.AspNetCore.Http.Generated + + } + ++ file sealed class ApiEndpointMetadata : IApiEndpointMetadata ++ { ++ public static readonly ApiEndpointMetadata Instance = new(); ++ ++ private ApiEndpointMetadata() ++ { ++ } ++ ++ public static void AddApiEndpointMetadataIfMissing(EndpointBuilder builder) ++ { ++ if (!builder.Metadata.Any(m => m is IApiEndpointMetadata)) ++ { ++ builder.Metadata.Add(Instance); ++ } ++ } ++ } + %GENERATEDCODEATTRIBUTE% + file static class GeneratedMetadataConstants + { +diff --git a/src/Http/Http.Extensions/test/RequestDelegateGenerator/Baselines/Multiple_MapAction_NoParam_StringReturn.generated.txt b/src/Http/Http.Extensions/test/RequestDelegateGenerator/Baselines/Multiple_MapAction_NoParam_StringReturn.generated.txt +index 79567d9d..bf51a399 100644 +--- a/src/Http/Http.Extensions/test/RequestDelegateGenerator/Baselines/Multiple_MapAction_NoParam_StringReturn.generated.txt ++++ b/src/Http/Http.Extensions/test/RequestDelegateGenerator/Baselines/Multiple_MapAction_NoParam_StringReturn.generated.txt +@@ -414,6 +414,22 @@ namespace Microsoft.AspNetCore.Http.Generated + + } + ++ file sealed class ApiEndpointMetadata : IApiEndpointMetadata ++ { ++ public static readonly ApiEndpointMetadata Instance = new(); ++ ++ private ApiEndpointMetadata() ++ { ++ } ++ ++ public static void AddApiEndpointMetadataIfMissing(EndpointBuilder builder) ++ { ++ if (!builder.Metadata.Any(m => m is IApiEndpointMetadata)) ++ { ++ builder.Metadata.Add(Instance); ++ } ++ } ++ } + %GENERATEDCODEATTRIBUTE% + file static class GeneratedMetadataConstants + { +diff --git a/src/Http/Http.Extensions/test/RequestDelegateGenerator/Baselines/Multiple_MapAction_WithParams_StringReturn.generated.txt b/src/Http/Http.Extensions/test/RequestDelegateGenerator/Baselines/Multiple_MapAction_WithParams_StringReturn.generated.txt +index 38e13d3e..ffb90a91 100644 +--- a/src/Http/Http.Extensions/test/RequestDelegateGenerator/Baselines/Multiple_MapAction_WithParams_StringReturn.generated.txt ++++ b/src/Http/Http.Extensions/test/RequestDelegateGenerator/Baselines/Multiple_MapAction_WithParams_StringReturn.generated.txt +@@ -428,6 +428,22 @@ namespace Microsoft.AspNetCore.Http.Generated + + } + ++ file sealed class ApiEndpointMetadata : IApiEndpointMetadata ++ { ++ public static readonly ApiEndpointMetadata Instance = new(); ++ ++ private ApiEndpointMetadata() ++ { ++ } ++ ++ public static void AddApiEndpointMetadataIfMissing(EndpointBuilder builder) ++ { ++ if (!builder.Metadata.Any(m => m is IApiEndpointMetadata)) ++ { ++ builder.Metadata.Add(Instance); ++ } ++ } ++ } + %GENERATEDCODEATTRIBUTE% + file static class GeneratedMetadataConstants + { +diff --git a/src/Http/Http.Extensions/test/RequestDelegateGenerator/Baselines/RequestDelegateValidateGeneratedFormCode.generated.txt b/src/Http/Http.Extensions/test/RequestDelegateGenerator/Baselines/RequestDelegateValidateGeneratedFormCode.generated.txt +index 905324b9..8119c318 100644 +--- a/src/Http/Http.Extensions/test/RequestDelegateGenerator/Baselines/RequestDelegateValidateGeneratedFormCode.generated.txt ++++ b/src/Http/Http.Extensions/test/RequestDelegateGenerator/Baselines/RequestDelegateValidateGeneratedFormCode.generated.txt +@@ -373,17 +373,17 @@ namespace Microsoft.AspNetCore.Http.Generated + + } + +-file sealed class AntiforgeryMetadata : IAntiforgeryMetadata +-{ +- public static readonly IAntiforgeryMetadata ValidationRequired = new AntiforgeryMetadata(true); +- +- public AntiforgeryMetadata(bool requiresValidation) ++ file sealed class AntiforgeryMetadata : IAntiforgeryMetadata + { +- RequiresValidation = requiresValidation; +- } ++ public static readonly IAntiforgeryMetadata ValidationRequired = new AntiforgeryMetadata(true); + +- public bool RequiresValidation { get; } +-} ++ public AntiforgeryMetadata(bool requiresValidation) ++ { ++ RequiresValidation = requiresValidation; ++ } ++ ++ public bool RequiresValidation { get; } ++ } + %GENERATEDCODEATTRIBUTE% + file static class GeneratedMetadataConstants + { +diff --git a/src/Http/Http.Extensions/test/RequestDelegateGenerator/Baselines/SupportsDifferentInterceptorsFromSameLocation.generated.txt b/src/Http/Http.Extensions/test/RequestDelegateGenerator/Baselines/SupportsDifferentInterceptorsFromSameLocation.generated.txt +index 5316ad22..fea0e359 100644 +--- a/src/Http/Http.Extensions/test/RequestDelegateGenerator/Baselines/SupportsDifferentInterceptorsFromSameLocation.generated.txt ++++ b/src/Http/Http.Extensions/test/RequestDelegateGenerator/Baselines/SupportsDifferentInterceptorsFromSameLocation.generated.txt +@@ -388,6 +388,22 @@ namespace Microsoft.AspNetCore.Http.Generated + + } + ++ file sealed class ApiEndpointMetadata : IApiEndpointMetadata ++ { ++ public static readonly ApiEndpointMetadata Instance = new(); ++ ++ private ApiEndpointMetadata() ++ { ++ } ++ ++ public static void AddApiEndpointMetadataIfMissing(EndpointBuilder builder) ++ { ++ if (!builder.Metadata.Any(m => m is IApiEndpointMetadata)) ++ { ++ builder.Metadata.Add(Instance); ++ } ++ } ++ } + %GENERATEDCODEATTRIBUTE% + file static class GeneratedMetadataConstants + { +diff --git a/src/Http/Http.Extensions/test/RequestDelegateGenerator/Baselines/SupportsSameInterceptorsFromDifferentFiles.generated.txt b/src/Http/Http.Extensions/test/RequestDelegateGenerator/Baselines/SupportsSameInterceptorsFromDifferentFiles.generated.txt +index aad88a30..cafc9280 100644 +--- a/src/Http/Http.Extensions/test/RequestDelegateGenerator/Baselines/SupportsSameInterceptorsFromDifferentFiles.generated.txt ++++ b/src/Http/Http.Extensions/test/RequestDelegateGenerator/Baselines/SupportsSameInterceptorsFromDifferentFiles.generated.txt +@@ -257,6 +257,22 @@ namespace Microsoft.AspNetCore.Http.Generated + + } + ++ file sealed class ApiEndpointMetadata : IApiEndpointMetadata ++ { ++ public static readonly ApiEndpointMetadata Instance = new(); ++ ++ private ApiEndpointMetadata() ++ { ++ } ++ ++ public static void AddApiEndpointMetadataIfMissing(EndpointBuilder builder) ++ { ++ if (!builder.Metadata.Any(m => m is IApiEndpointMetadata)) ++ { ++ builder.Metadata.Add(Instance); ++ } ++ } ++ } + %GENERATEDCODEATTRIBUTE% + file static class GeneratedMetadataConstants + { +diff --git a/src/Http/Http.Extensions/test/RequestDelegateGenerator/Baselines/VerifyAsParametersBaseline.generated.txt b/src/Http/Http.Extensions/test/RequestDelegateGenerator/Baselines/VerifyAsParametersBaseline.generated.txt +index 30b4541a..489a8b16 100644 +--- a/src/Http/Http.Extensions/test/RequestDelegateGenerator/Baselines/VerifyAsParametersBaseline.generated.txt ++++ b/src/Http/Http.Extensions/test/RequestDelegateGenerator/Baselines/VerifyAsParametersBaseline.generated.txt +@@ -446,6 +446,7 @@ namespace Microsoft.AspNetCore.Http.Generated + Debug.Assert(options.EndpointBuilder != null, "EndpointBuilder not found."); + options.EndpointBuilder.Metadata.Add(new System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.AspNetCore.Http.RequestDelegateGenerator, Version=42.42.42.42, Culture=neutral, PublicKeyToken=adb9793829ddae60", "42.42.42.42")); + options.EndpointBuilder.Metadata.Add(new AcceptsMetadata(contentTypes: GeneratedMetadataConstants.JsonContentType)); ++ options.EndpointBuilder.Metadata.Add(ApiEndpointMetadata.Instance); + options.EndpointBuilder.Metadata.Add(new ParameterBindingMetadata("HttpContext", new PropertyAsParameterInfo(false, typeof(Microsoft.AspNetCore.Http.Generators.Tests.ParametersListWithImplicitFromBody)!.GetProperty("HttpContext")!, typeof(Microsoft.AspNetCore.Http.Generators.Tests.ParametersListWithImplicitFromBody).GetConstructor(new[] { typeof(Microsoft.AspNetCore.Http.HttpContext), typeof(Microsoft.AspNetCore.Http.Generators.Tests.TodoStruct) })?.GetParameters()[0]), hasTryParse: false, hasBindAsync: false, isOptional: false)); + options.EndpointBuilder.Metadata.Add(new ParameterBindingMetadata("Todo", new PropertyAsParameterInfo(false, typeof(Microsoft.AspNetCore.Http.Generators.Tests.ParametersListWithImplicitFromBody)!.GetProperty("Todo")!, typeof(Microsoft.AspNetCore.Http.Generators.Tests.ParametersListWithImplicitFromBody).GetConstructor(new[] { typeof(Microsoft.AspNetCore.Http.HttpContext), typeof(Microsoft.AspNetCore.Http.Generators.Tests.TodoStruct) })?.GetParameters()[1]), hasTryParse: false, hasBindAsync: false, isOptional: false)); + options.EndpointBuilder.Metadata.Add(new ProducesResponseTypeMetadata(statusCode: StatusCodes.Status200OK, type: typeof(string), contentTypes: GeneratedMetadataConstants.PlaintextContentType)); +@@ -567,6 +568,7 @@ namespace Microsoft.AspNetCore.Http.Generated + Debug.Assert(options.EndpointBuilder != null, "EndpointBuilder not found."); + options.EndpointBuilder.Metadata.Add(new System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.AspNetCore.Http.RequestDelegateGenerator, Version=42.42.42.42, Culture=neutral, PublicKeyToken=adb9793829ddae60", "42.42.42.42")); + options.EndpointBuilder.Metadata.Add(new AcceptsMetadata(contentTypes: GeneratedMetadataConstants.JsonContentType)); ++ options.EndpointBuilder.Metadata.Add(ApiEndpointMetadata.Instance); + options.EndpointBuilder.Metadata.Add(new ParameterBindingMetadata("HttpContext", new PropertyAsParameterInfo(false, typeof(Microsoft.AspNetCore.Http.Generators.Tests.ParametersListWithMetadataType)!.GetProperty("HttpContext")!, typeof(Microsoft.AspNetCore.Http.Generators.Tests.ParametersListWithMetadataType).GetConstructor(new[] { typeof(Microsoft.AspNetCore.Http.HttpContext), typeof(Microsoft.AspNetCore.Http.Generators.Tests.AddsCustomParameterMetadataAsProperty) })?.GetParameters()[0]), hasTryParse: false, hasBindAsync: false, isOptional: false)); + options.EndpointBuilder.Metadata.Add(new ParameterBindingMetadata("Value", new PropertyAsParameterInfo(false, typeof(Microsoft.AspNetCore.Http.Generators.Tests.ParametersListWithMetadataType)!.GetProperty("Value")!, typeof(Microsoft.AspNetCore.Http.Generators.Tests.ParametersListWithMetadataType).GetConstructor(new[] { typeof(Microsoft.AspNetCore.Http.HttpContext), typeof(Microsoft.AspNetCore.Http.Generators.Tests.AddsCustomParameterMetadataAsProperty) })?.GetParameters()[1]), hasTryParse: false, hasBindAsync: false, isOptional: false)); + var parameterInfos = methodInfo.GetParameters(); +@@ -683,6 +685,7 @@ namespace Microsoft.AspNetCore.Http.Generated + Debug.Assert(options.EndpointBuilder != null, "EndpointBuilder not found."); + options.EndpointBuilder.Metadata.Add(new System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.AspNetCore.Http.RequestDelegateGenerator, Version=42.42.42.42, Culture=neutral, PublicKeyToken=adb9793829ddae60", "42.42.42.42")); + options.EndpointBuilder.Metadata.Add(new AcceptsMetadata(contentTypes: GeneratedMetadataConstants.JsonContentType)); ++ options.EndpointBuilder.Metadata.Add(ApiEndpointMetadata.Instance); + options.EndpointBuilder.Metadata.Add(new ParameterBindingMetadata("Todo", new PropertyAsParameterInfo(false, typeof(Microsoft.AspNetCore.Http.Generators.Tests.ParameterRecordStructWithJsonBodyOrService)!.GetProperty("Todo")!), hasTryParse: false, hasBindAsync: false, isOptional: false)); + options.EndpointBuilder.Metadata.Add(new ParameterBindingMetadata("Service", new PropertyAsParameterInfo(false, typeof(Microsoft.AspNetCore.Http.Generators.Tests.ParameterRecordStructWithJsonBodyOrService)!.GetProperty("Service")!), hasTryParse: false, hasBindAsync: false, isOptional: false)); + options.EndpointBuilder.Metadata.Add(new ProducesResponseTypeMetadata(statusCode: StatusCodes.Status200OK, type: typeof(string), contentTypes: GeneratedMetadataConstants.PlaintextContentType)); +@@ -966,6 +969,22 @@ namespace Microsoft.AspNetCore.Http.Generated + + } + ++ file sealed class ApiEndpointMetadata : IApiEndpointMetadata ++ { ++ public static readonly ApiEndpointMetadata Instance = new(); ++ ++ private ApiEndpointMetadata() ++ { ++ } ++ ++ public static void AddApiEndpointMetadataIfMissing(EndpointBuilder builder) ++ { ++ if (!builder.Metadata.Any(m => m is IApiEndpointMetadata)) ++ { ++ builder.Metadata.Add(Instance); ++ } ++ } ++ } + %GENERATEDCODEATTRIBUTE% + file static class GeneratedMetadataConstants + { +diff --git a/src/Http/Http.Extensions/test/RequestDelegateGenerator/RequestDelegateCreationTests.Metadata.cs b/src/Http/Http.Extensions/test/RequestDelegateGenerator/RequestDelegateCreationTests.Metadata.cs +index 68f0af00..1f3412e5 100644 +--- a/src/Http/Http.Extensions/test/RequestDelegateGenerator/RequestDelegateCreationTests.Metadata.cs ++++ b/src/Http/Http.Extensions/test/RequestDelegateGenerator/RequestDelegateCreationTests.Metadata.cs +@@ -83,17 +83,14 @@ app.MapGet("/", Task () => Task.FromResult("Hello, world!")); + } + + [Fact] +- public async Task MapAction_ReturnsTask_ProducesInferredMetadata() ++ public async Task MapAction_ReturnsTask_ProducesNoInferredProducesResponseTypeMetadata() + { + var (_, compilation) = await RunGeneratorAsync(""" + app.MapGet("/", Task () => Task.CompletedTask); + """); + var endpoint = GetEndpointFromCompilation(compilation); + +- var metadata = endpoint.Metadata.OfType().Single(); +- Assert.Equal(200, metadata.StatusCode); +- Assert.Equal("text/plain", metadata.ContentTypes.Single()); +- Assert.Equal(typeof(void), metadata.Type); ++ Assert.Empty(endpoint.Metadata.OfType()); + } + + [Fact] +@@ -111,17 +108,14 @@ app.MapGet("/", ValueTask () => ValueTask.FromResult("Hello, world!")); + } + + [Fact] +- public async Task MapAction_ReturnsValueTask_ProducesInferredMetadata() ++ public async Task MapAction_ReturnsValueTask_ProducesNoInferredProducesResponseTypeMetadata() + { + var (_, compilation) = await RunGeneratorAsync(""" + app.MapGet("/", ValueTask () => ValueTask.CompletedTask); + """); + var endpoint = GetEndpointFromCompilation(compilation); + +- var metadata = endpoint.Metadata.OfType().Single(); +- Assert.Equal(200, metadata.StatusCode); +- Assert.Equal("text/plain", metadata.ContentTypes.Single()); +- Assert.Equal(typeof(void), metadata.Type); ++ Assert.Empty(endpoint.Metadata.OfType()); + } + + [Fact] +@@ -512,6 +506,11 @@ app.MapPost("/test/pattern", [Attribute1, Attribute2] (AddsCustomParameterMetada + // Act + var endpoint = GetEndpointFromCompilation(compilation); + ++ // IApiEndpointMetadata is tricky to order consistently because it depends on whether AddsCustomParameterMetadata is registered ++ // as a service at runtime. However, the order of IApiEndpointMetadata is not significant since there's no way to override it ++ // other than removing it. ++ Assert.Single(endpoint.Metadata, m => m is IApiEndpointMetadata); ++ + // Assert + // NOTE: Depending on whether we are running under RDG or RDG, there are some generated types which + // don't have equivalents in the opposite. The two examples here are NullableContextAttribute which +@@ -525,7 +524,8 @@ app.MapPost("/test/pattern", [Attribute1, Attribute2] (AddsCustomParameterMetada + m is not HttpMethodMetadata && + m is not Attribute1 && + m is not Attribute2 && +- m is not IRouteDiagnosticsMetadata); ++ m is not IRouteDiagnosticsMetadata && ++ m is not IApiEndpointMetadata); + + Assert.Collection(filteredMetadata, + // Inferred AcceptsMetadata from RDF for complex type +diff --git a/src/Http/Http.Results/test/AcceptedAtRouteOfTResultTests.cs b/src/Http/Http.Results/test/AcceptedAtRouteOfTResultTests.cs +index 47b15693..1d53452f 100644 +--- a/src/Http/Http.Results/test/AcceptedAtRouteOfTResultTests.cs ++++ b/src/Http/Http.Results/test/AcceptedAtRouteOfTResultTests.cs +@@ -134,6 +134,8 @@ public class AcceptedAtRouteOfTResultTests + Assert.Equal(StatusCodes.Status202Accepted, producesResponseTypeMetadata.StatusCode); + Assert.Equal(typeof(Todo), producesResponseTypeMetadata.Type); + Assert.Single(producesResponseTypeMetadata.ContentTypes, "application/json"); ++ ++ Assert.Contains(builder.Metadata, m => m is IApiEndpointMetadata); + } + + [Fact] +diff --git a/src/Http/Http.Results/test/AcceptedAtRouteResultTests.cs b/src/Http/Http.Results/test/AcceptedAtRouteResultTests.cs +index 8f29f5a5..15a93310 100644 +--- a/src/Http/Http.Results/test/AcceptedAtRouteResultTests.cs ++++ b/src/Http/Http.Results/test/AcceptedAtRouteResultTests.cs +@@ -87,6 +87,8 @@ public class AcceptedAtRouteResultTests + var producesResponseTypeMetadata = builder.Metadata.OfType().Last(); + Assert.Equal(StatusCodes.Status202Accepted, producesResponseTypeMetadata.StatusCode); + Assert.Equal(typeof(void), producesResponseTypeMetadata.Type); ++ ++ Assert.Contains(builder.Metadata, m => m is IApiEndpointMetadata); + } + + [Fact] +diff --git a/src/Http/Http.Results/test/AcceptedOfTResultTests.cs b/src/Http/Http.Results/test/AcceptedOfTResultTests.cs +index 853a57d4..2ee6e031 100644 +--- a/src/Http/Http.Results/test/AcceptedOfTResultTests.cs ++++ b/src/Http/Http.Results/test/AcceptedOfTResultTests.cs +@@ -75,6 +75,8 @@ public class AcceptedOfTResultTests + Assert.Equal(StatusCodes.Status202Accepted, producesResponseTypeMetadata.StatusCode); + Assert.Equal(typeof(Todo), producesResponseTypeMetadata.Type); + Assert.Single(producesResponseTypeMetadata.ContentTypes, "application/json"); ++ ++ Assert.Contains(builder.Metadata, m => m is IApiEndpointMetadata); + } + + [Fact] +diff --git a/src/Http/Http.Results/test/AcceptedResultTests.cs b/src/Http/Http.Results/test/AcceptedResultTests.cs +index 7511b05f..171b4511 100644 +--- a/src/Http/Http.Results/test/AcceptedResultTests.cs ++++ b/src/Http/Http.Results/test/AcceptedResultTests.cs +@@ -44,6 +44,8 @@ public class AcceptedResultTests + var producesResponseTypeMetadata = builder.Metadata.OfType().Last(); + Assert.Equal(StatusCodes.Status202Accepted, producesResponseTypeMetadata.StatusCode); + Assert.Equal(typeof(void), producesResponseTypeMetadata.Type); ++ ++ Assert.Contains(builder.Metadata, m => m is IApiEndpointMetadata); + } + + [Fact] +diff --git a/src/Http/Http.Results/test/BadRequestOfTResultTests.cs b/src/Http/Http.Results/test/BadRequestOfTResultTests.cs +index 58e1e452..c930db6e 100644 +--- a/src/Http/Http.Results/test/BadRequestOfTResultTests.cs ++++ b/src/Http/Http.Results/test/BadRequestOfTResultTests.cs +@@ -118,6 +118,8 @@ public class BadRequestOfTResultTests + Assert.Equal(StatusCodes.Status400BadRequest, producesResponseTypeMetadata.StatusCode); + Assert.Equal(typeof(Todo), producesResponseTypeMetadata.Type); + Assert.Single(producesResponseTypeMetadata.ContentTypes, "application/json"); ++ ++ Assert.Contains(builder.Metadata, m => m is IApiEndpointMetadata); + } + + [Fact] +diff --git a/src/Http/Http.Results/test/BadRequestResultTests.cs b/src/Http/Http.Results/test/BadRequestResultTests.cs +index e8f3a444..cca2a4d1 100644 +--- a/src/Http/Http.Results/test/BadRequestResultTests.cs ++++ b/src/Http/Http.Results/test/BadRequestResultTests.cs +@@ -57,6 +57,8 @@ public class BadRequestResultTests + var producesResponseTypeMetadata = builder.Metadata.OfType().Last(); + Assert.Equal(StatusCodes.Status400BadRequest, producesResponseTypeMetadata.StatusCode); + Assert.Equal(typeof(void), producesResponseTypeMetadata.Type); ++ ++ Assert.Contains(builder.Metadata, m => m is IApiEndpointMetadata); + } + + [Fact] +diff --git a/src/Http/Http.Results/test/ConflictOfTResultTests.cs b/src/Http/Http.Results/test/ConflictOfTResultTests.cs +index 5e757e3b..be4e43d4 100644 +--- a/src/Http/Http.Results/test/ConflictOfTResultTests.cs ++++ b/src/Http/Http.Results/test/ConflictOfTResultTests.cs +@@ -96,6 +96,8 @@ public class ConflictOfTResultTests + Assert.Equal(StatusCodes.Status409Conflict, producesResponseTypeMetadata.StatusCode); + Assert.Equal(typeof(Todo), producesResponseTypeMetadata.Type); + Assert.Single(producesResponseTypeMetadata.ContentTypes, "application/json"); ++ ++ Assert.Contains(builder.Metadata, m => m is IApiEndpointMetadata); + } + + [Fact] +diff --git a/src/Http/Http.Results/test/ConflictResultTests.cs b/src/Http/Http.Results/test/ConflictResultTests.cs +index 88f64740..2f639948 100644 +--- a/src/Http/Http.Results/test/ConflictResultTests.cs ++++ b/src/Http/Http.Results/test/ConflictResultTests.cs +@@ -58,6 +58,8 @@ public class ConflictResultTests + var producesResponseTypeMetadata = builder.Metadata.OfType().Last(); + Assert.Equal(StatusCodes.Status409Conflict, producesResponseTypeMetadata.StatusCode); + Assert.Equal(typeof(void), producesResponseTypeMetadata.Type); ++ ++ Assert.Contains(builder.Metadata, m => m is IApiEndpointMetadata); + } + + [Fact] +diff --git a/src/Http/Http.Results/test/CreatedAtRouteOfTResultTests.cs b/src/Http/Http.Results/test/CreatedAtRouteOfTResultTests.cs +index dec5f3ce..a55f7dd6 100644 +--- a/src/Http/Http.Results/test/CreatedAtRouteOfTResultTests.cs ++++ b/src/Http/Http.Results/test/CreatedAtRouteOfTResultTests.cs +@@ -104,6 +104,8 @@ public partial class CreatedAtRouteOfTResultTests + Assert.Equal(StatusCodes.Status201Created, producesResponseTypeMetadata.StatusCode); + Assert.Equal(typeof(Todo), producesResponseTypeMetadata.Type); + Assert.Single(producesResponseTypeMetadata.ContentTypes, "application/json"); ++ ++ Assert.Contains(builder.Metadata, m => m is IApiEndpointMetadata); + } + + [Fact] +diff --git a/src/Http/Http.Results/test/CreatedAtRouteResultTests.cs b/src/Http/Http.Results/test/CreatedAtRouteResultTests.cs +index e91822af..5a36fdcc 100644 +--- a/src/Http/Http.Results/test/CreatedAtRouteResultTests.cs ++++ b/src/Http/Http.Results/test/CreatedAtRouteResultTests.cs +@@ -85,6 +85,8 @@ public partial class CreatedAtRouteResultTests + var producesResponseTypeMetadata = builder.Metadata.OfType().Last(); + Assert.Equal(StatusCodes.Status201Created, producesResponseTypeMetadata.StatusCode); + Assert.Equal(typeof(void), producesResponseTypeMetadata.Type); ++ ++ Assert.Contains(builder.Metadata, m => m is IApiEndpointMetadata); + } + + [Fact] +diff --git a/src/Http/Http.Results/test/CreatedOfTResultTests.cs b/src/Http/Http.Results/test/CreatedOfTResultTests.cs +index 9e5f0637..b4b57477 100644 +--- a/src/Http/Http.Results/test/CreatedOfTResultTests.cs ++++ b/src/Http/Http.Results/test/CreatedOfTResultTests.cs +@@ -110,6 +110,8 @@ public class CreatedOfTResultTests + Assert.Equal(StatusCodes.Status201Created, producesResponseTypeMetadata.StatusCode); + Assert.Equal(typeof(Todo), producesResponseTypeMetadata.Type); + Assert.Single(producesResponseTypeMetadata.ContentTypes, "application/json"); ++ ++ Assert.Contains(builder.Metadata, m => m is IApiEndpointMetadata); + } + + [Fact] +diff --git a/src/Http/Http.Results/test/CreatedResultTests.cs b/src/Http/Http.Results/test/CreatedResultTests.cs +index 21b678d3..af1c8a11 100644 +--- a/src/Http/Http.Results/test/CreatedResultTests.cs ++++ b/src/Http/Http.Results/test/CreatedResultTests.cs +@@ -75,6 +75,8 @@ public class CreatedResultTests + var producesResponseTypeMetadata = builder.Metadata.OfType().Last(); + Assert.Equal(StatusCodes.Status201Created, producesResponseTypeMetadata.StatusCode); + Assert.Equal(typeof(void), producesResponseTypeMetadata.Type); ++ ++ Assert.Contains(builder.Metadata, m => m is IApiEndpointMetadata); + } + + [Fact] +diff --git a/src/Http/Http.Results/test/InternalServerErrorOfTResultTests.cs b/src/Http/Http.Results/test/InternalServerErrorOfTResultTests.cs +index d063b4e6..1ee5bd75 100644 +--- a/src/Http/Http.Results/test/InternalServerErrorOfTResultTests.cs ++++ b/src/Http/Http.Results/test/InternalServerErrorOfTResultTests.cs +@@ -118,6 +118,8 @@ public class InternalServerErrorOfTResultTests + Assert.Equal(StatusCodes.Status500InternalServerError, producesResponseTypeMetadata.StatusCode); + Assert.Equal(typeof(Todo), producesResponseTypeMetadata.Type); + Assert.Single(producesResponseTypeMetadata.ContentTypes, "application/json"); ++ ++ Assert.Contains(builder.Metadata, m => m is IApiEndpointMetadata); + } + + [Fact] +diff --git a/src/Http/Http.Results/test/JsonResultTests.cs b/src/Http/Http.Results/test/JsonResultTests.cs +index 1c2d6d7f..52d76c0a 100644 +--- a/src/Http/Http.Results/test/JsonResultTests.cs ++++ b/src/Http/Http.Results/test/JsonResultTests.cs +@@ -1,11 +1,16 @@ + // Licensed to the .NET Foundation under one or more agreements. + // The .NET Foundation licenses this file to you under the MIT license. + ++using System.Reflection; + using System.Text; + using System.Text.Json; + using System.Text.Unicode; ++using Microsoft.AspNetCore.Builder; + using Microsoft.AspNetCore.Http.Json; ++using Microsoft.AspNetCore.Http.Metadata; + using Microsoft.AspNetCore.Mvc; ++using Microsoft.AspNetCore.Routing; ++using Microsoft.AspNetCore.Routing.Patterns; + using Microsoft.Extensions.DependencyInjection; + using Microsoft.Extensions.Logging; + using Microsoft.Extensions.Logging.Abstractions; +@@ -310,6 +315,24 @@ public class JsonResultTests + Assert.Equal(value, result.Value); + } + ++ [Fact] ++ public void PopulateMetadata_AddsNonBrowserEndpointMetadata() ++ { ++ // Arrange ++ JsonHttpResult MyApi() { throw new NotImplementedException(); } ++ var metadata = new List(); ++ var builder = new RouteEndpointBuilder(requestDelegate: null, RoutePatternFactory.Parse("/"), order: 0); ++ ++ // Act ++ PopulateMetadata>(((Delegate)MyApi).GetMethodInfo(), builder); ++ ++ // Assert ++ Assert.Contains(builder.Metadata, m => m is IApiEndpointMetadata); ++ } ++ ++ private static void PopulateMetadata(MethodInfo method, EndpointBuilder builder) ++ where TResult : IEndpointMetadataProvider => TResult.PopulateMetadata(method, builder); ++ + private static IServiceProvider CreateServices() + { + var services = new ServiceCollection(); +diff --git a/src/Http/Http.Results/test/NoContentResultTests.cs b/src/Http/Http.Results/test/NoContentResultTests.cs +index 31a7c8cb..fc1cae4a 100644 +--- a/src/Http/Http.Results/test/NoContentResultTests.cs ++++ b/src/Http/Http.Results/test/NoContentResultTests.cs +@@ -54,6 +54,9 @@ public class NoContentResultTests + var producesResponseTypeMetadata = builder.Metadata.OfType().Last(); + Assert.Equal(StatusCodes.Status204NoContent, producesResponseTypeMetadata.StatusCode); + Assert.Equal(typeof(void), producesResponseTypeMetadata.Type); ++ ++ // Assert ApiEndpointMetadata is added ++ Assert.Contains(builder.Metadata, m => m is IApiEndpointMetadata); + } + + [Fact] +diff --git a/src/Http/Http.Results/test/NotFoundOfTResultTests.cs b/src/Http/Http.Results/test/NotFoundOfTResultTests.cs +index 0aa82fdd..ec15a5c8 100644 +--- a/src/Http/Http.Results/test/NotFoundOfTResultTests.cs ++++ b/src/Http/Http.Results/test/NotFoundOfTResultTests.cs +@@ -78,6 +78,8 @@ public class NotFoundOfTResultTests + Assert.Equal(StatusCodes.Status404NotFound, producesResponseTypeMetadata.StatusCode); + Assert.Equal(typeof(Todo), producesResponseTypeMetadata.Type); + Assert.Single(producesResponseTypeMetadata.ContentTypes, "application/json"); ++ ++ Assert.Contains(builder.Metadata, m => m is IApiEndpointMetadata); + } + + [Fact] +diff --git a/src/Http/Http.Results/test/OkOfTResultTests.cs b/src/Http/Http.Results/test/OkOfTResultTests.cs +index 99ce735c..85693056 100644 +--- a/src/Http/Http.Results/test/OkOfTResultTests.cs ++++ b/src/Http/Http.Results/test/OkOfTResultTests.cs +@@ -95,6 +95,8 @@ public class OkOfTResultTests + Assert.Equal(StatusCodes.Status200OK, producesResponseTypeMetadata.StatusCode); + Assert.Equal(typeof(Todo), producesResponseTypeMetadata.Type); + Assert.Single(producesResponseTypeMetadata.ContentTypes, "application/json"); ++ ++ Assert.Contains(builder.Metadata, m => m is IApiEndpointMetadata); + } + + [Fact] +diff --git a/src/Http/Http.Results/test/OkResultTests.cs b/src/Http/Http.Results/test/OkResultTests.cs +index fe5db61f..98cac07c 100644 +--- a/src/Http/Http.Results/test/OkResultTests.cs ++++ b/src/Http/Http.Results/test/OkResultTests.cs +@@ -56,6 +56,8 @@ public class OkResultTests + var producesResponseTypeMetadata = builder.Metadata.OfType().Last(); + Assert.Equal(StatusCodes.Status200OK, producesResponseTypeMetadata.StatusCode); + Assert.Equal(typeof(void), producesResponseTypeMetadata.Type); ++ ++ Assert.Contains(builder.Metadata, m => m is IApiEndpointMetadata); + } + + [Fact] +diff --git a/src/Http/Http.Results/test/UnprocessableEntityOfTResultTests.cs b/src/Http/Http.Results/test/UnprocessableEntityOfTResultTests.cs +index 6ec306cb..8c8161f9 100644 +--- a/src/Http/Http.Results/test/UnprocessableEntityOfTResultTests.cs ++++ b/src/Http/Http.Results/test/UnprocessableEntityOfTResultTests.cs +@@ -95,6 +95,8 @@ public class UnprocessableEntityOfTResultTests + Assert.Equal(StatusCodes.Status422UnprocessableEntity, producesResponseTypeMetadata.StatusCode); + Assert.Equal(typeof(Todo), producesResponseTypeMetadata.Type); + Assert.Single(producesResponseTypeMetadata.ContentTypes, "application/json"); ++ ++ Assert.Contains(builder.Metadata, m => m is IApiEndpointMetadata); + } + + [Fact] +diff --git a/src/Http/Http.Results/test/UnprocessableEntityResultTests.cs b/src/Http/Http.Results/test/UnprocessableEntityResultTests.cs +index 36edb892..7931b226 100644 +--- a/src/Http/Http.Results/test/UnprocessableEntityResultTests.cs ++++ b/src/Http/Http.Results/test/UnprocessableEntityResultTests.cs +@@ -57,6 +57,8 @@ public class UnprocessableEntityResultTests + var producesResponseTypeMetadata = builder.Metadata.OfType().Last(); + Assert.Equal(StatusCodes.Status422UnprocessableEntity, producesResponseTypeMetadata.StatusCode); + Assert.Equal(typeof(void), producesResponseTypeMetadata.Type); ++ ++ Assert.Contains(builder.Metadata, m => m is IApiEndpointMetadata); + } + + [Fact] +diff --git a/src/Mvc/Mvc.Core/test/ApplicationModels/DefaultApplicationModelProviderTest.cs b/src/Mvc/Mvc.Core/test/ApplicationModels/DefaultApplicationModelProviderTest.cs +index 19aea8a9..c8c6368f 100644 +--- a/src/Mvc/Mvc.Core/test/ApplicationModels/DefaultApplicationModelProviderTest.cs ++++ b/src/Mvc/Mvc.Core/test/ApplicationModels/DefaultApplicationModelProviderTest.cs +@@ -3,6 +3,7 @@ + + using System.Reflection; + using Microsoft.AspNetCore.Http; ++using Microsoft.AspNetCore.Http.Metadata; + using Microsoft.AspNetCore.Mvc.ActionConstraints; + using Microsoft.AspNetCore.Mvc.Filters; + using Microsoft.AspNetCore.Mvc.ModelBinding; +@@ -1277,8 +1278,9 @@ public class DefaultApplicationModelProviderTest + + // Assert + Assert.NotNull(selector.EndpointMetadata); +- Assert.Single(selector.EndpointMetadata); +- Assert.IsType(selector.EndpointMetadata.Single()); ++ Assert.Equal(2, selector.EndpointMetadata.Count); ++ Assert.Single(selector.EndpointMetadata.OfType()); ++ Assert.Single(selector.EndpointMetadata.OfType()); + Assert.Equal(200, ((ProducesResponseTypeMetadata)selector.EndpointMetadata[0]).StatusCode); + } + +diff --git a/src/Security/Authentication/test/CookieTests.cs b/src/Security/Authentication/test/CookieTests.cs +index cb65ba5a..3dc0d638 100644 +--- a/src/Security/Authentication/test/CookieTests.cs ++++ b/src/Security/Authentication/test/CookieTests.cs +@@ -11,6 +11,7 @@ using Microsoft.AspNetCore.Builder; + using Microsoft.AspNetCore.DataProtection; + using Microsoft.AspNetCore.Hosting; + using Microsoft.AspNetCore.Http; ++using Microsoft.AspNetCore.Http.Metadata; + using Microsoft.AspNetCore.TestHost; + using Microsoft.AspNetCore.InternalTesting; + using Microsoft.Extensions.DependencyInjection; +@@ -96,6 +97,30 @@ public class CookieTests : SharedAuthenticationTests { }); ++ using var server = host.GetTestServer(); ++ var transaction = await SendAsync(server, "http://example.com/api/challenge"); ++ Assert.Equal(HttpStatusCode.Unauthorized, transaction.Response.StatusCode); ++ var responded = transaction.Response.Headers.GetValues("Location"); ++ Assert.Single(responded); ++ Assert.StartsWith("http://example.com/Account/Login", responded.Single()); ++ } ++ ++ [Fact] ++ public async Task ApiEndpointForbidReturns403WithLocationHeader() ++ { ++ using var host = await CreateHost(s => { }); ++ using var server = host.GetTestServer(); ++ var transaction = await SendAsync(server, "http://example.com/api/forbid"); ++ Assert.Equal(HttpStatusCode.Forbidden, transaction.Response.StatusCode); ++ var responded = transaction.Response.Headers.GetValues("Location"); ++ Assert.Single(responded); ++ Assert.StartsWith("http://example.com/Account/AccessDenied", responded.Single()); ++ } ++ + [Fact] + public async Task ProtectedCustomRequestShouldRedirectToCustomRedirectUri() + { +@@ -1879,8 +1904,28 @@ public class CookieTests : SharedAuthenticationTests ++ { ++ var apiRouteGroup = endpoints.MapGroup("/api").WithMetadata(new TestApiEndpointMetadata()); ++ // Add endpoints with IApiEndpointMetadata ++ apiRouteGroup.MapGet("/challenge", async context => ++ { ++ await context.ChallengeAsync(CookieAuthenticationDefaults.AuthenticationScheme); ++ }); ++ ++ apiRouteGroup.MapGet("/forbid", async context => ++ { ++ await context.ForbidAsync(CookieAuthenticationDefaults.AuthenticationScheme); ++ }); ++ }); + }) +- .ConfigureServices(configureServices)) ++ .ConfigureServices(services => ++ { ++ services.AddRoutingCore(); ++ configureServices(services); ++ })) + .Build(); + + await host.StartAsync(); +@@ -1949,4 +1994,8 @@ public class CookieTests : SharedAuthenticationTests(); ++ ++ Assert.NotNull(found); ++ Assert.Equal("second", found.Name); ++ Assert.Null(collection.GetMetadata()); ++ } ++ ++ [Fact] ++ public void GetOrderedMetadataPreservesRegistrationOrder() ++ { ++ var first = new AugMarkerMetadata("first"); ++ var second = new AugMarkerMetadata("second"); ++ var collection = new EndpointMetadataCollection(first, new AugOtherMetadata(), second); ++ ++ var ordered = collection.GetOrderedMetadata(); ++ ++ Assert.Equal(new[] { "first", "second" }, ordered.Select(m => m.Name).ToArray()); ++ Assert.Equal(3, collection.Count()); ++ } ++ ++ private sealed class AugMarkerMetadata ++ { ++ public AugMarkerMetadata(string name) ++ { ++ Name = name; ++ } ++ ++ public string Name { get; } ++ } ++ ++ private sealed class AugOtherMetadata ++ { ++ } ++ ++ private sealed class AugUnusedMetadata ++ { ++ } ++} +diff --git a/src/Http/Http.Extensions/test/ApiEndpointMetadataRdfAugTests.cs b/src/Http/Http.Extensions/test/ApiEndpointMetadataRdfAugTests.cs +new file mode 100644 +index 0000000..c6ffaf5 +--- /dev/null ++++ b/src/Http/Http.Extensions/test/ApiEndpointMetadataRdfAugTests.cs +@@ -0,0 +1,58 @@ ++// Licensed to the .NET Foundation under one or more agreements. ++// The .NET Foundation licenses this file to you under the MIT license. ++ ++using System; ++using System.Linq; ++using System.Threading.Tasks; ++using Microsoft.AspNetCore.Http; ++using Microsoft.AspNetCore.Http.Metadata; ++using Xunit; ++ ++namespace Microsoft.AspNetCore.Http.Extensions.Tests; ++ ++// Augmented suite (lolbench-aug). The requirement promises that route handler ++// endpoints which read a JSON request body or respond with JSON are ++// automatically marked as API endpoints, while plain-text and void endpoints ++// stay unmarked so browser navigation keeps its existing behavior. These tests ++// pin that inference through the public RequestDelegateFactory.Create surface. ++public class ApiEndpointMetadataRdfAugTests ++{ ++ [Fact] ++ public void JsonRequestBodyEndpointGetsApiEndpointMetadata() ++ { ++ Assert.Equal(1, CountApiEndpointMetadata((Todo todo) => "ok")); ++ } ++ ++ [Fact] ++ public void JsonResponseEndpointGetsApiEndpointMetadata() ++ { ++ Assert.Equal(1, CountApiEndpointMetadata(() => new Todo(1, "a"))); ++ Assert.Equal(1, CountApiEndpointMetadata(async () => ++ { ++ await Task.Yield(); ++ return new Todo(2, "b"); ++ })); ++ } ++ ++ [Fact] ++ public void JsonBodyAndResponseEndpointGetsSingleApiEndpointMetadata() ++ { ++ Assert.True(CountApiEndpointMetadata((Todo todo) => new Todo(todo.Id, todo.Title)) >= 1); ++ } ++ ++ [Fact] ++ public void PlainTextAndVoidEndpointsGetNoApiEndpointMetadata() ++ { ++ Assert.Equal(0, CountApiEndpointMetadata(() => "hello")); ++ Assert.Equal(0, CountApiEndpointMetadata(() => { })); ++ Assert.Equal(0, CountApiEndpointMetadata(() => Task.CompletedTask)); ++ } ++ ++ private static int CountApiEndpointMetadata(Delegate handler) ++ { ++ var result = RequestDelegateFactory.Create(handler); ++ return result.EndpointMetadata.Count(m => m is IApiEndpointMetadata); ++ } ++ ++ private record Todo(int Id, string Title); ++} +diff --git a/src/Http/Http.Results/test/ApiEndpointMetadataResultsAugTests.cs b/src/Http/Http.Results/test/ApiEndpointMetadataResultsAugTests.cs +new file mode 100644 +index 0000000..a3f096e +--- /dev/null ++++ b/src/Http/Http.Results/test/ApiEndpointMetadataResultsAugTests.cs +@@ -0,0 +1,80 @@ ++// Licensed to the .NET Foundation under one or more agreements. ++// The .NET Foundation licenses this file to you under the MIT license. ++ ++using System; ++using System.Linq; ++using System.Reflection; ++using Microsoft.AspNetCore.Builder; ++using Microsoft.AspNetCore.Http.Metadata; ++using Microsoft.AspNetCore.Routing; ++using Microsoft.AspNetCore.Routing.Patterns; ++using Xunit; ++ ++namespace Microsoft.AspNetCore.Http.HttpResults; ++ ++// Augmented suite (lolbench-aug). The requirement promises that endpoints with ++// TypedResults return types recognized as API-oriented are automatically ++// assigned IApiEndpointMetadata. These tests pin that contract per result ++// family through the public IEndpointMetadataProvider surface, mirroring the ++// PopulateMetadata test idiom already used in this project. ++public class ApiEndpointMetadataResultsAugTests ++{ ++ [Fact] ++ public void AcceptedFamilyResultsProvideApiEndpointMetadata() ++ { ++ Assert.True(ProvidesApiEndpointMetadata()); ++ Assert.True(ProvidesApiEndpointMetadata>()); ++ Assert.True(ProvidesApiEndpointMetadata()); ++ Assert.True(ProvidesApiEndpointMetadata>()); ++ } ++ ++ [Fact] ++ public void CreatedFamilyResultsProvideApiEndpointMetadata() ++ { ++ Assert.True(ProvidesApiEndpointMetadata()); ++ Assert.True(ProvidesApiEndpointMetadata>()); ++ Assert.True(ProvidesApiEndpointMetadata()); ++ Assert.True(ProvidesApiEndpointMetadata>()); ++ } ++ ++ [Fact] ++ public void ClientErrorFamilyResultsProvideApiEndpointMetadata() ++ { ++ Assert.True(ProvidesApiEndpointMetadata()); ++ Assert.True(ProvidesApiEndpointMetadata>()); ++ Assert.True(ProvidesApiEndpointMetadata()); ++ Assert.True(ProvidesApiEndpointMetadata>()); ++ Assert.True(ProvidesApiEndpointMetadata()); ++ Assert.True(ProvidesApiEndpointMetadata>()); ++ Assert.True(ProvidesApiEndpointMetadata>()); ++ } ++ ++ [Fact] ++ public void OkJsonAndServerFamilyResultsProvideApiEndpointMetadata() ++ { ++ Assert.True(ProvidesApiEndpointMetadata()); ++ Assert.True(ProvidesApiEndpointMetadata>()); ++ Assert.True(ProvidesApiEndpointMetadata>()); ++ Assert.True(ProvidesApiEndpointMetadata>()); ++ Assert.True(ProvidesApiEndpointMetadata()); ++ Assert.True(ProvidesApiEndpointMetadata>()); ++ } ++ ++ [Fact] ++ public void ProblemFamilyResultsProvideApiEndpointMetadata() ++ { ++ Assert.True(ProvidesApiEndpointMetadata()); ++ Assert.True(ProvidesApiEndpointMetadata()); ++ } ++ ++ private static bool ProvidesApiEndpointMetadata() ++ where TResult : IEndpointMetadataProvider ++ { ++ static TResult Stub() => throw new NotImplementedException(); ++ var builder = new RouteEndpointBuilder(requestDelegate: null, RoutePatternFactory.Parse("/"), order: 0); ++ TResult.PopulateMetadata(((Delegate)Stub).GetMethodInfo(), builder); ++ return builder.Metadata.Any(m => m is IApiEndpointMetadata); ++ } ++ ++ private record Todo(int Id, string Title); ++} +diff --git a/src/Mvc/Mvc.ApiExplorer/test/ApiEndpointMetadataApiExplorerAugTests.cs b/src/Mvc/Mvc.ApiExplorer/test/ApiEndpointMetadataApiExplorerAugTests.cs +new file mode 100644 +index 0000000..d318c7d +--- /dev/null ++++ b/src/Mvc/Mvc.ApiExplorer/test/ApiEndpointMetadataApiExplorerAugTests.cs +@@ -0,0 +1,79 @@ ++// Licensed to the .NET Foundation under one or more agreements. ++// The .NET Foundation licenses this file to you under the MIT license. ++ ++using System; ++using System.Collections.Generic; ++using System.Linq; ++using System.Threading.Tasks; ++using Microsoft.AspNetCore.Builder; ++using Microsoft.AspNetCore.Http; ++using Microsoft.AspNetCore.Mvc.ApiExplorer; ++using Microsoft.AspNetCore.Routing; ++using Microsoft.AspNetCore.Routing.Patterns; ++using Microsoft.Extensions.DependencyInjection; ++using Microsoft.Extensions.FileProviders; ++using Microsoft.Extensions.Hosting; ++using Xunit; ++ ++namespace Microsoft.AspNetCore.Mvc.ApiExplorer; ++ ++// Augmented suite (lolbench-aug). With the requirement in place, API Explorer ++// must not require unreferenced code to describe route handler endpoints: ++// responses wrapped in Task/ValueTask are treated as void (no inferred ++// response type) unless additional metadata says otherwise, while plain JSON ++// object responses keep their inferred response type. Driven through the ++// public AddEndpointsApiExplorer + IApiDescriptionGroupCollectionProvider ++// surface. ++public class ApiEndpointMetadataApiExplorerAugTests ++{ ++ [Fact] ++ public void TaskWrappedMinimalEndpointResponsesAreTreatedAsVoid() ++ { ++ var descriptions = GetApiDescriptions( ++ ("/plain", () => new AugTodo(1, "a")), ++ ("/wrapped", () => Task.FromResult(new AugTodo(2, "b")))); ++ ++ var plain = Assert.Single(descriptions, d => d.RelativePath == "plain"); ++ Assert.Contains(plain.SupportedResponseTypes, r => r.Type == typeof(AugTodo)); ++ ++ var wrapped = Assert.Single(descriptions, d => d.RelativePath == "wrapped"); ++ Assert.DoesNotContain(wrapped.SupportedResponseTypes, r => r.Type == typeof(AugTodo)); ++ Assert.DoesNotContain(wrapped.SupportedResponseTypes, r => r.Type == typeof(Task)); ++ } ++ ++ private static IReadOnlyList GetApiDescriptions(params (string Pattern, Delegate Handler)[] routes) ++ { ++ var endpoints = new List(); ++ foreach (var (pattern, handler) in routes) ++ { ++ // Metadata-bare endpoints: the response type must be inferred from ++ // the handler MethodInfo alone (no ProducesResponseTypeMetadata), ++ // which is exactly the inference path the requirement constrains. ++ var builder = new RouteEndpointBuilder(requestDelegate: _ => Task.CompletedTask, RoutePatternFactory.Parse(pattern), order: 0); ++ builder.Metadata.Add(handler.Method); ++ builder.Metadata.Add(new HttpMethodMetadata(new[] { "GET" })); ++ endpoints.Add(builder.Build()); ++ } ++ ++ var services = new ServiceCollection(); ++ services.AddLogging(); ++ services.AddRouting(); ++ services.AddSingleton(new AugHostEnvironment()); ++ services.AddEndpointsApiExplorer(); ++ services.AddSingleton(new DefaultEndpointDataSource(endpoints)); ++ ++ using var provider = services.BuildServiceProvider(); ++ var groups = provider.GetRequiredService().ApiDescriptionGroups; ++ return groups.Items.SelectMany(g => g.Items).ToArray(); ++ } ++ ++ private record AugTodo(int Id, string Title); ++ ++ private sealed class AugHostEnvironment : IHostEnvironment ++ { ++ public string EnvironmentName { get; set; } = "Development"; ++ public string ApplicationName { get; set; } = "ApiEndpointMetadataApiExplorerAugTests"; ++ public string ContentRootPath { get; set; } = "."; ++ public IFileProvider ContentRootFileProvider { get; set; } = new NullFileProvider(); ++ } ++} +diff --git a/src/Mvc/Mvc.Core/test/ApiEndpointMetadataMvcAugTests.cs b/src/Mvc/Mvc.Core/test/ApiEndpointMetadataMvcAugTests.cs +new file mode 100644 +index 0000000..4744839 +--- /dev/null ++++ b/src/Mvc/Mvc.Core/test/ApiEndpointMetadataMvcAugTests.cs +@@ -0,0 +1,22 @@ ++// Licensed to the .NET Foundation under one or more agreements. ++// The .NET Foundation licenses this file to you under the MIT license. ++ ++using Microsoft.AspNetCore.Http.Metadata; ++using Xunit; ++ ++namespace Microsoft.AspNetCore.Mvc; ++ ++// Augmented suite (lolbench-aug). The requirement promises that endpoints ++// attributed with ApiController are recognized as API endpoints. The attribute ++// itself is the endpoint metadata MVC attaches to those endpoints, so the ++// contract is that the public ApiController attribute surfaces ++// IApiEndpointMetadata. ++public class ApiEndpointMetadataMvcAugTests ++{ ++ [Fact] ++ public void ApiControllerAttributeProvidesApiEndpointMetadata() ++ { ++ var attribute = new ApiControllerAttribute(); ++ Assert.IsAssignableFrom(attribute); ++ } ++} +diff --git a/src/SignalR/common/Http.Connections/test/ApiEndpointMetadataConnectionsAugTests.cs b/src/SignalR/common/Http.Connections/test/ApiEndpointMetadataConnectionsAugTests.cs +new file mode 100644 +index 0000000..5413b08 +--- /dev/null ++++ b/src/SignalR/common/Http.Connections/test/ApiEndpointMetadataConnectionsAugTests.cs +@@ -0,0 +1,73 @@ ++// Licensed to the .NET Foundation under one or more agreements. ++// The .NET Foundation licenses this file to you under the MIT license. ++ ++using System; ++using System.Threading.Tasks; ++using Microsoft.AspNetCore.Builder; ++using Microsoft.AspNetCore.Connections; ++using Microsoft.AspNetCore.Hosting; ++using Microsoft.AspNetCore.Http.Metadata; ++using Microsoft.AspNetCore.Routing; ++using Microsoft.Extensions.DependencyInjection; ++using Microsoft.Extensions.Hosting; ++using Xunit; ++ ++namespace Microsoft.AspNetCore.Http.Connections.Tests; ++ ++// Augmented suite (lolbench-aug). The requirement promises that endpoints which ++// are not intended for browser navigation are automatically assigned ++// IApiEndpointMetadata so authentication handlers prefer status codes over ++// redirects. Connection (SignalR transport) endpoints are such endpoints; this ++// test pins the contract through the public MapConnectionHandler surface, ++// mirroring the host pattern of MapConnectionHandlerTests in this project. ++public class ApiEndpointMetadataConnectionsAugTests ++{ ++ [Fact] ++ public void MapConnectionHandlerEndpointsProvideApiEndpointMetadata() ++ { ++ using (var host = BuildWebHost("/aug", o => { })) ++ { ++ host.Start(); ++ ++ var dataSource = host.Services.GetRequiredService(); ++ // MapConnectionHandler registers two endpoints (negotiate + transport). ++ Assert.Equal(2, dataSource.Endpoints.Count); ++ foreach (var endpoint in dataSource.Endpoints) ++ { ++ Assert.NotNull(endpoint.Metadata.GetMetadata()); ++ } ++ } ++ } ++ ++ private static IHost BuildWebHost(string path, Action configureOptions) where TConnectionHandler : ConnectionHandler ++ { ++ return new HostBuilder() ++ .ConfigureWebHost(webHostBuilder => ++ { ++ webHostBuilder ++ .UseUrls("http://127.0.0.1:0") ++ .UseKestrel() ++ .ConfigureServices(services => ++ { ++ services.AddConnections(); ++ }) ++ .Configure(app => ++ { ++ app.UseRouting(); ++ app.UseEndpoints(routes => ++ { ++ routes.MapConnectionHandler(path, configureOptions); ++ }); ++ }); ++ }) ++ .Build(); ++ } ++ ++ private class AugConnectionHandler : ConnectionHandler ++ { ++ public override Task OnConnectedAsync(ConnectionContext connection) ++ { ++ return Task.CompletedTask; ++ } ++ } ++} diff --git a/aspnetcore_1/tests/private/f2p.txt b/aspnetcore_1/tests/private/f2p.txt new file mode 100644 index 0000000000000000000000000000000000000000..c0d721261136c698b9e2b896c2d7236fdd38d595 --- /dev/null +++ b/aspnetcore_1/tests/private/f2p.txt @@ -0,0 +1,2 @@ +src/Security/Authentication/test/Microsoft.AspNetCore.Authentication.Test.csproj::CookieTests.ApiEndpointChallengeReturns401WithLocationHeader +src/Security/Authentication/test/Microsoft.AspNetCore.Authentication.Test.csproj::CookieTests.ApiEndpointForbidReturns403WithLocationHeader diff --git a/aspnetcore_1/tests/private/f2p_aug.txt b/aspnetcore_1/tests/private/f2p_aug.txt new file mode 100644 index 0000000000000000000000000000000000000000..cd9e72f8c94b2b885a969b76374e318fee383dc0 --- /dev/null +++ b/aspnetcore_1/tests/private/f2p_aug.txt @@ -0,0 +1,11 @@ +src/Http/Http.Results/test/Microsoft.AspNetCore.Http.Results.Tests.csproj::ApiEndpointMetadataResultsAugTests.AcceptedFamilyResultsProvideApiEndpointMetadata +src/Http/Http.Results/test/Microsoft.AspNetCore.Http.Results.Tests.csproj::ApiEndpointMetadataResultsAugTests.CreatedFamilyResultsProvideApiEndpointMetadata +src/Http/Http.Results/test/Microsoft.AspNetCore.Http.Results.Tests.csproj::ApiEndpointMetadataResultsAugTests.ClientErrorFamilyResultsProvideApiEndpointMetadata +src/Http/Http.Results/test/Microsoft.AspNetCore.Http.Results.Tests.csproj::ApiEndpointMetadataResultsAugTests.OkJsonAndServerFamilyResultsProvideApiEndpointMetadata +src/Http/Http.Results/test/Microsoft.AspNetCore.Http.Results.Tests.csproj::ApiEndpointMetadataResultsAugTests.ProblemFamilyResultsProvideApiEndpointMetadata +src/Http/Http.Extensions/test/Microsoft.AspNetCore.Http.Extensions.Tests.csproj::ApiEndpointMetadataRdfAugTests.JsonRequestBodyEndpointGetsApiEndpointMetadata +src/Http/Http.Extensions/test/Microsoft.AspNetCore.Http.Extensions.Tests.csproj::ApiEndpointMetadataRdfAugTests.JsonResponseEndpointGetsApiEndpointMetadata +src/Http/Http.Extensions/test/Microsoft.AspNetCore.Http.Extensions.Tests.csproj::ApiEndpointMetadataRdfAugTests.JsonBodyAndResponseEndpointGetsSingleApiEndpointMetadata +src/Http/Http.Extensions/test/Microsoft.AspNetCore.Http.Extensions.Tests.csproj::ApiEndpointMetadataRdfAugTests.PlainTextAndVoidEndpointsGetNoApiEndpointMetadata +src/SignalR/common/Http.Connections/test/Microsoft.AspNetCore.Http.Connections.Tests.csproj::ApiEndpointMetadataConnectionsAugTests.MapConnectionHandlerEndpointsProvideApiEndpointMetadata +src/Mvc/Mvc.Core/test/Microsoft.AspNetCore.Mvc.Core.Test.csproj::ApiEndpointMetadataMvcAugTests.ApiControllerAttributeProvidesApiEndpointMetadata diff --git a/aspnetcore_1/tests/private/omitted.patch b/aspnetcore_1/tests/private/omitted.patch new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/aspnetcore_1/tests/private/p2p.txt b/aspnetcore_1/tests/private/p2p.txt new file mode 100644 index 0000000000000000000000000000000000000000..ea9211306dbe7dd7a9a3a4c2d3c6547454d802ff --- /dev/null +++ b/aspnetcore_1/tests/private/p2p.txt @@ -0,0 +1,48 @@ +src/Http/Http.Abstractions/test/Microsoft.AspNetCore.Http.Abstractions.Tests.csproj::PathStringTests.HashCode_CheckNullAndEmptyHaveSameHashcodes +src/Http/Http.Abstractions/test/Microsoft.AspNetCore.Http.Abstractions.Tests.csproj::PathStringTests.Equals_EmptyPathStringAndDefaultPathString +src/Http/Http.Abstractions/test/Microsoft.AspNetCore.Http.Abstractions.Tests.csproj::Microsoft.AspNetCore.Builder.Extensions.MapPathMiddlewareTests.NullArguments_ArgumentNullException +src/Http/Http.Abstractions/test/Microsoft.AspNetCore.Http.Abstractions.Tests.csproj::Microsoft.AspNetCore.Builder.Extensions.MapPathMiddlewareTests.PathMatchFunc_BranchTaken +src/Http/Http.Abstractions/test/Microsoft.AspNetCore.Http.Abstractions.Tests.csproj::Microsoft.AspNetCore.Builder.Extensions.MapPathMiddlewareTests.PathMatchAction_BranchTaken +src/Http/Http.Abstractions/test/Microsoft.AspNetCore.Http.Abstractions.Tests.csproj::Microsoft.AspNetCore.Builder.Extensions.MapPathMiddlewareTests.PathMatchAction_BranchTaken_WithPreserveMatchedPathSegment +src/Http/Http.Abstractions/test/Microsoft.AspNetCore.Http.Abstractions.Tests.csproj::Microsoft.AspNetCore.Builder.Extensions.MapPathMiddlewareTests.MatchPathWithTrailingSlashThrowsException +src/Http/Http.Abstractions/test/Microsoft.AspNetCore.Http.Abstractions.Tests.csproj::Microsoft.AspNetCore.Builder.Extensions.MapPathMiddlewareTests.PathMismatchFunc_PassedThrough +src/Http/Http.Abstractions/test/Microsoft.AspNetCore.Http.Abstractions.Tests.csproj::Microsoft.AspNetCore.Builder.Extensions.MapPathMiddlewareTests.PathMismatchAction_PassedThrough +src/Http/Http.Abstractions/test/Microsoft.AspNetCore.Http.Abstractions.Tests.csproj::Microsoft.AspNetCore.Builder.Extensions.MapPathMiddlewareTests.ChainedRoutes_Success +src/Http/Http.Abstractions/test/Microsoft.AspNetCore.Http.Abstractions.Tests.csproj::Microsoft.AspNetCore.Builder.Extensions.MapPathMiddlewareTests.ApplicationBuilderMapOverloadPreferredOverEndpointBuilderGivenStringPathAndImplicitLambdaParameterType +src/Http/Http.Abstractions/test/Microsoft.AspNetCore.Http.Abstractions.Tests.csproj::Microsoft.AspNetCore.Builder.Extensions.MapPathMiddlewareTests.ApplicationBuilderMapOverloadPreferredOverEndpointBuilderGivenStringPathAndExplicitLambdaParameterType +src/Http/Http.Abstractions/test/Microsoft.AspNetCore.Http.Abstractions.Tests.csproj::Microsoft.AspNetCore.Builder.Extensions.MapPredicateMiddlewareTests.PredicateTrue_BranchTaken +src/Http/Http.Abstractions/test/Microsoft.AspNetCore.Http.Abstractions.Tests.csproj::Microsoft.AspNetCore.Builder.Extensions.MapPredicateMiddlewareTests.PredicateTrueAction_BranchTaken +src/Http/Http.Abstractions/test/Microsoft.AspNetCore.Http.Abstractions.Tests.csproj::Microsoft.AspNetCore.Builder.Extensions.MapPredicateMiddlewareTests.PredicateFalseAction_PassThrough +src/Http/Http.Abstractions/test/Microsoft.AspNetCore.Http.Abstractions.Tests.csproj::Microsoft.AspNetCore.Builder.Extensions.MapPredicateMiddlewareTests.ChainedPredicates_Success +src/Http/Http.Abstractions/test/Microsoft.AspNetCore.Http.Abstractions.Tests.csproj::Microsoft.AspNetCore.Builder.Extensions.UseExtensionsTests.UseCallsNextMiddleware +src/Http/Http.Abstractions/test/Microsoft.AspNetCore.Http.Abstractions.Tests.csproj::Microsoft.AspNetCore.Builder.Extensions.UseExtensionsTests.ThrowFromMiddlewareFlowsBackToInvoke +src/Http/Http.Abstractions/test/Microsoft.AspNetCore.Http.Abstractions.Tests.csproj::Microsoft.AspNetCore.Http.Abstractions.HttpMethodslTests.CanonicalizedValue_Success +src/Http/Http.Abstractions/test/Microsoft.AspNetCore.Http.Abstractions.Tests.csproj::Microsoft.AspNetCore.Http.Abstractions.HttpProtocolTests.Http3_Success +src/Http/Http.Abstractions/test/Microsoft.AspNetCore.Http.Abstractions.Tests.csproj::Microsoft.AspNetCore.Http.Abstractions.HttpProtocolTests.IsHttp3_Success +src/Http/Http.Abstractions/test/Microsoft.AspNetCore.Http.Abstractions.Tests.csproj::Microsoft.AspNetCore.Http.Abstractions.HttpProtocolTests.Http2_Success +src/Http/Http.Abstractions/test/Microsoft.AspNetCore.Http.Abstractions.Tests.csproj::Microsoft.AspNetCore.Http.Abstractions.HttpProtocolTests.IsHttp2_Success +src/Http/Http.Abstractions/test/Microsoft.AspNetCore.Http.Abstractions.Tests.csproj::Microsoft.AspNetCore.Http.Abstractions.HttpProtocolTests.Http11_Success +src/Http/Http.Abstractions/test/Microsoft.AspNetCore.Http.Abstractions.Tests.csproj::Microsoft.AspNetCore.Http.Abstractions.HttpProtocolTests.IsHttp11_Success +src/Http/Http.Abstractions/test/Microsoft.AspNetCore.Http.Abstractions.Tests.csproj::Microsoft.AspNetCore.Http.Abstractions.HttpProtocolTests.Http10_Success +src/Http/Http.Abstractions/test/Microsoft.AspNetCore.Http.Abstractions.Tests.csproj::Microsoft.AspNetCore.Http.Abstractions.HttpProtocolTests.IsHttp10_Success +src/Http/Http.Abstractions/test/Microsoft.AspNetCore.Http.Abstractions.Tests.csproj::Microsoft.AspNetCore.Http.Abstractions.HttpProtocolTests.Http09_Success +src/Http/Http.Abstractions/test/Microsoft.AspNetCore.Http.Abstractions.Tests.csproj::Microsoft.AspNetCore.Http.Abstractions.HttpProtocolTests.IsHttp09_Success +src/Http/Http.Abstractions/test/Microsoft.AspNetCore.Http.Abstractions.Tests.csproj::Microsoft.AspNetCore.Http.Abstractions.HttpProtocolTests.GetHttpProtocol_CorrectIETFVersion +src/Http/Http.Abstractions/test/Microsoft.AspNetCore.Http.Abstractions.Tests.csproj::Microsoft.AspNetCore.Http.Abstractions.HttpProtocolTests.GetHttpProtocol_ThrowErrorForUnknownVersion +src/Http/Http.Abstractions/test/Microsoft.AspNetCore.Http.Abstractions.Tests.csproj::Microsoft.AspNetCore.Http.Abstractions.QueryStringTests.CtorThrows_IfQueryDoesNotHaveLeadingQuestionMark +src/Http/Http.Abstractions/test/Microsoft.AspNetCore.Http.Abstractions.Tests.csproj::Microsoft.AspNetCore.Http.Abstractions.QueryStringTests.CtorNullOrEmpty_Success +src/Http/Http.Abstractions/test/Microsoft.AspNetCore.Http.Abstractions.Tests.csproj::Microsoft.AspNetCore.Http.Abstractions.QueryStringTests.CtorJustAQuestionMark_Success +src/Http/Http.Abstractions/test/Microsoft.AspNetCore.Http.Abstractions.Tests.csproj::Microsoft.AspNetCore.Http.Abstractions.QueryStringTests.ToString_EncodesHash +src/Http/Http.Abstractions/test/Microsoft.AspNetCore.Http.Abstractions.Tests.csproj::Microsoft.AspNetCore.Http.Abstractions.QueryStringTests.CreateNameValue_Success +src/Http/Http.Abstractions/test/Microsoft.AspNetCore.Http.Abstractions.Tests.csproj::Microsoft.AspNetCore.Http.Abstractions.QueryStringTests.CreateFromList_Success +src/Http/Http.Abstractions/test/Microsoft.AspNetCore.Http.Abstractions.Tests.csproj::Microsoft.AspNetCore.Http.Abstractions.QueryStringTests.CreateFromListStringValues_Success +src/Http/Http.Abstractions/test/Microsoft.AspNetCore.Http.Abstractions.Tests.csproj::Microsoft.AspNetCore.Http.Abstractions.QueryStringTests.AddQueryString_Success +src/Http/Http.Abstractions/test/Microsoft.AspNetCore.Http.Abstractions.Tests.csproj::Microsoft.AspNetCore.Http.Abstractions.QueryStringTests.AddNameValue_Success +src/Http/Http.Abstractions/test/Microsoft.AspNetCore.Http.Abstractions.Tests.csproj::Microsoft.AspNetCore.Http.Abstractions.QueryStringTests.Equals_EmptyQueryStringAndDefaultQueryString +src/Http/Http.Abstractions/test/Microsoft.AspNetCore.Http.Abstractions.Tests.csproj::Microsoft.AspNetCore.Http.Abstractions.QueryStringTests.NotEquals_DefaultQueryStringAndNonNullQueryString +src/Http/Http.Abstractions/test/Microsoft.AspNetCore.Http.Abstractions.Tests.csproj::Microsoft.AspNetCore.Http.Abstractions.QueryStringTests.NotEquals_EmptyQueryStringAndNonNullQueryString +src/Http/Http.Abstractions/test/Microsoft.AspNetCore.Http.Abstractions.Tests.csproj::Microsoft.AspNetCore.Http.Abstractions.Tests.CookieBuilderTests.ConfiguresSecurePolicy +src/Http/Http.Abstractions/test/Microsoft.AspNetCore.Http.Abstractions.Tests.csproj::Microsoft.AspNetCore.Http.Abstractions.Tests.CookieBuilderTests.ComputesExpiration +src/Http/Http.Abstractions/test/Microsoft.AspNetCore.Http.Abstractions.Tests.csproj::Microsoft.AspNetCore.Http.Abstractions.Tests.CookieBuilderTests.ComputesMaxAge +src/Http/Http.Abstractions/test/Microsoft.AspNetCore.Http.Abstractions.Tests.csproj::Microsoft.AspNetCore.Http.Abstractions.Tests.CookieBuilderTests.CookieBuilderPreservesDefaultPath +src/Http/Http.Abstractions/test/Microsoft.AspNetCore.Http.Abstractions.Tests.csproj::Microsoft.AspNetCore.Http.Abstractions.Tests.CookieBuilderTests.CookieBuilder_Extensions_Added diff --git a/aspnetcore_1/tests/private/p2p_aug.txt b/aspnetcore_1/tests/private/p2p_aug.txt new file mode 100644 index 0000000000000000000000000000000000000000..73fdbf3221a3ac79d6051e583645c534df1c1e52 --- /dev/null +++ b/aspnetcore_1/tests/private/p2p_aug.txt @@ -0,0 +1,2 @@ +src/Http/Http.Abstractions/test/Microsoft.AspNetCore.Http.Abstractions.Tests.csproj::EndpointMetadataCollectionAugTests.GetMetadataReturnsMostRecentMatch +src/Http/Http.Abstractions/test/Microsoft.AspNetCore.Http.Abstractions.Tests.csproj::EndpointMetadataCollectionAugTests.GetOrderedMetadataPreservesRegistrationOrder diff --git a/aspnetcore_1/tests/private/run_tests.sh b/aspnetcore_1/tests/private/run_tests.sh new file mode 100644 index 0000000000000000000000000000000000000000..210c6bf4a4f922cb49480956a5d1b91320abcec0 --- /dev/null +++ b/aspnetcore_1/tests/private/run_tests.sh @@ -0,0 +1,173 @@ +#!/usr/bin/env bash +# LoLBench runner for ASP.NET Core PR-62816 (IApiEndpointMetadata). +# docker run --rm -v $(pwd)/solution.patch:/in/solution.patch:ro -v $(pwd)/out:/out lolbench/aspnet-pr-62816:1 +# Modes: LOLBENCH_MODE=validate_pre | validate_post | eval +# +# Selectors: `::`. The image already ran +# ./restore.sh (arcade props + .dotnet + packages, all gitignored so `git clean -fd` +# keeps them), so tests run --no-restore via the provisioned .dotnet/dotnet. A build +# failure (e.g. the new IApiEndpointMetadata absent pre-state) -> ERROR (compile-flip). +set -uo pipefail + +PRIV=/opt/lolbench/private +SRC=/workspace/aspnetcore +DOTNET="$SRC/.dotnet/dotnet" +MODE=${LOLBENCH_MODE:-eval} +SUITE=${LOLBENCH_SUITE:-orig} +INSTANCE_ID="ASP.NET-Core_Issue-62883_PR-62816" +export DOTNET_CLI_TELEMETRY_OPTOUT=1 DOTNET_NOLOGO=1 DOTNET_SKIP_FIRST_TIME_EXPERIENCE=1 +LEVERS="-p:TreatWarningsAsErrors=false -p:RestoreEnablePackagePruning=false" + +log() { echo "[run_tests $MODE/$SUITE] $*" >&2; } + +case "$SUITE" in + orig|aug|union) ;; + *) echo "[run_tests] FATAL: unknown LOLBENCH_SUITE=$SUITE" >&2; exit 2 ;; +esac + +HAS_AUG=0 +if [ -f "$PRIV/eval_tests_aug.patch" ] && [ -f "$PRIV/f2p_aug.txt" ] && [ -f "$PRIV/p2p_aug.txt" ]; then + HAS_AUG=1 +fi +if [ "$SUITE" != "orig" ] && [ "$HAS_AUG" -eq 0 ]; then + log "WARN: LOLBENCH_SUITE=$SUITE but no augmentation shipped; falling back to orig" + SUITE=orig +fi + +# Active selector files for this suite (orig stays byte-identical to the +# pre-augmentation behavior). +F2P_FILE="$PRIV/f2p.txt"; P2P_FILE="$PRIV/p2p.txt" +case "$SUITE" in + aug) + F2P_FILE="$PRIV/f2p_aug.txt"; P2P_FILE="$PRIV/p2p_aug.txt" ;; + union) + cat "$PRIV/f2p.txt" "$PRIV/f2p_aug.txt" > /tmp/f2p_union.txt + cat "$PRIV/p2p.txt" "$PRIV/p2p_aug.txt" > /tmp/p2p_union.txt + F2P_FILE=/tmp/f2p_union.txt; P2P_FILE=/tmp/p2p_union.txt ;; +esac + +emit_error() { + local cat=$1 applied=$2 build_status=$3 + python3 - "$cat" "$applied" "$build_status" "$INSTANCE_ID" "$F2P_FILE" "$P2P_FILE" "$SUITE" "$HAS_AUG" <<'EOF' >/out/agent_report.json +import json, sys +cat, applied_s, build_s, instance, f2p_p, p2p_p, suite, has_aug = sys.argv[1:9] +applied = applied_s.lower() == "true" +f2p_n = sum(1 for l in open(f2p_p) if l.strip()); p2p_n = sum(1 for l in open(p2p_p) if l.strip()) +print(json.dumps({"instance_id": instance, "suite": suite, "augmentation_available": has_aug == "1", + "applied": applied, "build": {"status": build_s}, + "f2p": {"passed":0,"failed":0,"errored":f2p_n,"skipped":0,"total":f2p_n}, + "p2p": {"passed":0,"failed":0,"errored":p2p_n,"skipped":0,"total":p2p_n}, + "resolved": False, "error_categories": [cat]}, indent=2)) +EOF +} + +case "$MODE" in + validate_pre) SRC_PATCH="" ;; + validate_post) + if [ -f /solution/solution.patch ]; then + SRC_PATCH=/solution/solution.patch + else + SRC_PATCH="$PRIV/solution.patch" + fi ;; + eval) + [ -f /in/solution.patch ] || { emit_error missing_solution_patch false skipped; exit 0; } + AGENT_PATCH=/tmp/lolbench_agent_patch.diff + cp /in/solution.patch "$AGENT_PATCH" + chmod 0600 "$AGENT_PATCH" + SRC_PATCH="$AGENT_PATCH" ;; + *) emit_error harness_error false skipped; exit 0 ;; +esac + +cd "$SRC" +git config --global --add safe.directory "$SRC" +git reset --hard base >/dev/null 2>&1; git clean -fd >/dev/null 2>&1 # -fd (no -x): keep gitignored .dotnet/ + artifacts/ +if [ -n "$SRC_PATCH" ]; then + git apply --binary --check "$SRC_PATCH" 2>/tmp/e || { log "src patch fail"; cat /tmp/e >&2; emit_error patch_apply_failure false skipped; exit 0; } + git apply --binary "$SRC_PATCH" + # LoLBench eval-patch-collision guard (re-verify remediation): if the agent patch touched files the + # eval test patches own (test fixtures the agent must not modify), restore + # those paths (both sides of every diff/rename) to the base state so + # eval_tests(.aug).patch always applies. Agent source changes are preserved. + for _lb_ep in "$PRIV/eval_helpers.patch" "$PRIV/eval_tests.patch" "$PRIV/eval_tests_aug.patch"; do + [ -f "$_lb_ep" ] || continue + { sed -n 's|^diff --git a/\(.*\) b/\(.*\)$|\1\n\2|p' "$_lb_ep" + sed -n 's|^rename from \(.*\)$|\1|p' "$_lb_ep" + sed -n 's|^rename to \(.*\)$|\1|p' "$_lb_ep"; } | sort -u | while read -r _lb_f; do + [ -n "$_lb_f" ] || continue + git checkout HEAD -- "$_lb_f" >/dev/null 2>&1 || rm -f "$_lb_f" >/dev/null 2>&1 || true + done + done +fi +git apply --binary --check "$PRIV/eval_tests.patch" 2>/tmp/e || { log "eval patch fail"; cat /tmp/e >&2; emit_error eval_patch_apply_failure true skipped; exit 0; } +git apply --binary "$PRIV/eval_tests.patch" +if [ "$HAS_AUG" -eq 1 ] && [ "$SUITE" != "orig" ]; then + git apply --binary --check "$PRIV/eval_tests_aug.patch" 2>/tmp/e || { log "aug patch fail"; cat /tmp/e >&2; emit_error eval_aug_patch_apply_failure true skipped; exit 0; } + git apply --binary "$PRIV/eval_tests_aug.patch" +fi + +run_selectors() { + local sel_file=$1 out_json=$2 + python3 - "$sel_file" "$out_json" "$SRC" "$DOTNET" "$LEVERS" <<'PY' +import json, subprocess, sys, os, glob, xml.etree.ElementTree as ET +sel_file, out_json, src, dotnet, levers = sys.argv[1:6] +sels = [l.strip() for l in open(sel_file) if l.strip()] +groups = {} +for s in sels: + proj, _, filt = s.partition("::") + groups.setdefault(proj, []).append((s, filt)) +status = {} +for proj, items in groups.items(): + trx_dir = "/tmp/trx_" + os.path.basename(proj).replace("/", "_") + # A stale trx from an earlier invocation in the same container must never + # be parsed as this run's results (e.g. when this run's build fails). + import shutil; shutil.rmtree(trx_dir, ignore_errors=True) + os.makedirs(trx_dir, exist_ok=True) + flt = " | ".join(f"FullyQualifiedName~{f}" for _, f in items) + cmd = [dotnet, "test", proj, "--no-restore", "--filter", flt, "--nologo"] + levers.split() + \ + ["--logger", "trx;LogFileName=r.trx", "--results-directory", trx_dir] + p = subprocess.run(cmd, cwd=src, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True) + out = p.stdout + build_failed = ("Build FAILED" in out or "error CS" in out or ("MSB" in out and "error" in out)) + trx_files = glob.glob(os.path.join(trx_dir, "*.trx")) + results = {} + if trx_files: + try: + root = ET.parse(trx_files[-1]).getroot() + for utr in root.iter("{http://microsoft.com/schemas/VisualStudio/TeamTest/2010}UnitTestResult"): + results[utr.get("testName", "")] = utr.get("outcome", "") + except Exception: + pass + for sel, filt in items: + if build_failed and not results: + status[sel] = "ERROR"; continue + leaf = filt.split(".")[-1] + hit = next((o for n, o in results.items() if leaf in n), None) + status[sel] = {"Passed":"PASSED","Failed":"FAILED","NotExecuted":"SKIPPED"}.get(hit, "ERROR") +json.dump(status, open(out_json, "w")) +PY +} + +run_selectors "$F2P_FILE" /tmp/f2p.json +run_selectors "$P2P_FILE" /tmp/p2p.json + +python3 - "$F2P_FILE" "$P2P_FILE" /tmp/f2p.json /tmp/p2p.json "$INSTANCE_ID" "$MODE" "$SUITE" "$HAS_AUG" <<'PY' +import json, sys +ff, pf, fl, pl, inst, mode, suite, has_aug = sys.argv[1:9] +fids=[l.strip() for l in open(ff) if l.strip()]; pids=[l.strip() for l in open(pf) if l.strip()] +fr=json.load(open(fl)); pr=json.load(open(pl)) +def bucket(ids,rep): + out={"PASSED":[],"FAILED":[],"ERROR":[],"SKIPPED":[]} + for i in ids: + s=rep.get(i,"ERROR") + out[s if s in out else "ERROR"].append(i) + return out +f=bucket(fids,fr); p=bucket(pids,pr) +resolved=len(f["PASSED"])==len(fids) and len(p["PASSED"])==len(pids) +grader={"instance_id":inst,"mode":mode,"suite":suite,"augmentation_available":has_aug=="1","applied":True,"build":{"status":"ok"},"f2p":f,"p2p":p,"resolved":resolved} +def cnts(d,ids): + return {"passed":len(d["PASSED"]),"failed":len(d["FAILED"]),"errored":len(d["ERROR"]),"skipped":len(d["SKIPPED"]),"total":len(ids)} +agent={"instance_id":inst,"suite":suite,"augmentation_available":has_aug=="1","applied":True,"build":{"status":"ok"},"f2p":cnts(f,fids),"p2p":cnts(p,pids),"resolved":resolved,"error_categories":[]} +json.dump(grader,open("/out/grader_report.json","w"),indent=2) +json.dump(agent,open("/out/agent_report.json","w"),indent=2) +print(json.dumps(grader,indent=2)) +PY diff --git a/aspnetcore_1/tests/private/spec.json b/aspnetcore_1/tests/private/spec.json new file mode 100644 index 0000000000000000000000000000000000000000..9d88d930ee0b20e2b4ce668012f64edcbe949bf0 --- /dev/null +++ b/aspnetcore_1/tests/private/spec.json @@ -0,0 +1,652 @@ +{ + "instance_id": "ASP.NET-Core_Issue-62883_PR-62816", + "repo": "dotnet/aspnetcore", + "language": "C#", + "image": "lolbench/aspnet-pr-62816:1", + "base_commit": "c56ce2f92858158819569e11d4131c09fd847764", + "pr_head_sha": "295944574c37f46859348d6fcd3d5adf48c70bf7", + "pr_link": "https://github.com/dotnet/aspnetcore/pull/62816", + "requirement_doc": "https://github.com/dotnet/aspnetcore/issues/62883", + "test_framework": "dotnet_test(xunit)", + "test_level": "system", + "env": { + "dotnet_sdk": "10.0.100-preview.7", + "build": "arcade ./restore.sh", + "pin_shim": "beta.25372.103->.107 (global.json + eng/Versions.props)", + "levers": "--warnaserror false -p:TreatWarningsAsErrors=false" + }, + "fail_to_pass": [ + "src/Security/Authentication/test/Microsoft.AspNetCore.Authentication.Test.csproj::CookieTests.ApiEndpointChallengeReturns401WithLocationHeader", + "src/Security/Authentication/test/Microsoft.AspNetCore.Authentication.Test.csproj::CookieTests.ApiEndpointForbidReturns403WithLocationHeader" + ], + "pass_to_pass": [ + "src/Http/Http.Abstractions/test/Microsoft.AspNetCore.Http.Abstractions.Tests.csproj::PathStringTests.HashCode_CheckNullAndEmptyHaveSameHashcodes", + "src/Http/Http.Abstractions/test/Microsoft.AspNetCore.Http.Abstractions.Tests.csproj::PathStringTests.Equals_EmptyPathStringAndDefaultPathString", + "src/Http/Http.Abstractions/test/Microsoft.AspNetCore.Http.Abstractions.Tests.csproj::Microsoft.AspNetCore.Builder.Extensions.MapPathMiddlewareTests.NullArguments_ArgumentNullException", + "src/Http/Http.Abstractions/test/Microsoft.AspNetCore.Http.Abstractions.Tests.csproj::Microsoft.AspNetCore.Builder.Extensions.MapPathMiddlewareTests.PathMatchFunc_BranchTaken", + "src/Http/Http.Abstractions/test/Microsoft.AspNetCore.Http.Abstractions.Tests.csproj::Microsoft.AspNetCore.Builder.Extensions.MapPathMiddlewareTests.PathMatchAction_BranchTaken", + "src/Http/Http.Abstractions/test/Microsoft.AspNetCore.Http.Abstractions.Tests.csproj::Microsoft.AspNetCore.Builder.Extensions.MapPathMiddlewareTests.PathMatchAction_BranchTaken_WithPreserveMatchedPathSegment", + "src/Http/Http.Abstractions/test/Microsoft.AspNetCore.Http.Abstractions.Tests.csproj::Microsoft.AspNetCore.Builder.Extensions.MapPathMiddlewareTests.MatchPathWithTrailingSlashThrowsException", + "src/Http/Http.Abstractions/test/Microsoft.AspNetCore.Http.Abstractions.Tests.csproj::Microsoft.AspNetCore.Builder.Extensions.MapPathMiddlewareTests.PathMismatchFunc_PassedThrough", + "src/Http/Http.Abstractions/test/Microsoft.AspNetCore.Http.Abstractions.Tests.csproj::Microsoft.AspNetCore.Builder.Extensions.MapPathMiddlewareTests.PathMismatchAction_PassedThrough", + "src/Http/Http.Abstractions/test/Microsoft.AspNetCore.Http.Abstractions.Tests.csproj::Microsoft.AspNetCore.Builder.Extensions.MapPathMiddlewareTests.ChainedRoutes_Success", + "src/Http/Http.Abstractions/test/Microsoft.AspNetCore.Http.Abstractions.Tests.csproj::Microsoft.AspNetCore.Builder.Extensions.MapPathMiddlewareTests.ApplicationBuilderMapOverloadPreferredOverEndpointBuilderGivenStringPathAndImplicitLambdaParameterType", + "src/Http/Http.Abstractions/test/Microsoft.AspNetCore.Http.Abstractions.Tests.csproj::Microsoft.AspNetCore.Builder.Extensions.MapPathMiddlewareTests.ApplicationBuilderMapOverloadPreferredOverEndpointBuilderGivenStringPathAndExplicitLambdaParameterType", + "src/Http/Http.Abstractions/test/Microsoft.AspNetCore.Http.Abstractions.Tests.csproj::Microsoft.AspNetCore.Builder.Extensions.MapPredicateMiddlewareTests.PredicateTrue_BranchTaken", + "src/Http/Http.Abstractions/test/Microsoft.AspNetCore.Http.Abstractions.Tests.csproj::Microsoft.AspNetCore.Builder.Extensions.MapPredicateMiddlewareTests.PredicateTrueAction_BranchTaken", + "src/Http/Http.Abstractions/test/Microsoft.AspNetCore.Http.Abstractions.Tests.csproj::Microsoft.AspNetCore.Builder.Extensions.MapPredicateMiddlewareTests.PredicateFalseAction_PassThrough", + "src/Http/Http.Abstractions/test/Microsoft.AspNetCore.Http.Abstractions.Tests.csproj::Microsoft.AspNetCore.Builder.Extensions.MapPredicateMiddlewareTests.ChainedPredicates_Success", + "src/Http/Http.Abstractions/test/Microsoft.AspNetCore.Http.Abstractions.Tests.csproj::Microsoft.AspNetCore.Builder.Extensions.UseExtensionsTests.UseCallsNextMiddleware", + "src/Http/Http.Abstractions/test/Microsoft.AspNetCore.Http.Abstractions.Tests.csproj::Microsoft.AspNetCore.Builder.Extensions.UseExtensionsTests.ThrowFromMiddlewareFlowsBackToInvoke", + "src/Http/Http.Abstractions/test/Microsoft.AspNetCore.Http.Abstractions.Tests.csproj::Microsoft.AspNetCore.Http.Abstractions.HttpMethodslTests.CanonicalizedValue_Success", + "src/Http/Http.Abstractions/test/Microsoft.AspNetCore.Http.Abstractions.Tests.csproj::Microsoft.AspNetCore.Http.Abstractions.HttpProtocolTests.Http3_Success", + "src/Http/Http.Abstractions/test/Microsoft.AspNetCore.Http.Abstractions.Tests.csproj::Microsoft.AspNetCore.Http.Abstractions.HttpProtocolTests.IsHttp3_Success", + "src/Http/Http.Abstractions/test/Microsoft.AspNetCore.Http.Abstractions.Tests.csproj::Microsoft.AspNetCore.Http.Abstractions.HttpProtocolTests.Http2_Success", + "src/Http/Http.Abstractions/test/Microsoft.AspNetCore.Http.Abstractions.Tests.csproj::Microsoft.AspNetCore.Http.Abstractions.HttpProtocolTests.IsHttp2_Success", + "src/Http/Http.Abstractions/test/Microsoft.AspNetCore.Http.Abstractions.Tests.csproj::Microsoft.AspNetCore.Http.Abstractions.HttpProtocolTests.Http11_Success", + "src/Http/Http.Abstractions/test/Microsoft.AspNetCore.Http.Abstractions.Tests.csproj::Microsoft.AspNetCore.Http.Abstractions.HttpProtocolTests.IsHttp11_Success", + "src/Http/Http.Abstractions/test/Microsoft.AspNetCore.Http.Abstractions.Tests.csproj::Microsoft.AspNetCore.Http.Abstractions.HttpProtocolTests.Http10_Success", + "src/Http/Http.Abstractions/test/Microsoft.AspNetCore.Http.Abstractions.Tests.csproj::Microsoft.AspNetCore.Http.Abstractions.HttpProtocolTests.IsHttp10_Success", + "src/Http/Http.Abstractions/test/Microsoft.AspNetCore.Http.Abstractions.Tests.csproj::Microsoft.AspNetCore.Http.Abstractions.HttpProtocolTests.Http09_Success", + "src/Http/Http.Abstractions/test/Microsoft.AspNetCore.Http.Abstractions.Tests.csproj::Microsoft.AspNetCore.Http.Abstractions.HttpProtocolTests.IsHttp09_Success", + "src/Http/Http.Abstractions/test/Microsoft.AspNetCore.Http.Abstractions.Tests.csproj::Microsoft.AspNetCore.Http.Abstractions.HttpProtocolTests.GetHttpProtocol_CorrectIETFVersion", + "src/Http/Http.Abstractions/test/Microsoft.AspNetCore.Http.Abstractions.Tests.csproj::Microsoft.AspNetCore.Http.Abstractions.HttpProtocolTests.GetHttpProtocol_ThrowErrorForUnknownVersion", + "src/Http/Http.Abstractions/test/Microsoft.AspNetCore.Http.Abstractions.Tests.csproj::Microsoft.AspNetCore.Http.Abstractions.QueryStringTests.CtorThrows_IfQueryDoesNotHaveLeadingQuestionMark", + "src/Http/Http.Abstractions/test/Microsoft.AspNetCore.Http.Abstractions.Tests.csproj::Microsoft.AspNetCore.Http.Abstractions.QueryStringTests.CtorNullOrEmpty_Success", + "src/Http/Http.Abstractions/test/Microsoft.AspNetCore.Http.Abstractions.Tests.csproj::Microsoft.AspNetCore.Http.Abstractions.QueryStringTests.CtorJustAQuestionMark_Success", + "src/Http/Http.Abstractions/test/Microsoft.AspNetCore.Http.Abstractions.Tests.csproj::Microsoft.AspNetCore.Http.Abstractions.QueryStringTests.ToString_EncodesHash", + "src/Http/Http.Abstractions/test/Microsoft.AspNetCore.Http.Abstractions.Tests.csproj::Microsoft.AspNetCore.Http.Abstractions.QueryStringTests.CreateNameValue_Success", + "src/Http/Http.Abstractions/test/Microsoft.AspNetCore.Http.Abstractions.Tests.csproj::Microsoft.AspNetCore.Http.Abstractions.QueryStringTests.CreateFromList_Success", + "src/Http/Http.Abstractions/test/Microsoft.AspNetCore.Http.Abstractions.Tests.csproj::Microsoft.AspNetCore.Http.Abstractions.QueryStringTests.CreateFromListStringValues_Success", + "src/Http/Http.Abstractions/test/Microsoft.AspNetCore.Http.Abstractions.Tests.csproj::Microsoft.AspNetCore.Http.Abstractions.QueryStringTests.AddQueryString_Success", + "src/Http/Http.Abstractions/test/Microsoft.AspNetCore.Http.Abstractions.Tests.csproj::Microsoft.AspNetCore.Http.Abstractions.QueryStringTests.AddNameValue_Success", + "src/Http/Http.Abstractions/test/Microsoft.AspNetCore.Http.Abstractions.Tests.csproj::Microsoft.AspNetCore.Http.Abstractions.QueryStringTests.Equals_EmptyQueryStringAndDefaultQueryString", + "src/Http/Http.Abstractions/test/Microsoft.AspNetCore.Http.Abstractions.Tests.csproj::Microsoft.AspNetCore.Http.Abstractions.QueryStringTests.NotEquals_DefaultQueryStringAndNonNullQueryString", + "src/Http/Http.Abstractions/test/Microsoft.AspNetCore.Http.Abstractions.Tests.csproj::Microsoft.AspNetCore.Http.Abstractions.QueryStringTests.NotEquals_EmptyQueryStringAndNonNullQueryString", + "src/Http/Http.Abstractions/test/Microsoft.AspNetCore.Http.Abstractions.Tests.csproj::Microsoft.AspNetCore.Http.Abstractions.Tests.CookieBuilderTests.ConfiguresSecurePolicy", + "src/Http/Http.Abstractions/test/Microsoft.AspNetCore.Http.Abstractions.Tests.csproj::Microsoft.AspNetCore.Http.Abstractions.Tests.CookieBuilderTests.ComputesExpiration", + "src/Http/Http.Abstractions/test/Microsoft.AspNetCore.Http.Abstractions.Tests.csproj::Microsoft.AspNetCore.Http.Abstractions.Tests.CookieBuilderTests.ComputesMaxAge", + "src/Http/Http.Abstractions/test/Microsoft.AspNetCore.Http.Abstractions.Tests.csproj::Microsoft.AspNetCore.Http.Abstractions.Tests.CookieBuilderTests.CookieBuilderPreservesDefaultPath", + "src/Http/Http.Abstractions/test/Microsoft.AspNetCore.Http.Abstractions.Tests.csproj::Microsoft.AspNetCore.Http.Abstractions.Tests.CookieBuilderTests.CookieBuilder_Extensions_Added" + ], + "solution_patch_sha256": "0283acb46f50363523d796d4c6a9cf6113284998712f6248282411c70cfb9af5", + "eval_tests_patch_sha256": "2b30df6ee4a521bd2186195438c234c1799c7367a56b01b6c6c3a3498dd70ee3", + "omitted_patch_sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", + "validation_status": "validated", + "platform": "linux/amd64,linux/arm64", + "diff_source": "local_git_diff(base..head per PR file)", + "f2p_mechanism": "compile-flip: IApiEndpointMetadata absent at pre-state -> Authentication.Test fails to compile -> ERROR; present post-state -> 401/403 instead of login redirect -> PASS", + "section6": "Codex PASS \u2014 F2P bodies name only test helpers + pre-existing public APIs; the test-local TestApiEndpointMetadata implements the documented IApiEndpointMetadata interface (req doc: 'public interface IApiEndpointMetadata'); concrete ApiEndpointMetadata class is not named. P2P is uncontaminated: 48 pre-existing upstream Http.Abstractions xUnit selectors in files not modified by the PR/eval patches; p2p_aug.txt remains synthesized-only with 2 selectors, so union P2P=50.", + "validation": { + "orig_pre": { + "f2p": "0/2 pass (2 ERROR compile-flip)", + "p2p": "48/48 PASS", + "resolved": false + }, + "orig_post": { + "f2p": "2/2 PASS", + "p2p": "48/48 PASS", + "resolved": true + }, + "union_pre": { + "f2p": "0/14 pass (1 FAILED, 13 ERROR)", + "p2p": "50/50 PASS", + "resolved": false + }, + "union_post": { + "f2p": "14/14 PASS", + "p2p": "50/50 PASS", + "resolved": true + }, + "validated_at": "2026-06-16", + "runner_note": "run_tests.sh now passes --no-restore to honor the image pre-restore/offline contract documented in the runner comments." + }, + "coverage_status": "measured", + "coverage_note": "Expanded original P2P selectors on 2026-06-16 and refreshed orig/aug/union coverage with coverlet.console 6.0.4 using the suite-aware coverage image. coverage_report_orig.json: 9.23% (6/65), coverage_report_aug.json: 84.62% (55/65), coverage_report_union.json and coverage_report.json: 93.85% (61/65); all coverage_complete=true. The added original P2P selectors exercise pre-existing Http.Abstractions behavior and do not cover additional PR-added lines; union coverage remains driven by the augmented F2P suite.", + "merge_commit_sha": "295944574c37f46859348d6fcd3d5adf48c70bf7", + "test_cmd_template": "dotnet test --filter FullyQualifiedName~ --nologo", + "log_parser": "trx", + "agent_contract": { + "input": "/in/solution.patch", + "output": "/out/agent_report.json", + "invocation": "docker run --rm -v $(pwd)/solution.patch:/in/solution.patch:ro -v $(pwd)/out:/out lolbench/aspnet-pr-62816:1" + }, + "triage": { + "test_level_policy": "F2P selectors remain system-level tests for the documented cookie/API endpoint behavior. P2P selectors are pre-existing upstream xUnit guardrail tests; P2P does not require system/e2e scope.", + "fail_to_pass": { + "src/Security/Authentication/test/Microsoft.AspNetCore.Authentication.Test.csproj::CookieTests.ApiEndpointChallengeReturns401WithLocationHeader": { + "test_level": "system", + "system_reason": "Executed by the LoLBench bundle runner against the rebuilt project rather than by exposing implementation files to the agent.", + "public_surface": "dotnet_test(xunit)", + "runner_surface": "./run_tests.sh", + "internal_symbol_check": "No source-symbol invocation finding was recorded for this bundle in the latest audit." + }, + "src/Security/Authentication/test/Microsoft.AspNetCore.Authentication.Test.csproj::CookieTests.ApiEndpointForbidReturns403WithLocationHeader": { + "test_level": "system", + "system_reason": "Executed by the LoLBench bundle runner against the rebuilt project rather than by exposing implementation files to the agent.", + "public_surface": "dotnet_test(xunit)", + "runner_surface": "./run_tests.sh", + "internal_symbol_check": "No source-symbol invocation finding was recorded for this bundle in the latest audit." + } + }, + "pass_to_pass": { + "src/Http/Http.Abstractions/test/Microsoft.AspNetCore.Http.Abstractions.Tests.csproj::PathStringTests.HashCode_CheckNullAndEmptyHaveSameHashcodes": { + "test_level": "unit", + "p2p_scope": "Pre-existing upstream xUnit selector in Microsoft.AspNetCore.Http.Abstractions.Tests; included as a P2P guardrail, so the F2P system/e2e requirement does not apply.", + "public_surface": "dotnet_test(xunit)", + "runner_surface": "./run_tests.sh", + "internal_symbol_check": "Selector existed before the eval patches and is outside files modified by the golden patch/eval augmentation." + }, + "src/Http/Http.Abstractions/test/Microsoft.AspNetCore.Http.Abstractions.Tests.csproj::PathStringTests.Equals_EmptyPathStringAndDefaultPathString": { + "test_level": "unit", + "p2p_scope": "Pre-existing upstream xUnit selector in Microsoft.AspNetCore.Http.Abstractions.Tests; included as a P2P guardrail, so the F2P system/e2e requirement does not apply.", + "public_surface": "dotnet_test(xunit)", + "runner_surface": "./run_tests.sh", + "internal_symbol_check": "Selector existed before the eval patches and is outside files modified by the golden patch/eval augmentation." + }, + "src/Http/Http.Abstractions/test/Microsoft.AspNetCore.Http.Abstractions.Tests.csproj::Microsoft.AspNetCore.Builder.Extensions.MapPathMiddlewareTests.NullArguments_ArgumentNullException": { + "test_level": "unit", + "p2p_scope": "Pre-existing upstream xUnit selector in Microsoft.AspNetCore.Http.Abstractions.Tests; included as a P2P guardrail, so the F2P system/e2e requirement does not apply.", + "public_surface": "dotnet_test(xunit)", + "runner_surface": "./run_tests.sh", + "internal_symbol_check": "Selector existed before the eval patches and is outside files modified by the golden patch/eval augmentation." + }, + "src/Http/Http.Abstractions/test/Microsoft.AspNetCore.Http.Abstractions.Tests.csproj::Microsoft.AspNetCore.Builder.Extensions.MapPathMiddlewareTests.PathMatchFunc_BranchTaken": { + "test_level": "unit", + "p2p_scope": "Pre-existing upstream xUnit selector in Microsoft.AspNetCore.Http.Abstractions.Tests; included as a P2P guardrail, so the F2P system/e2e requirement does not apply.", + "public_surface": "dotnet_test(xunit)", + "runner_surface": "./run_tests.sh", + "internal_symbol_check": "Selector existed before the eval patches and is outside files modified by the golden patch/eval augmentation." + }, + "src/Http/Http.Abstractions/test/Microsoft.AspNetCore.Http.Abstractions.Tests.csproj::Microsoft.AspNetCore.Builder.Extensions.MapPathMiddlewareTests.PathMatchAction_BranchTaken": { + "test_level": "unit", + "p2p_scope": "Pre-existing upstream xUnit selector in Microsoft.AspNetCore.Http.Abstractions.Tests; included as a P2P guardrail, so the F2P system/e2e requirement does not apply.", + "public_surface": "dotnet_test(xunit)", + "runner_surface": "./run_tests.sh", + "internal_symbol_check": "Selector existed before the eval patches and is outside files modified by the golden patch/eval augmentation." + }, + "src/Http/Http.Abstractions/test/Microsoft.AspNetCore.Http.Abstractions.Tests.csproj::Microsoft.AspNetCore.Builder.Extensions.MapPathMiddlewareTests.PathMatchAction_BranchTaken_WithPreserveMatchedPathSegment": { + "test_level": "unit", + "p2p_scope": "Pre-existing upstream xUnit selector in Microsoft.AspNetCore.Http.Abstractions.Tests; included as a P2P guardrail, so the F2P system/e2e requirement does not apply.", + "public_surface": "dotnet_test(xunit)", + "runner_surface": "./run_tests.sh", + "internal_symbol_check": "Selector existed before the eval patches and is outside files modified by the golden patch/eval augmentation." + }, + "src/Http/Http.Abstractions/test/Microsoft.AspNetCore.Http.Abstractions.Tests.csproj::Microsoft.AspNetCore.Builder.Extensions.MapPathMiddlewareTests.MatchPathWithTrailingSlashThrowsException": { + "test_level": "unit", + "p2p_scope": "Pre-existing upstream xUnit selector in Microsoft.AspNetCore.Http.Abstractions.Tests; included as a P2P guardrail, so the F2P system/e2e requirement does not apply.", + "public_surface": "dotnet_test(xunit)", + "runner_surface": "./run_tests.sh", + "internal_symbol_check": "Selector existed before the eval patches and is outside files modified by the golden patch/eval augmentation." + }, + "src/Http/Http.Abstractions/test/Microsoft.AspNetCore.Http.Abstractions.Tests.csproj::Microsoft.AspNetCore.Builder.Extensions.MapPathMiddlewareTests.PathMismatchFunc_PassedThrough": { + "test_level": "unit", + "p2p_scope": "Pre-existing upstream xUnit selector in Microsoft.AspNetCore.Http.Abstractions.Tests; included as a P2P guardrail, so the F2P system/e2e requirement does not apply.", + "public_surface": "dotnet_test(xunit)", + "runner_surface": "./run_tests.sh", + "internal_symbol_check": "Selector existed before the eval patches and is outside files modified by the golden patch/eval augmentation." + }, + "src/Http/Http.Abstractions/test/Microsoft.AspNetCore.Http.Abstractions.Tests.csproj::Microsoft.AspNetCore.Builder.Extensions.MapPathMiddlewareTests.PathMismatchAction_PassedThrough": { + "test_level": "unit", + "p2p_scope": "Pre-existing upstream xUnit selector in Microsoft.AspNetCore.Http.Abstractions.Tests; included as a P2P guardrail, so the F2P system/e2e requirement does not apply.", + "public_surface": "dotnet_test(xunit)", + "runner_surface": "./run_tests.sh", + "internal_symbol_check": "Selector existed before the eval patches and is outside files modified by the golden patch/eval augmentation." + }, + "src/Http/Http.Abstractions/test/Microsoft.AspNetCore.Http.Abstractions.Tests.csproj::Microsoft.AspNetCore.Builder.Extensions.MapPathMiddlewareTests.ChainedRoutes_Success": { + "test_level": "unit", + "p2p_scope": "Pre-existing upstream xUnit selector in Microsoft.AspNetCore.Http.Abstractions.Tests; included as a P2P guardrail, so the F2P system/e2e requirement does not apply.", + "public_surface": "dotnet_test(xunit)", + "runner_surface": "./run_tests.sh", + "internal_symbol_check": "Selector existed before the eval patches and is outside files modified by the golden patch/eval augmentation." + }, + "src/Http/Http.Abstractions/test/Microsoft.AspNetCore.Http.Abstractions.Tests.csproj::Microsoft.AspNetCore.Builder.Extensions.MapPathMiddlewareTests.ApplicationBuilderMapOverloadPreferredOverEndpointBuilderGivenStringPathAndImplicitLambdaParameterType": { + "test_level": "unit", + "p2p_scope": "Pre-existing upstream xUnit selector in Microsoft.AspNetCore.Http.Abstractions.Tests; included as a P2P guardrail, so the F2P system/e2e requirement does not apply.", + "public_surface": "dotnet_test(xunit)", + "runner_surface": "./run_tests.sh", + "internal_symbol_check": "Selector existed before the eval patches and is outside files modified by the golden patch/eval augmentation." + }, + "src/Http/Http.Abstractions/test/Microsoft.AspNetCore.Http.Abstractions.Tests.csproj::Microsoft.AspNetCore.Builder.Extensions.MapPathMiddlewareTests.ApplicationBuilderMapOverloadPreferredOverEndpointBuilderGivenStringPathAndExplicitLambdaParameterType": { + "test_level": "unit", + "p2p_scope": "Pre-existing upstream xUnit selector in Microsoft.AspNetCore.Http.Abstractions.Tests; included as a P2P guardrail, so the F2P system/e2e requirement does not apply.", + "public_surface": "dotnet_test(xunit)", + "runner_surface": "./run_tests.sh", + "internal_symbol_check": "Selector existed before the eval patches and is outside files modified by the golden patch/eval augmentation." + }, + "src/Http/Http.Abstractions/test/Microsoft.AspNetCore.Http.Abstractions.Tests.csproj::Microsoft.AspNetCore.Builder.Extensions.MapPredicateMiddlewareTests.PredicateTrue_BranchTaken": { + "test_level": "unit", + "p2p_scope": "Pre-existing upstream xUnit selector in Microsoft.AspNetCore.Http.Abstractions.Tests; included as a P2P guardrail, so the F2P system/e2e requirement does not apply.", + "public_surface": "dotnet_test(xunit)", + "runner_surface": "./run_tests.sh", + "internal_symbol_check": "Selector existed before the eval patches and is outside files modified by the golden patch/eval augmentation." + }, + "src/Http/Http.Abstractions/test/Microsoft.AspNetCore.Http.Abstractions.Tests.csproj::Microsoft.AspNetCore.Builder.Extensions.MapPredicateMiddlewareTests.PredicateTrueAction_BranchTaken": { + "test_level": "unit", + "p2p_scope": "Pre-existing upstream xUnit selector in Microsoft.AspNetCore.Http.Abstractions.Tests; included as a P2P guardrail, so the F2P system/e2e requirement does not apply.", + "public_surface": "dotnet_test(xunit)", + "runner_surface": "./run_tests.sh", + "internal_symbol_check": "Selector existed before the eval patches and is outside files modified by the golden patch/eval augmentation." + }, + "src/Http/Http.Abstractions/test/Microsoft.AspNetCore.Http.Abstractions.Tests.csproj::Microsoft.AspNetCore.Builder.Extensions.MapPredicateMiddlewareTests.PredicateFalseAction_PassThrough": { + "test_level": "unit", + "p2p_scope": "Pre-existing upstream xUnit selector in Microsoft.AspNetCore.Http.Abstractions.Tests; included as a P2P guardrail, so the F2P system/e2e requirement does not apply.", + "public_surface": "dotnet_test(xunit)", + "runner_surface": "./run_tests.sh", + "internal_symbol_check": "Selector existed before the eval patches and is outside files modified by the golden patch/eval augmentation." + }, + "src/Http/Http.Abstractions/test/Microsoft.AspNetCore.Http.Abstractions.Tests.csproj::Microsoft.AspNetCore.Builder.Extensions.MapPredicateMiddlewareTests.ChainedPredicates_Success": { + "test_level": "unit", + "p2p_scope": "Pre-existing upstream xUnit selector in Microsoft.AspNetCore.Http.Abstractions.Tests; included as a P2P guardrail, so the F2P system/e2e requirement does not apply.", + "public_surface": "dotnet_test(xunit)", + "runner_surface": "./run_tests.sh", + "internal_symbol_check": "Selector existed before the eval patches and is outside files modified by the golden patch/eval augmentation." + }, + "src/Http/Http.Abstractions/test/Microsoft.AspNetCore.Http.Abstractions.Tests.csproj::Microsoft.AspNetCore.Builder.Extensions.UseExtensionsTests.UseCallsNextMiddleware": { + "test_level": "unit", + "p2p_scope": "Pre-existing upstream xUnit selector in Microsoft.AspNetCore.Http.Abstractions.Tests; included as a P2P guardrail, so the F2P system/e2e requirement does not apply.", + "public_surface": "dotnet_test(xunit)", + "runner_surface": "./run_tests.sh", + "internal_symbol_check": "Selector existed before the eval patches and is outside files modified by the golden patch/eval augmentation." + }, + "src/Http/Http.Abstractions/test/Microsoft.AspNetCore.Http.Abstractions.Tests.csproj::Microsoft.AspNetCore.Builder.Extensions.UseExtensionsTests.ThrowFromMiddlewareFlowsBackToInvoke": { + "test_level": "unit", + "p2p_scope": "Pre-existing upstream xUnit selector in Microsoft.AspNetCore.Http.Abstractions.Tests; included as a P2P guardrail, so the F2P system/e2e requirement does not apply.", + "public_surface": "dotnet_test(xunit)", + "runner_surface": "./run_tests.sh", + "internal_symbol_check": "Selector existed before the eval patches and is outside files modified by the golden patch/eval augmentation." + }, + "src/Http/Http.Abstractions/test/Microsoft.AspNetCore.Http.Abstractions.Tests.csproj::Microsoft.AspNetCore.Http.Abstractions.HttpMethodslTests.CanonicalizedValue_Success": { + "test_level": "unit", + "p2p_scope": "Pre-existing upstream xUnit selector in Microsoft.AspNetCore.Http.Abstractions.Tests; included as a P2P guardrail, so the F2P system/e2e requirement does not apply.", + "public_surface": "dotnet_test(xunit)", + "runner_surface": "./run_tests.sh", + "internal_symbol_check": "Selector existed before the eval patches and is outside files modified by the golden patch/eval augmentation." + }, + "src/Http/Http.Abstractions/test/Microsoft.AspNetCore.Http.Abstractions.Tests.csproj::Microsoft.AspNetCore.Http.Abstractions.HttpProtocolTests.Http3_Success": { + "test_level": "unit", + "p2p_scope": "Pre-existing upstream xUnit selector in Microsoft.AspNetCore.Http.Abstractions.Tests; included as a P2P guardrail, so the F2P system/e2e requirement does not apply.", + "public_surface": "dotnet_test(xunit)", + "runner_surface": "./run_tests.sh", + "internal_symbol_check": "Selector existed before the eval patches and is outside files modified by the golden patch/eval augmentation." + }, + "src/Http/Http.Abstractions/test/Microsoft.AspNetCore.Http.Abstractions.Tests.csproj::Microsoft.AspNetCore.Http.Abstractions.HttpProtocolTests.IsHttp3_Success": { + "test_level": "unit", + "p2p_scope": "Pre-existing upstream xUnit selector in Microsoft.AspNetCore.Http.Abstractions.Tests; included as a P2P guardrail, so the F2P system/e2e requirement does not apply.", + "public_surface": "dotnet_test(xunit)", + "runner_surface": "./run_tests.sh", + "internal_symbol_check": "Selector existed before the eval patches and is outside files modified by the golden patch/eval augmentation." + }, + "src/Http/Http.Abstractions/test/Microsoft.AspNetCore.Http.Abstractions.Tests.csproj::Microsoft.AspNetCore.Http.Abstractions.HttpProtocolTests.Http2_Success": { + "test_level": "unit", + "p2p_scope": "Pre-existing upstream xUnit selector in Microsoft.AspNetCore.Http.Abstractions.Tests; included as a P2P guardrail, so the F2P system/e2e requirement does not apply.", + "public_surface": "dotnet_test(xunit)", + "runner_surface": "./run_tests.sh", + "internal_symbol_check": "Selector existed before the eval patches and is outside files modified by the golden patch/eval augmentation." + }, + "src/Http/Http.Abstractions/test/Microsoft.AspNetCore.Http.Abstractions.Tests.csproj::Microsoft.AspNetCore.Http.Abstractions.HttpProtocolTests.IsHttp2_Success": { + "test_level": "unit", + "p2p_scope": "Pre-existing upstream xUnit selector in Microsoft.AspNetCore.Http.Abstractions.Tests; included as a P2P guardrail, so the F2P system/e2e requirement does not apply.", + "public_surface": "dotnet_test(xunit)", + "runner_surface": "./run_tests.sh", + "internal_symbol_check": "Selector existed before the eval patches and is outside files modified by the golden patch/eval augmentation." + }, + "src/Http/Http.Abstractions/test/Microsoft.AspNetCore.Http.Abstractions.Tests.csproj::Microsoft.AspNetCore.Http.Abstractions.HttpProtocolTests.Http11_Success": { + "test_level": "unit", + "p2p_scope": "Pre-existing upstream xUnit selector in Microsoft.AspNetCore.Http.Abstractions.Tests; included as a P2P guardrail, so the F2P system/e2e requirement does not apply.", + "public_surface": "dotnet_test(xunit)", + "runner_surface": "./run_tests.sh", + "internal_symbol_check": "Selector existed before the eval patches and is outside files modified by the golden patch/eval augmentation." + }, + "src/Http/Http.Abstractions/test/Microsoft.AspNetCore.Http.Abstractions.Tests.csproj::Microsoft.AspNetCore.Http.Abstractions.HttpProtocolTests.IsHttp11_Success": { + "test_level": "unit", + "p2p_scope": "Pre-existing upstream xUnit selector in Microsoft.AspNetCore.Http.Abstractions.Tests; included as a P2P guardrail, so the F2P system/e2e requirement does not apply.", + "public_surface": "dotnet_test(xunit)", + "runner_surface": "./run_tests.sh", + "internal_symbol_check": "Selector existed before the eval patches and is outside files modified by the golden patch/eval augmentation." + }, + "src/Http/Http.Abstractions/test/Microsoft.AspNetCore.Http.Abstractions.Tests.csproj::Microsoft.AspNetCore.Http.Abstractions.HttpProtocolTests.Http10_Success": { + "test_level": "unit", + "p2p_scope": "Pre-existing upstream xUnit selector in Microsoft.AspNetCore.Http.Abstractions.Tests; included as a P2P guardrail, so the F2P system/e2e requirement does not apply.", + "public_surface": "dotnet_test(xunit)", + "runner_surface": "./run_tests.sh", + "internal_symbol_check": "Selector existed before the eval patches and is outside files modified by the golden patch/eval augmentation." + }, + "src/Http/Http.Abstractions/test/Microsoft.AspNetCore.Http.Abstractions.Tests.csproj::Microsoft.AspNetCore.Http.Abstractions.HttpProtocolTests.IsHttp10_Success": { + "test_level": "unit", + "p2p_scope": "Pre-existing upstream xUnit selector in Microsoft.AspNetCore.Http.Abstractions.Tests; included as a P2P guardrail, so the F2P system/e2e requirement does not apply.", + "public_surface": "dotnet_test(xunit)", + "runner_surface": "./run_tests.sh", + "internal_symbol_check": "Selector existed before the eval patches and is outside files modified by the golden patch/eval augmentation." + }, + "src/Http/Http.Abstractions/test/Microsoft.AspNetCore.Http.Abstractions.Tests.csproj::Microsoft.AspNetCore.Http.Abstractions.HttpProtocolTests.Http09_Success": { + "test_level": "unit", + "p2p_scope": "Pre-existing upstream xUnit selector in Microsoft.AspNetCore.Http.Abstractions.Tests; included as a P2P guardrail, so the F2P system/e2e requirement does not apply.", + "public_surface": "dotnet_test(xunit)", + "runner_surface": "./run_tests.sh", + "internal_symbol_check": "Selector existed before the eval patches and is outside files modified by the golden patch/eval augmentation." + }, + "src/Http/Http.Abstractions/test/Microsoft.AspNetCore.Http.Abstractions.Tests.csproj::Microsoft.AspNetCore.Http.Abstractions.HttpProtocolTests.IsHttp09_Success": { + "test_level": "unit", + "p2p_scope": "Pre-existing upstream xUnit selector in Microsoft.AspNetCore.Http.Abstractions.Tests; included as a P2P guardrail, so the F2P system/e2e requirement does not apply.", + "public_surface": "dotnet_test(xunit)", + "runner_surface": "./run_tests.sh", + "internal_symbol_check": "Selector existed before the eval patches and is outside files modified by the golden patch/eval augmentation." + }, + "src/Http/Http.Abstractions/test/Microsoft.AspNetCore.Http.Abstractions.Tests.csproj::Microsoft.AspNetCore.Http.Abstractions.HttpProtocolTests.GetHttpProtocol_CorrectIETFVersion": { + "test_level": "unit", + "p2p_scope": "Pre-existing upstream xUnit selector in Microsoft.AspNetCore.Http.Abstractions.Tests; included as a P2P guardrail, so the F2P system/e2e requirement does not apply.", + "public_surface": "dotnet_test(xunit)", + "runner_surface": "./run_tests.sh", + "internal_symbol_check": "Selector existed before the eval patches and is outside files modified by the golden patch/eval augmentation." + }, + "src/Http/Http.Abstractions/test/Microsoft.AspNetCore.Http.Abstractions.Tests.csproj::Microsoft.AspNetCore.Http.Abstractions.HttpProtocolTests.GetHttpProtocol_ThrowErrorForUnknownVersion": { + "test_level": "unit", + "p2p_scope": "Pre-existing upstream xUnit selector in Microsoft.AspNetCore.Http.Abstractions.Tests; included as a P2P guardrail, so the F2P system/e2e requirement does not apply.", + "public_surface": "dotnet_test(xunit)", + "runner_surface": "./run_tests.sh", + "internal_symbol_check": "Selector existed before the eval patches and is outside files modified by the golden patch/eval augmentation." + }, + "src/Http/Http.Abstractions/test/Microsoft.AspNetCore.Http.Abstractions.Tests.csproj::Microsoft.AspNetCore.Http.Abstractions.QueryStringTests.CtorThrows_IfQueryDoesNotHaveLeadingQuestionMark": { + "test_level": "unit", + "p2p_scope": "Pre-existing upstream xUnit selector in Microsoft.AspNetCore.Http.Abstractions.Tests; included as a P2P guardrail, so the F2P system/e2e requirement does not apply.", + "public_surface": "dotnet_test(xunit)", + "runner_surface": "./run_tests.sh", + "internal_symbol_check": "Selector existed before the eval patches and is outside files modified by the golden patch/eval augmentation." + }, + "src/Http/Http.Abstractions/test/Microsoft.AspNetCore.Http.Abstractions.Tests.csproj::Microsoft.AspNetCore.Http.Abstractions.QueryStringTests.CtorNullOrEmpty_Success": { + "test_level": "unit", + "p2p_scope": "Pre-existing upstream xUnit selector in Microsoft.AspNetCore.Http.Abstractions.Tests; included as a P2P guardrail, so the F2P system/e2e requirement does not apply.", + "public_surface": "dotnet_test(xunit)", + "runner_surface": "./run_tests.sh", + "internal_symbol_check": "Selector existed before the eval patches and is outside files modified by the golden patch/eval augmentation." + }, + "src/Http/Http.Abstractions/test/Microsoft.AspNetCore.Http.Abstractions.Tests.csproj::Microsoft.AspNetCore.Http.Abstractions.QueryStringTests.CtorJustAQuestionMark_Success": { + "test_level": "unit", + "p2p_scope": "Pre-existing upstream xUnit selector in Microsoft.AspNetCore.Http.Abstractions.Tests; included as a P2P guardrail, so the F2P system/e2e requirement does not apply.", + "public_surface": "dotnet_test(xunit)", + "runner_surface": "./run_tests.sh", + "internal_symbol_check": "Selector existed before the eval patches and is outside files modified by the golden patch/eval augmentation." + }, + "src/Http/Http.Abstractions/test/Microsoft.AspNetCore.Http.Abstractions.Tests.csproj::Microsoft.AspNetCore.Http.Abstractions.QueryStringTests.ToString_EncodesHash": { + "test_level": "unit", + "p2p_scope": "Pre-existing upstream xUnit selector in Microsoft.AspNetCore.Http.Abstractions.Tests; included as a P2P guardrail, so the F2P system/e2e requirement does not apply.", + "public_surface": "dotnet_test(xunit)", + "runner_surface": "./run_tests.sh", + "internal_symbol_check": "Selector existed before the eval patches and is outside files modified by the golden patch/eval augmentation." + }, + "src/Http/Http.Abstractions/test/Microsoft.AspNetCore.Http.Abstractions.Tests.csproj::Microsoft.AspNetCore.Http.Abstractions.QueryStringTests.CreateNameValue_Success": { + "test_level": "unit", + "p2p_scope": "Pre-existing upstream xUnit selector in Microsoft.AspNetCore.Http.Abstractions.Tests; included as a P2P guardrail, so the F2P system/e2e requirement does not apply.", + "public_surface": "dotnet_test(xunit)", + "runner_surface": "./run_tests.sh", + "internal_symbol_check": "Selector existed before the eval patches and is outside files modified by the golden patch/eval augmentation." + }, + "src/Http/Http.Abstractions/test/Microsoft.AspNetCore.Http.Abstractions.Tests.csproj::Microsoft.AspNetCore.Http.Abstractions.QueryStringTests.CreateFromList_Success": { + "test_level": "unit", + "p2p_scope": "Pre-existing upstream xUnit selector in Microsoft.AspNetCore.Http.Abstractions.Tests; included as a P2P guardrail, so the F2P system/e2e requirement does not apply.", + "public_surface": "dotnet_test(xunit)", + "runner_surface": "./run_tests.sh", + "internal_symbol_check": "Selector existed before the eval patches and is outside files modified by the golden patch/eval augmentation." + }, + "src/Http/Http.Abstractions/test/Microsoft.AspNetCore.Http.Abstractions.Tests.csproj::Microsoft.AspNetCore.Http.Abstractions.QueryStringTests.CreateFromListStringValues_Success": { + "test_level": "unit", + "p2p_scope": "Pre-existing upstream xUnit selector in Microsoft.AspNetCore.Http.Abstractions.Tests; included as a P2P guardrail, so the F2P system/e2e requirement does not apply.", + "public_surface": "dotnet_test(xunit)", + "runner_surface": "./run_tests.sh", + "internal_symbol_check": "Selector existed before the eval patches and is outside files modified by the golden patch/eval augmentation." + }, + "src/Http/Http.Abstractions/test/Microsoft.AspNetCore.Http.Abstractions.Tests.csproj::Microsoft.AspNetCore.Http.Abstractions.QueryStringTests.AddQueryString_Success": { + "test_level": "unit", + "p2p_scope": "Pre-existing upstream xUnit selector in Microsoft.AspNetCore.Http.Abstractions.Tests; included as a P2P guardrail, so the F2P system/e2e requirement does not apply.", + "public_surface": "dotnet_test(xunit)", + "runner_surface": "./run_tests.sh", + "internal_symbol_check": "Selector existed before the eval patches and is outside files modified by the golden patch/eval augmentation." + }, + "src/Http/Http.Abstractions/test/Microsoft.AspNetCore.Http.Abstractions.Tests.csproj::Microsoft.AspNetCore.Http.Abstractions.QueryStringTests.AddNameValue_Success": { + "test_level": "unit", + "p2p_scope": "Pre-existing upstream xUnit selector in Microsoft.AspNetCore.Http.Abstractions.Tests; included as a P2P guardrail, so the F2P system/e2e requirement does not apply.", + "public_surface": "dotnet_test(xunit)", + "runner_surface": "./run_tests.sh", + "internal_symbol_check": "Selector existed before the eval patches and is outside files modified by the golden patch/eval augmentation." + }, + "src/Http/Http.Abstractions/test/Microsoft.AspNetCore.Http.Abstractions.Tests.csproj::Microsoft.AspNetCore.Http.Abstractions.QueryStringTests.Equals_EmptyQueryStringAndDefaultQueryString": { + "test_level": "unit", + "p2p_scope": "Pre-existing upstream xUnit selector in Microsoft.AspNetCore.Http.Abstractions.Tests; included as a P2P guardrail, so the F2P system/e2e requirement does not apply.", + "public_surface": "dotnet_test(xunit)", + "runner_surface": "./run_tests.sh", + "internal_symbol_check": "Selector existed before the eval patches and is outside files modified by the golden patch/eval augmentation." + }, + "src/Http/Http.Abstractions/test/Microsoft.AspNetCore.Http.Abstractions.Tests.csproj::Microsoft.AspNetCore.Http.Abstractions.QueryStringTests.NotEquals_DefaultQueryStringAndNonNullQueryString": { + "test_level": "unit", + "p2p_scope": "Pre-existing upstream xUnit selector in Microsoft.AspNetCore.Http.Abstractions.Tests; included as a P2P guardrail, so the F2P system/e2e requirement does not apply.", + "public_surface": "dotnet_test(xunit)", + "runner_surface": "./run_tests.sh", + "internal_symbol_check": "Selector existed before the eval patches and is outside files modified by the golden patch/eval augmentation." + }, + "src/Http/Http.Abstractions/test/Microsoft.AspNetCore.Http.Abstractions.Tests.csproj::Microsoft.AspNetCore.Http.Abstractions.QueryStringTests.NotEquals_EmptyQueryStringAndNonNullQueryString": { + "test_level": "unit", + "p2p_scope": "Pre-existing upstream xUnit selector in Microsoft.AspNetCore.Http.Abstractions.Tests; included as a P2P guardrail, so the F2P system/e2e requirement does not apply.", + "public_surface": "dotnet_test(xunit)", + "runner_surface": "./run_tests.sh", + "internal_symbol_check": "Selector existed before the eval patches and is outside files modified by the golden patch/eval augmentation." + }, + "src/Http/Http.Abstractions/test/Microsoft.AspNetCore.Http.Abstractions.Tests.csproj::Microsoft.AspNetCore.Http.Abstractions.Tests.CookieBuilderTests.ConfiguresSecurePolicy": { + "test_level": "unit", + "p2p_scope": "Pre-existing upstream xUnit selector in Microsoft.AspNetCore.Http.Abstractions.Tests; included as a P2P guardrail, so the F2P system/e2e requirement does not apply.", + "public_surface": "dotnet_test(xunit)", + "runner_surface": "./run_tests.sh", + "internal_symbol_check": "Selector existed before the eval patches and is outside files modified by the golden patch/eval augmentation." + }, + "src/Http/Http.Abstractions/test/Microsoft.AspNetCore.Http.Abstractions.Tests.csproj::Microsoft.AspNetCore.Http.Abstractions.Tests.CookieBuilderTests.ComputesExpiration": { + "test_level": "unit", + "p2p_scope": "Pre-existing upstream xUnit selector in Microsoft.AspNetCore.Http.Abstractions.Tests; included as a P2P guardrail, so the F2P system/e2e requirement does not apply.", + "public_surface": "dotnet_test(xunit)", + "runner_surface": "./run_tests.sh", + "internal_symbol_check": "Selector existed before the eval patches and is outside files modified by the golden patch/eval augmentation." + }, + "src/Http/Http.Abstractions/test/Microsoft.AspNetCore.Http.Abstractions.Tests.csproj::Microsoft.AspNetCore.Http.Abstractions.Tests.CookieBuilderTests.ComputesMaxAge": { + "test_level": "unit", + "p2p_scope": "Pre-existing upstream xUnit selector in Microsoft.AspNetCore.Http.Abstractions.Tests; included as a P2P guardrail, so the F2P system/e2e requirement does not apply.", + "public_surface": "dotnet_test(xunit)", + "runner_surface": "./run_tests.sh", + "internal_symbol_check": "Selector existed before the eval patches and is outside files modified by the golden patch/eval augmentation." + }, + "src/Http/Http.Abstractions/test/Microsoft.AspNetCore.Http.Abstractions.Tests.csproj::Microsoft.AspNetCore.Http.Abstractions.Tests.CookieBuilderTests.CookieBuilderPreservesDefaultPath": { + "test_level": "unit", + "p2p_scope": "Pre-existing upstream xUnit selector in Microsoft.AspNetCore.Http.Abstractions.Tests; included as a P2P guardrail, so the F2P system/e2e requirement does not apply.", + "public_surface": "dotnet_test(xunit)", + "runner_surface": "./run_tests.sh", + "internal_symbol_check": "Selector existed before the eval patches and is outside files modified by the golden patch/eval augmentation." + }, + "src/Http/Http.Abstractions/test/Microsoft.AspNetCore.Http.Abstractions.Tests.csproj::Microsoft.AspNetCore.Http.Abstractions.Tests.CookieBuilderTests.CookieBuilder_Extensions_Added": { + "test_level": "unit", + "p2p_scope": "Pre-existing upstream xUnit selector in Microsoft.AspNetCore.Http.Abstractions.Tests; included as a P2P guardrail, so the F2P system/e2e requirement does not apply.", + "public_surface": "dotnet_test(xunit)", + "runner_surface": "./run_tests.sh", + "internal_symbol_check": "Selector existed before the eval patches and is outside files modified by the golden patch/eval augmentation." + } + } + }, + "augmented": { + "fail_to_pass": [ + "src/Http/Http.Results/test/Microsoft.AspNetCore.Http.Results.Tests.csproj::ApiEndpointMetadataResultsAugTests.AcceptedFamilyResultsProvideApiEndpointMetadata", + "src/Http/Http.Results/test/Microsoft.AspNetCore.Http.Results.Tests.csproj::ApiEndpointMetadataResultsAugTests.CreatedFamilyResultsProvideApiEndpointMetadata", + "src/Http/Http.Results/test/Microsoft.AspNetCore.Http.Results.Tests.csproj::ApiEndpointMetadataResultsAugTests.ClientErrorFamilyResultsProvideApiEndpointMetadata", + "src/Http/Http.Results/test/Microsoft.AspNetCore.Http.Results.Tests.csproj::ApiEndpointMetadataResultsAugTests.OkJsonAndServerFamilyResultsProvideApiEndpointMetadata", + "src/Http/Http.Results/test/Microsoft.AspNetCore.Http.Results.Tests.csproj::ApiEndpointMetadataResultsAugTests.ProblemFamilyResultsProvideApiEndpointMetadata", + "src/Http/Http.Extensions/test/Microsoft.AspNetCore.Http.Extensions.Tests.csproj::ApiEndpointMetadataRdfAugTests.JsonRequestBodyEndpointGetsApiEndpointMetadata", + "src/Http/Http.Extensions/test/Microsoft.AspNetCore.Http.Extensions.Tests.csproj::ApiEndpointMetadataRdfAugTests.JsonResponseEndpointGetsApiEndpointMetadata", + "src/Http/Http.Extensions/test/Microsoft.AspNetCore.Http.Extensions.Tests.csproj::ApiEndpointMetadataRdfAugTests.JsonBodyAndResponseEndpointGetsSingleApiEndpointMetadata", + "src/Http/Http.Extensions/test/Microsoft.AspNetCore.Http.Extensions.Tests.csproj::ApiEndpointMetadataRdfAugTests.PlainTextAndVoidEndpointsGetNoApiEndpointMetadata", + "src/SignalR/common/Http.Connections/test/Microsoft.AspNetCore.Http.Connections.Tests.csproj::ApiEndpointMetadataConnectionsAugTests.MapConnectionHandlerEndpointsProvideApiEndpointMetadata", + "src/Mvc/Mvc.Core/test/Microsoft.AspNetCore.Mvc.Core.Test.csproj::ApiEndpointMetadataMvcAugTests.ApiControllerAttributeProvidesApiEndpointMetadata" + ], + "pass_to_pass": [ + "src/Http/Http.Abstractions/test/Microsoft.AspNetCore.Http.Abstractions.Tests.csproj::EndpointMetadataCollectionAugTests.GetMetadataReturnsMostRecentMatch", + "src/Http/Http.Abstractions/test/Microsoft.AspNetCore.Http.Abstractions.Tests.csproj::EndpointMetadataCollectionAugTests.GetOrderedMetadataPreservesRegistrationOrder" + ], + "eval_tests_aug_patch_sha256": "5b1150d118f167a377e4907697de92a76ef716b017fd58f504a3efb6e18cd0ca", + "triage": { + "test_level_policy": "All augmented selectors drive behavior through pre-existing public surfaces (IEndpointMetadataProvider.PopulateMetadata, RequestDelegateFactory.Create, MapConnectionHandler, ApiControllerAttribute, AddEndpointsApiExplorer/IApiDescriptionGroupCollectionProvider, EndpointMetadataCollection) and assert on IApiEndpointMetadata, which the requirement doc names explicitly. No internal symbols (no *.Internal.* namespaces, no internal classes) and no PR-added symbols absent from the requirement doc are referenced; the concrete ApiEndpointMetadata singleton class is never named. F2P files reference IApiEndpointMetadata and therefore compile-flip at pre-state; the P2P file references only pre-existing types and passes at pre-state.", + "fail_to_pass": { + "src/Http/Http.Results/test/Microsoft.AspNetCore.Http.Results.Tests.csproj::ApiEndpointMetadataResultsAugTests.AcceptedFamilyResultsProvideApiEndpointMetadata": { + "requirement_sections": [ + "Background and Motivation", + "Proposed API" + ], + "public_surface": "IEndpointMetadataProvider.PopulateMetadata (pre-existing public static interface surface of the TypedResults types) + IApiEndpointMetadata (named in the requirement doc)", + "mutants_targeted": [ + "mutant_001_internal_metadata_not_marker" + ], + "rationale": "The requirement promises TypedResults return types recognized as API-oriented are automatically assigned IApiEndpointMetadata. Pins that contract for Accepted/Accepted/AcceptedAtRoute/AcceptedAtRoute by populating endpoint metadata through the public PopulateMetadata surface and asserting an IApiEndpointMetadata instance is present. Compile-flips pre-state (IApiEndpointMetadata absent)." + }, + "src/Http/Http.Results/test/Microsoft.AspNetCore.Http.Results.Tests.csproj::ApiEndpointMetadataResultsAugTests.CreatedFamilyResultsProvideApiEndpointMetadata": { + "requirement_sections": [ + "Background and Motivation", + "Proposed API" + ], + "public_surface": "IEndpointMetadataProvider.PopulateMetadata (pre-existing public static interface surface of the TypedResults types) + IApiEndpointMetadata (named in the requirement doc)", + "mutants_targeted": [ + "mutant_001_internal_metadata_not_marker" + ], + "rationale": "The requirement promises TypedResults return types recognized as API-oriented are automatically assigned IApiEndpointMetadata. Pins that contract for Created/Created/CreatedAtRoute/CreatedAtRoute by populating endpoint metadata through the public PopulateMetadata surface and asserting an IApiEndpointMetadata instance is present. Compile-flips pre-state (IApiEndpointMetadata absent)." + }, + "src/Http/Http.Results/test/Microsoft.AspNetCore.Http.Results.Tests.csproj::ApiEndpointMetadataResultsAugTests.ClientErrorFamilyResultsProvideApiEndpointMetadata": { + "requirement_sections": [ + "Background and Motivation", + "Proposed API" + ], + "public_surface": "IEndpointMetadataProvider.PopulateMetadata (pre-existing public static interface surface of the TypedResults types) + IApiEndpointMetadata (named in the requirement doc)", + "mutants_targeted": [ + "mutant_001_internal_metadata_not_marker" + ], + "rationale": "The requirement promises TypedResults return types recognized as API-oriented are automatically assigned IApiEndpointMetadata. Pins that contract for BadRequest/Conflict/UnprocessableEntity (+)/NotFound by populating endpoint metadata through the public PopulateMetadata surface and asserting an IApiEndpointMetadata instance is present. Compile-flips pre-state (IApiEndpointMetadata absent)." + }, + "src/Http/Http.Results/test/Microsoft.AspNetCore.Http.Results.Tests.csproj::ApiEndpointMetadataResultsAugTests.OkJsonAndServerFamilyResultsProvideApiEndpointMetadata": { + "requirement_sections": [ + "Background and Motivation", + "Proposed API" + ], + "public_surface": "IEndpointMetadataProvider.PopulateMetadata (pre-existing public static interface surface of the TypedResults types) + IApiEndpointMetadata (named in the requirement doc)", + "mutants_targeted": [ + "mutant_001_internal_metadata_not_marker", + "mutant_013_json_typed_result_not_marker", + "mutant_015_ok_typed_result_unmarked" + ], + "rationale": "The requirement promises TypedResults return types recognized as API-oriented are automatically assigned IApiEndpointMetadata. Pins that contract for Ok/Ok/JsonHttpResult/InternalServerError/NoContent/ServerSentEventsResult by populating endpoint metadata through the public PopulateMetadata surface and asserting an IApiEndpointMetadata instance is present. Compile-flips pre-state (IApiEndpointMetadata absent)." + }, + "src/Http/Http.Results/test/Microsoft.AspNetCore.Http.Results.Tests.csproj::ApiEndpointMetadataResultsAugTests.ProblemFamilyResultsProvideApiEndpointMetadata": { + "requirement_sections": [ + "Background and Motivation", + "Proposed API" + ], + "public_surface": "IEndpointMetadataProvider.PopulateMetadata (pre-existing public static interface surface of the TypedResults types) + IApiEndpointMetadata (named in the requirement doc)", + "mutants_targeted": [ + "mutant_001_internal_metadata_not_marker", + "mutant_014_problem_typed_result_not_marker", + "mutant_016_validation_problem_typed_result_unmarked" + ], + "rationale": "The requirement promises TypedResults return types recognized as API-oriented are automatically assigned IApiEndpointMetadata. Pins that contract for ProblemHttpResult/ValidationProblem by populating endpoint metadata through the public PopulateMetadata surface and asserting an IApiEndpointMetadata instance is present. Compile-flips pre-state (IApiEndpointMetadata absent)." + }, + "src/Http/Http.Extensions/test/Microsoft.AspNetCore.Http.Extensions.Tests.csproj::ApiEndpointMetadataRdfAugTests.JsonRequestBodyEndpointGetsApiEndpointMetadata": { + "requirement_sections": [ + "Background and Motivation" + ], + "public_surface": "RequestDelegateFactory.Create (pre-existing public minimal-API factory) + RequestDelegateResult.EndpointMetadata", + "mutants_targeted": [ + "mutant_005_rdf_json_request_body_not_marked" + ], + "rationale": "Endpoints that read a JSON request body must be automatically marked as API endpoints: a (Todo todo) => string handler yields exactly one IApiEndpointMetadata entry." + }, + "src/Http/Http.Extensions/test/Microsoft.AspNetCore.Http.Extensions.Tests.csproj::ApiEndpointMetadataRdfAugTests.JsonResponseEndpointGetsApiEndpointMetadata": { + "requirement_sections": [ + "Background and Motivation" + ], + "public_surface": "RequestDelegateFactory.Create + RequestDelegateResult.EndpointMetadata", + "mutants_targeted": [ + "mutant_006_rdf_json_response_not_marked" + ], + "rationale": "Endpoints that respond with JSON (plain object and Task-wrapped object handlers) must be automatically marked as API endpoints." + }, + "src/Http/Http.Extensions/test/Microsoft.AspNetCore.Http.Extensions.Tests.csproj::ApiEndpointMetadataRdfAugTests.JsonBodyAndResponseEndpointGetsSingleApiEndpointMetadata": { + "requirement_sections": [ + "Background and Motivation" + ], + "public_surface": "RequestDelegateFactory.Create + RequestDelegateResult.EndpointMetadata", + "mutants_targeted": [ + "mutant_005_rdf_json_request_body_not_marked", + "mutant_006_rdf_json_response_not_marked" + ], + "rationale": "An endpoint with both a JSON body parameter and a JSON response is marked exactly once (the response-side inference deduplicates against the body-side marking)." + }, + "src/Http/Http.Extensions/test/Microsoft.AspNetCore.Http.Extensions.Tests.csproj::ApiEndpointMetadataRdfAugTests.PlainTextAndVoidEndpointsGetNoApiEndpointMetadata": { + "requirement_sections": [ + "Background and Motivation" + ], + "public_surface": "RequestDelegateFactory.Create + RequestDelegateResult.EndpointMetadata", + "mutants_targeted": [], + "rationale": "Negative guard: browser-navigable endpoints (string/plain-text, void, bare Task) must NOT be marked, preserving cookie login redirects for non-API endpoints." + }, + "src/SignalR/common/Http.Connections/test/Microsoft.AspNetCore.Http.Connections.Tests.csproj::ApiEndpointMetadataConnectionsAugTests.MapConnectionHandlerEndpointsProvideApiEndpointMetadata": { + "requirement_sections": [ + "Background and Motivation", + "Proposed API" + ], + "public_surface": "ConnectionEndpointRouteBuilderExtensions.MapConnectionHandler (pre-existing public SignalR transport mapping) + EndpointDataSource", + "mutants_targeted": [ + "mutant_011_signalr_metadata_not_added", + "mutant_012_signalr_metadata_wrong_marker" + ], + "rationale": "SignalR connection endpoints are not browser-navigation endpoints; both mapped endpoints (negotiate + transport) must expose IApiEndpointMetadata." + }, + "src/Mvc/Mvc.Core/test/Microsoft.AspNetCore.Mvc.Core.Test.csproj::ApiEndpointMetadataMvcAugTests.ApiControllerAttributeProvidesApiEndpointMetadata": { + "requirement_sections": [ + "Background and Motivation", + "Proposed API" + ], + "public_surface": "ApiControllerAttribute (pre-existing public attribute, named in the requirement doc) + IApiEndpointMetadata", + "mutants_targeted": [ + "mutant_010_api_controller_attribute_not_marker" + ], + "rationale": "Endpoints attributed with ApiController are recognized as API endpoints: MVC surfaces controller attributes as endpoint metadata, so the attribute itself must implement IApiEndpointMetadata." + } + }, + "pass_to_pass": { + "src/Http/Http.Abstractions/test/Microsoft.AspNetCore.Http.Abstractions.Tests.csproj::EndpointMetadataCollectionAugTests.GetMetadataReturnsMostRecentMatch": { + "requirement_sections": [ + "Proposed API" + ], + "public_surface": "EndpointMetadataCollection (pre-existing public type, unmodified by the PR)", + "rationale": "The requirement adds only a metadata interface and explicitly introduces no new attributes or extension methods; GetMetadata must keep returning the most recent match for unrelated metadata types." + }, + "src/Http/Http.Abstractions/test/Microsoft.AspNetCore.Http.Abstractions.Tests.csproj::EndpointMetadataCollectionAugTests.GetOrderedMetadataPreservesRegistrationOrder": { + "requirement_sections": [ + "Proposed API" + ], + "public_surface": "EndpointMetadataCollection (pre-existing public type, unmodified by the PR)", + "rationale": "Same no-modification clause: GetOrderedMetadata must keep registration order and enumeration must keep collection semantics for test-local metadata types." + } + } + }, + "mutant_set_revision": { + "date": "2026-06-16", + "removed": [ + "mutant_007_rdg_requires_json_body_and_response", + "mutant_008_rdg_add_if_missing_inverted", + "mutant_009_rdg_json_accepts_unmarked" + ], + "reason": "unreachable", + "note": "3 unreachable mutant(s) removed from mutations/ per the 2026-06-16 mutant-kill audit (no \u00a76-clean test can kill this unreachable mutant); union now kills all 13 remaining mutants.", + "new_total": 13, + "union_kills_all_remaining": true + }, + "f2p_aug_sha256": "653ebd830dc6eab281ca273745e16762dc422cd8c76d1fc44ac0a07c80075fb6" + }, + "coverage": { + "orig": 9.23, + "aug": 84.62, + "union": 93.85, + "denominator": "union_executable_lines" + } +} diff --git a/aspnetcore_1/tests/report_to_reward.py b/aspnetcore_1/tests/report_to_reward.py new file mode 100644 index 0000000000000000000000000000000000000000..01758344225d03e06f14b64a6c455d80b7ec0d81 --- /dev/null +++ b/aspnetcore_1/tests/report_to_reward.py @@ -0,0 +1,73 @@ +#!/usr/bin/env python3 +import argparse +import json +from pathlib import Path + + +def rate(bucket): + total = float(bucket.get("total", 0) or 0) + if total <= 0: + return 0.0 + return float(bucket.get("passed", 0) or 0) / total + + +def write_json(path, payload): + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(json.dumps(payload, indent=2, sort_keys=True) + "\n") + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument("--suite", default="union") + parser.add_argument("--missing-patch") + parser.add_argument("--invalid-suite", action="store_true") + parser.add_argument("--runner-rc", type=int, default=0) + parser.add_argument("agent_report") + parser.add_argument("reward_file") + args = parser.parse_args() + + report_path = Path(args.agent_report) + reward_path = Path(args.reward_file) + + if args.invalid_suite: + reward = {"reward": 0.0, "resolved": 0.0, "applied": 0.0, "build_ok": 0.0, "f2p_pass_rate": 0.0, "p2p_pass_rate": 0.0, "harness_ok": 1.0} + sanitized = {"instance_id": "aspnetcore_1", "suite": args.suite, "applied": False, "resolved": False, "error_categories": ["invalid_lolbench_suite"]} + write_json(report_path, sanitized) + write_json(reward_path, reward) + print(f"LoLBench reward=0 invalid suite {args.suite!r}") + return 0 + + if args.missing_patch: + reward = {"reward": 0.0, "resolved": 0.0, "applied": 0.0, "build_ok": 0.0, "f2p_pass_rate": 0.0, "p2p_pass_rate": 0.0, "harness_ok": 1.0} + sanitized = {"instance_id": "aspnetcore_1", "suite": args.suite, "applied": False, "resolved": False, "error_categories": ["missing_solution_patch"]} + write_json(report_path, sanitized) + write_json(reward_path, reward) + print("LoLBench reward=0 missing solution patch") + return 0 + + if not report_path.exists(): + reward = {"reward": 0.0, "resolved": 0.0, "applied": 0.0, "build_ok": 0.0, "f2p_pass_rate": 0.0, "p2p_pass_rate": 0.0, "harness_ok": 0.0} + write_json(reward_path, reward) + print(f"LoLBench reward=0 no agent_report.json runner_rc={args.runner_rc}") + return 0 + + report = json.loads(report_path.read_text()) + build_status = report.get("build", {}).get("status") + resolved = bool(report.get("resolved")) + applied = bool(report.get("applied")) + reward = { + "reward": 1.0 if resolved else 0.0, + "resolved": 1.0 if resolved else 0.0, + "applied": 1.0 if applied else 0.0, + "build_ok": 1.0 if build_status == "ok" else 0.0, + "f2p_pass_rate": rate(report.get("f2p", {})), + "p2p_pass_rate": rate(report.get("p2p", {})), + "harness_ok": 1.0 if args.runner_rc == 0 else 0.0, + } + write_json(reward_path, reward) + print("LoLBench reward={reward} resolved={resolved} f2p={f2p_pass_rate:.3f} p2p={p2p_pass_rate:.3f}".format(**reward)) + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/aspnetcore_1/tests/test.sh b/aspnetcore_1/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..45ba2abd4f682d021752e6966a772a0ee2edb9f5 --- /dev/null +++ b/aspnetcore_1/tests/test.sh @@ -0,0 +1,43 @@ +#!/usr/bin/env bash +set -euo pipefail + +suite=${LOLBENCH_SUITE:-union} +mode=${LOLBENCH_MODE:-eval} +patch=${LOLBENCH_SOLUTION_PATCH:-/logs/artifacts/solution.patch} +private_log=/tmp/lolbench-private-run.log + +mkdir -p /logs/verifier /logs/artifacts /in /out + +case "$suite" in + orig|aug|union) ;; + *) + python3 /tests/report_to_reward.py --suite "$suite" --invalid-suite /out/agent_report.json /logs/verifier/reward.json + exit 0 + ;; +esac + +if [ "$mode" = "eval" ] && [ ! -s "$patch" ]; then + python3 /tests/report_to_reward.py --suite "$suite" --missing-patch "$patch" /out/agent_report.json /logs/verifier/reward.json + exit 0 +fi + +if [ "$mode" = "eval" ]; then + cp "$patch" /in/solution.patch + chmod 0400 /in/solution.patch +fi + +set +e +LOLBENCH_MODE="$mode" LOLBENCH_SUITE="$suite" /opt/lolbench/private/run_tests.sh >"$private_log" 2>&1 +runner_rc=$? +set -e + +cp "$private_log" /logs/verifier/private_run.log +if [ -f /out/grader_report.json ]; then + cp /out/grader_report.json /logs/verifier/grader_report.json +fi + +python3 /tests/report_to_reward.py --suite "$suite" --runner-rc "$runner_rc" /out/agent_report.json /logs/verifier/reward.json + +if [ -f /out/agent_report.json ]; then + cp /out/agent_report.json /logs/verifier/agent_report.json +fi diff --git a/cargo_1/README.md b/cargo_1/README.md new file mode 100644 index 0000000000000000000000000000000000000000..3949a9367628e9299fd746b7219bc96126f618a6 --- /dev/null +++ b/cargo_1/README.md @@ -0,0 +1,87 @@ +# LoLBench Harbor Task: cargo_1 + +This is a Harbor-format LoLBench task generated from `Cargo_RFC-3553-SBOM-support_PR-13709`. + +Selected source instance: + +- Harbor ID: `cargo_1` +- PR: `rust-lang/cargo#13709` +- Base commit: `392d68bff462015e8e7d8588333a09b08b4a10a6` +- Test modes: `orig, aug, union` +- Default/canonical mode: `union` +- Harbor image: `smartdub26/lolbench-linux:cargo_1-1.0.0` +- Docker Hub image: `smartdub26/lolbench-linux:cargo_1-1.0.0` + +## Image Setup + +Prefer the published Docker Hub image when it is available. Harbor refers to +the image as `smartdub26/lolbench-linux:cargo_1-1.0.0`, so Docker can pull it +directly when it is not present locally: + +```bash +docker pull smartdub26/lolbench-linux:cargo_1-1.0.0 +``` + +Only if the Docker Hub image is unavailable, build the single task image +locally: + +```bash +docker build -t lolbench/cargo_1:1.0.0 harbor_tasks/cargo_1/environment +docker tag lolbench/cargo_1:1.0.0 smartdub26/lolbench-linux:cargo_1-1.0.0 +``` + +The image contains the processed source tree at the base commit under +`/workspace/cargo`. Harbor must not mount a host source checkout +for the agent. + +## Run an Agent + +```bash +.harbor-venv/bin/harbor run \ + -p harbor_tasks/cargo_1 \ + -a codex \ + -m "" \ + --job-name cargo_1_agent_union \ + --jobs-dir harbor_runs/cargo_1 \ + --no-delete \ + --n-concurrent 1 \ + --ve LOLBENCH_SUITE=union +``` + +After implementing the requirement, the agent must clean any test-file edits +and run: + +```bash +lolbench-submit +``` + +## Evaluate a Patch + +Choose one mode with `LOLBENCH_SUITE=orig`, `aug`, or `union`; if unset, the +task defaults to `union`. + +```bash +PATCH="$(pwd)/path/to/solution.patch" + +.harbor-venv/bin/harbor run \ + -p harbor_tasks/cargo_1 \ + -a oracle \ + --job-name cargo_1_eval_union \ + --jobs-dir harbor_runs/cargo_1 \ + --no-delete \ + --n-concurrent 1 \ + --mounts '[{"type":"bind","source":"'"$PATCH"'","target":"/candidate/solution.patch","read_only":true}]' \ + --ae LOLBENCH_ORACLE_PATCH=/candidate/solution.patch \ + --ve LOLBENCH_SUITE=union +``` + +Outputs: + +```bash +find harbor_runs/cargo_1/cargo_1_eval_union -path '*/verifier/agent_report.json' -print +find harbor_runs/cargo_1/cargo_1_eval_union -path '*/verifier/reward.json' -print +``` + +`tests/docker-compose.yaml` is a verifier-only Harbor overlay. It mounts +`tests/`, `tests/private/`, and `solution/` into the separate verifier +container; none of those paths are mounted into the agent container. diff --git a/cargo_1/environment/Dockerfile b/cargo_1/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..2bbc7dfde727571ebf30b2e2f4a1d7459709108b --- /dev/null +++ b/cargo_1/environment/Dockerfile @@ -0,0 +1,66 @@ +# LoLBench eval image: rust-lang/cargo PR-13709 (RFC 3553 SBOM support) +FROM rust:1.85-bookworm + +ARG BASE_COMMIT=392d68bff462015e8e7d8588333a09b08b4a10a6 +ARG MERGE_COMMIT=5f833db69be1ae445a75e79c777cd34f3ba778a8 + +RUN apt-get update -qq && apt-get install -y --no-install-recommends \ + git ca-certificates curl pkg-config libssl-dev cmake gcc g++ \ + && rm -rf /var/lib/apt/lists/* + +RUN mkdir -p /opt/lolbench/private /in /out /workspace + +WORKDIR /workspace +RUN git init cargo && \ + cd cargo && \ + git remote add origin https://github.com/rust-lang/cargo.git && \ + git fetch --no-tags origin ${MERGE_COMMIT} && \ + git checkout ${BASE_COMMIT} && \ + git ls-files -z > /tmp/cargo-base-files && \ + git config user.email lolbench@local && \ + git config user.name lolbench && \ + if ! git diff --quiet || ! git diff --cached --quiet || [ -n "$(git ls-files --others --exclude-standard)" ]; then \ + git add -A && git -c commit.gpgsign=false commit -q -m "LoLBench environment overlay"; \ + fi && \ + git tag -f base && git tag -f lolbench-base && \ + git for-each-ref --format='%(refname)' refs/heads refs/remotes refs/tags | \ + while read ref; do \ + case "$ref" in refs/tags/base|refs/tags/lolbench-base) ;; *) git update-ref -d "$ref" ;; esac; \ + done && \ + ( git remote remove origin 2>/dev/null || true ) && \ + rm -f .git/FETCH_HEAD && \ + git reflog expire --expire=now --all && \ + git repack -Ad && \ + git prune --expire=now && \ + rm /tmp/cargo-base-files && \ + git config --global --add safe.directory /workspace/cargo + +# Warm cargo build cache +RUN cd /workspace/cargo && \ + cargo fetch && \ + CARGO_BUILD_JOBS=2 cargo build --test testsuite -j 2 2>&1 | tail -60 +RUN rustup target add wasm32-unknown-unknown + +# Harbor runtime adapter: keep the image public/agent-safe. +RUN mkdir -p /opt/lolbench /logs/artifacts /logs/agent /logs/verifier /in /out && \ + if ! id -u agent >/dev/null 2>&1; then useradd -m -s /bin/bash agent; fi +COPY metadata.json /opt/lolbench/metadata.json +COPY lolbench-submit /usr/local/bin/lolbench-submit +RUN chmod +x /usr/local/bin/lolbench-submit && \ + git config --global --add safe.directory /workspace/cargo && \ + if [ -d /workspace/cargo/.git ]; then \ + cd /workspace/cargo && LC_ALL=C git ls-files --others --exclude-standard | LC_ALL=C sort > /opt/lolbench/base_untracked.txt; \ + else \ + : > /opt/lolbench/base_untracked.txt; \ + fi && \ + mkdir -p /home/agent/.cargo && \ + if [ -d /usr/local/cargo/registry ]; then mkdir -p /home/agent/.cargo/registry && cp -a /usr/local/cargo/registry/. /home/agent/.cargo/registry/; fi && \ + if [ -d /usr/local/cargo/git ]; then mkdir -p /home/agent/.cargo/git && cp -a /usr/local/cargo/git/. /home/agent/.cargo/git/; fi && \ + chown -R agent:agent /workspace/cargo /logs /home/agent +ENV HOME=/home/agent +USER agent +WORKDIR /workspace/cargo +ENV CARGO_HOME=/home/agent/.cargo +ENV PATH=/usr/local/cargo/bin:$PATH +ENV LOLBENCH_INSTANCE_ID=cargo_1 +ENV LOLBENCH_SOURCE_SLUG=Cargo_RFC-3553-SBOM-support_PR-13709 diff --git a/cargo_1/environment/docker-compose.yaml b/cargo_1/environment/docker-compose.yaml new file mode 100644 index 0000000000000000000000000000000000000000..7ed45f87dc9faf9df284f5b10d6d2289781ff254 --- /dev/null +++ b/cargo_1/environment/docker-compose.yaml @@ -0,0 +1,3 @@ +services: + main: + pull_policy: missing diff --git a/cargo_1/environment/lolbench-submit b/cargo_1/environment/lolbench-submit new file mode 100644 index 0000000000000000000000000000000000000000..b3426184f1a568aaf145f148348c3c5e85cfa773 --- /dev/null +++ b/cargo_1/environment/lolbench-submit @@ -0,0 +1,33 @@ +#!/usr/bin/env bash +set -euo pipefail +export LC_ALL=C + +repo=${1:-$PWD} +out=${LOLBENCH_PATCH_OUT:-/logs/artifacts/solution.patch} + +mkdir -p "$(dirname "$out")" +cd "$repo" + +baseline=/opt/lolbench/base_untracked.txt +current=$(mktemp) +new_files=$(mktemp) +trap 'rm -f "$current" "$new_files"' EXIT + +git ls-files --others --exclude-standard | sort > "$current" +if [ -f "$baseline" ]; then + comm -13 "$baseline" "$current" > "$new_files" +else + cp "$current" "$new_files" +fi + +if [ -s "$new_files" ]; then + xargs -r git add -N -- < "$new_files" +fi + +git diff --binary > "$out" + +if [ ! -s "$out" ]; then + echo "warning: wrote an empty solution patch to $out" >&2 +else + echo "wrote solution patch to $out" +fi diff --git a/cargo_1/environment/metadata.json b/cargo_1/environment/metadata.json new file mode 100644 index 0000000000000000000000000000000000000000..20245a59793ab62d466b57de4c179c218152b9f3 --- /dev/null +++ b/cargo_1/environment/metadata.json @@ -0,0 +1,22 @@ +{ + "instance_id": "cargo_1", + "source_instance_id": "Cargo_RFC-3553-SBOM-support_PR-13709", + "source_slug": "Cargo_RFC-3553-SBOM-support_PR-13709", + "docker_slug": "Cargo_RFC-3553-SBOM-support_PR-13709", + "dockerhub_image": "smartdub26/lolbench-linux:cargo_1-1.0.0", + "project": "cargo", + "repo": "rust-lang/cargo", + "requirement_doc": "https://github.com/rust-lang/rfcs/pull/3553", + "pr_link": "https://github.com/rust-lang/cargo/pull/13709", + "base_commit": "392d68bff462015e8e7d8588333a09b08b4a10a6", + "merge_commit": "5f833db69be1ae445a75e79c777cd34f3ba778a8", + "source_history_policy": "ancestors-only", + "lolbench_test_modes": [ + "orig", + "aug", + "union" + ], + "default_lolbench_suite": "union", + "canonical_lolbench_suite": "union", + "augmentation_available": true +} diff --git a/cargo_1/environment/source_audit.json b/cargo_1/environment/source_audit.json new file mode 100644 index 0000000000000000000000000000000000000000..b556b9b7bfd4c825bcc7428c46f188ffdf5d3ace --- /dev/null +++ b/cargo_1/environment/source_audit.json @@ -0,0 +1,6 @@ +{ + "source_policy": "dockerfile_fetch_historyless_base_snapshot", + "base_commit": "392d68bff462015e8e7d8588333a09b08b4a10a6", + "repo": "rust-lang/cargo", + "note": "The generated Dockerfile fetches the base commit with ancestor history, preserves .git, removes post-base refs/remotes/reflogs, and prunes unreachable future commit objects during image build." +} diff --git a/cargo_1/instruction.md b/cargo_1/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..6ddd803372b903e6a561022ceebf1c00194b08fe --- /dev/null +++ b/cargo_1/instruction.md @@ -0,0 +1,231 @@ +You are working in `/workspace/cargo`, a source tree checked out at +the base commit for this task. Implement the requested behavior in the source +tree, then run: + +```bash +lolbench-submit +``` + +Do not stop after editing files, running tests, or describing the solution. The +task is complete only when `lolbench-submit` has created +`/logs/artifacts/solution.patch`. If that file does not exist, continue +working and run `lolbench-submit` again. + +That command writes your implementation diff to +`/logs/artifacts/solution.patch`, which is the artifact the Harbor verifier +will grade. Before running `lolbench-submit`, clean or revert any test files +you created or modified; test files must not be included in the final +`solution.patch`. + +This environment has no outbound internet access — `curl`/`wget`, `git fetch`/`clone`, package installs, and web fetch/search will all fail. Implement the requirements using only the code already in the workspace and your own knowledge; do not attempt to fetch or search external resources. + +Now please implement the following requirements in the source tree: + +--- + +- Feature Name: `cargo-sbom` +- Start Date: 2023-11-01 +- RFC PR: [rust-lang/rfcs#3553](https://github.com/rust-lang/rfcs/pull/3553) +- Rust Issue: [rust-lang/rust#0000](https://github.com/rust-lang/rust/issues/0000) + +# Summary +[summary]: #summary + +This RFC adds an option to Cargo that emits information for building a Software Bill of Materials (SBOM) precursor file alongside compiled artifacts. Similar to how Cargo "dep-info" (.d) files, this change emits SBOM data in a Cargo-specific format alongside outputs in the `target` directory. External tools or Cargo subcommands can consume this file and transform it into an SBOM such as SPDX or CycloneDX. + +# Motivation +[motivation]: #motivation + +An SBOM (software bill of materials) is a list of all components and dependencies used to build a piece of software. The two leading SBOM formats being adopted by industry are SPDX and CycloneDX. Both are still evolving and have multiple specification versions & data formats (JSON, XML). + +New government initiatives aimed at improving the security of the software supply chain such as the US "Executive Order 14028: Improving the Nation's Cybersecurity" or the EU "Cyber Resilience Act" require a Software Bill of Materials. Generating accurate SBOMs with Cargo is currently difficult because, depending on target selection or activated features, the dependencies may be different. + +For workspaces that generate multiple compiled artifacts, each artifact may have different dependencies referenced. Existing tools (see prior art section) attempt to approximate the correct dependency set, however precise dependency information for each compiled artifact is difficult without built-in Cargo support. Generating the SBOM information at the same time as the compiled artifact allows precise dependency information to be emitted for each compiled artifact. + +# Guide-level explanation +[guide-level-explanation]: #guide-level-explanation + +The generation of SBOM information is controlled by Cargo's configuration. To enable SBOM generation, set the following configuration: + +```toml +[build] +sbom = true +``` + +Or use the environment variable `CARGO_BUILD_SBOM=true`. + +This feature is unstable and additionally requires the `-Zsbom` command-line flag (e.g. `cargo build -Zsbom`). Setting only `[build] sbom = true` or `CARGO_BUILD_SBOM=true` WITHOUT `-Zsbom` does NOT enable SBOM output — Cargo emits the warning `` ignoring 'sbom' config, pass `-Zsbom` to enable it `` and produces no file. Passing `-Zsbom` alone without the config/env var also produces no output. BOTH are required. + +If enabled, an SBOM file will be placed next to each compiled artifact for `bin`, `staticlib`, `cdylib` crate types in the `target` directory with the name `.cargo-sbom.json`. The SBOM will contain information about dependencies used to build the compiled artifact. + +# Reference-level explanation +[reference-level-explanation]: #reference-level-explanation + +The SBOM file generated by Cargo is *not* intended as a final SBOM artifact, but rather a precursor. Post-processing tooling can use the information produced here as part of building a final SBOM. + +The SBOM file will be written to disk before `rustc` is executed for the each artifact. This enables [`RUSTC_WORKSPACE_WRAPPER`](https://doc.rust-lang.org/cargo/reference/config.html#buildrustc-workspace-wrapper) to point at a program that can utilize the SBOM file to embed information into the binary if desired. The environment variable `CARGO_SBOM_PATH` will be set to the full path to the SBOM file. + +## Format +The format will use JSON, but the exact format is not specified in this RFC. Additional fields can be added as needed. The JSON will include a `format-version` in case breaking changes are necessary. + +In the merged implementation the top-level JSON object has these keys: `version` (integer schema version, currently `1` — the field is named `version`, NOT `format-version`), `root` (index into `crates`), `crates` (array of objects `{ id: PackageIdSpec string, kind: array of target-kind strings (e.g. bin/lib/custom-build/proc-macro), features: array of activated-feature strings, dependencies: array of { index, kind: normal|build } }`), `rustc` (object with version/wrapper/workspace_wrapper/commit_hash/host/verbose_version), and `target` (the requested target triple). The emitted field is `version`, superseding the RFC's `format-version` named above. + +### Resolved Dependency Tree +The SBOM file will include the following information for each crate. Note that a crate refers to a [single build unit (library or executable)](https://doc.rust-lang.org/cargo/appendix/glossary.html#crate). +A [package](https://doc.rust-lang.org/cargo/appendix/glossary.html#package) may contain multiple crates. +- Package ID +- Name +- Version +- Source (registry / git / path etc.) +- Checksum (if available) +- Dependencies +- Type (normal, build) +- Activated features + +If a crate is used as both a normal dependency and a build dependency that is separately compiled, then separate entries will exist in the dependency tree with the correct activated features listed for each instance. + +Checksum is an optional field, since only crates from registries have checksums. If a checksum is needed for a crate that comes from a path dependency for example, it will be up to the post-processing tool to produce an appropriate value. + +If further information is needed (such as license), then the post-processing tool can use `cargo metadata` or another mechanism to find it. + +### Resolved build configuration +- Rust toolchain version +- `RUSTFLAGS` +- Current build profile name +- Selected profile values + +## Security + +Cargo's SBOM file provides a report of the components and dependencies used by cargo to build a software artifact. + +Cargo does not defend against malicious components or dependencies changing the SBOM, or accidentally or maliciously concealing themselves from the SBOM. In particular, components or dependencies added by build scripts or external tools might not be accurately represented in the SBOM file produced by Cargo. Ideally, tools should provide their own SBOMs, and build scripts should modify the SBOM via supported cargo interfaces (see future possibilities). + +# Drawbacks +[drawbacks]: #drawbacks + +It introduces yet another SBOM format. However, the format is specifically designed to be used as an intermediate, to be converted to an industry-standard format by external tooling. + +# Rationale and alternatives +[rationale-and-alternatives]: #rationale-and-alternatives + +Since there is no consensus on a single SBOM format within the software industry, and existing formats are still evolving, Cargo should not pick an existing SBOM format. If Cargo were to use existing SBOM formats, multiple formats (and multiple versions of each format) would need to be supported. The task of generating a specific SBOM format is best left to applications outside Cargo or Cargo extension. Cargo is not in a position to produce an SBOM that is compliant with internal and external regulations. + +Unfortunately it's difficult to extract accurate SBOM information with existing options. Using the `Cargo.lock` file or `cargo metadata` overincludes dependencies. Additionally, since Cargo has many different commands that produce compiled artifacts (build, test, bench, etc.) and each of these commands take arguments that can affect the dependency list it's difficult to ensure that the correct dependency list is used. + +Adding an option to `cargo metadata` to support resolver v2 would help with overinclusion of dependencies, but still makes it difficult to ensure the exact set of features, command-line arguments, and other options match the command used to produce the final artifact. The CLI would need substantial changes to allow users to control package and build target selection. Additionally, since build scripts (`build.rs`) may impact the output, `cargo metadata` may need to execute them. + +Another alternative is to extract information by setting the `RUSTC_WRAPPER` environment variable, then capture feature flags and dependencies via a wrapper tool. This would require the wrapper tool to parse the rustc command line arguments to capture the set of feature flags and referenced dependencies. This approach would prevent other uses of `RUSTC_WRAPPER`, as well as being potentially fragile. + +# Prior art +[prior-art]: #prior-art + +* [RFC2801](https://github.com/rust-lang/rfcs/pull/2801): Proposes embedding dependency information directly into the binary. Implemented as the `cargo auditable` extension. +* [cargo-auditable](https://github.com/rust-secure-code/cargo-auditable): Cargo extension that embeds a subset of the information described in this RFC directly into the binary. The JSON format used by this RFC could be based on the cargo-auditable format. +* [cargo-cyclonedx](https://github.com/CycloneDX/cyclonedx-rust-cargo): Cargo extension to generate a CycloneDX SBOM. +* [cargo-bom](https://github.com/sensorfu/cargo-bom): Cargo extension to generate a BOM in an ASCII format including license information. +* [cargo build-plan (#5579)](https://github.com/rust-lang/cargo/issues/5579): Provides an option to emit a JSON representation of the commands to execute, without actually running them. This option has poor integration with `build.rs` and was [planned for deletion](https://github.com/rust-lang/cargo/issues/7614) in 2018. +* [cargo unit graph (#8002)](https://github.com/rust-lang/cargo/issues/8002): Very similar to what this RFC intends on writing to disk. However, since unit-graph runs wihtout a build, it cannot take `build.rs` output into account. + +# Unresolved questions +[unresolved-questions]: #unresolved-questions + +The exact specifics about what will be included in the SBOM and the specific JSON format are subject to change during the implementation of the RFC. + +# Future possibilities +[future-possibilities]: #future-possibilities + +Additional fields can be added to the SBOM without a breaking change as new requirements are identified such as: +* Environment variables read +* Additional profile flags +* External tool versions (linker, C compiler, OS) + +## Build scripts +Build scripts could communicate back to Cargo to inject additional dependencies into the SBOM. For example, if a crate builds `C` code and then links with it, it would emit a build script instruction that causes Cargo to read in a file describing the `C` dependency. +``` +cargo::sbom= +```` +Cargo would then include the additional dependency information in the SBOM graph. + +## Embedding dependency information into binaries +The implementation of [RFC2801](https://github.com/rust-lang/rfcs/pull/2801) could be based on the information provided by this RFC. + +## Linked Issue rust-lang/cargo#5579 — Tracking issue for build plan generation (--build-plan) + +*Source: https://github.com/rust-lang/cargo/issues/5579* + +### cargo#5579: Body + +> Implemented in https://github.com/rust-lang/cargo/pull/5301, Cargo gained the ability to produce a JSON build plan containing a list of commands that need to be executed to build a target. +> +> The feature is currently unstable and requires a nightly Cargo release as well as the `-Zunstable-options` command line argument. This issue tracks its eventual stabilization. +> +> This feature was originally requested in https://github.com/rust-lang/cargo/issues/3815 to facilitate Cargo's integration into other build systems. + +**State:** closed +**Title:** Tracking issue for build plan generation (--build-plan) + +Cited by RFC 3553 as prior art for emitting structured JSON metadata from Cargo, which the new `*.cargo-sbom.json` output extends in a more focused direction. + +## Linked Issue rust-lang/cargo#7614 — Should build-plans be deleted? + +*Source: https://github.com/rust-lang/cargo/issues/7614* + +### cargo#7614: Body (excerpt) + +> The cargo team has been talking about this for some time now, and this is an issue I'd like to open to cc others and get some discussion about this. +> +> The build-plan feature of Cargo is broken, and has always been broken. It has never actually accounted for all the build intricacies of crate graphs that Cargo supports. It was landed to unblock initial work with the understanding that it wouldn't be stabilized before it was fleshed out more, but the work to flesh it out more hasn't happened since then. The build plan does not support, for example: +> +> - Transitively passing arguments from build scripts to later crates +> - Encoding information about pipelining +> - Requires implementors to have their own parsing of build script outputs and such + +**State:** closed +**Title:** Should build-plans be deleted? + +This issue is cited as evidence that `--build-plan` is not a viable extension point for SBOM generation; RFC 3553 therefore proposes a new SBOM-precursor file written alongside compiled artifacts rather than extending `--build-plan`. + +## Linked Issue rust-lang/cargo#8002 — Tracking issue for --unit-graph + +*Source: https://github.com/rust-lang/cargo/issues/8002* + +### cargo#8002: Body (excerpt) + +> Implementation: https://github.com/rust-lang/cargo/pull/7977 +> Documentation: https://doc.rust-lang.org/nightly/cargo/reference/unstable.html#unit-graph +> +> **Summary** +> The `--unit-graph` flag emits a JSON structure showing Cargo's internal unit graph. +> +> **Unresolved issues** +> +> - Is there a better way to expose this information? I think in many cases, to make this useful, you have to also run `cargo metadata` (to get package names, for example). It seems a little silly to have to run two commands. + +**State:** open +**Title:** Tracking issue for --unit-graph + +Cited by RFC 3553 as the closest existing Cargo introspection feature; this RFC proposes a complementary, artifact-scoped output rather than extending `--unit-graph`. + +## Linked Reference: RFC 2801 (rust-lang/rfcs#2801) — Embedding dependency information + +*Source: https://github.com/rust-lang/rfcs/pull/2801* + +RFC 2801 proposes embedding dependency information inside compiled Rust binaries. RFC 3553's *Future possibilities* section identifies RFC 2801's implementation as a downstream consumer that could read the new `cargo-sbom.json` precursor instead of duplicating dependency-graph traversal. The two RFCs are linked at the design level: 3553 produces the data on disk, 2801 (if accepted) consumes it for binary embedding. + +## Linked Reference: cargo-auditable (rust-secure-code/cargo-auditable) and cargo-bom (sensorfu/cargo-bom) + +*Source: https://github.com/rust-secure-code/cargo-auditable and https://github.com/sensorfu/cargo-bom* + +These two third-party Cargo subcommands are listed in RFC 3553's *Prior art* section as the closest existing solutions: + +- **cargo-auditable** embeds dependency information into the binary (overlaps with RFC 2801's scope). +- **cargo-bom** generates a CycloneDX SBOM by traversing the Cargo metadata graph. + +Both are limited by their inability to see exactly which dependencies Cargo activated for each compiled artifact, which the RFC's per-artifact `cargo-sbom.json` resolves. + +## Linked Reference: CycloneDX/cyclonedx-rust-cargo + +*Source: https://github.com/CycloneDX/cyclonedx-rust-cargo* + +The CycloneDX-Rust-Cargo project is the reference downstream tool that consumes Cargo metadata and produces CycloneDX-format SBOMs. It is cited by RFC 3553 as the canonical example of a "post-processing tool" that the new precursor file is intended to feed. + diff --git a/cargo_1/solution/solution.patch b/cargo_1/solution/solution.patch new file mode 100644 index 0000000000000000000000000000000000000000..8d6521046fe385a21e0337d77534b7083881cf6c --- /dev/null +++ b/cargo_1/solution/solution.patch @@ -0,0 +1,578 @@ +diff --git a/Cargo.lock b/Cargo.lock +--- a/Cargo.lock ++++ b/Cargo.lock +@@ -457,7 +457,7 @@ version = "0.4.2" + + [[package]] + name = "cargo-test-support" +-version = "0.7.2" ++version = "0.7.3" + dependencies = [ + "anstream", + "anstyle", +diff --git a/src/cargo/core/compiler/build_config.rs b/src/cargo/core/compiler/build_config.rs +--- a/src/cargo/core/compiler/build_config.rs ++++ b/src/cargo/core/compiler/build_config.rs +@@ -48,6 +48,8 @@ pub struct BuildConfig { + pub future_incompat_report: bool, + /// Which kinds of build timings to output (empty if none). + pub timing_outputs: Vec, ++ /// Output SBOM precursor files. ++ pub sbom: bool, + } + + fn default_parallelism() -> CargoResult { +@@ -99,6 +101,17 @@ impl BuildConfig { + }, + }; + ++ // If sbom flag is set, it requires the unstable feature ++ let sbom = match (cfg.sbom, gctx.cli_unstable().sbom) { ++ (Some(sbom), true) => sbom, ++ (Some(_), false) => { ++ gctx.shell() ++ .warn("ignoring 'sbom' config, pass `-Zsbom` to enable it")?; ++ false ++ } ++ (None, _) => false, ++ }; ++ + Ok(BuildConfig { + requested_kinds, + jobs, +@@ -115,6 +128,7 @@ impl BuildConfig { + export_dir: None, + future_incompat_report: false, + timing_outputs: Vec::new(), ++ sbom, + }) + } + +diff --git a/src/cargo/core/compiler/build_context/target_info.rs b/src/cargo/core/compiler/build_context/target_info.rs +--- a/src/cargo/core/compiler/build_context/target_info.rs ++++ b/src/cargo/core/compiler/build_context/target_info.rs +@@ -72,6 +72,8 @@ pub enum FileFlavor { + Rmeta, + /// Piece of external debug information (e.g., `.dSYM`/`.pdb` file). + DebugInfo, ++ /// SBOM (Software Bill of Materials pre-cursor) file (e.g. cargo-sbon.json). ++ Sbom, + } + + /// Type of each file generated by a Unit. +diff --git a/src/cargo/core/compiler/build_runner/compilation_files.rs b/src/cargo/core/compiler/build_runner/compilation_files.rs +--- a/src/cargo/core/compiler/build_runner/compilation_files.rs ++++ b/src/cargo/core/compiler/build_runner/compilation_files.rs +@@ -495,13 +495,37 @@ impl<'a, 'gctx: 'a> CompilationFiles<'a, 'gctx> { + CompileMode::Test + | CompileMode::Build + | CompileMode::Bench +- | CompileMode::Check { .. } => self.calc_outputs_rustc(unit, bcx)?, ++ | CompileMode::Check { .. } => { ++ let mut outputs = self.calc_outputs_rustc(unit, bcx)?; ++ if bcx.build_config.sbom && bcx.gctx.cli_unstable().sbom { ++ let sbom_files: Vec<_> = outputs ++ .iter() ++ .filter(|o| matches!(o.flavor, FileFlavor::Normal | FileFlavor::Linkable)) ++ .map(|output| OutputFile { ++ path: Self::append_sbom_suffix(&output.path), ++ hardlink: output.hardlink.as_ref().map(Self::append_sbom_suffix), ++ export_path: output.export_path.as_ref().map(Self::append_sbom_suffix), ++ flavor: FileFlavor::Sbom, ++ }) ++ .collect(); ++ outputs.extend(sbom_files.into_iter()); ++ } ++ outputs ++ } + }; + debug!("Target filenames: {:?}", ret); + + Ok(Arc::new(ret)) + } + ++ /// Append the SBOM suffix to the file name. ++ fn append_sbom_suffix(link: &PathBuf) -> PathBuf { ++ const SBOM_FILE_EXTENSION: &str = ".cargo-sbom.json"; ++ let mut link_buf = link.clone().into_os_string(); ++ link_buf.push(SBOM_FILE_EXTENSION); ++ PathBuf::from(link_buf) ++ } ++ + /// Computes the actual, full pathnames for all the files generated by rustc. + /// + /// The `OutputFile` also contains the paths where those files should be +diff --git a/src/cargo/core/compiler/build_runner/mod.rs b/src/cargo/core/compiler/build_runner/mod.rs +--- a/src/cargo/core/compiler/build_runner/mod.rs ++++ b/src/cargo/core/compiler/build_runner/mod.rs +@@ -309,7 +309,10 @@ impl<'a, 'gctx> BuildRunner<'a, 'gctx> { + + fn collect_tests_and_executables(&mut self, unit: &Unit) -> CargoResult<()> { + for output in self.outputs(unit)?.iter() { +- if output.flavor == FileFlavor::DebugInfo || output.flavor == FileFlavor::Auxiliary { ++ if matches!( ++ output.flavor, ++ FileFlavor::DebugInfo | FileFlavor::Auxiliary | FileFlavor::Sbom ++ ) { + continue; + } + +@@ -446,6 +449,16 @@ impl<'a, 'gctx> BuildRunner<'a, 'gctx> { + self.files().metadata(unit).unit_id() + } + ++ /// Returns the list of SBOM output file paths for a given [`Unit`]. ++ pub fn sbom_output_files(&self, unit: &Unit) -> CargoResult> { ++ Ok(self ++ .outputs(unit)? ++ .iter() ++ .filter(|o| o.flavor == FileFlavor::Sbom) ++ .map(|o| o.path.clone()) ++ .collect()) ++ } ++ + pub fn is_primary_package(&self, unit: &Unit) -> bool { + self.primary_packages.contains(&unit.pkg.package_id()) + } +diff --git a/src/cargo/core/compiler/fingerprint/mod.rs b/src/cargo/core/compiler/fingerprint/mod.rs +--- a/src/cargo/core/compiler/fingerprint/mod.rs ++++ b/src/cargo/core/compiler/fingerprint/mod.rs +@@ -1517,7 +1517,12 @@ fn calculate_normal( + let outputs = build_runner + .outputs(unit)? + .iter() +- .filter(|output| !matches!(output.flavor, FileFlavor::DebugInfo | FileFlavor::Auxiliary)) ++ .filter(|output| { ++ !matches!( ++ output.flavor, ++ FileFlavor::DebugInfo | FileFlavor::Auxiliary | FileFlavor::Sbom ++ ) ++ }) + .map(|output| output.path.clone()) + .collect(); + +diff --git a/src/cargo/core/compiler/mod.rs b/src/cargo/core/compiler/mod.rs +--- a/src/cargo/core/compiler/mod.rs ++++ b/src/cargo/core/compiler/mod.rs +@@ -47,6 +47,7 @@ pub(crate) mod layout; + mod links; + mod lto; + mod output_depinfo; ++mod output_sbom; + pub mod rustdoc; + pub mod standard_lib; + mod timings; +@@ -60,7 +61,7 @@ use std::env; + use std::ffi::{OsStr, OsString}; + use std::fmt::Display; + use std::fs::{self, File}; +-use std::io::{BufRead, Write}; ++use std::io::{BufRead, BufWriter, Write}; + use std::path::{Path, PathBuf}; + use std::sync::Arc; + +@@ -85,6 +86,7 @@ use self::job_queue::{Job, JobQueue, JobState, Work}; + pub(crate) use self::layout::Layout; + pub use self::lto::Lto; + use self::output_depinfo::output_depinfo; ++use self::output_sbom::build_sbom; + use self::unit_graph::UnitDep; + use crate::core::compiler::future_incompat::FutureIncompatReport; + pub use crate::core::compiler::unit::{Unit, UnitInterner}; +@@ -307,6 +309,8 @@ fn rustc( + let script_metadata = build_runner.find_build_script_metadata(unit); + let is_local = unit.is_local(); + let artifact = unit.artifact; ++ let sbom_files = build_runner.sbom_output_files(unit)?; ++ let sbom = build_sbom(build_runner, unit)?; + + let hide_diagnostics_for_scrape_unit = build_runner.bcx.unit_can_fail_for_docscraping(unit) + && !matches!( +@@ -392,6 +396,12 @@ fn rustc( + if build_plan { + state.build_plan(buildkey, rustc.clone(), outputs.clone()); + } else { ++ for file in sbom_files { ++ tracing::debug!("writing sbom to {}", file.display()); ++ let outfile = BufWriter::new(paths::create(&file)?); ++ serde_json::to_writer(outfile, &sbom)?; ++ } ++ + let result = exec + .exec( + &rustc, +@@ -685,6 +695,7 @@ where + /// completion of other units will be added later in runtime, such as flags + /// from build scripts. + fn prepare_rustc(build_runner: &BuildRunner<'_, '_>, unit: &Unit) -> CargoResult { ++ let gctx = build_runner.bcx.gctx; + let is_primary = build_runner.is_primary_package(unit); + let is_workspace = build_runner.bcx.ws.is_member(&unit.pkg); + +@@ -700,7 +711,7 @@ fn prepare_rustc(build_runner: &BuildRunner<'_, '_>, unit: &Unit) -> CargoResult + base.args(args); + } + base.args(&unit.rustflags); +- if build_runner.bcx.gctx.cli_unstable().binary_dep_depinfo { ++ if gctx.cli_unstable().binary_dep_depinfo { + base.arg("-Z").arg("binary-dep-depinfo"); + } + if build_runner.bcx.gctx.cli_unstable().checksum_freshness { +@@ -709,6 +720,8 @@ fn prepare_rustc(build_runner: &BuildRunner<'_, '_>, unit: &Unit) -> CargoResult + + if is_primary { + base.env("CARGO_PRIMARY_PACKAGE", "1"); ++ let file_list = std::env::join_paths(build_runner.sbom_output_files(unit)?)?; ++ base.env("CARGO_SBOM_PATH", file_list); + } + + if unit.target.is_test() || unit.target.is_bench() { +diff --git a/src/cargo/core/compiler/output_depinfo.rs b/src/cargo/core/compiler/output_depinfo.rs +--- a/src/cargo/core/compiler/output_depinfo.rs ++++ b/src/cargo/core/compiler/output_depinfo.rs +@@ -141,11 +141,12 @@ pub fn output_depinfo(build_runner: &mut BuildRunner<'_, '_>, unit: &Unit) -> Ca + .map(|f| render_filename(f, basedir)) + .collect::>>()?; + +- for output in build_runner +- .outputs(unit)? +- .iter() +- .filter(|o| !matches!(o.flavor, FileFlavor::DebugInfo | FileFlavor::Auxiliary)) +- { ++ for output in build_runner.outputs(unit)?.iter().filter(|o| { ++ !matches!( ++ o.flavor, ++ FileFlavor::DebugInfo | FileFlavor::Auxiliary | FileFlavor::Sbom ++ ) ++ }) { + if let Some(ref link_dst) = output.hardlink { + let output_path = link_dst.with_extension("d"); + if success { +diff --git a/src/cargo/core/compiler/output_sbom.rs b/src/cargo/core/compiler/output_sbom.rs +new file mode 100644 +--- /dev/null ++++ b/src/cargo/core/compiler/output_sbom.rs +@@ -0,0 +1,181 @@ ++//! cargo-sbom precursor files for external tools to create SBOM files from. ++//! See [`build_sbom_graph`] for more. ++ ++use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet}; ++use std::path::PathBuf; ++ ++use cargo_util_schemas::core::PackageIdSpec; ++use itertools::Itertools; ++use serde::Serialize; ++ ++use crate::core::TargetKind; ++use crate::util::interning::InternedString; ++use crate::util::Rustc; ++use crate::CargoResult; ++ ++use super::{BuildRunner, CompileMode, Unit}; ++ ++/// Typed version of a SBOM format version number. ++#[derive(Serialize, Copy, Clone, Debug, Ord, PartialOrd, Eq, PartialEq)] ++pub struct SbomFormatVersion(u32); ++ ++#[derive(Debug, Copy, Clone, PartialEq, PartialOrd, Eq, Ord, Serialize)] ++#[serde(rename_all = "snake_case")] ++enum SbomDependencyType { ++ /// A dependency linked to the artifact produced by this unit. ++ Normal, ++ /// A dependency needed to run the build for this unit (e.g. a build script or proc-macro). ++ /// The dependency is not linked to the artifact produced by this unit. ++ Build, ++} ++ ++#[derive(Serialize, Copy, Clone, Debug, Ord, PartialOrd, Eq, PartialEq)] ++struct SbomIndex(usize); ++ ++#[derive(Serialize, Clone, Debug)] ++#[serde(rename_all = "snake_case")] ++struct SbomDependency { ++ index: SbomIndex, ++ kind: SbomDependencyType, ++} ++ ++#[derive(Serialize, Clone, Debug)] ++#[serde(rename_all = "snake_case")] ++struct SbomCrate { ++ id: PackageIdSpec, ++ features: Vec, ++ dependencies: Vec, ++ kind: TargetKind, ++} ++ ++impl SbomCrate { ++ pub fn new(unit: &Unit) -> Self { ++ let package_id = unit.pkg.package_id().to_spec(); ++ let features = unit.features.iter().map(|f| f.to_string()).collect_vec(); ++ Self { ++ id: package_id, ++ features, ++ dependencies: Vec::new(), ++ kind: unit.target.kind().clone(), ++ } ++ } ++} ++ ++#[derive(Serialize, Clone)] ++#[serde(rename_all = "snake_case")] ++struct SbomRustc { ++ version: String, ++ wrapper: Option, ++ workspace_wrapper: Option, ++ commit_hash: Option, ++ host: String, ++ verbose_version: String, ++} ++ ++impl From<&Rustc> for SbomRustc { ++ fn from(rustc: &Rustc) -> Self { ++ Self { ++ version: rustc.version.to_string(), ++ wrapper: rustc.wrapper.clone(), ++ workspace_wrapper: rustc.workspace_wrapper.clone(), ++ commit_hash: rustc.commit_hash.clone(), ++ host: rustc.host.to_string(), ++ verbose_version: rustc.verbose_version.clone(), ++ } ++ } ++} ++ ++#[derive(Serialize)] ++#[serde(rename_all = "snake_case")] ++pub struct Sbom { ++ version: SbomFormatVersion, ++ root: SbomIndex, ++ crates: Vec, ++ rustc: SbomRustc, ++ target: InternedString, ++} ++ ++/// Build an [`Sbom`] for the given [`Unit`]. ++pub fn build_sbom(build_runner: &BuildRunner<'_, '_>, root: &Unit) -> CargoResult { ++ let bcx = build_runner.bcx; ++ let rustc: SbomRustc = bcx.rustc().into(); ++ ++ let mut crates = Vec::new(); ++ let sbom_graph = build_sbom_graph(build_runner, root); ++ ++ // Build set of indicies for each node in the graph for fast lookup. ++ let indicies: HashMap<&Unit, SbomIndex> = sbom_graph ++ .keys() ++ .enumerate() ++ .map(|(i, dep)| (*dep, SbomIndex(i))) ++ .collect(); ++ ++ // Add a item to the crates list for each node in the graph. ++ for (unit, edges) in sbom_graph { ++ let mut krate = SbomCrate::new(unit); ++ for (dep, kind) in edges { ++ krate.dependencies.push(SbomDependency { ++ index: indicies[dep], ++ kind: kind, ++ }); ++ } ++ crates.push(krate); ++ } ++ let target = match root.kind { ++ super::CompileKind::Host => build_runner.bcx.host_triple(), ++ super::CompileKind::Target(target) => target.rustc_target(), ++ }; ++ Ok(Sbom { ++ version: SbomFormatVersion(1), ++ crates, ++ root: indicies[root], ++ rustc, ++ target, ++ }) ++} ++ ++/// List all dependencies, including transitive ones. A dependency can also appear multiple times ++/// if it's using different settings, e.g. profile, features or crate versions. ++/// ++/// Returns a graph of dependencies. ++fn build_sbom_graph<'a>( ++ build_runner: &'a BuildRunner<'_, '_>, ++ root: &'a Unit, ++) -> BTreeMap<&'a Unit, BTreeSet<(&'a Unit, SbomDependencyType)>> { ++ tracing::trace!("building sbom graph for {}", root.pkg.package_id()); ++ ++ let mut queue = Vec::new(); ++ let mut sbom_graph: BTreeMap<&Unit, BTreeSet<(&Unit, SbomDependencyType)>> = BTreeMap::new(); ++ let mut visited = HashSet::new(); ++ ++ // Search to collect all dependencies of the root unit. ++ queue.push((root, root, false)); ++ while let Some((node, parent, is_build_dep)) = queue.pop() { ++ let dependencies = sbom_graph.entry(parent).or_default(); ++ for dep in build_runner.unit_deps(node) { ++ let dep = &dep.unit; ++ let (next_parent, next_is_build_dep) = if dep.mode == CompileMode::RunCustomBuild { ++ // Nodes in the SBOM graph for building/running build scripts are moved on to their parent as build dependencies. ++ (parent, true) ++ } else { ++ // Proc-macros and build scripts are marked as build dependencies. ++ let dep_type = match is_build_dep || dep.target.proc_macro() { ++ false => SbomDependencyType::Normal, ++ true => SbomDependencyType::Build, ++ }; ++ dependencies.insert((dep, dep_type)); ++ tracing::trace!( ++ "adding sbom edge {} -> {} ({:?})", ++ parent.pkg.package_id(), ++ dep.pkg.package_id(), ++ dep_type, ++ ); ++ (dep, false) ++ }; ++ if visited.insert(dep) { ++ queue.push((dep, next_parent, next_is_build_dep)); ++ } ++ } ++ } ++ sbom_graph ++} +diff --git a/src/cargo/core/features.rs b/src/cargo/core/features.rs +--- a/src/cargo/core/features.rs ++++ b/src/cargo/core/features.rs +@@ -792,6 +792,7 @@ unstable_cli_options!( + root_dir: Option = ("Set the root directory relative to which paths are printed (defaults to workspace root)"), + rustdoc_map: bool = ("Allow passing external documentation mappings to rustdoc"), + rustdoc_scrape_examples: bool = ("Allows Rustdoc to scrape code examples from reverse-dependencies"), ++ sbom: bool = ("Enable the `sbom` option in build config in .cargo/config.toml file"), + script: bool = ("Enable support for single-file, `.rs` packages"), + separate_nightlies: bool, + skip_rustdoc_fingerprint: bool, +@@ -1304,6 +1305,7 @@ impl CliUnstable { + "root-dir" => self.root_dir = v.map(|v| v.into()), + "rustdoc-map" => self.rustdoc_map = parse_empty(k, v)?, + "rustdoc-scrape-examples" => self.rustdoc_scrape_examples = parse_empty(k, v)?, ++ "sbom" => self.sbom = parse_empty(k, v)?, + "separate-nightlies" => self.separate_nightlies = parse_empty(k, v)?, + "checksum-freshness" => self.checksum_freshness = parse_empty(k, v)?, + "skip-rustdoc-fingerprint" => self.skip_rustdoc_fingerprint = parse_empty(k, v)?, +diff --git a/src/cargo/util/context/mod.rs b/src/cargo/util/context/mod.rs +--- a/src/cargo/util/context/mod.rs ++++ b/src/cargo/util/context/mod.rs +@@ -2692,6 +2692,8 @@ pub struct CargoBuildConfig { + pub out_dir: Option, + pub artifact_dir: Option, + pub warnings: Option, ++ /// Unstable feature `-Zsbom`. ++ pub sbom: Option, + } + + /// Whether warnings should warn, be allowed, or cause an error. +diff --git a/src/doc/src/reference/unstable.md b/src/doc/src/reference/unstable.md +--- a/src/doc/src/reference/unstable.md ++++ b/src/doc/src/reference/unstable.md +@@ -74,6 +74,7 @@ Each new feature described below should explain how to use it. + * [public-dependency](#public-dependency) --- Allows dependencies to be classified as either public or private. + * [msrv-policy](#msrv-policy) --- MSRV-aware resolver and version selection + * [precise-pre-release](#precise-pre-release) --- Allows pre-release versions to be selected with `update --precise` ++ * [sbom](#sbom) --- Generates SBOM pre-cursor files for compiled artifacts + * [update-breaking](#update-breaking) --- Allows upgrading to breaking versions with `update --breaking` + * [feature-unification](#feature-unification) --- Enable new feature unification modes in workspaces + * Output behavior +@@ -419,6 +420,99 @@ It's possible to update `my-dependency` to a pre-release with `update -Zunstable + This is because `0.1.2-pre.0` is considered compatible with `0.1.1`. + It would not be possible to upgrade to `0.2.0-pre.0` from `0.1.1` in the same way. + ++## sbom ++* Tracking Issue: [#13709](https://github.com/rust-lang/cargo/pull/13709) ++* RFC: [#3553](https://github.com/rust-lang/rfcs/pull/3553) ++ ++The `sbom` build config allows to generate so-called SBOM pre-cursor files ++alongside each compiled artifact. A Software Bill Of Material (SBOM) tool can ++incorporate these generated files to collect important information from the cargo ++build process that are difficult or impossible to obtain in another way. ++ ++To enable this feature either set the `sbom` field in the `.cargo/config.toml` ++ ++```toml ++[unstable] ++sbom = true ++ ++[build] ++sbom = true ++``` ++ ++or set the `CARGO_BUILD_SBOM` environment variable to `true`. The functionality ++is available behind the flag `-Z sbom`. ++ ++The generated output files are in JSON format and follow the naming scheme ++`.cargo-sbom.json`. The JSON file contains information about dependencies, ++target, features and the used `rustc` compiler. ++ ++SBOM pre-cursor files are generated for all executable and linkable outputs ++that are uplifted into the target or artifact directories. ++ ++### Environment variables Cargo sets for crates ++ ++* `CARGO_SBOM_PATH` -- a list of generated SBOM precursor files, separated by the platform PATH separator. The list can be split with `std::env::split_paths`. ++ ++### SBOM pre-cursor schema ++ ++```json5 ++{ ++ // Schema version. ++ "version": 1, ++ // Index into the crates array for the root crate. ++ "root": 0, ++ // Array of all crates. There may be duplicates of the same crate if that ++ // crate is compiled differently (different opt-level, features, etc). ++ "crates": [ ++ { ++ // Package ID specification ++ "id": "path+file:///sample-package#0.1.0", ++ // List of target kinds: bin, lib, rlib, dylib, cdylib, staticlib, proc-macro, example, test, bench, custom-build ++ "kind": ["bin"], ++ // Enabled feature flags. ++ "features": [], ++ // Dependencies for this crate. ++ "dependencies": [ ++ { ++ // Index in to the crates array. ++ "index": 1, ++ // Dependency kind: ++ // Normal: A dependency linked to the artifact produced by this crate. ++ // Build: A compile-time dependency used to build this crate (build-script or proc-macro). ++ "kind": "normal" ++ }, ++ { ++ // A crate can depend on another crate with both normal and build edges. ++ "index": 1, ++ "kind": "build" ++ } ++ ] ++ }, ++ { ++ "id": "registry+https://github.com/rust-lang/crates.io-index#zerocopy@0.8.16", ++ "kind": ["bin"], ++ "features": [], ++ "dependencies": [] ++ } ++ ], ++ // Information about rustc used to perform the compilation. ++ "rustc": { ++ // Compiler version ++ "version": "1.86.0-nightly", ++ // Compiler wrapper ++ "wrapper": null, ++ // Compiler workspace wrapper ++ "workspace_wrapper": null, ++ // Commit hash for rustc ++ "commit_hash": "bef3c3b01f690de16738b1c9f36470fbfc6ac623", ++ // Host target triple ++ "host": "x86_64-pc-windows-msvc", ++ // Verbose version string: `rustc -vV` ++ "verbose_version": "rustc 1.86.0-nightly (bef3c3b01 2025-02-04)\nbinary: rustc\ncommit-hash: bef3c3b01f690de16738b1c9f36470fbfc6ac623\ncommit-date: 2025-02-04\nhost: x86_64-pc-windows-msvc\nrelease: 1.86.0-nightly\nLLVM version: 19.1.7\n" ++ } ++} ++``` ++ + ## update-breaking + + * Tracking Issue: [#12425](https://github.com/rust-lang/cargo/issues/12425) diff --git a/cargo_1/solution/solve.sh b/cargo_1/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..aa9aef757852354c2d7dddceddedb571dd6fe590 --- /dev/null +++ b/cargo_1/solution/solve.sh @@ -0,0 +1,7 @@ +#!/usr/bin/env bash +set -euo pipefail + +cd /workspace/cargo +patch=${LOLBENCH_ORACLE_PATCH:-/solution/solution.patch} +git apply "$patch" +lolbench-submit diff --git a/cargo_1/task.toml b/cargo_1/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..66ba52f73e4a5dea73968992ef8c2c1caff03bc3 --- /dev/null +++ b/cargo_1/task.toml @@ -0,0 +1,60 @@ +schema_version = "1.3" + +[task] +name = "lolbench/cargo_1" +description = "Implement Cargo - RFC 3553: SBOM support." +authors = [{ name = "LoLBench maintainers" }] +keywords = ["lolbench", "coding-agent", "cargo", "rust"] + +[metadata] +instance_id = "cargo_1" +source_instance_id = "Cargo_RFC-3553-SBOM-support_PR-13709" +source_slug = "Cargo_RFC-3553-SBOM-support_PR-13709" +docker_slug = "Cargo_RFC-3553-SBOM-support_PR-13709" +dockerhub_image = "smartdub26/lolbench-linux:cargo_1-1.0.0" +project = "cargo" +repo = "rust-lang/cargo" +requirement_doc = "https://github.com/rust-lang/rfcs/pull/3553" +pr_link = "https://github.com/rust-lang/cargo/pull/13709" +base_commit = "392d68bff462015e8e7d8588333a09b08b4a10a6" +merge_commit = "5f833db69be1ae445a75e79c777cd34f3ba778a8" +test_level = "system" +source_history_policy = "ancestors-only" +lolbench_test_modes = ["orig", "aug", "union"] +default_lolbench_suite = "union" +canonical_lolbench_suite = "union" +augmentation_available = true +verifier_network_policy = "public" +verifier_network_reason = "The Harbor verifier runs in a separate container and may use network access; migrated LoLBench verifier assets are mounted only in the verifier phase." + +[environment] +build_timeout_sec = 3600.0 +docker_image = "smartdub26/lolbench-linux:cargo_1-1.0.0" +network_mode = "public" +os = "linux" +cpus = 4 +memory_mb = 14336 +storage_mb = 20480 + +[agent] +timeout_sec = 21600.0 +user = "agent" +network_mode = "allowlist" +allowed_hosts = ["openrouter.ai", "api.openai.com", "api.anthropic.com"] + +[verifier] +timeout_sec = 7200.0 +user = "root" +environment_mode = "separate" +network_mode = "public" + +[verifier.env] +LOLBENCH_SUITE = "union" + +[verifier.environment] +docker_image = "smartdub26/lolbench-linux:cargo_1-1.0.0" +network_mode = "public" +os = "linux" +cpus = 4 +memory_mb = 14336 +storage_mb = 20480 diff --git a/cargo_1/tests/docker-compose.yaml b/cargo_1/tests/docker-compose.yaml new file mode 100644 index 0000000000000000000000000000000000000000..f5091b9298e127a1efbe69deeed699c907e025c1 --- /dev/null +++ b/cargo_1/tests/docker-compose.yaml @@ -0,0 +1,16 @@ +services: + main: + pull_policy: missing + volumes: + - type: bind + source: . + target: /tests + read_only: true + - type: bind + source: ./private + target: /opt/lolbench/private + read_only: true + - type: bind + source: ../solution + target: /solution + read_only: true diff --git a/cargo_1/tests/private/eval_tests.patch b/cargo_1/tests/private/eval_tests.patch new file mode 100644 index 0000000000000000000000000000000000000000..c5fbf5c1307cc59b0598329e42b687f5602311cd --- /dev/null +++ b/cargo_1/tests/private/eval_tests.patch @@ -0,0 +1,806 @@ +diff --git a/crates/cargo-test-support/Cargo.toml b/crates/cargo-test-support/Cargo.toml +--- a/crates/cargo-test-support/Cargo.toml ++++ b/crates/cargo-test-support/Cargo.toml +@@ -1,6 +1,6 @@ + [package] + name = "cargo-test-support" +-version = "0.7.2" ++version = "0.7.3" + edition.workspace = true + rust-version = "1.85" # MSRV:1 + license.workspace = true +diff --git a/crates/cargo-test-support/src/lib.rs b/crates/cargo-test-support/src/lib.rs +--- a/crates/cargo-test-support/src/lib.rs ++++ b/crates/cargo-test-support/src/lib.rs +@@ -415,6 +415,16 @@ impl Project { + .join(paths::get_lib_filename(name, kind)) + } + ++ /// Path to a dynamic library. ++ /// ex: `/path/to/cargo/target/cit/t0/foo/target/debug/examples/libex.dylib` ++ pub fn dylib(&self, name: &str) -> PathBuf { ++ self.target_debug_dir().join(format!( ++ "{}{name}{}", ++ env::consts::DLL_PREFIX, ++ env::consts::DLL_SUFFIX ++ )) ++ } ++ + /// Path to a debug binary. + /// + /// ex: `$CARGO_TARGET_TMPDIR/cit/t0/foo/target/debug/foo` +diff --git a/tests/testsuite/cargo/z_help/stdout.term.svg b/tests/testsuite/cargo/z_help/stdout.term.svg +--- a/tests/testsuite/cargo/z_help/stdout.term.svg ++++ b/tests/testsuite/cargo/z_help/stdout.term.svg +@@ -1,4 +1,4 @@ +- ++ +
2. Otherwise defer **forward** to the next window opening after the desired time (never earlier); if no window opening exists before `NotAfter`, do not schedule renewal and surface a `WindowError`. Boundaries at a window's start/exclusive-end are compliant. | *Add appropriate conditions to the cert status.* | +| **Disabled** | — | Certificate renewal is **disabled** (no renewal scheduling). | *None — renewal not performed.* | + +*Tip:* When `renewal.windows` are omitted, `RenewBefore` falls back to the existing renew-before behavior, so the table's "No windows" row reflects current behavior. + +### Timezones + +For the sake of uniformity, all `windows` defintions are going to be treated as UTC by the **controller**. `renewal.windows` definitions +allow IANA timezones for better configurations. + +## Controller logic + +### Current behavior + +Cert-manager typically schedules a renewal event when the certificate's +`NotAfter` minus `renewBefore` is reached (or earlier, depending on +internal jitter and queueing). The controller reconciles Certificates +and triggers issuers. + +### Updated behavior + +1. On reconcile, compute `desiredRenewalTime` using existing logic + (expiry - `renewBefore`). +2. If `renewal.policy == Disabled`: + - Do not schedule renewal operations. + - Set a `RenewalDisabled` condition in status with a helpful + message and the `observedGeneration` when it was last observed. +3. Else if `renewalPolicy.policy == RenewBefore`: + - Keep the existing behavior of cert-manager that is to use `renewBefore`. + Find a `renewalTime` which fits in the window. If it doesn't fit the window + then add a status message; also add a message if the `renewalTime` compliant with + the window falls after expiration. + +### Edge cases + +- If windows are misconfigured (invalid timezone, invalid time + string), set a `status.renewal.window.valid=false` condition and **do not** + schedule renewals until corrected. + +## Status changes and Conditions + +Add the following `renewal` field to the status and also update some existing fields accordingly: + +```yaml +status: + renewalTime: "" # Update this according to the controller logic. Existing field. + lastFailureTime: "" # Again this exists and probably doesn't need to be touched. + renewal: + policy: RenewBefore + windows: # This will only be set if windows is set. + valid: "True" + # Every renewal check would add a condition and mark the cert as ready or not along with proper reasons + conditions: [] +``` + +When a renewal is attempted or completed, existing issuance conditions +(e.g., `Issuing`, `Ready`) still apply. + +## API examples + +### 1) Disable renewal completely + +``` yaml +apiVersion: cert-manager.io/v1 +kind: Certificate +metadata: + name: no-renewal-cert +spec: + secretName: no-renewal + dnsNames: ["test.example.com"] + renewal: + policy: Disabled +``` + +## Interactions with other features + +- **ACME rate limits**: By allowing windows, users may unintentionally + bunch renewal attempts into smaller time periods. Document guidance + about rate limits and encourage staggered windows for many + Certificates. +- **Certificate controllers / Reloader / Pod restarts**: If another + controller watches secret updates and triggers restarts, users + should ensure windows align with maintenance windows. This feature + intentionally provides that control. +- **Manual renewal**: `kubectl cert-manager renew` (or similar manual + actions) should continue to work irrespective of `disabled` or + windows because those are meant to affect automatic renewal + only---**unless** the user explicitly requests that manual + operations be blocked (not proposed here). + +## Safety and UX considerations + +- Make `disabled` explicit and require no special RBAC. +- For any configuration parsing error, surface the problem in a + `RenewalConfigInvalid` status to avoid silent misbehavior. +- Provide helpful CLI/`kubectl` hints in messages where appropriate + (e.g. `To renew manually: kubectl cert-manager renew certificate/no-renewal-cert`). + +## Implementation plan (rough) + +1. Update API types (Go structs) and CRD YAML. +2. Add status condition types and helper methods. +3. Extend the Certificate reconciler to evaluate `renewal`: + - Validate `renewal` early in reconcile. + - Compute next allowed window. + - Requeue reconcile for next allowed start when necessary. +4. Ensure the reconciler honors the policy as time progresses: renewal + occurs only inside configured windows, is skipped when the policy is + `Disabled`, and under `RenewBefore` renewal defers **forward** to the next window opening when the desired time is outside all windows. +5. Documentation: user guide, examples, migration notes. + +## Validation and Admission + +- No admission webhook required for initial iteration. CRD validation + should constrain `start`/`end` format using regex and invalid values + will be caught at runtime with `RenewalConfigInvalid`). + +## Metrics and Monitoring + +Suggested metrics additions: - +`certmanager_certificate_renewal_deferred_total{reason="outside_window"}` - +`certmanager_certificate_renewal_bypassed_total{reason="expiry_imminent"}` + +Document that operators should alert on many `renewal_deferred` events +for certificates approaching expiry. + +## Alternatives considered + +1. **Cron-like schedule field**: More expressive (cron expression) but + increases complexity for users and parsing. +2. **External scheduler integration**: Leave renewal control to an + external controller. This keeps core simpler but adds operational + burden. +3. **Per-issuer scheduling**: Instead of per-Certificate, allow Issuers + to be configured with windows. This reduces per-certificate + flexibility. + +We opted for per-Certificate windows for fine-grained control and +simplicity of the API. + +## Migration story + +- Old Certificates without `renewal` behave exactly as today. +- Adding `renewal` is opt-in. +- No existing certificates are changed. diff --git a/cert-manager_1/solution/solution.patch b/cert-manager_1/solution/solution.patch new file mode 100644 index 0000000000000000000000000000000000000000..a665eaedbed3e68322e61e1eda24177937865c03 --- /dev/null +++ b/cert-manager_1/solution/solution.patch @@ -0,0 +1,2500 @@ +diff --git a/internal/apis/certmanager/types_certificate.go b/internal/apis/certmanager/types_certificate.go +index 5c7aed2e2..8336ee437 100644 +--- a/internal/apis/certmanager/types_certificate.go ++++ b/internal/apis/certmanager/types_certificate.go +@@ -169,6 +169,11 @@ type CertificateSpec struct { + // +optional + RenewBeforePercentage *int32 + ++ // `renewal` allows configuration of how your certificate is renewed. If the policy mentioned is ++ // `RenewBefore` then the controller respects `renewBefore` and `renewBeforePercentage`. ++ // +optional ++ Renewal *CertificateRenewal ++ + // Requested DNS subject alternative names. + DNSNames []string + +@@ -490,6 +495,34 @@ const ( + Modern2023PKCS12Profile PKCS12Profile = "Modern2023" + ) + ++type CertificateRenewal struct { ++ // `policy` must be one of `Disabled`, `RenewBefore`. ++ Policy CertificateRenewalPolicy ++ ++ // `windows` mentions the behavior of when the renewal must happen. ++ Windows []CertificateRenewalWindows ++} ++ ++type CertificateRenewalPolicy string ++ ++const ( ++ RenewBefore CertificateRenewalPolicy = "RenewBefore" ++ Disabled CertificateRenewalPolicy = "Disabled" ++) ++ ++// CertificateRenewalWindows is the definition for renewal windows ++type CertificateRenewalWindows struct { ++ // `timezone` is IANA compliant timezone. ++ Timezone string ++ ++ // `windowDuration` is how long the cron definition is active for. ++ // Value must be in units accepted by Go time.ParseDuration https://golang.org/pkg/time/#ParseDuration. ++ WindowDuration *metav1.Duration ++ ++ // `cron` is a cron compliant string to allow when the renewal should be allowed. ++ Cron string ++} ++ + // CertificateStatus defines the observed state of Certificate + type CertificateStatus struct { + // List of status conditions to indicate the status of certificates. +diff --git a/internal/apis/certmanager/v1/zz_generated.conversion.go b/internal/apis/certmanager/v1/zz_generated.conversion.go +index 8e7938ea3..0406b318e 100644 +--- a/internal/apis/certmanager/v1/zz_generated.conversion.go ++++ b/internal/apis/certmanager/v1/zz_generated.conversion.go +@@ -114,6 +114,26 @@ func RegisterConversions(s *runtime.Scheme) error { + }); err != nil { + return err + } ++ if err := s.AddGeneratedConversionFunc((*certmanagerv1.CertificateRenewal)(nil), (*certmanager.CertificateRenewal)(nil), func(a, b interface{}, scope conversion.Scope) error { ++ return Convert_v1_CertificateRenewal_To_certmanager_CertificateRenewal(a.(*certmanagerv1.CertificateRenewal), b.(*certmanager.CertificateRenewal), scope) ++ }); err != nil { ++ return err ++ } ++ if err := s.AddGeneratedConversionFunc((*certmanager.CertificateRenewal)(nil), (*certmanagerv1.CertificateRenewal)(nil), func(a, b interface{}, scope conversion.Scope) error { ++ return Convert_certmanager_CertificateRenewal_To_v1_CertificateRenewal(a.(*certmanager.CertificateRenewal), b.(*certmanagerv1.CertificateRenewal), scope) ++ }); err != nil { ++ return err ++ } ++ if err := s.AddGeneratedConversionFunc((*certmanagerv1.CertificateRenewalWindows)(nil), (*certmanager.CertificateRenewalWindows)(nil), func(a, b interface{}, scope conversion.Scope) error { ++ return Convert_v1_CertificateRenewalWindows_To_certmanager_CertificateRenewalWindows(a.(*certmanagerv1.CertificateRenewalWindows), b.(*certmanager.CertificateRenewalWindows), scope) ++ }); err != nil { ++ return err ++ } ++ if err := s.AddGeneratedConversionFunc((*certmanager.CertificateRenewalWindows)(nil), (*certmanagerv1.CertificateRenewalWindows)(nil), func(a, b interface{}, scope conversion.Scope) error { ++ return Convert_certmanager_CertificateRenewalWindows_To_v1_CertificateRenewalWindows(a.(*certmanager.CertificateRenewalWindows), b.(*certmanagerv1.CertificateRenewalWindows), scope) ++ }); err != nil { ++ return err ++ } + if err := s.AddGeneratedConversionFunc((*certmanagerv1.CertificateRequest)(nil), (*certmanager.CertificateRequest)(nil), func(a, b interface{}, scope conversion.Scope) error { + return Convert_v1_CertificateRequest_To_certmanager_CertificateRequest(a.(*certmanagerv1.CertificateRequest), b.(*certmanager.CertificateRequest), scope) + }); err != nil { +@@ -667,6 +687,52 @@ func Convert_certmanager_CertificatePrivateKey_To_v1_CertificatePrivateKey(in *c + return autoConvert_certmanager_CertificatePrivateKey_To_v1_CertificatePrivateKey(in, out, s) + } + ++func autoConvert_v1_CertificateRenewal_To_certmanager_CertificateRenewal(in *certmanagerv1.CertificateRenewal, out *certmanager.CertificateRenewal, s conversion.Scope) error { ++ out.Policy = certmanager.CertificateRenewalPolicy(in.Policy) ++ out.Windows = *(*[]certmanager.CertificateRenewalWindows)(unsafe.Pointer(&in.Windows)) ++ return nil ++} ++ ++// Convert_v1_CertificateRenewal_To_certmanager_CertificateRenewal is an autogenerated conversion function. ++func Convert_v1_CertificateRenewal_To_certmanager_CertificateRenewal(in *certmanagerv1.CertificateRenewal, out *certmanager.CertificateRenewal, s conversion.Scope) error { ++ return autoConvert_v1_CertificateRenewal_To_certmanager_CertificateRenewal(in, out, s) ++} ++ ++func autoConvert_certmanager_CertificateRenewal_To_v1_CertificateRenewal(in *certmanager.CertificateRenewal, out *certmanagerv1.CertificateRenewal, s conversion.Scope) error { ++ out.Policy = certmanagerv1.CertificateRenewalPolicy(in.Policy) ++ out.Windows = *(*[]certmanagerv1.CertificateRenewalWindows)(unsafe.Pointer(&in.Windows)) ++ return nil ++} ++ ++// Convert_certmanager_CertificateRenewal_To_v1_CertificateRenewal is an autogenerated conversion function. ++func Convert_certmanager_CertificateRenewal_To_v1_CertificateRenewal(in *certmanager.CertificateRenewal, out *certmanagerv1.CertificateRenewal, s conversion.Scope) error { ++ return autoConvert_certmanager_CertificateRenewal_To_v1_CertificateRenewal(in, out, s) ++} ++ ++func autoConvert_v1_CertificateRenewalWindows_To_certmanager_CertificateRenewalWindows(in *certmanagerv1.CertificateRenewalWindows, out *certmanager.CertificateRenewalWindows, s conversion.Scope) error { ++ out.Timezone = in.Timezone ++ out.WindowDuration = (*metav1.Duration)(unsafe.Pointer(in.WindowDuration)) ++ out.Cron = in.Cron ++ return nil ++} ++ ++// Convert_v1_CertificateRenewalWindows_To_certmanager_CertificateRenewalWindows is an autogenerated conversion function. ++func Convert_v1_CertificateRenewalWindows_To_certmanager_CertificateRenewalWindows(in *certmanagerv1.CertificateRenewalWindows, out *certmanager.CertificateRenewalWindows, s conversion.Scope) error { ++ return autoConvert_v1_CertificateRenewalWindows_To_certmanager_CertificateRenewalWindows(in, out, s) ++} ++ ++func autoConvert_certmanager_CertificateRenewalWindows_To_v1_CertificateRenewalWindows(in *certmanager.CertificateRenewalWindows, out *certmanagerv1.CertificateRenewalWindows, s conversion.Scope) error { ++ out.Timezone = in.Timezone ++ out.WindowDuration = (*metav1.Duration)(unsafe.Pointer(in.WindowDuration)) ++ out.Cron = in.Cron ++ return nil ++} ++ ++// Convert_certmanager_CertificateRenewalWindows_To_v1_CertificateRenewalWindows is an autogenerated conversion function. ++func Convert_certmanager_CertificateRenewalWindows_To_v1_CertificateRenewalWindows(in *certmanager.CertificateRenewalWindows, out *certmanagerv1.CertificateRenewalWindows, s conversion.Scope) error { ++ return autoConvert_certmanager_CertificateRenewalWindows_To_v1_CertificateRenewalWindows(in, out, s) ++} ++ + func autoConvert_v1_CertificateRequest_To_certmanager_CertificateRequest(in *certmanagerv1.CertificateRequest, out *certmanager.CertificateRequest, s conversion.Scope) error { + out.ObjectMeta = in.ObjectMeta + if err := Convert_v1_CertificateRequestSpec_To_certmanager_CertificateRequestSpec(&in.Spec, &out.Spec, s); err != nil { +@@ -864,6 +930,7 @@ func autoConvert_v1_CertificateSpec_To_certmanager_CertificateSpec(in *certmanag + out.Duration = (*metav1.Duration)(unsafe.Pointer(in.Duration)) + out.RenewBefore = (*metav1.Duration)(unsafe.Pointer(in.RenewBefore)) + out.RenewBeforePercentage = (*int32)(unsafe.Pointer(in.RenewBeforePercentage)) ++ out.Renewal = (*certmanager.CertificateRenewal)(unsafe.Pointer(in.Renewal)) + out.DNSNames = *(*[]string)(unsafe.Pointer(&in.DNSNames)) + out.IPAddresses = *(*[]string)(unsafe.Pointer(&in.IPAddresses)) + out.URIs = *(*[]string)(unsafe.Pointer(&in.URIs)) +@@ -906,6 +973,7 @@ func autoConvert_certmanager_CertificateSpec_To_v1_CertificateSpec(in *certmanag + out.Duration = (*metav1.Duration)(unsafe.Pointer(in.Duration)) + out.RenewBefore = (*metav1.Duration)(unsafe.Pointer(in.RenewBefore)) + out.RenewBeforePercentage = (*int32)(unsafe.Pointer(in.RenewBeforePercentage)) ++ out.Renewal = (*certmanagerv1.CertificateRenewal)(unsafe.Pointer(in.Renewal)) + out.DNSNames = *(*[]string)(unsafe.Pointer(&in.DNSNames)) + out.IPAddresses = *(*[]string)(unsafe.Pointer(&in.IPAddresses)) + out.URIs = *(*[]string)(unsafe.Pointer(&in.URIs)) +diff --git a/internal/apis/certmanager/validation/certificate.go b/internal/apis/certmanager/validation/certificate.go +index de109d223..8a0b9f4f6 100644 +--- a/internal/apis/certmanager/validation/certificate.go ++++ b/internal/apis/certmanager/validation/certificate.go +@@ -37,6 +37,7 @@ import ( + "github.com/cert-manager/cert-manager/internal/webhook/feature" + "github.com/cert-manager/cert-manager/pkg/api/util" + cmapi "github.com/cert-manager/cert-manager/pkg/apis/certmanager/v1" ++ utilpkg "github.com/cert-manager/cert-manager/pkg/util" + utilfeature "github.com/cert-manager/cert-manager/pkg/util/feature" + "github.com/cert-manager/cert-manager/pkg/util/pki" + ) +@@ -72,7 +73,7 @@ func ValidateCertificateSpec(crt *internalcmapi.CertificateSpec, fldPath *field. + + el = append(el, validateIssuerRef(crt.IssuerRef, fldPath)...) + +- var commonName = crt.CommonName ++ commonName := crt.CommonName + if crt.LiteralSubject != "" { + if !utilfeature.DefaultFeatureGate.Enabled(feature.LiteralCertificateSubject) { + el = append(el, field.Forbidden(fldPath.Child("literalSubject"), "Feature gate LiteralCertificateSubject must be enabled on both webhook and controller to use the alpha `literalSubject` field")) +@@ -231,6 +232,10 @@ func ValidateCertificateSpec(crt *internalcmapi.CertificateSpec, fldPath *field. + el = append(el, validateKeystores(crt, fldPath)...) + } + ++ if crt.Renewal != nil { ++ el = append(el, validateCertificateRenewal(crt, fldPath)...) ++ } ++ + return el + } + +@@ -445,3 +450,43 @@ func validateKeystores(crt *internalcmapi.CertificateSpec, fldPath *field.Path) + + return el + } ++ ++func validateCertificateRenewal(crt *internalcmapi.CertificateSpec, fldPath *field.Path) field.ErrorList { ++ var el field.ErrorList ++ switch crt.Renewal.Policy { ++ case internalcmapi.RenewBefore: ++ case internalcmapi.Disabled: ++ if len(crt.Renewal.Windows) > 0 { ++ el = append(el, field.Forbidden(fldPath.Child("renewal", "windows"), "windows cannot be set when `renewal.policy` is set to Disabled")) ++ } ++ return el ++ default: ++ el = append(el, field.NotSupported(fldPath.Child("renewal", "policy"), crt.Renewal.Policy, []string{string(internalcmapi.Disabled), string(internalcmapi.RenewBefore)})) ++ } ++ ++ if crt.Renewal.Windows != nil { ++ for i, window := range crt.Renewal.Windows { ++ el = append(el, validateCertificateRenewalWindows(window, fldPath.Child("renewal", "windows").Index(i))...) ++ } ++ } ++ ++ return el ++} ++ ++func validateCertificateRenewalWindows(window internalcmapi.CertificateRenewalWindows, fldPath *field.Path) field.ErrorList { ++ var el field.ErrorList ++ ++ if window.WindowDuration == nil { ++ el = append(el, field.Required(fldPath.Child("windowDuration"), "windowDuration must be specified and should be greater than 0")) ++ } ++ ++ if _, err := time.LoadLocation(window.Timezone); err != nil && window.Timezone != "" { ++ el = append(el, field.Invalid(fldPath.Child("timezone"), window.Timezone, "invalid value for timezone. timezone must be IANA compliant")) ++ } ++ ++ if _, err := utilpkg.CronParse(window.Cron, window.Timezone); err != nil { ++ el = append(el, field.Invalid(fldPath.Child("cron"), window.Cron, fmt.Sprintf("invalid cron syntax: %s. cron needs to follow: cron.Minute | cron.Hour | cron.Dom | cron.Month | cron.Dow", err.Error()))) ++ } ++ ++ return el ++} +diff --git a/internal/apis/certmanager/zz_generated.deepcopy.go b/internal/apis/certmanager/zz_generated.deepcopy.go +index d64f9cd5e..87ac6cbeb 100644 +--- a/internal/apis/certmanager/zz_generated.deepcopy.go ++++ b/internal/apis/certmanager/zz_generated.deepcopy.go +@@ -198,6 +198,50 @@ func (in *CertificatePrivateKey) DeepCopy() *CertificatePrivateKey { + return out + } + ++// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. ++func (in *CertificateRenewal) DeepCopyInto(out *CertificateRenewal) { ++ *out = *in ++ if in.Windows != nil { ++ in, out := &in.Windows, &out.Windows ++ *out = make([]CertificateRenewalWindows, len(*in)) ++ for i := range *in { ++ (*in)[i].DeepCopyInto(&(*out)[i]) ++ } ++ } ++ return ++} ++ ++// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new CertificateRenewal. ++func (in *CertificateRenewal) DeepCopy() *CertificateRenewal { ++ if in == nil { ++ return nil ++ } ++ out := new(CertificateRenewal) ++ in.DeepCopyInto(out) ++ return out ++} ++ ++// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. ++func (in *CertificateRenewalWindows) DeepCopyInto(out *CertificateRenewalWindows) { ++ *out = *in ++ if in.WindowDuration != nil { ++ in, out := &in.WindowDuration, &out.WindowDuration ++ *out = new(v1.Duration) ++ **out = **in ++ } ++ return ++} ++ ++// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new CertificateRenewalWindows. ++func (in *CertificateRenewalWindows) DeepCopy() *CertificateRenewalWindows { ++ if in == nil { ++ return nil ++ } ++ out := new(CertificateRenewalWindows) ++ in.DeepCopyInto(out) ++ return out ++} ++ + // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. + func (in *CertificateRequest) DeepCopyInto(out *CertificateRequest) { + *out = *in +@@ -421,6 +465,11 @@ func (in *CertificateSpec) DeepCopyInto(out *CertificateSpec) { + *out = new(int32) + **out = **in + } ++ if in.Renewal != nil { ++ in, out := &in.Renewal, &out.Renewal ++ *out = new(CertificateRenewal) ++ (*in).DeepCopyInto(*out) ++ } + if in.DNSNames != nil { + in, out := &in.DNSNames, &out.DNSNames + *out = make([]string, len(*in)) +diff --git a/internal/controller/certificates/policies/checks.go b/internal/controller/certificates/policies/checks.go +index 02d6fa980..83afaccf7 100644 +--- a/internal/controller/certificates/policies/checks.go ++++ b/internal/controller/certificates/policies/checks.go +@@ -270,7 +270,15 @@ func CurrentCertificateNearingExpiry(c clock.Clock) Func { + notBefore := metav1.NewTime(x509Cert.NotBefore) + notAfter := metav1.NewTime(x509Cert.NotAfter) + crt := input.Certificate +- renewalTime := pki.RenewalTime(notBefore.Time, notAfter.Time, crt.Spec.RenewBefore, crt.Spec.RenewBeforePercentage) ++ ++ reason := Renewing ++ message := fmt.Sprintf("Renewing certificate as renewal was scheduled at %s", input.Certificate.Status.RenewalTime) ++ ++ renewalTime, err := pki.RenewalTime(notBefore.Time, notAfter.Time, crt.Spec.RenewBefore, crt.Spec.RenewBeforePercentage, crt.Spec.Renewal) ++ if err != nil { ++ reason = WindowError ++ message = err.Error() ++ } + + renewIn := renewalTime.Time.Sub(c.Now()) + if renewIn > 0 { +@@ -278,7 +286,7 @@ func CurrentCertificateNearingExpiry(c clock.Clock) Func { + return "", "", false + } + +- return Renewing, fmt.Sprintf("Renewing certificate as renewal was scheduled at %s", input.Certificate.Status.RenewalTime), true ++ return reason, message, true + } + } + +@@ -308,8 +316,10 @@ func formatIssuerRef(name, kind, group string) string { + return fmt.Sprintf("%s.%s/%s", kind, group, name) + } + +-const defaultIssuerKind = "Issuer" +-const defaultIssuerGroup = "cert-manager.io" ++const ( ++ defaultIssuerKind = "Issuer" ++ defaultIssuerGroup = "cert-manager.io" ++) + + func issuerKindsEqual(l, r string) bool { + if l == "" { +diff --git a/internal/controller/certificates/policies/constants.go b/internal/controller/certificates/policies/constants.go +index ba320fdc9..d6493d2cd 100644 +--- a/internal/controller/certificates/policies/constants.go ++++ b/internal/controller/certificates/policies/constants.go +@@ -53,6 +53,9 @@ const ( + // Expired is a policy violation reason for a scenario where Certificate has + // expired. + Expired string = "Expired" ++ // WindowError is a policy violation for a scenario where a time couldn't be ++ // found due to a cron misconfiguration or validation. ++ WindowError string = "WindowError" + // SecretTemplateMismatch is a policy violation whereby the Certificate's + // SecretTemplate is not reflected on the target Secret, either by having + // extra, missing, or wrong Annotations or Labels. +diff --git a/internal/cron/constantdelay.go b/internal/cron/constantdelay.go +new file mode 100644 +index 000000000..b359ce17b +--- /dev/null ++++ b/internal/cron/constantdelay.go +@@ -0,0 +1,35 @@ ++// +skip_license_check ++ ++/* ++This file contains portions of code directly taken from the 'robfig/cron' project. ++A copy of the license for this code can be found in the file named LICENSE in ++this directory. ++*/ ++ ++package cron ++ ++import "time" ++ ++// ConstantDelaySchedule represents a simple recurring duty cycle, e.g. "Every 5 minutes". ++// It does not support jobs more frequent than once a second. ++type ConstantDelaySchedule struct { ++ Delay time.Duration ++} ++ ++// Every returns a crontab Schedule that activates once every duration. ++// Delays of less than a second are not supported (will round up to 1 second). ++// Any fields less than a Second are truncated. ++func Every(duration time.Duration) ConstantDelaySchedule { ++ if duration < time.Second { ++ duration = time.Second ++ } ++ return ConstantDelaySchedule{ ++ Delay: duration - time.Duration(duration.Nanoseconds())%time.Second, ++ } ++} ++ ++// Next returns the next time this should be run. ++// This rounds so that the next activation time will be on the second. ++func (schedule ConstantDelaySchedule) Next(t time.Time) time.Time { ++ return t.Add(schedule.Delay - time.Duration(t.Nanosecond())*time.Nanosecond) ++} +diff --git a/internal/cron/cron.go b/internal/cron/cron.go +new file mode 100644 +index 000000000..2f6f372b4 +--- /dev/null ++++ b/internal/cron/cron.go +@@ -0,0 +1,353 @@ ++// +skip_license_check ++ ++/* ++This file contains portions of code directly taken from the 'robfig/cron' project. ++A copy of the license for this code can be found in the file named LICENSE in ++this directory. ++*/ ++ ++package cron ++ ++import ( ++ "context" ++ "sort" ++ "sync" ++ "time" ++) ++ ++// Cron keeps track of any number of entries, invoking the associated func as ++// specified by the schedule. It may be started, stopped, and the entries may ++// be inspected while running. ++type Cron struct { ++ entries []*Entry ++ stop chan struct{} ++ add chan *Entry ++ remove chan EntryID ++ snapshot chan chan []Entry ++ running bool ++ logger Logger ++ runningMu sync.Mutex ++ location *time.Location ++ parser Parser ++ nextID EntryID ++ jobWaiter sync.WaitGroup ++} ++ ++// Job is an interface for submitted cron jobs. ++type Job interface { ++ Run() ++} ++ ++// Schedule describes a job's duty cycle. ++type Schedule interface { ++ // Next returns the next activation time, later than the given time. ++ // Next is invoked initially, and then each time the job is run. ++ Next(time.Time) time.Time ++} ++ ++// EntryID identifies an entry within a Cron instance ++type EntryID int ++ ++// Entry consists of a schedule and the func to execute on that schedule. ++type Entry struct { ++ // ID is the cron-assigned ID of this entry, which may be used to look up a ++ // snapshot or remove it. ++ ID EntryID ++ ++ // Schedule on which this job should be run. ++ Schedule Schedule ++ ++ // Next time the job will run, or the zero time if Cron has not been ++ // started or this entry's schedule is unsatisfiable ++ Next time.Time ++ ++ // Prev is the last time this job was run, or the zero time if never. ++ Prev time.Time ++ ++ // WrappedJob is the thing to run when the Schedule is activated. ++ WrappedJob Job ++ ++ // Job is the thing that was submitted to cron. ++ // It is kept around so that user code that needs to get at the job later, ++ // e.g. via Entries() can do so. ++ Job Job ++} ++ ++// Valid returns true if this is not the zero entry. ++func (e Entry) Valid() bool { return e.ID != 0 } ++ ++// byTime is a wrapper for sorting the entry array by time ++// (with zero time at the end). ++type byTime []*Entry ++ ++func (s byTime) Len() int { return len(s) } ++func (s byTime) Swap(i, j int) { s[i], s[j] = s[j], s[i] } ++func (s byTime) Less(i, j int) bool { ++ // Two zero times should return false. ++ // Otherwise, zero is "greater" than any other time. ++ // (To sort it at the end of the list.) ++ if s[i].Next.IsZero() { ++ return false ++ } ++ if s[j].Next.IsZero() { ++ return true ++ } ++ return s[i].Next.Before(s[j].Next) ++} ++ ++// New returns a new Cron job runner, modified by the given options. ++// ++// Available Settings ++// ++// Time Zone ++// Description: The time zone in which schedules are interpreted ++// Default: time.Local ++// ++// Parser ++// Description: Parser converts cron spec strings into cron.Schedules. ++// Default: Accepts this spec: https://en.wikipedia.org/wiki/Cron ++// ++// Chain ++// Description: Wrap submitted jobs to customize behavior. ++// Default: A chain that recovers panics and logs them to stderr. ++// ++// See "cron.With*" to modify the default behavior. ++func New(opts ...Option) *Cron { ++ c := &Cron{ ++ entries: nil, ++ add: make(chan *Entry), ++ stop: make(chan struct{}), ++ snapshot: make(chan chan []Entry), ++ remove: make(chan EntryID), ++ running: false, ++ runningMu: sync.Mutex{}, ++ logger: DefaultLogger, ++ location: time.Local, //nolint: gosmopolitan // This is just a default ++ parser: standardParser, ++ } ++ for _, opt := range opts { ++ opt(c) ++ } ++ return c ++} ++ ++// FuncJob is a wrapper that turns a func() into a cron.Job ++type FuncJob func() ++ ++func (f FuncJob) Run() { f() } ++ ++// AddFunc adds a func to the Cron to be run on the given schedule. ++// The spec is parsed using the time zone of this Cron instance as the default. ++// An opaque ID is returned that can be used to later remove it. ++func (c *Cron) AddFunc(spec string, cmd func()) (EntryID, error) { ++ return c.AddJob(spec, FuncJob(cmd)) ++} ++ ++// AddJob adds a Job to the Cron to be run on the given schedule. ++// The spec is parsed using the time zone of this Cron instance as the default. ++// An opaque ID is returned that can be used to later remove it. ++func (c *Cron) AddJob(spec string, cmd Job) (EntryID, error) { ++ schedule, err := c.parser.Parse(spec) ++ if err != nil { ++ return 0, err ++ } ++ return c.Schedule(schedule, cmd), nil ++} ++ ++// Schedule adds a Job to the Cron to be run on the given schedule. ++// The job is wrapped with the configured Chain. ++func (c *Cron) Schedule(schedule Schedule, cmd Job) EntryID { ++ c.runningMu.Lock() ++ defer c.runningMu.Unlock() ++ c.nextID++ ++ entry := &Entry{ ++ ID: c.nextID, ++ Schedule: schedule, ++ Job: cmd, ++ } ++ if !c.running { ++ c.entries = append(c.entries, entry) ++ } else { ++ c.add <- entry ++ } ++ return entry.ID ++} ++ ++// Entries returns a snapshot of the cron entries. ++func (c *Cron) Entries() []Entry { ++ c.runningMu.Lock() ++ defer c.runningMu.Unlock() ++ if c.running { ++ replyChan := make(chan []Entry, 1) ++ c.snapshot <- replyChan ++ return <-replyChan ++ } ++ return c.entrySnapshot() ++} ++ ++// Location gets the time zone location ++func (c *Cron) Location() *time.Location { ++ return c.location ++} ++ ++// Entry returns a snapshot of the given entry, or nil if it couldn't be found. ++func (c *Cron) Entry(id EntryID) Entry { ++ for _, entry := range c.Entries() { ++ if id == entry.ID { ++ return entry ++ } ++ } ++ return Entry{} ++} ++ ++// Remove an entry from being run in the future. ++func (c *Cron) Remove(id EntryID) { ++ c.runningMu.Lock() ++ defer c.runningMu.Unlock() ++ if c.running { ++ c.remove <- id ++ } else { ++ c.removeEntry(id) ++ } ++} ++ ++// Start the cron scheduler in its own goroutine, or no-op if already started. ++func (c *Cron) Start() { ++ c.runningMu.Lock() ++ defer c.runningMu.Unlock() ++ if c.running { ++ return ++ } ++ c.running = true ++ go c.run() ++} ++ ++// Run the cron scheduler, or no-op if already running. ++func (c *Cron) Run() { ++ c.runningMu.Lock() ++ if c.running { ++ c.runningMu.Unlock() ++ return ++ } ++ c.running = true ++ c.runningMu.Unlock() ++ c.run() ++} ++ ++// run the scheduler.. this is private just due to the need to synchronize ++// access to the 'running' state variable. ++func (c *Cron) run() { ++ c.logger.Info("start") ++ ++ // Figure out the next activation times for each entry. ++ now := c.now() ++ for _, entry := range c.entries { ++ entry.Next = entry.Schedule.Next(now) ++ c.logger.Info("schedule", "now", now, "entry", entry.ID, "next", entry.Next) ++ } ++ ++ for { ++ // Determine the next entry to run. ++ sort.Sort(byTime(c.entries)) ++ ++ var timer *time.Timer ++ if len(c.entries) == 0 || c.entries[0].Next.IsZero() { ++ // If there are no entries yet, just sleep - it still handles new entries ++ // and stop requests. ++ timer = time.NewTimer(100000 * time.Hour) ++ } else { ++ timer = time.NewTimer(c.entries[0].Next.Sub(now)) ++ } ++ ++ for { ++ select { ++ case now = <-timer.C: ++ now = now.In(c.location) ++ c.logger.Info("wake", "now", now) ++ ++ // Run every entry whose next time was less than now ++ for _, e := range c.entries { ++ if e.Next.After(now) || e.Next.IsZero() { ++ break ++ } ++ c.startJob(e.WrappedJob) ++ e.Prev = e.Next ++ e.Next = e.Schedule.Next(now) ++ c.logger.Info("run", "now", now, "entry", e.ID, "next", e.Next) ++ } ++ ++ case newEntry := <-c.add: ++ timer.Stop() ++ now = c.now() ++ newEntry.Next = newEntry.Schedule.Next(now) ++ c.entries = append(c.entries, newEntry) ++ c.logger.Info("added", "now", now, "entry", newEntry.ID, "next", newEntry.Next) ++ ++ case replyChan := <-c.snapshot: ++ replyChan <- c.entrySnapshot() ++ continue ++ ++ case <-c.stop: ++ timer.Stop() ++ c.logger.Info("stop") ++ return ++ ++ case id := <-c.remove: ++ timer.Stop() ++ now = c.now() ++ c.removeEntry(id) ++ c.logger.Info("removed", "entry", id) ++ } ++ ++ break ++ } ++ } ++} ++ ++// startJob runs the given job in a new goroutine. ++func (c *Cron) startJob(j Job) { ++ c.jobWaiter.Go(func() { ++ j.Run() ++ }) ++} ++ ++// now returns current time in c location ++func (c *Cron) now() time.Time { ++ return time.Now().In(c.location) ++} ++ ++// Stop stops the cron scheduler if it is running; otherwise it does nothing. ++// A context is returned so the caller can wait for running jobs to complete. ++func (c *Cron) Stop() context.Context { ++ c.runningMu.Lock() ++ defer c.runningMu.Unlock() ++ if c.running { ++ c.stop <- struct{}{} ++ c.running = false ++ } ++ ctx, cancel := context.WithCancel(context.Background()) ++ go func() { ++ c.jobWaiter.Wait() ++ cancel() ++ }() ++ return ctx ++} ++ ++// entrySnapshot returns a copy of the current cron entry list. ++func (c *Cron) entrySnapshot() []Entry { ++ var entries = make([]Entry, len(c.entries)) ++ for i, e := range c.entries { ++ entries[i] = *e ++ } ++ return entries ++} ++ ++func (c *Cron) removeEntry(id EntryID) { ++ var entries []*Entry ++ for _, e := range c.entries { ++ if e.ID != id { ++ entries = append(entries, e) ++ } ++ } ++ c.entries = entries ++} +diff --git a/internal/cron/logger.go b/internal/cron/logger.go +new file mode 100644 +index 000000000..565067f4d +--- /dev/null ++++ b/internal/cron/logger.go +@@ -0,0 +1,94 @@ ++// +skip_license_check ++ ++/* ++This file contains portions of code directly taken from the 'robfig/cron' project. ++A copy of the license for this code can be found in the file named LICENSE in ++this directory. ++*/ ++ ++package cron ++ ++import ( ++ "io" ++ "log" ++ "os" ++ "strings" ++ "time" ++) ++ ++// DefaultLogger is used by Cron if none is specified. ++var DefaultLogger Logger = PrintfLogger(log.New(os.Stdout, "cron: ", log.LstdFlags)) ++ ++// DiscardLogger can be used by callers to discard all log messages. ++var DiscardLogger Logger = PrintfLogger(log.New(io.Discard, "", 0)) ++ ++// Logger is the interface used in this package for logging, so that any backend ++// can be plugged in. It is a subset of the github.com/go-logr/logr interface. ++type Logger interface { ++ // Info logs routine messages about cron's operation. ++ Info(msg string, keysAndValues ...any) ++ // Error logs an error condition. ++ Error(err error, msg string, keysAndValues ...any) ++} ++ ++// PrintfLogger wraps a Printf-based logger (such as the standard library "log") ++// into an implementation of the Logger interface which logs errors only. ++func PrintfLogger(l interface{ Printf(string, ...any) }) Logger { ++ return printfLogger{l, false} ++} ++ ++// VerbosePrintfLogger wraps a Printf-based logger (such as the standard library ++// "log") into an implementation of the Logger interface which logs everything. ++func VerbosePrintfLogger(l interface{ Printf(string, ...any) }) Logger { ++ return printfLogger{l, true} ++} ++ ++type printfLogger struct { ++ logger interface{ Printf(string, ...any) } ++ logInfo bool ++} ++ ++func (pl printfLogger) Info(msg string, keysAndValues ...any) { ++ if pl.logInfo { ++ keysAndValues = formatTimes(keysAndValues) ++ pl.logger.Printf( ++ formatString(len(keysAndValues)), ++ append([]any{msg}, keysAndValues...)...) ++ } ++} ++ ++func (pl printfLogger) Error(err error, msg string, keysAndValues ...any) { ++ keysAndValues = formatTimes(keysAndValues) ++ pl.logger.Printf( ++ formatString(len(keysAndValues)+2), ++ append([]any{msg, "error", err}, keysAndValues...)...) ++} ++ ++// formatString returns a logfmt-like format string for the number of ++// key/values. ++func formatString(numKeysAndValues int) string { ++ var sb strings.Builder ++ sb.WriteString("%s") ++ if numKeysAndValues > 0 { ++ sb.WriteString(", ") ++ } ++ for i := range numKeysAndValues / 2 { ++ if i > 0 { ++ sb.WriteString(", ") ++ } ++ sb.WriteString("%v=%v") ++ } ++ return sb.String() ++} ++ ++// formatTimes formats any time.Time values as RFC3339. ++func formatTimes(keysAndValues []any) []any { ++ var formattedArgs []any ++ for _, arg := range keysAndValues { ++ if t, ok := arg.(time.Time); ok { ++ arg = t.Format(time.RFC3339) ++ } ++ formattedArgs = append(formattedArgs, arg) ++ } ++ return formattedArgs ++} +diff --git a/internal/cron/option.go b/internal/cron/option.go +new file mode 100644 +index 000000000..56739c499 +--- /dev/null ++++ b/internal/cron/option.go +@@ -0,0 +1,45 @@ ++// +skip_license_check ++ ++/* ++This file contains portions of code directly taken from the 'robfig/cron' project. ++A copy of the license for this code can be found in the file named LICENSE in ++this directory. ++*/ ++ ++package cron ++ ++import ( ++ "time" ++) ++ ++// Option represents a modification to the default behavior of a Cron. ++type Option func(*Cron) ++ ++// WithLocation overrides the timezone of the cron instance. ++func WithLocation(loc *time.Location) Option { ++ return func(c *Cron) { ++ c.location = loc ++ } ++} ++ ++// WithSeconds overrides the parser used for interpreting job schedules to ++// include a seconds field as the first one. ++func WithSeconds() Option { ++ return WithParser(NewParser( ++ Second | Minute | Hour | Dom | Month | Dow | Descriptor, ++ )) ++} ++ ++// WithParser overrides the parser used for interpreting job schedules. ++func WithParser(p Parser) Option { ++ return func(c *Cron) { ++ c.parser = p ++ } ++} ++ ++// WithLogger uses the provided logger. ++func WithLogger(logger Logger) Option { ++ return func(c *Cron) { ++ c.logger = logger ++ } ++} +diff --git a/internal/cron/parser.go b/internal/cron/parser.go +new file mode 100644 +index 000000000..ee05d3a22 +--- /dev/null ++++ b/internal/cron/parser.go +@@ -0,0 +1,444 @@ ++// +skip_license_check ++ ++/* ++This file contains portions of code directly taken from the 'robfig/cron' project. ++A copy of the license for this code can be found in the file named LICENSE in ++this directory. ++*/ ++ ++package cron ++ ++import ( ++ "fmt" ++ "math" ++ "strconv" ++ "strings" ++ "time" ++) ++ ++// Configuration options for creating a parser. Most options specify which ++// fields should be included, while others enable features. If a field is not ++// included the parser will assume a default value. These options do not change ++// the order fields are parse in. ++type ParseOption int ++ ++const ( ++ Second ParseOption = 1 << iota // Seconds field, default 0 ++ SecondOptional // Optional seconds field, default 0 ++ Minute // Minutes field, default 0 ++ Hour // Hours field, default 0 ++ Dom // Day of month field, default * ++ Month // Month field, default * ++ Dow // Day of week field, default * ++ DowOptional // Optional day of week field, default * ++ Descriptor // Allow descriptors such as @monthly, @weekly, etc. ++) ++ ++var places = []ParseOption{ ++ Second, ++ Minute, ++ Hour, ++ Dom, ++ Month, ++ Dow, ++} ++ ++var defaults = []string{ ++ "0", ++ "0", ++ "0", ++ "*", ++ "*", ++ "*", ++} ++ ++// A custom Parser that can be configured. ++type Parser struct { ++ options ParseOption ++} ++ ++// NewParser creates a Parser with custom options. ++// ++// It panics if more than one Optional is given, since it would be impossible to ++// correctly infer which optional is provided or missing in general. ++// ++// Examples ++// ++// // Standard parser without descriptors ++// specParser := NewParser(Minute | Hour | Dom | Month | Dow) ++// sched, err := specParser.Parse("0 0 15 */3 *") ++// ++// // Same as above, just excludes time fields ++// subsParser := NewParser(Dom | Month | Dow) ++// sched, err := specParser.Parse("15 */3 *") ++// ++// // Same as above, just makes Dow optional ++// subsParser := NewParser(Dom | Month | DowOptional) ++// sched, err := specParser.Parse("15 */3") ++func NewParser(options ParseOption) Parser { ++ optionals := 0 ++ if options&DowOptional > 0 { ++ optionals++ ++ } ++ if options&SecondOptional > 0 { ++ optionals++ ++ } ++ if optionals > 1 { ++ panic("multiple optionals may not be configured") ++ } ++ return Parser{options} ++} ++ ++// Parse returns a new crontab schedule representing the given spec. ++// It returns a descriptive error if the spec is not valid. ++// It accepts crontab specs and features configured by NewParser. ++func (p Parser) Parse(spec string) (Schedule, error) { ++ if len(spec) == 0 { ++ return nil, fmt.Errorf("empty spec string") ++ } ++ ++ // Extract timezone if present ++ //nolint: gosmopolitan // this makes sense as it also handles other locations below ++ var loc = time.Local ++ if strings.HasPrefix(spec, "TZ=") || strings.HasPrefix(spec, "CRON_TZ=") { ++ var err error ++ i := strings.Index(spec, " ") ++ eq := strings.Index(spec, "=") ++ if loc, err = time.LoadLocation(spec[eq+1 : i]); err != nil { ++ return nil, fmt.Errorf("provided bad location %s: %v", spec[eq+1:i], err) ++ } ++ spec = strings.TrimSpace(spec[i:]) ++ } ++ ++ // Handle named schedules (descriptors), if configured ++ if strings.HasPrefix(spec, "@") { ++ if p.options&Descriptor == 0 { ++ return nil, fmt.Errorf("parser does not accept descriptors: %v", spec) ++ } ++ return parseDescriptor(spec, loc) ++ } ++ ++ // Split on whitespace. ++ fields := strings.Fields(spec) ++ ++ // Validate & fill in any omitted or optional fields ++ var err error ++ fields, err = normalizeFields(fields, p.options) ++ if err != nil { ++ return nil, err ++ } ++ ++ field := func(field string, r bounds) uint64 { ++ if err != nil { ++ return 0 ++ } ++ var bits uint64 ++ bits, err = getField(field, r) ++ return bits ++ } ++ ++ var ( ++ second = field(fields[0], seconds) ++ minute = field(fields[1], minutes) ++ hour = field(fields[2], hours) ++ dayofmonth = field(fields[3], dom) ++ month = field(fields[4], months) ++ dayofweek = field(fields[5], dow) ++ ) ++ if err != nil { ++ return nil, err ++ } ++ ++ return &SpecSchedule{ ++ Second: second, ++ Minute: minute, ++ Hour: hour, ++ Dom: dayofmonth, ++ Month: month, ++ Dow: dayofweek, ++ Location: loc, ++ }, nil ++} ++ ++// normalizeFields takes a subset set of the time fields and returns the full set ++// with defaults (zeroes) populated for unset fields. ++// ++// As part of performing this function, it also validates that the provided ++// fields are compatible with the configured options. ++func normalizeFields(fields []string, options ParseOption) ([]string, error) { ++ // Validate optionals & add their field to options ++ optionals := 0 ++ if options&SecondOptional > 0 { ++ options |= Second ++ optionals++ ++ } ++ if options&DowOptional > 0 { ++ options |= Dow ++ optionals++ ++ } ++ if optionals > 1 { ++ return nil, fmt.Errorf("multiple optionals may not be configured") ++ } ++ ++ // Figure out how many fields we need ++ maxField := 0 ++ for _, place := range places { ++ if options&place > 0 { ++ maxField++ ++ } ++ } ++ minField := maxField - optionals ++ ++ // Validate number of fields ++ if count := len(fields); count < minField || count > maxField { ++ if minField == maxField { ++ return nil, fmt.Errorf("expected exactly %d fields, found %d: %s", minField, count, fields) ++ } ++ return nil, fmt.Errorf("expected %d to %d fields, found %d: %s", minField, maxField, count, fields) ++ } ++ ++ // Populate the optional field if not provided ++ if minField < maxField && len(fields) == minField { ++ switch { ++ case options&DowOptional > 0: ++ fields = append(fields, defaults[5]) // TODO: improve access to default ++ case options&SecondOptional > 0: ++ fields = append([]string{defaults[0]}, fields...) ++ default: ++ return nil, fmt.Errorf("unknown optional field") ++ } ++ } ++ ++ // Populate all fields not part of options with their defaults ++ n := 0 ++ expandedFields := make([]string, len(places)) ++ copy(expandedFields, defaults) ++ for i, place := range places { ++ if options&place > 0 { ++ expandedFields[i] = fields[n] ++ n++ ++ } ++ } ++ return expandedFields, nil ++} ++ ++var standardParser = NewParser( ++ Minute | Hour | Dom | Month | Dow | Descriptor, ++) ++ ++// ParseStandard returns a new crontab schedule representing the given ++// standardSpec (https://en.wikipedia.org/wiki/Cron). It requires 5 entries ++// representing: minute, hour, day of month, month and day of week, in that ++// order. It returns a descriptive error if the spec is not valid. ++// ++// It accepts ++// - Standard crontab specs, e.g. "* * * * ?" ++// - Descriptors, e.g. "@midnight", "@every 1h30m" ++func ParseStandard(standardSpec string) (Schedule, error) { ++ return standardParser.Parse(standardSpec) ++} ++ ++// getField returns an Int with the bits set representing all of the times that ++// the field represents or error parsing field value. A "field" is a comma-separated ++// list of "ranges". ++func getField(field string, r bounds) (uint64, error) { ++ var bits uint64 ++ ranges := strings.FieldsFunc(field, func(r rune) bool { return r == ',' }) ++ for _, expr := range ranges { ++ bit, err := getRange(expr, r) ++ if err != nil { ++ return bits, err ++ } ++ bits |= bit ++ } ++ return bits, nil ++} ++ ++// getRange returns the bits indicated by the given expression: ++// ++// number | number "-" number [ "/" number ] ++// ++// or error parsing range. ++func getRange(expr string, r bounds) (uint64, error) { ++ var ( ++ start, end, step uint ++ rangeAndStep = strings.Split(expr, "/") ++ lowAndHigh = strings.Split(rangeAndStep[0], "-") ++ singleDigit = len(lowAndHigh) == 1 ++ err error ++ ) ++ ++ var extra uint64 ++ if lowAndHigh[0] == "*" || lowAndHigh[0] == "?" { ++ start = r.min ++ end = r.max ++ extra = starBit ++ } else { ++ start, err = parseIntOrName(lowAndHigh[0], r.names) ++ if err != nil { ++ return 0, err ++ } ++ switch len(lowAndHigh) { ++ case 1: ++ end = start ++ case 2: ++ end, err = parseIntOrName(lowAndHigh[1], r.names) ++ if err != nil { ++ return 0, err ++ } ++ default: ++ return 0, fmt.Errorf("too many hyphens: %s", expr) ++ } ++ } ++ ++ switch len(rangeAndStep) { ++ case 1: ++ step = 1 ++ case 2: ++ step, err = mustParseInt(rangeAndStep[1]) ++ if err != nil { ++ return 0, err ++ } ++ ++ // Special handling: "N/step" means "N-max/step". ++ if singleDigit { ++ end = r.max ++ } ++ if step > 1 { ++ extra = 0 ++ } ++ default: ++ return 0, fmt.Errorf("too many slashes: %s", expr) ++ } ++ ++ if start < r.min { ++ return 0, fmt.Errorf("beginning of range (%d) below minimum (%d): %s", start, r.min, expr) ++ } ++ if end > r.max { ++ return 0, fmt.Errorf("end of range (%d) above maximum (%d): %s", end, r.max, expr) ++ } ++ if start > end { ++ return 0, fmt.Errorf("beginning of range (%d) beyond end of range (%d): %s", start, end, expr) ++ } ++ if step == 0 { ++ return 0, fmt.Errorf("step of range should be a positive number: %s", expr) ++ } ++ ++ return getBits(start, end, step) | extra, nil ++} ++ ++// parseIntOrName returns the (possibly-named) integer contained in expr. ++func parseIntOrName(expr string, names map[string]uint) (uint, error) { ++ if names != nil { ++ if namedInt, ok := names[strings.ToLower(expr)]; ok { ++ return namedInt, nil ++ } ++ } ++ return mustParseInt(expr) ++} ++ ++// mustParseInt parses the given expression as an int or returns an error. ++func mustParseInt(expr string) (uint, error) { ++ num, err := strconv.Atoi(expr) ++ if err != nil { ++ return 0, fmt.Errorf("failed to parse int from %s: %s", expr, err) ++ } ++ if num < 0 { ++ return 0, fmt.Errorf("negative number (%d) not allowed: %s", num, expr) ++ } ++ ++ return uint(num), nil ++} ++ ++// getBits sets all bits in the range [min, max], modulo the given step size. ++func getBits(minSize, maxSize, step uint) uint64 { ++ var bits uint64 ++ ++ // If step is 1, use shifts. ++ if step == 1 { ++ return ^(math.MaxUint64 << (maxSize + 1)) & (math.MaxUint64 << minSize) ++ } ++ ++ // Else, use a simple loop. ++ for i := minSize; i <= maxSize; i += step { ++ bits |= 1 << i ++ } ++ return bits ++} ++ ++// all returns all bits within the given bounds. (plus the star bit) ++func all(r bounds) uint64 { ++ return getBits(r.min, r.max, 1) | starBit ++} ++ ++// parseDescriptor returns a predefined schedule for the expression, or error if none matches. ++func parseDescriptor(descriptor string, loc *time.Location) (Schedule, error) { ++ switch descriptor { ++ case "@yearly", "@annually": ++ return &SpecSchedule{ ++ Second: 1 << seconds.min, ++ Minute: 1 << minutes.min, ++ Hour: 1 << hours.min, ++ Dom: 1 << dom.min, ++ Month: 1 << months.min, ++ Dow: all(dow), ++ Location: loc, ++ }, nil ++ ++ case "@monthly": ++ return &SpecSchedule{ ++ Second: 1 << seconds.min, ++ Minute: 1 << minutes.min, ++ Hour: 1 << hours.min, ++ Dom: 1 << dom.min, ++ Month: all(months), ++ Dow: all(dow), ++ Location: loc, ++ }, nil ++ ++ case "@weekly": ++ return &SpecSchedule{ ++ Second: 1 << seconds.min, ++ Minute: 1 << minutes.min, ++ Hour: 1 << hours.min, ++ Dom: all(dom), ++ Month: all(months), ++ Dow: 1 << dow.min, ++ Location: loc, ++ }, nil ++ ++ case "@daily", "@midnight": ++ return &SpecSchedule{ ++ Second: 1 << seconds.min, ++ Minute: 1 << minutes.min, ++ Hour: 1 << hours.min, ++ Dom: all(dom), ++ Month: all(months), ++ Dow: all(dow), ++ Location: loc, ++ }, nil ++ ++ case "@hourly": ++ return &SpecSchedule{ ++ Second: 1 << seconds.min, ++ Minute: 1 << minutes.min, ++ Hour: all(hours), ++ Dom: all(dom), ++ Month: all(months), ++ Dow: all(dow), ++ Location: loc, ++ }, nil ++ ++ } ++ ++ const every = "@every " ++ if strings.HasPrefix(descriptor, every) { ++ duration, err := time.ParseDuration(descriptor[len(every):]) ++ if err != nil { ++ return nil, fmt.Errorf("failed to parse duration %s: %s", descriptor, err) ++ } ++ return Every(duration), nil ++ } ++ ++ return nil, fmt.Errorf("unrecognized descriptor: %s", descriptor) ++} +diff --git a/internal/cron/spec.go b/internal/cron/spec.go +new file mode 100644 +index 000000000..00a355c04 +--- /dev/null ++++ b/internal/cron/spec.go +@@ -0,0 +1,204 @@ ++// +skip_license_check ++ ++/* ++This file contains portions of code directly taken from the 'robfig/cron' project. ++A copy of the license for this code can be found in the file named LICENSE in ++this directory. ++*/ ++ ++package cron ++ ++import "time" ++ ++// SpecSchedule specifies a duty cycle (to the second granularity), based on a ++// traditional crontab specification. It is computed initially and stored as bit sets. ++type SpecSchedule struct { ++ Second, Minute, Hour, Dom, Month, Dow uint64 ++ ++ // Override location for this schedule. ++ Location *time.Location ++} ++ ++// bounds provides a range of acceptable values (plus a map of name to value). ++type bounds struct { ++ min, max uint ++ names map[string]uint ++} ++ ++// The bounds for each field. ++var ( ++ seconds = bounds{0, 59, nil} ++ minutes = bounds{0, 59, nil} ++ hours = bounds{0, 23, nil} ++ dom = bounds{1, 31, nil} ++ months = bounds{1, 12, map[string]uint{ ++ "jan": 1, ++ "feb": 2, ++ "mar": 3, ++ "apr": 4, ++ "may": 5, ++ "jun": 6, ++ "jul": 7, ++ "aug": 8, ++ "sep": 9, ++ "oct": 10, ++ "nov": 11, ++ "dec": 12, ++ }} ++ dow = bounds{0, 6, map[string]uint{ ++ "sun": 0, ++ "mon": 1, ++ "tue": 2, ++ "wed": 3, ++ "thu": 4, ++ "fri": 5, ++ "sat": 6, ++ }} ++) ++ ++const ( ++ // Set the top bit if a star was included in the expression. ++ starBit = 1 << 63 ++) ++ ++// Next returns the next time this schedule is activated, greater than the given ++// time. If no time can be found to satisfy the schedule, return the zero time. ++func (s *SpecSchedule) Next(t time.Time) time.Time { ++ // General approach ++ // ++ // For Month, Day, Hour, Minute, Second: ++ // Check if the time value matches. If yes, continue to the next field. ++ // If the field doesn't match the schedule, then increment the field until it matches. ++ // While incrementing the field, a wrap-around brings it back to the beginning ++ // of the field list (since it is necessary to re-verify previous field ++ // values) ++ ++ // Convert the given time into the schedule's timezone, if one is specified. ++ // Save the original timezone so we can convert back after we find a time. ++ // Note that schedules without a time zone specified (time.Local) are treated ++ // as local to the time provided. ++ origLocation := t.Location() ++ loc := s.Location ++ //nolint: gosmopolitan // this makes sense as it also handles other locations below ++ if loc == time.Local { ++ loc = t.Location() ++ } ++ //nolint:gosmopolitan ++ if s.Location != time.Local { ++ t = t.In(s.Location) ++ } ++ ++ // Start at the earliest possible time (the upcoming second). ++ t = t.Add(1*time.Second - time.Duration(t.Nanosecond())*time.Nanosecond) ++ ++ // This flag indicates whether a field has been incremented. ++ added := false ++ ++ // If no time is found within five years, return zero. ++ yearLimit := t.Year() + 5 ++ ++WRAP: ++ if t.Year() > yearLimit { ++ return time.Time{} ++ } ++ ++ // Find the first applicable month. ++ // If it's this month, then do nothing. ++ //nolint:gosec ++ for 1< 12 { ++ t = t.Add(time.Duration(24-t.Hour()) * time.Hour) ++ } else { ++ t = t.Add(time.Duration(-t.Hour()) * time.Hour) ++ } ++ } ++ ++ if t.Day() == 1 { ++ goto WRAP ++ } ++ } ++ ++ //nolint:gosec ++ for 1< 0 ++ //nolint:gosec ++ dowMatch = 1< 0 ++ ) ++ if s.Dom&starBit > 0 || s.Dow&starBit > 0 { ++ return domMatch && dowMatch ++ } ++ return domMatch || dowMatch ++} +diff --git a/internal/generated/openapi/zz_generated.openapi.go b/internal/generated/openapi/zz_generated.openapi.go +index 37ffccbb1..274ac4a34 100644 +--- a/internal/generated/openapi/zz_generated.openapi.go ++++ b/internal/generated/openapi/zz_generated.openapi.go +@@ -81,6 +81,8 @@ func GetOpenAPIDefinitions(ref common.ReferenceCallback) map[string]common.OpenA + "github.com/cert-manager/cert-manager/pkg/apis/certmanager/v1.CertificateKeystores": schema_pkg_apis_certmanager_v1_CertificateKeystores(ref), + "github.com/cert-manager/cert-manager/pkg/apis/certmanager/v1.CertificateList": schema_pkg_apis_certmanager_v1_CertificateList(ref), + "github.com/cert-manager/cert-manager/pkg/apis/certmanager/v1.CertificatePrivateKey": schema_pkg_apis_certmanager_v1_CertificatePrivateKey(ref), ++ "github.com/cert-manager/cert-manager/pkg/apis/certmanager/v1.CertificateRenewal": schema_pkg_apis_certmanager_v1_CertificateRenewal(ref), ++ "github.com/cert-manager/cert-manager/pkg/apis/certmanager/v1.CertificateRenewalWindows": schema_pkg_apis_certmanager_v1_CertificateRenewalWindows(ref), + "github.com/cert-manager/cert-manager/pkg/apis/certmanager/v1.CertificateRequest": schema_pkg_apis_certmanager_v1_CertificateRequest(ref), + "github.com/cert-manager/cert-manager/pkg/apis/certmanager/v1.CertificateRequestCondition": schema_pkg_apis_certmanager_v1_CertificateRequestCondition(ref), + "github.com/cert-manager/cert-manager/pkg/apis/certmanager/v1.CertificateRequestList": schema_pkg_apis_certmanager_v1_CertificateRequestList(ref), +@@ -2854,6 +2856,82 @@ func schema_pkg_apis_certmanager_v1_CertificatePrivateKey(ref common.ReferenceCa + } + } + ++func schema_pkg_apis_certmanager_v1_CertificateRenewal(ref common.ReferenceCallback) common.OpenAPIDefinition { ++ return common.OpenAPIDefinition{ ++ Schema: spec.Schema{ ++ SchemaProps: spec.SchemaProps{ ++ Type: []string{"object"}, ++ Properties: map[string]spec.Schema{ ++ "policy": { ++ SchemaProps: spec.SchemaProps{ ++ Description: "`policy` must be one of `Disabled`, `RenewBefore`.", ++ Type: []string{"string"}, ++ Format: "", ++ }, ++ }, ++ "windows": { ++ VendorExtensible: spec.VendorExtensible{ ++ Extensions: spec.Extensions{ ++ "x-kubernetes-list-type": "atomic", ++ }, ++ }, ++ SchemaProps: spec.SchemaProps{ ++ Description: "`windows` mentions the behavior of when the renewal must happen.", ++ Type: []string{"array"}, ++ Items: &spec.SchemaOrArray{ ++ Schema: &spec.Schema{ ++ SchemaProps: spec.SchemaProps{ ++ Default: map[string]interface{}{}, ++ Ref: ref("github.com/cert-manager/cert-manager/pkg/apis/certmanager/v1.CertificateRenewalWindows"), ++ }, ++ }, ++ }, ++ }, ++ }, ++ }, ++ }, ++ }, ++ Dependencies: []string{ ++ "github.com/cert-manager/cert-manager/pkg/apis/certmanager/v1.CertificateRenewalWindows"}, ++ } ++} ++ ++func schema_pkg_apis_certmanager_v1_CertificateRenewalWindows(ref common.ReferenceCallback) common.OpenAPIDefinition { ++ return common.OpenAPIDefinition{ ++ Schema: spec.Schema{ ++ SchemaProps: spec.SchemaProps{ ++ Description: "CertificateRenewalWindows is the definition for renewal windows", ++ Type: []string{"object"}, ++ Properties: map[string]spec.Schema{ ++ "timezone": { ++ SchemaProps: spec.SchemaProps{ ++ Description: "`timezone` is IANA compliant timezone. For example America/Denver. If this field is not set, timezone is treated as UTC.", ++ Type: []string{"string"}, ++ Format: "", ++ }, ++ }, ++ "windowDuration": { ++ SchemaProps: spec.SchemaProps{ ++ Description: "`windowDuration` is how long the cron definition is active for. Value must be in units accepted by Go time.ParseDuration https://golang.org/pkg/time/#ParseDuration.", ++ Ref: ref(metav1.Duration{}.OpenAPIModelName()), ++ }, ++ }, ++ "cron": { ++ SchemaProps: spec.SchemaProps{ ++ Description: "`cron` is a cron compliant string to allow when the renewal should be allowed. Format is as shown below: * * * * * | | | | | | | | | day of the week (0–6) (Sunday to Saturday; | | | month (1–12) 7 is also Sunday on some systems) | | day of the month (1–31) | hour (0–23) minute (0–59)", ++ Type: []string{"string"}, ++ Format: "", ++ }, ++ }, ++ }, ++ Required: []string{"windowDuration", "cron"}, ++ }, ++ }, ++ Dependencies: []string{ ++ metav1.Duration{}.OpenAPIModelName()}, ++ } ++} ++ + func schema_pkg_apis_certmanager_v1_CertificateRequest(ref common.ReferenceCallback) common.OpenAPIDefinition { + return common.OpenAPIDefinition{ + Schema: spec.Schema{ +@@ -3275,6 +3353,12 @@ func schema_pkg_apis_certmanager_v1_CertificateSpec(ref common.ReferenceCallback + Format: "int32", + }, + }, ++ "renewal": { ++ SchemaProps: spec.SchemaProps{ ++ Description: "`renewal` allows configuration of how your certificate is renewed. If the policy mentioned is `RenewBefore` then the controller respects `renewBefore` and `renewBeforePercentage`.", ++ Ref: ref("github.com/cert-manager/cert-manager/pkg/apis/certmanager/v1.CertificateRenewal"), ++ }, ++ }, + "dnsNames": { + VendorExtensible: spec.VendorExtensible{ + Extensions: spec.Extensions{ +@@ -3485,7 +3569,7 @@ func schema_pkg_apis_certmanager_v1_CertificateSpec(ref common.ReferenceCallback + }, + }, + Dependencies: []string{ +- "github.com/cert-manager/cert-manager/pkg/apis/certmanager/v1.CertificateAdditionalOutputFormat", "github.com/cert-manager/cert-manager/pkg/apis/certmanager/v1.CertificateKeystores", "github.com/cert-manager/cert-manager/pkg/apis/certmanager/v1.CertificatePrivateKey", "github.com/cert-manager/cert-manager/pkg/apis/certmanager/v1.CertificateSecretTemplate", "github.com/cert-manager/cert-manager/pkg/apis/certmanager/v1.NameConstraints", "github.com/cert-manager/cert-manager/pkg/apis/certmanager/v1.OtherName", "github.com/cert-manager/cert-manager/pkg/apis/certmanager/v1.X509Subject", "github.com/cert-manager/cert-manager/pkg/apis/meta/v1.IssuerReference", metav1.Duration{}.OpenAPIModelName()}, ++ "github.com/cert-manager/cert-manager/pkg/apis/certmanager/v1.CertificateAdditionalOutputFormat", "github.com/cert-manager/cert-manager/pkg/apis/certmanager/v1.CertificateKeystores", "github.com/cert-manager/cert-manager/pkg/apis/certmanager/v1.CertificatePrivateKey", "github.com/cert-manager/cert-manager/pkg/apis/certmanager/v1.CertificateRenewal", "github.com/cert-manager/cert-manager/pkg/apis/certmanager/v1.CertificateSecretTemplate", "github.com/cert-manager/cert-manager/pkg/apis/certmanager/v1.NameConstraints", "github.com/cert-manager/cert-manager/pkg/apis/certmanager/v1.OtherName", "github.com/cert-manager/cert-manager/pkg/apis/certmanager/v1.X509Subject", "github.com/cert-manager/cert-manager/pkg/apis/meta/v1.IssuerReference", metav1.Duration{}.OpenAPIModelName()}, + } + } + +@@ -4786,7 +4870,7 @@ func schema_pkg_apis_meta_v1_IssuerReference(ref common.ReferenceCallback) commo + return common.OpenAPIDefinition{ + Schema: spec.Schema{ + SchemaProps: spec.SchemaProps{ +- Description: "IssuerReference is a reference to a certificate issuer object with a given name, kind and group.", ++ Description: "ObjectReference is a reference to an object with a given name, kind and group.\n\nDeprecated: Use IssuerReference instead.", + Type: []string{"object"}, + Properties: map[string]spec.Schema{ + "name": { +diff --git a/pkg/apis/certmanager/v1/types_certificate.go b/pkg/apis/certmanager/v1/types_certificate.go +index 80e641520..6863b2a9c 100644 +--- a/pkg/apis/certmanager/v1/types_certificate.go ++++ b/pkg/apis/certmanager/v1/types_certificate.go +@@ -206,6 +206,11 @@ type CertificateSpec struct { + // +optional + RenewBeforePercentage *int32 `json:"renewBeforePercentage,omitempty"` + ++ // `renewal` allows configuration of how your certificate is renewed. If the policy mentioned is ++ // `RenewBefore` then the controller respects `renewBefore` and `renewBeforePercentage`. ++ // +optional ++ Renewal *CertificateRenewal `json:"renewal,omitempty"` ++ + // Requested DNS subject alternative names. + // +optional + // +listType=atomic +@@ -583,6 +588,52 @@ const ( + Modern2023PKCS12Profile PKCS12Profile = "Modern2023" + ) + ++type CertificateRenewal struct { ++ // `policy` must be one of `Disabled`, `RenewBefore`. ++ // +kubebuilder:validation:Enum=RenewBefore;Disabled ++ Policy CertificateRenewalPolicy `json:"policy,omitempty"` ++ ++ // `windows` mentions the behavior of when the renewal must happen. ++ // +listType=atomic ++ // +optional ++ Windows []CertificateRenewalWindows `json:"windows,omitempty"` ++} ++ ++type CertificateRenewalPolicy string ++ ++const ( ++ CertificateRenewalPolicyRenewBefore CertificateRenewalPolicy = "RenewBefore" ++ CertificateRenewalPolicyDisabled CertificateRenewalPolicy = "Disabled" ++) ++ ++// CertificateRenewalWindows is the definition for renewal windows ++type CertificateRenewalWindows struct { ++ // `timezone` is IANA compliant timezone. For example America/Denver. ++ // If this field is not set, timezone is treated as UTC. ++ // +kubebuilder:validation:MinLength=1 ++ // +optional ++ Timezone string `json:"timezone,omitempty"` ++ ++ // `windowDuration` is how long the cron definition is active for. ++ // Value must be in units accepted by Go time.ParseDuration https://golang.org/pkg/time/#ParseDuration. ++ // +kubebuilder:validation:Type=string ++ // +kubebuilder:validation:Pattern="^([0-9]+(\\.[0-9]+)?(s|m|h))+$" ++ // +required ++ WindowDuration *metav1.Duration `json:"windowDuration,omitempty"` ++ ++ // `cron` is a cron compliant string to allow when the renewal should be allowed. Format is as shown below: ++ // * * * * * ++ // | | | | | ++ // | | | | day of the week (0–6) (Sunday to Saturday; ++ // | | | month (1–12) 7 is also Sunday on some systems) ++ // | | day of the month (1–31) ++ // | hour (0–23) ++ // minute (0–59) ++ // +kubebuilder:validation:MinLength=1 ++ // +required ++ Cron string `json:"cron,omitempty"` ++} ++ + // CertificateStatus defines the observed state of Certificate + type CertificateStatus struct { + // List of status conditions to indicate the status of certificates. +diff --git a/pkg/apis/certmanager/v1/zz_generated.deepcopy.go b/pkg/apis/certmanager/v1/zz_generated.deepcopy.go +index e889ecf1a..306ccce0f 100644 +--- a/pkg/apis/certmanager/v1/zz_generated.deepcopy.go ++++ b/pkg/apis/certmanager/v1/zz_generated.deepcopy.go +@@ -198,6 +198,50 @@ func (in *CertificatePrivateKey) DeepCopy() *CertificatePrivateKey { + return out + } + ++// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. ++func (in *CertificateRenewal) DeepCopyInto(out *CertificateRenewal) { ++ *out = *in ++ if in.Windows != nil { ++ in, out := &in.Windows, &out.Windows ++ *out = make([]CertificateRenewalWindows, len(*in)) ++ for i := range *in { ++ (*in)[i].DeepCopyInto(&(*out)[i]) ++ } ++ } ++ return ++} ++ ++// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new CertificateRenewal. ++func (in *CertificateRenewal) DeepCopy() *CertificateRenewal { ++ if in == nil { ++ return nil ++ } ++ out := new(CertificateRenewal) ++ in.DeepCopyInto(out) ++ return out ++} ++ ++// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. ++func (in *CertificateRenewalWindows) DeepCopyInto(out *CertificateRenewalWindows) { ++ *out = *in ++ if in.WindowDuration != nil { ++ in, out := &in.WindowDuration, &out.WindowDuration ++ *out = new(metav1.Duration) ++ **out = **in ++ } ++ return ++} ++ ++// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new CertificateRenewalWindows. ++func (in *CertificateRenewalWindows) DeepCopy() *CertificateRenewalWindows { ++ if in == nil { ++ return nil ++ } ++ out := new(CertificateRenewalWindows) ++ in.DeepCopyInto(out) ++ return out ++} ++ + // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. + func (in *CertificateRequest) DeepCopyInto(out *CertificateRequest) { + *out = *in +@@ -421,6 +465,11 @@ func (in *CertificateSpec) DeepCopyInto(out *CertificateSpec) { + *out = new(int32) + **out = **in + } ++ if in.Renewal != nil { ++ in, out := &in.Renewal, &out.Renewal ++ *out = new(CertificateRenewal) ++ (*in).DeepCopyInto(*out) ++ } + if in.DNSNames != nil { + in, out := &in.DNSNames, &out.DNSNames + *out = make([]string, len(*in)) +diff --git a/pkg/client/applyconfigurations/certmanager/v1/certificaterenewal.go b/pkg/client/applyconfigurations/certmanager/v1/certificaterenewal.go +new file mode 100644 +index 000000000..e52d91039 +--- /dev/null ++++ b/pkg/client/applyconfigurations/certmanager/v1/certificaterenewal.go +@@ -0,0 +1,59 @@ ++/* ++Copyright The cert-manager Authors. ++ ++Licensed under the Apache License, Version 2.0 (the "License"); ++you may not use this file except in compliance with the License. ++You may obtain a copy of the License at ++ ++ http://www.apache.org/licenses/LICENSE-2.0 ++ ++Unless required by applicable law or agreed to in writing, software ++distributed under the License is distributed on an "AS IS" BASIS, ++WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ++See the License for the specific language governing permissions and ++limitations under the License. ++*/ ++ ++// Code generated by applyconfiguration-gen. DO NOT EDIT. ++ ++package v1 ++ ++import ( ++ certmanagerv1 "github.com/cert-manager/cert-manager/pkg/apis/certmanager/v1" ++) ++ ++// CertificateRenewalApplyConfiguration represents a declarative configuration of the CertificateRenewal type for use ++// with apply. ++type CertificateRenewalApplyConfiguration struct { ++ // `policy` must be one of `Disabled`, `RenewBefore`. ++ Policy *certmanagerv1.CertificateRenewalPolicy `json:"policy,omitempty"` ++ // `windows` mentions the behavior of when the renewal must happen. ++ Windows []CertificateRenewalWindowsApplyConfiguration `json:"windows,omitempty"` ++} ++ ++// CertificateRenewalApplyConfiguration constructs a declarative configuration of the CertificateRenewal type for use with ++// apply. ++func CertificateRenewal() *CertificateRenewalApplyConfiguration { ++ return &CertificateRenewalApplyConfiguration{} ++} ++ ++// WithPolicy sets the Policy field in the declarative configuration to the given value ++// and returns the receiver, so that objects can be built by chaining "With" function invocations. ++// If called multiple times, the Policy field is set to the value of the last call. ++func (b *CertificateRenewalApplyConfiguration) WithPolicy(value certmanagerv1.CertificateRenewalPolicy) *CertificateRenewalApplyConfiguration { ++ b.Policy = &value ++ return b ++} ++ ++// WithWindows adds the given value to the Windows field in the declarative configuration ++// and returns the receiver, so that objects can be build by chaining "With" function invocations. ++// If called multiple times, values provided by each call will be appended to the Windows field. ++func (b *CertificateRenewalApplyConfiguration) WithWindows(values ...*CertificateRenewalWindowsApplyConfiguration) *CertificateRenewalApplyConfiguration { ++ for i := range values { ++ if values[i] == nil { ++ panic("nil value passed to WithWindows") ++ } ++ b.Windows = append(b.Windows, *values[i]) ++ } ++ return b ++} +diff --git a/pkg/client/applyconfigurations/certmanager/v1/certificaterenewalwindows.go b/pkg/client/applyconfigurations/certmanager/v1/certificaterenewalwindows.go +new file mode 100644 +index 000000000..b4b8dc509 +--- /dev/null ++++ b/pkg/client/applyconfigurations/certmanager/v1/certificaterenewalwindows.go +@@ -0,0 +1,75 @@ ++/* ++Copyright The cert-manager Authors. ++ ++Licensed under the Apache License, Version 2.0 (the "License"); ++you may not use this file except in compliance with the License. ++You may obtain a copy of the License at ++ ++ http://www.apache.org/licenses/LICENSE-2.0 ++ ++Unless required by applicable law or agreed to in writing, software ++distributed under the License is distributed on an "AS IS" BASIS, ++WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ++See the License for the specific language governing permissions and ++limitations under the License. ++*/ ++ ++// Code generated by applyconfiguration-gen. DO NOT EDIT. ++ ++package v1 ++ ++import ( ++ metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" ++) ++ ++// CertificateRenewalWindowsApplyConfiguration represents a declarative configuration of the CertificateRenewalWindows type for use ++// with apply. ++// ++// CertificateRenewalWindows is the definition for renewal windows ++type CertificateRenewalWindowsApplyConfiguration struct { ++ // `timezone` is IANA compliant timezone. For example America/Denver. ++ // If this field is not set, timezone is treated as UTC. ++ Timezone *string `json:"timezone,omitempty"` ++ // `windowDuration` is how long the cron definition is active for. ++ // Value must be in units accepted by Go time.ParseDuration https://golang.org/pkg/time/#ParseDuration. ++ WindowDuration *metav1.Duration `json:"windowDuration,omitempty"` ++ // `cron` is a cron compliant string to allow when the renewal should be allowed. Format is as shown below: ++ // * * * * * ++ // | | | | | ++ // | | | | day of the week (0–6) (Sunday to Saturday; ++ // | | | month (1–12) 7 is also Sunday on some systems) ++ // | | day of the month (1–31) ++ // | hour (0–23) ++ // minute (0–59) ++ Cron *string `json:"cron,omitempty"` ++} ++ ++// CertificateRenewalWindowsApplyConfiguration constructs a declarative configuration of the CertificateRenewalWindows type for use with ++// apply. ++func CertificateRenewalWindows() *CertificateRenewalWindowsApplyConfiguration { ++ return &CertificateRenewalWindowsApplyConfiguration{} ++} ++ ++// WithTimezone sets the Timezone field in the declarative configuration to the given value ++// and returns the receiver, so that objects can be built by chaining "With" function invocations. ++// If called multiple times, the Timezone field is set to the value of the last call. ++func (b *CertificateRenewalWindowsApplyConfiguration) WithTimezone(value string) *CertificateRenewalWindowsApplyConfiguration { ++ b.Timezone = &value ++ return b ++} ++ ++// WithWindowDuration sets the WindowDuration field in the declarative configuration to the given value ++// and returns the receiver, so that objects can be built by chaining "With" function invocations. ++// If called multiple times, the WindowDuration field is set to the value of the last call. ++func (b *CertificateRenewalWindowsApplyConfiguration) WithWindowDuration(value metav1.Duration) *CertificateRenewalWindowsApplyConfiguration { ++ b.WindowDuration = &value ++ return b ++} ++ ++// WithCron sets the Cron field in the declarative configuration to the given value ++// and returns the receiver, so that objects can be built by chaining "With" function invocations. ++// If called multiple times, the Cron field is set to the value of the last call. ++func (b *CertificateRenewalWindowsApplyConfiguration) WithCron(value string) *CertificateRenewalWindowsApplyConfiguration { ++ b.Cron = &value ++ return b ++} +diff --git a/pkg/client/applyconfigurations/certmanager/v1/certificatespec.go b/pkg/client/applyconfigurations/certmanager/v1/certificatespec.go +index 47adfb4e9..1e9c58e8a 100644 +--- a/pkg/client/applyconfigurations/certmanager/v1/certificatespec.go ++++ b/pkg/client/applyconfigurations/certmanager/v1/certificatespec.go +@@ -101,6 +101,9 @@ type CertificateSpecApplyConfiguration struct { + // minutes. + // Cannot be set if the `renewBefore` field is set. + RenewBeforePercentage *int32 `json:"renewBeforePercentage,omitempty"` ++ // `renewal` allows configuration of how your certificate is renewed. If the policy mentioned is ++ // `RenewBefore` then the controller respects `renewBefore` and `renewBeforePercentage`. ++ Renewal *CertificateRenewalApplyConfiguration `json:"renewal,omitempty"` + // Requested DNS subject alternative names. + DNSNames []string `json:"dnsNames,omitempty"` + // Requested IP address subject alternative names. +@@ -237,6 +240,14 @@ func (b *CertificateSpecApplyConfiguration) WithRenewBeforePercentage(value int3 + return b + } + ++// WithRenewal sets the Renewal field in the declarative configuration to the given value ++// and returns the receiver, so that objects can be built by chaining "With" function invocations. ++// If called multiple times, the Renewal field is set to the value of the last call. ++func (b *CertificateSpecApplyConfiguration) WithRenewal(value *CertificateRenewalApplyConfiguration) *CertificateSpecApplyConfiguration { ++ b.Renewal = value ++ return b ++} ++ + // WithDNSNames adds the given value to the DNSNames field in the declarative configuration + // and returns the receiver, so that objects can be build by chaining "With" function invocations. + // If called multiple times, values provided by each call will be appended to the DNSNames field. +diff --git a/pkg/client/applyconfigurations/internal/internal.go b/pkg/client/applyconfigurations/internal/internal.go +index cac0cadc5..d76c344c7 100644 +--- a/pkg/client/applyconfigurations/internal/internal.go ++++ b/pkg/client/applyconfigurations/internal/internal.go +@@ -1224,6 +1224,30 @@ var schemaYAML = typed.YAMLObject(`types: + - name: size + type: + scalar: numeric ++- name: com.github.cert-manager.cert-manager.pkg.apis.certmanager.v1.CertificateRenewal ++ map: ++ fields: ++ - name: policy ++ type: ++ scalar: string ++ - name: windows ++ type: ++ list: ++ elementType: ++ namedType: com.github.cert-manager.cert-manager.pkg.apis.certmanager.v1.CertificateRenewalWindows ++ elementRelationship: atomic ++- name: com.github.cert-manager.cert-manager.pkg.apis.certmanager.v1.CertificateRenewalWindows ++ map: ++ fields: ++ - name: cron ++ type: ++ scalar: string ++ - name: timezone ++ type: ++ scalar: string ++ - name: windowDuration ++ type: ++ namedType: Duration.v1.meta.apis.pkg.apimachinery.k8s.io + - name: com.github.cert-manager.cert-manager.pkg.apis.certmanager.v1.CertificateRequest + map: + fields: +@@ -1407,6 +1431,9 @@ var schemaYAML = typed.YAMLObject(`types: + - name: renewBeforePercentage + type: + scalar: numeric ++ - name: renewal ++ type: ++ namedType: com.github.cert-manager.cert-manager.pkg.apis.certmanager.v1.CertificateRenewal + - name: revisionHistoryLimit + type: + scalar: numeric +diff --git a/pkg/client/applyconfigurations/utils.go b/pkg/client/applyconfigurations/utils.go +index 0729e915a..c38f34103 100644 +--- a/pkg/client/applyconfigurations/utils.go ++++ b/pkg/client/applyconfigurations/utils.go +@@ -124,6 +124,10 @@ func ForKind(kind schema.GroupVersionKind) interface{} { + return &applyconfigurationscertmanagerv1.CertificateKeystoresApplyConfiguration{} + case certmanagerv1.SchemeGroupVersion.WithKind("CertificatePrivateKey"): + return &applyconfigurationscertmanagerv1.CertificatePrivateKeyApplyConfiguration{} ++ case certmanagerv1.SchemeGroupVersion.WithKind("CertificateRenewal"): ++ return &applyconfigurationscertmanagerv1.CertificateRenewalApplyConfiguration{} ++ case certmanagerv1.SchemeGroupVersion.WithKind("CertificateRenewalWindows"): ++ return &applyconfigurationscertmanagerv1.CertificateRenewalWindowsApplyConfiguration{} + case certmanagerv1.SchemeGroupVersion.WithKind("CertificateRequest"): + return &applyconfigurationscertmanagerv1.CertificateRequestApplyConfiguration{} + case certmanagerv1.SchemeGroupVersion.WithKind("CertificateRequestCondition"): +diff --git a/pkg/controller/certificates/readiness/readiness_controller.go b/pkg/controller/certificates/readiness/readiness_controller.go +index a5e7ac798..fc4f11576 100644 +--- a/pkg/controller/certificates/readiness/readiness_controller.go ++++ b/pkg/controller/certificates/readiness/readiness_controller.go +@@ -25,8 +25,10 @@ import ( + apiequality "k8s.io/apimachinery/pkg/api/equality" + apierrors "k8s.io/apimachinery/pkg/api/errors" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" ++ "k8s.io/apimachinery/pkg/labels" + "k8s.io/apimachinery/pkg/types" + "k8s.io/client-go/tools/cache" ++ "k8s.io/client-go/tools/record" + "k8s.io/client-go/util/workqueue" + + internalcertificates "github.com/cert-manager/cert-manager/internal/controller/certificates" +@@ -60,6 +62,7 @@ type controller struct { + certificateRequestLister cmlisters.CertificateRequestLister + secretLister internalinformers.SecretLister + client cmclient.Interface ++ recorder record.EventRecorder + gatherer *policies.Gatherer + // policyEvaluator builds Ready condition of a Certificate based on policy evaluation + policyEvaluator policyEvaluatorFunc +@@ -101,26 +104,17 @@ func NewController( + } + + // When a CertificateRequest resource changes, enqueue the Certificate resource that owns it. +- if _, err := certificateRequestInformer.Informer().AddEventHandler( +- controllerpkg.BlockingEventHandler( +- certificates.EnqueueCertificatesForResourceUsingPredicates[*cmapi.CertificateRequest]( +- log, queue, certificateInformer.Lister(), +- predicate.ResourceOwnerOf, +- ), +- ), +- ); err != nil { ++ if _, err := certificateRequestInformer.Informer().AddEventHandler(controllerpkg.BlockingEventHandler( ++ certificates.EnqueueCertificatesForResourceUsingPredicates(log, queue, certificateInformer.Lister(), labels.Everything(), predicate.ResourceOwnerOf), ++ )); err != nil { + return nil, nil, nil, fmt.Errorf("error setting up event handler: %v", err) + } + // When a Secret resource changes, enqueue any Certificate resources that name it as spec.secretName. +- if _, err := secretsInformer.Informer().AddEventHandler( +- controllerpkg.BlockingEventHandler( +- // Trigger reconciles on changes to the Secret named `spec.secretName` +- certificates.EnqueueCertificatesForResourceUsingPredicates( +- log, queue, certificateInformer.Lister(), +- predicate.ExtractResourceName[*corev1.Secret](predicate.CertificateSecretName), +- ), +- ), +- ); err != nil { ++ if _, err := secretsInformer.Informer().AddEventHandler(controllerpkg.BlockingEventHandler( ++ // Trigger reconciles on changes to the Secret named `spec.secretName` ++ certificates.EnqueueCertificatesForResourceUsingPredicates(log, queue, certificateInformer.Lister(), labels.Everything(), ++ predicate.ExtractResourceName(predicate.CertificateSecretName)), ++ )); err != nil { + return nil, nil, nil, fmt.Errorf("error setting up event handler: %v", err) + } + +@@ -138,6 +132,7 @@ func NewController( + certificateRequestLister: certificateRequestInformer.Lister(), + secretLister: secretsInformer.Lister(), + client: ctx.CMClient, ++ recorder: ctx.Recorder, + gatherer: &policies.Gatherer{ + CertificateRequestLister: certificateRequestInformer.Lister(), + SecretLister: secretsInformer.Lister(), +@@ -189,7 +184,15 @@ func (c *controller) ProcessItem(ctx context.Context, key types.NamespacedName) + + notBefore := metav1.NewTime(x509cert.NotBefore) + notAfter := metav1.NewTime(x509cert.NotAfter) +- renewalTime := c.renewalTimeCalculator(x509cert.NotBefore, x509cert.NotAfter, crt.Spec.RenewBefore, crt.Spec.RenewBeforePercentage) ++ renewalTime, err := c.renewalTimeCalculator(x509cert.NotBefore, x509cert.NotAfter, crt.Spec.RenewBefore, crt.Spec.RenewBeforePercentage, crt.Spec.Renewal) ++ ++ if err != nil { ++ reason := policies.WindowError ++ message := fmt.Sprintf("Could not calculate renewal time: %v", err) ++ apiutil.SetCertificateCondition(crt, crt.Generation, cmapi.CertificateConditionReady, cmmeta.ConditionFalse, reason, message) ++ ++ c.recorder.Event(crt, corev1.EventTypeWarning, reason, message) ++ } + + // update Certificate's Status + crt.Status.NotBefore = ¬Before +diff --git a/pkg/controller/certificates/trigger/trigger_controller.go b/pkg/controller/certificates/trigger/trigger_controller.go +index 5ffd2800d..1a6659c85 100644 +--- a/pkg/controller/certificates/trigger/trigger_controller.go ++++ b/pkg/controller/certificates/trigger/trigger_controller.go +@@ -26,6 +26,7 @@ import ( + corev1 "k8s.io/api/core/v1" + k8sErrors "k8s.io/apimachinery/pkg/api/errors" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" ++ "k8s.io/apimachinery/pkg/labels" + "k8s.io/apimachinery/pkg/types" + "k8s.io/client-go/tools/cache" + "k8s.io/client-go/tools/record" +@@ -106,26 +107,17 @@ func NewController( + } + + // When a CertificateRequest resource changes, enqueue the Certificate resource that owns it. +- if _, err := certificateRequestInformer.Informer().AddEventHandler( +- controllerpkg.BlockingEventHandler( +- certificates.EnqueueCertificatesForResourceUsingPredicates[*cmapi.CertificateRequest]( +- log, queue, certificateInformer.Lister(), +- predicate.ResourceOwnerOf, +- ), +- ), +- ); err != nil { ++ if _, err := certificateRequestInformer.Informer().AddEventHandler(controllerpkg.BlockingEventHandler( ++ certificates.EnqueueCertificatesForResourceUsingPredicates(log, queue, certificateInformer.Lister(), labels.Everything(), predicate.ResourceOwnerOf), ++ )); err != nil { + return nil, nil, nil, fmt.Errorf("error setting up event handler: %v", err) + } + // When a Secret resource changes, enqueue any Certificate resources that name it as spec.secretName. +- if _, err := secretsInformer.Informer().AddEventHandler( +- controllerpkg.BlockingEventHandler( +- // Trigger reconciles on changes to the Secret named `spec.secretName` +- certificates.EnqueueCertificatesForResourceUsingPredicates( +- log, queue, certificateInformer.Lister(), +- predicate.ExtractResourceName[*corev1.Secret](predicate.CertificateSecretName), +- ), +- ), +- ); err != nil { ++ if _, err := secretsInformer.Informer().AddEventHandler(controllerpkg.BlockingEventHandler( ++ // Trigger reconciles on changes to the Secret named `spec.secretName` ++ certificates.EnqueueCertificatesForResourceUsingPredicates(log, queue, certificateInformer.Lister(), labels.Everything(), ++ predicate.ExtractResourceName(predicate.CertificateSecretName)), ++ )); err != nil { + return nil, nil, nil, fmt.Errorf("error setting up event handler: %v", err) + } + +@@ -223,8 +215,13 @@ func (c *controller) ProcessItem(ctx context.Context, key types.NamespacedName) + } + + reason, message, reissue := c.shouldReissue(input) ++ if reason == policies.WindowError { ++ c.recorder.Event(crt, corev1.EventTypeWarning, reason, fmt.Sprintf("Renewing certificate without satisfying renewal windows due to %s", message)) ++ message = fmt.Sprintf("Renewing certificate without satisfying renewal windows at: %s", crt.Status.RenewalTime) ++ reason = policies.Renewing ++ } ++ + if !reissue { +- // no re-issuance required, return early + return nil + } + +diff --git a/pkg/util/pki/renewaltime.go b/pkg/util/pki/renewaltime.go +index 6e558abca..1a8281021 100644 +--- a/pkg/util/pki/renewaltime.go ++++ b/pkg/util/pki/renewaltime.go +@@ -17,13 +17,17 @@ limitations under the License. + package pki + + import ( ++ "fmt" + "time" + + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" ++ ++ apiv1 "github.com/cert-manager/cert-manager/pkg/apis/certmanager/v1" ++ "github.com/cert-manager/cert-manager/pkg/util" + ) + + // RenewalTimeFunc is a custom function type for calculating renewal time of a certificate. +-type RenewalTimeFunc func(time.Time, time.Time, *metav1.Duration, *int32) *metav1.Time ++type RenewalTimeFunc func(time.Time, time.Time, *metav1.Duration, *int32, *apiv1.CertificateRenewal) (*metav1.Time, error) + + // RenewalTime calculates renewal time for a certificate. + // If renewBefore is non-nil and less than the certificate's lifetime, renewal +@@ -32,14 +36,14 @@ type RenewalTimeFunc func(time.Time, time.Time, *metav1.Duration, *int32) *metav + // will be the computed period before expiry based on the renewBeforePercentage + // value and certificate lifetime. + // Default renewal time is 2/3 through certificate's lifetime. +-func RenewalTime(notBefore, notAfter time.Time, renewBefore *metav1.Duration, renewBeforePercentage *int32) *metav1.Time { +- // 1. Calculate how long before expiry a cert should be renewed ++func RenewalTime(notBefore, notAfter time.Time, renewBefore *metav1.Duration, renewBeforePercentage *int32, renewalSpec *apiv1.CertificateRenewal) (*metav1.Time, error) { ++ // 1. Start calculation of desired renewal time based on renewBefore and renewBeforePercentage. ++ // 1.1: Calculate how long before expiry a cert should be renewed + actualDuration := notAfter.Sub(notBefore) + +- actualRenewBefore := RenewBefore(actualDuration, renewBefore, renewBeforePercentage) +- +- // 2. Calculate when a cert should be renewed ++ actualRenewBefore := desiredRenewalTime(actualDuration, renewBefore, renewBeforePercentage) + ++ // 1.2: Calculate when a cert should be renewed + // Truncate the renewal time to nearest second. This is important + // because the renewal time also gets stored on Certificate's status + // where it is truncated to the nearest second. We use the renewal time +@@ -51,17 +55,33 @@ func RenewalTime(notBefore, notAfter time.Time, renewBefore *metav1.Duration, re + // causing Certificates to not be automatically renewed. See + // https://github.com/cert-manager/cert-manager/pull/4399. + rt := metav1.NewTime(notAfter.Add(-1 * actualRenewBefore).Truncate(time.Second)) +- return &rt ++ ++ // 2. If there is no renewal spec then just return the desired renewal time calculated above. ++ if renewalSpec == nil { ++ return &rt, nil ++ } ++ ++ switch renewalSpec.Policy { ++ case apiv1.CertificateRenewalPolicyDisabled: ++ return nil, nil ++ case apiv1.CertificateRenewalPolicyRenewBefore: ++ return applyRenewBeforeWithWindows(notAfter, notBefore, rt.Time, renewalSpec.Windows) ++ default: ++ return nil, fmt.Errorf("unsupported renewal policy: %s", renewalSpec.Policy) ++ } + } + +-// RenewBefore calculates how far before expiry a certificate should be renewed. ++// desiredRenewalTime calculates how far before expiry a certificate should be renewed. + // If renewBefore is non-nil and less than the certificate's lifetime, renewal + // time will be the computed renewBefore period before expiry. + // If renewBeforePercentage is non-nil and in the range (0,100), renewal time + // will be the computed period before expiry based on the renewBeforePercentage + // and actualDuration values. + // Default is 2/3 through certificate's lifetime. +-func RenewBefore(actualDuration time.Duration, renewBefore *metav1.Duration, renewBeforePercentage *int32) time.Duration { ++ ++// Note that this function used to be called RenewBefore and was an exported function which would expose the renewal time. ++// Currently, this function calculates the desired renewal time and feeds into the renewal windows logic called above. ++func desiredRenewalTime(actualDuration time.Duration, renewBefore *metav1.Duration, renewBeforePercentage *int32) time.Duration { + // If spec.renewBefore or spec.renewBeforePercentage was set (and is + // valid) respect that. We don't want to prevent users from renewing + // longer lived certs more frequently. +@@ -74,3 +94,171 @@ func RenewBefore(actualDuration time.Duration, renewBefore *metav1.Duration, ren + // Otherwise, default to renewing 2/3 through certificate's lifetime. + return actualDuration / 3 + } ++ ++// applyRenewBeforeWithWindows calculates effective renewal time with windows in it. We want the logic to be as follows: ++// Take in the desiredRenewalTime from the function above and look forward and backward to find a desirable time which satisfies ++// the cron window along with the cronSeconds duration. If we find a time that is before the renewalTime we return that first. ++func applyRenewBeforeWithWindows(notAfter, notBefore, desiredRenewalTime time.Time, windows []apiv1.CertificateRenewalWindows) (*metav1.Time, error) { ++ var ( ++ bestBefore *time.Time ++ bestAfter *time.Time ++ ) ++ ++ if len(windows) == 0 { ++ return &metav1.Time{Time: desiredRenewalTime}, nil ++ } ++ ++ for _, w := range windows { ++ loc := time.UTC ++ if w.Timezone != "" { ++ if tz, err := time.LoadLocation(w.Timezone); err == nil { ++ loc = tz ++ } else { ++ // This shouldn't get triggered as we validate timezones in the validation webhook. ++ return nil, fmt.Errorf("error parsing timezone in window %s", err.Error()) ++ } ++ } ++ ++ cronSched, err := util.CronParse(w.Cron, loc.String()) ++ if err != nil { ++ return nil, fmt.Errorf("error parsing cron in window %s", err.Error()) ++ } ++ ++ if w.WindowDuration == nil || w.WindowDuration.Duration <= 0 { ++ return nil, fmt.Errorf("windowDuration must be a positive duration in window %v", w) ++ } ++ ++ // Any renewal logic should only start after notBefore and before notAfter. Bounds are [notBefore - dur, notAfter + dur) ++ searchMin := notBefore.Add(-w.WindowDuration.Duration) ++ searchMax := notAfter.Add(w.WindowDuration.Duration) ++ ++ bestBefore = findBeforeDesired(cronSched, searchMin, searchMax, desiredRenewalTime, bestBefore, w.WindowDuration.Duration) ++ bestAfter = findAfterDesired(cronSched, searchMin, searchMax, desiredRenewalTime, bestAfter, w.WindowDuration.Duration) ++ } ++ ++ if bestBefore != nil { ++ return &metav1.Time{Time: *bestBefore}, nil ++ } ++ ++ if bestAfter != nil { ++ return &metav1.Time{Time: *bestAfter}, nil ++ } ++ ++ return &metav1.Time{Time: desiredRenewalTime}, fmt.Errorf("cannot find a time with the given windows between %s and %s for: %s", notBefore, notAfter, desiredRenewalTime) ++} ++ ++// bsFindEarliestWindowBeforeDesired performs a binary search over time to find ++// the latest cron window start S such that: ++// ++// minTime <= S < maxTime ++// ++// where S is a time produced by sched.Next(..). ++func bsFindLatestWindowBeforeDesired(sched util.CronSchedule, minTime, maxTime time.Time) *time.Time { ++ if !minTime.Before(maxTime) { ++ return nil ++ } ++ ++ // If the first instance that matches the cron is after the max bound then we don't have a earliest window before desired renewal. ++ if sched.Next(minTime.Add(-time.Second)).After(maxTime) { ++ return nil ++ } ++ ++ low := minTime ++ high := maxTime ++ ++ // We binary search on the time range [low, high), maintaining the invariant: ++ // ++ // There exists at least one cron start S such that: ++ // low <= S <= maxTime ++ // ++ // and S is produced by sched.Next(..). ++ for high.Sub(low) > time.Second { ++ mid := low.Add(high.Sub(low) / 2) ++ next := sched.Next(mid) ++ ++ if next.After(maxTime) { ++ high = mid ++ } else { ++ low = mid ++ } ++ } ++ ++ last := sched.Next(low.Add(-time.Second)) ++ if last.After(maxTime) { ++ return nil ++ } ++ ++ return &last ++} ++ ++// findBeforeDesired returns a time that matches the cron schedule before the desiredRenewalTime. This function makes use of a binary search ++// algorithm, with the bounds defined by searchMin and searchMax (desiredRenewalTime if it's before searchMax), to find a time which matches the cron schedule. ++// if the desiredRenewalTime is in [lastStart, lastStart+duration) we just return that else we return lastStart+duration. ++func findBeforeDesired(cronSched util.CronSchedule, searchMin, searchMax, desiredRenewalTime time.Time, bestBefore *time.Time, duration time.Duration) *time.Time { ++ if desiredRenewalTime.Before(searchMin) { ++ return nil ++ } ++ var beforeMax time.Time ++ if desiredRenewalTime.Before(searchMax) { ++ beforeMax = desiredRenewalTime ++ } else { ++ beforeMax = searchMax ++ } ++ lastStart := bsFindLatestWindowBeforeDesired(cronSched, searchMin, beforeMax) ++ if lastStart != nil { ++ end := lastStart.Add(duration) ++ ++ var candidateBefore time.Time ++ if !desiredRenewalTime.Before(*lastStart) && desiredRenewalTime.Before(end) { ++ candidateBefore = desiredRenewalTime ++ } else { ++ candidateBefore = end ++ } ++ ++ // This is done to ensure that any candidateBefore is not before the desired renewal time. ++ if !candidateBefore.Before(desiredRenewalTime) { ++ if bestBefore == nil || candidateBefore.After(*bestBefore) { ++ c := candidateBefore ++ bestBefore = &c ++ } ++ } ++ } ++ ++ return bestBefore ++} ++ ++// findAfterDesired returns the first instance of time that matches the cronSched after the desiredRenewalTime. ++func findAfterDesired(cronSched util.CronSchedule, searchMin, searchMax, desiredRenewalTime time.Time, bestAfter *time.Time, duration time.Duration) *time.Time { ++ var afterMin time.Time ++ if desiredRenewalTime.After(searchMin) { ++ afterMin = desiredRenewalTime ++ } else { ++ afterMin = searchMin ++ } ++ start := cronSched.Next(afterMin.Add(-time.Second)) ++ if start.After(searchMax) { ++ return nil ++ } ++ ++ end := start.Add(duration) ++ ++ var candidateAfter time.Time ++ switch { ++ case !desiredRenewalTime.Before(start) && desiredRenewalTime.Before(end): ++ candidateAfter = desiredRenewalTime ++ case desiredRenewalTime.Before(start): ++ candidateAfter = start ++ default: ++ candidateAfter = time.Time{} ++ } ++ ++ // This check ensures that candidateAfter is never before the desiredRenewalTime ++ if !candidateAfter.IsZero() && !candidateAfter.Before(desiredRenewalTime) { ++ if bestAfter == nil || candidateAfter.Before(*bestAfter) { ++ c := candidateAfter ++ bestAfter = &c ++ } ++ } ++ ++ return bestAfter ++} +diff --git a/pkg/util/util.go b/pkg/util/util.go +index 7893e43b9..9161c62b9 100644 +--- a/pkg/util/util.go ++++ b/pkg/util/util.go +@@ -24,10 +24,18 @@ import ( + "net/url" + "slices" + "strings" ++ "time" + ++ "github.com/cert-manager/cert-manager/internal/cron" + cmapi "github.com/cert-manager/cert-manager/pkg/apis/certmanager/v1" + ) + ++// CronSchedule defines the minimal schedule behavior exposed by this package, ++// decoupling callers from the internal cron implementation. ++type CronSchedule interface { ++ Next(time.Time) time.Time ++} ++ + // genericEqualUnsorted reports whether two slices are identical up to reordering + // using a comparison function. + // If the lengths are different, genericEqualUnsorted returns false. Otherwise, the +@@ -136,3 +144,19 @@ func SplitWithEscapeCSV(in string) ([]string, error) { + + return records[0], nil + } ++ ++// CronParse parses the given cron syntax to return a cron schedule interface. It also takes in an optional timezone which would parse the ++// cron schedule in that timezone. timeZone must be an IANA compliant time zone (e.g. America/Denver). ++func CronParse(origCronString, timeZone string) (CronSchedule, error) { ++ cronString := origCronString ++ if timeZone != "" { ++ cronString = fmt.Sprintf("CRON_TZ=%s %s", timeZone, origCronString) ++ } ++ s, err := cron. ++ NewParser(cron.Minute | cron.Hour | cron.Dom | cron.Month | cron.Dow | cron.Descriptor). ++ Parse(cronString) ++ if err == nil { ++ return s, nil ++ } ++ return nil, fmt.Errorf("failed to parse cron spec '%s': %w", origCronString, err) ++} diff --git a/cert-manager_1/solution/solve.sh b/cert-manager_1/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..d9bfc75d2f97bdc0c27fc1cbcc8f398971cfd9aa --- /dev/null +++ b/cert-manager_1/solution/solve.sh @@ -0,0 +1,7 @@ +#!/usr/bin/env bash +set -euo pipefail + +cd /workspace/cert-manager +patch=${LOLBENCH_ORACLE_PATCH:-/solution/solution.patch} +git apply "$patch" +lolbench-submit diff --git a/cert-manager_1/task.toml b/cert-manager_1/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..aea905fca8beb7db49d7914f55889a6113334f59 --- /dev/null +++ b/cert-manager_1/task.toml @@ -0,0 +1,60 @@ +schema_version = "1.3" + +[task] +name = "lolbench/cert-manager_1" +description = "Implement cert-manager." +authors = [{ name = "LoLBench maintainers" }] +keywords = ["lolbench", "coding-agent", "cert", "manager", "go"] + +[metadata] +instance_id = "cert-manager_1" +source_instance_id = "cert-manager_certificate-renewal-control_PR-8258" +source_slug = "cert-manager_certificate-renewal-control_PR-8258" +docker_slug = "cert-manager_certificate-renewal-control_PR-8258" +dockerhub_image = "smartdub26/lolbench-linux:cert-manager_1-1.0.0" +project = "cert-manager" +repo = "cert-manager/cert-manager" +requirement_doc = "https://github.com/cert-manager/cert-manager/pull/8258" +pr_link = "https://github.com/cert-manager/cert-manager/pull/8258" +base_commit = "788c2f25fe3542e0163cd8d295efd215b3ccbe3b" +merge_commit = "1756a823b00d337d33058c528a8a3c349388e93f" +test_level = "system" +source_history_policy = "ancestors-only" +lolbench_test_modes = ["orig", "aug", "union"] +default_lolbench_suite = "union" +canonical_lolbench_suite = "union" +augmentation_available = true +verifier_network_policy = "public" +verifier_network_reason = "The Harbor verifier runs in a separate container and may use network access; migrated LoLBench verifier assets are mounted only in the verifier phase." + +[environment] +build_timeout_sec = 3600.0 +docker_image = "smartdub26/lolbench-linux:cert-manager_1-1.0.0" +network_mode = "public" +os = "linux" +cpus = 4 +memory_mb = 7168 +storage_mb = 20480 + +[agent] +timeout_sec = 21600.0 +user = "agent" +network_mode = "allowlist" +allowed_hosts = ["openrouter.ai", "api.openai.com", "api.anthropic.com"] + +[verifier] +timeout_sec = 7200.0 +user = "root" +environment_mode = "separate" +network_mode = "public" + +[verifier.env] +LOLBENCH_SUITE = "union" + +[verifier.environment] +docker_image = "smartdub26/lolbench-linux:cert-manager_1-1.0.0" +network_mode = "public" +os = "linux" +cpus = 4 +memory_mb = 7168 +storage_mb = 20480 diff --git a/cert-manager_1/tests/docker-compose.yaml b/cert-manager_1/tests/docker-compose.yaml new file mode 100644 index 0000000000000000000000000000000000000000..f5091b9298e127a1efbe69deeed699c907e025c1 --- /dev/null +++ b/cert-manager_1/tests/docker-compose.yaml @@ -0,0 +1,16 @@ +services: + main: + pull_policy: missing + volumes: + - type: bind + source: . + target: /tests + read_only: true + - type: bind + source: ./private + target: /opt/lolbench/private + read_only: true + - type: bind + source: ../solution + target: /solution + read_only: true diff --git a/cert-manager_1/tests/private/eval_tests.patch b/cert-manager_1/tests/private/eval_tests.patch new file mode 100644 index 0000000000000000000000000000000000000000..08608685f265239764e29c3d088a8ee39ad61c46 --- /dev/null +++ b/cert-manager_1/tests/private/eval_tests.patch @@ -0,0 +1,504 @@ +diff --git a/internal/apis/certmanager/validation/certificate_test.go b/internal/apis/certmanager/validation/certificate_test.go +index 427630001..ebb9aed0b 100644 +--- a/internal/apis/certmanager/validation/certificate_test.go ++++ b/internal/apis/certmanager/validation/certificate_test.go +@@ -890,6 +890,51 @@ func TestValidateCertificate(t *testing.T) { + }, + }, + }, ++ "invalid windows when renewal policy is disabled": { ++ cfg: &internalcmapi.Certificate{ ++ Spec: internalcmapi.CertificateSpec{ ++ CommonName: "testcn", ++ SecretName: "abc", ++ IssuerRef: validIssuerRef, ++ PrivateKey: &internalcmapi.CertificatePrivateKey{ ++ RotationPolicy: internalcmapi.RotationPolicyNever, ++ }, ++ Renewal: &internalcmapi.CertificateRenewal{ ++ Policy: internalcmapi.Disabled, ++ Windows: []internalcmapi.CertificateRenewalWindows{ ++ { ++ WindowDuration: &metav1.Duration{Duration: time.Hour * 2}, ++ Cron: "0 12 * * *", ++ }, ++ }, ++ }, ++ }, ++ }, ++ errs: []*field.Error{ ++ field.Forbidden(fldPath.Child("renewal", "windows"), "windows cannot be set when `renewal.policy` is set to Disabled"), ++ }, ++ }, ++ "valid renewal config with single window": { ++ cfg: &internalcmapi.Certificate{ ++ Spec: internalcmapi.CertificateSpec{ ++ CommonName: "testcn", ++ SecretName: "abc", ++ IssuerRef: validIssuerRef, ++ PrivateKey: &internalcmapi.CertificatePrivateKey{ ++ RotationPolicy: internalcmapi.RotationPolicyNever, ++ }, ++ Renewal: &internalcmapi.CertificateRenewal{ ++ Policy: internalcmapi.RenewBefore, ++ Windows: []internalcmapi.CertificateRenewalWindows{ ++ { ++ WindowDuration: &metav1.Duration{Duration: time.Hour * 2}, ++ Cron: "0 12 * * *", ++ }, ++ }, ++ }, ++ }, ++ }, ++ }, + } + for n, s := range scenarios { + t.Run(n, func(t *testing.T) { +diff --git a/pkg/controller/certificates/readiness/readiness_controller_test.go b/pkg/controller/certificates/readiness/readiness_controller_test.go +index 6fa353d70..bfb2d9555 100644 +--- a/pkg/controller/certificates/readiness/readiness_controller_test.go ++++ b/pkg/controller/certificates/readiness/readiness_controller_test.go +@@ -17,6 +17,7 @@ limitations under the License. + package readiness + + import ( ++ "fmt" + "testing" + "time" + +@@ -43,9 +44,9 @@ func policyEvaluatorBuilder(c cmapi.CertificateCondition) policyEvaluatorFunc { + } + + // renewalTimeBuilder returns a fake renewalTimeFunc for ReadinessController. +-func renewalTimeBuilder(rt *metav1.Time) pki.RenewalTimeFunc { +- return func(notBefore, notAfter time.Time, renewBefore *metav1.Duration, renewBeforePercentage *int32) *metav1.Time { +- return rt ++func renewalTimeBuilder(rt *metav1.Time, err error) pki.RenewalTimeFunc { ++ return func(notBefore, notAfter time.Time, renewBefore *metav1.Duration, renewBeforePercentage *int32, renewalSpec *cmapi.CertificateRenewal) (*metav1.Time, error) { ++ return rt, err + } + } + +@@ -100,6 +101,9 @@ func TestProcessItem(t *testing.T) { + // renewalTime will be the updated Certificate's status.renewalTime + renewalTime *metav1.Time + ++ // renewalTimeError will be the error that should be returned from the renewal function ++ renewalTimeError error ++ + wantsErr bool + }{ + "do nothing if an empty 'key' is used": {}, +@@ -240,6 +244,22 @@ func TestProcessItem(t *testing.T) { + secretShouldExist: true, + certShouldUpdate: false, + }, ++ "update status as not ready (Ready=False) with invalid renewal time": { ++ condition: cmapi.CertificateCondition{ ++ Type: cmapi.CertificateConditionReady, ++ Status: cmmeta.ConditionFalse, ++ Reason: policies.WindowError, ++ Message: "Could not calculate renewal time: cannot find a time with the given windows", ++ LastTransitionTime: &metaNow, ++ }, ++ cert: gen.CertificateFrom(cert), ++ certShouldUpdate: true, ++ secretShouldExist: true, ++ notAfter: func(m metav1.Time) *metav1.Time { return &m }(metav1.NewTime(now.Add(time.Hour * 2).Truncate(time.Second))), ++ notBefore: func(m metav1.Time) *metav1.Time { return &m }(metav1.NewTime(now.Truncate(time.Second))), ++ renewalTime: func() *metav1.Time { return nil }(), ++ renewalTimeError: fmt.Errorf("cannot find a time with the given windows"), ++ }, + } + for name, test := range tests { + t.Run(name, func(t *testing.T) { +@@ -282,7 +302,10 @@ func TestProcessItem(t *testing.T) { + w.controller.policyEvaluator = policyEvaluatorBuilder(test.condition) + + // Override controller's renewalTime func with a fake that returns test.renewalTime. +- w.controller.renewalTimeCalculator = renewalTimeBuilder(test.renewalTime) ++ w.controller.renewalTimeCalculator = renewalTimeBuilder(test.renewalTime, test.renewalTimeError) ++ ++ // Override controller's event recorder with a fake recorder to capture some events. ++ w.controller.recorder = new(testpkg.FakeRecorder) + + // If Certificate's status should be updated, + // build the expected Certificate and use it to set the expected update action on builder. +diff --git a/pkg/controller/certificates/trigger/trigger_controller_test.go b/pkg/controller/certificates/trigger/trigger_controller_test.go +index a850a344d..b83beead9 100644 +--- a/pkg/controller/certificates/trigger/trigger_controller_test.go ++++ b/pkg/controller/certificates/trigger/trigger_controller_test.go +@@ -71,7 +71,7 @@ func Test_controller_ProcessItem(t *testing.T) { + // For example, "Normal Issuing Re-issuance forced by unit test case" + // where 'Normal' is the event severity, 'Issuing' is the reason and the + // remainder is the message. +- wantEvent string ++ wantEvent []string + + // wantConditions is the expected set of conditions on the Certificate + // resource if an Update is made. +@@ -159,7 +159,7 @@ func Test_controller_ProcessItem(t *testing.T) { + return "ForceTriggered", "Re-issuance forced by unit test case", true + } + }, +- wantEvent: "Normal Issuing Re-issuance forced by unit test case", ++ wantEvent: []string{"Normal Issuing Re-issuance forced by unit test case"}, + wantConditions: []cmapi.CertificateCondition{{ + Type: "Issuing", + Status: "True", +@@ -213,7 +213,7 @@ func Test_controller_ProcessItem(t *testing.T) { + return "ForceTriggered", "Re-issuance forced by unit test case", true + } + }, +- wantEvent: "Normal Issuing Re-issuance forced by unit test case", ++ wantEvent: []string{"Normal Issuing Re-issuance forced by unit test case"}, + wantConditions: []cmapi.CertificateCondition{{ + Type: "Issuing", + Status: "True", +@@ -238,7 +238,7 @@ func Test_controller_ProcessItem(t *testing.T) { + return "ForceTriggered", "Re-issuance forced by unit test case", true + } + }, +- wantEvent: "Normal Issuing Re-issuance forced by unit test case", ++ wantEvent: []string{"Normal Issuing Re-issuance forced by unit test case"}, + wantConditions: []cmapi.CertificateCondition{{ + Type: "Issuing", + Status: "True", +@@ -293,7 +293,7 @@ func Test_controller_ProcessItem(t *testing.T) { + return "ForceTriggered", "Re-issuance forced by unit test case", true + } + }, +- wantEvent: "Normal Issuing Re-issuance forced by unit test case", ++ wantEvent: []string{"Normal Issuing Re-issuance forced by unit test case"}, + wantConditions: []cmapi.CertificateCondition{{ + Type: "Issuing", + Status: "True", +@@ -338,7 +338,7 @@ func Test_controller_ProcessItem(t *testing.T) { + return "ForceTriggered", "Re-issuance forced by unit test case", true + } + }, +- wantEvent: "Normal Issuing Re-issuance forced by unit test case", ++ wantEvent: []string{"Normal Issuing Re-issuance forced by unit test case"}, + wantConditions: []cmapi.CertificateCondition{{ + Type: "Issuing", + Status: "True", +@@ -378,6 +378,39 @@ func Test_controller_ProcessItem(t *testing.T) { + wantDataForCertificateCalled: false, + wantShouldReissueCalled: false, + }, ++ "should set Issuing=True when renewal time is not found because it doesn't match the windows configured": { ++ existingCertificate: gen.Certificate("cert-1", ++ gen.SetCertificateNamespace("testns"), ++ gen.SetCertificateGeneration(42), ++ gen.SetCertificateRenewalWindows([]cmapi.CertificateRenewalWindows{ ++ { ++ Timezone: time.UTC.String(), ++ WindowDuration: &metav1.Duration{Duration: time.Hour * 2}, ++ Cron: "0 10 * * *", ++ }, ++ }), ++ ), ++ wantShouldReissueCalled: true, ++ wantDataForCertificateCalled: true, ++ mockDataForCertificateReturn: policies.Input{}, ++ mockShouldReissue: func(t *testing.T) policies.Func { ++ return func(gotInput policies.Input) (string, string, bool) { ++ return policies.WindowError, "cannot find renewal time in window", true ++ } ++ }, ++ wantEvent: []string{ ++ "Warning WindowError Renewing certificate without satisfying renewal windows due to cannot find renewal time in window", ++ "Normal Issuing Renewing certificate without satisfying renewal windows at: ", ++ }, ++ wantConditions: []cmapi.CertificateCondition{{ ++ Type: "Issuing", ++ ObservedGeneration: 42, ++ Status: "True", ++ Reason: "Renewing", ++ Message: "Renewing certificate without satisfying renewal windows at: ", ++ LastTransitionTime: &fixedNow, ++ }}, ++ }, + } + for name, test := range tests { + t.Run(name, func(t *testing.T) { +@@ -441,8 +474,8 @@ func Test_controller_ProcessItem(t *testing.T) { + )), + ) + } +- if test.wantEvent != "" { +- builder.ExpectedEvents = []string{test.wantEvent} ++ if test.wantEvent != nil { ++ builder.ExpectedEvents = test.wantEvent + } + + builder.Start() +@@ -477,7 +510,7 @@ func Test_controller_ProcessItem(t *testing.T) { + } + + func Test_shouldBackoffReissuingOnFailure(t *testing.T) { +- clock := fakeclock.NewFakeClock(time.Date(2020, 11, 20, 16, 05, 00, 0000, time.UTC)) ++ clock := fakeclock.NewFakeClock(time.Date(2020, 11, 20, 16, 0o5, 0o0, 0o000, time.UTC)) + + // We don't need to full bundle, just a simple CertificateRequest. + createCertificateRequestOrPanic := func(crt *cmapi.Certificate) *cmapi.CertificateRequest { +@@ -845,6 +878,5 @@ func Test_shouldBackoffReissuingOnFailure(t *testing.T) { + assert.Equal(t, test.wantBackoff, gotBackoff) + assert.Equal(t, test.wantDelay, gotDelay) + }) +- + } + } +diff --git a/pkg/util/pki/renewaltime_test.go b/pkg/util/pki/renewaltime_test.go +index 7362cd7c6..ce552cf9f 100644 +--- a/pkg/util/pki/renewaltime_test.go ++++ b/pkg/util/pki/renewaltime_test.go +@@ -24,6 +24,8 @@ import ( + "github.com/stretchr/testify/assert" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/utils/ptr" ++ ++ apiv1 "github.com/cert-manager/cert-manager/pkg/apis/certmanager/v1" + ) + + func TestRenewalTime(t *testing.T) { +@@ -93,7 +95,8 @@ func TestRenewalTime(t *testing.T) { + } + for n, s := range tests { + t.Run(n, func(t *testing.T) { +- renewalTime := RenewalTime(s.notBefore, s.notAfter, s.renewBefore, s.renewBeforePct) ++ renewalTime, err := RenewalTime(s.notBefore, s.notAfter, s.renewBefore, s.renewBeforePct, nil) ++ assert.Nil(t, err) + assert.Equal(t, s.expectedRenewalTime, renewalTime, fmt.Sprintf("Expected renewal time: %v got: %v", s.expectedRenewalTime, renewalTime)) + }) + } +@@ -136,8 +139,206 @@ func TestRenewBefore(t *testing.T) { + } + for n, s := range tests { + t.Run(n, func(t *testing.T) { +- renewBefore := RenewBefore(duration, s.renewBefore, s.renewBeforePct) ++ renewBefore := desiredRenewalTime(duration, s.renewBefore, s.renewBeforePct) + assert.Equal(t, s.expectedRenewBefore, renewBefore, fmt.Sprintf("Expected renewBefore time: %v got: %v", s.expectedRenewBefore, renewBefore)) + }) + } + } ++ ++func midnightUTC(t time.Time) time.Time { ++ y, m, d := t.Date() ++ ++ return time.Date(y, m, d, 0, 0, 0, 0, time.UTC) ++} ++ ++func getNextWeekday(t time.Time, f func(time.Weekday) bool) time.Time { ++ for { ++ if f(t.Weekday()) { ++ return t ++ } ++ ++ t = t.AddDate(0, 0, 1) ++ } ++} ++ ++func mustLoc(t *testing.T, name string) *time.Location { ++ t.Helper() ++ loc, err := time.LoadLocation(name) ++ if err != nil { ++ t.Fatalf("failed to load location %v", err) ++ } ++ return loc ++} ++ ++// TestRenewalWithWindowsForRenewBefore tests renewal logic with windows for `RenewBefore` policy. ++func TestRenewalWithWindowsForRenewBefore(t *testing.T) { ++ type scenario struct { ++ notBefore time.Time ++ notAfter time.Time ++ targetRenewalTime time.Time ++ expectedRenewalTime time.Time ++ wantErr bool ++ renewalSpec *apiv1.CertificateRenewal ++ } ++ ++ now := time.Now().UTC().Truncate(time.Second) ++ future := midnightUTC(now.AddDate(0, 0, 5)) ++ denverMDT := midnightUTC(time.Date(2026, time.March, 8, 0, 0, 0, 0, time.UTC)) // Approximate daylight savings start time. This is intentionally set to 2026 to avoid future changes to DST patterns breaking tests. ++ denverMST := midnightUTC(time.Date(2026, time.November, 1, 0, 0, 0, 0, time.UTC)) // Approximate daylight savings end time ++ tests := map[string]scenario{ ++ "single window, renewal time within window": { ++ notAfter: future.Add(48 * time.Hour), ++ targetRenewalTime: future.Add(10*time.Hour + 30*time.Minute), ++ expectedRenewalTime: future.Add(24 * time.Hour).Add(-(13*time.Hour + 30*time.Minute)), ++ notBefore: midnightUTC(now.AddDate(0, 0, -10)), ++ renewalSpec: &apiv1.CertificateRenewal{ ++ Policy: apiv1.CertificateRenewalPolicyRenewBefore, ++ Windows: []apiv1.CertificateRenewalWindows{ ++ { ++ Timezone: time.UTC.String(), ++ WindowDuration: &metav1.Duration{Duration: time.Hour * 2}, ++ Cron: "0 10 * * *", ++ }, ++ }, ++ }, ++ }, ++ "single window, time outside window": { ++ notAfter: future.Add(48 * time.Hour), ++ targetRenewalTime: future.Add(13 * time.Hour), ++ notBefore: midnightUTC(now.AddDate(0, 0, -10)), ++ expectedRenewalTime: future.Add(24 * time.Hour).Add(10 * time.Hour), ++ renewalSpec: &apiv1.CertificateRenewal{ ++ Policy: apiv1.CertificateRenewalPolicyRenewBefore, ++ Windows: []apiv1.CertificateRenewalWindows{ ++ { ++ Timezone: time.UTC.String(), ++ WindowDuration: &metav1.Duration{Duration: time.Hour * 2}, ++ Cron: "0 10 * * *", ++ }, ++ }, ++ }, ++ }, ++ "single window, renewal time before the window": { ++ notBefore: midnightUTC(now.AddDate(0, 0, -10)), ++ notAfter: future.Add(24 * time.Hour), ++ targetRenewalTime: future.Add(9 * time.Hour), ++ expectedRenewalTime: future.Add(15 * time.Hour), ++ renewalSpec: &apiv1.CertificateRenewal{ ++ Policy: apiv1.CertificateRenewalPolicyRenewBefore, ++ Windows: []apiv1.CertificateRenewalWindows{ ++ { ++ Timezone: time.UTC.String(), ++ WindowDuration: &metav1.Duration{Duration: time.Hour * 2}, ++ Cron: "0 15 * * *", ++ }, ++ }, ++ }, ++ }, ++ "multiple windows, weekday and weekend": { ++ notBefore: midnightUTC(now.AddDate(0, 0, -10)), ++ notAfter: getNextWeekday(future, func(w time.Weekday) bool { ++ return w == time.Saturday ++ }).Add(24 * time.Hour), ++ targetRenewalTime: getNextWeekday(future, func(w time.Weekday) bool { ++ return w == time.Saturday ++ }).Add(6 * time.Hour), ++ expectedRenewalTime: getNextWeekday(future, func(w time.Weekday) bool { ++ return w == time.Saturday ++ }).Add(10 * time.Hour), ++ renewalSpec: &apiv1.CertificateRenewal{ ++ Policy: apiv1.CertificateRenewalPolicyRenewBefore, ++ Windows: []apiv1.CertificateRenewalWindows{ ++ { ++ Timezone: time.UTC.String(), ++ Cron: "0 23 * * 1-5", ++ WindowDuration: &metav1.Duration{Duration: time.Hour * 2}, ++ }, ++ { ++ Timezone: time.UTC.String(), ++ Cron: "0 10 * * 6,0", ++ WindowDuration: &metav1.Duration{Duration: time.Hour * 4}, ++ }, ++ }, ++ }, ++ }, ++ "single window, renewal time within window, different timezone": { ++ notAfter: future.Add(48 * time.Hour), ++ targetRenewalTime: time.Date(future.Year(), future.Month(), future.Day(), 10, 30, 0, 0, mustLoc(t, "America/Phoenix")), ++ expectedRenewalTime: time.Date(future.Year(), future.Month(), future.Day()+1, 0, 0, 0, 0, mustLoc(t, "America/Phoenix")).Add(-(13*time.Hour + 30*time.Minute)).UTC(), ++ notBefore: midnightUTC(now.AddDate(0, 0, -10)), ++ renewalSpec: &apiv1.CertificateRenewal{ ++ Policy: apiv1.CertificateRenewalPolicyRenewBefore, ++ Windows: []apiv1.CertificateRenewalWindows{ ++ { ++ // Choosing America/Phoenix to avoid DST issues in test ++ Timezone: "America/Phoenix", ++ Cron: "0 10 * * *", ++ WindowDuration: &metav1.Duration{Duration: time.Hour * 2}, ++ }, ++ }, ++ }, ++ }, ++ "single window, renewal time in daylight savings (on to off) time zone": { ++ notAfter: denverMST.Add(48 * time.Hour), ++ targetRenewalTime: time.Date(denverMST.Year(), denverMST.Month(), denverMST.Day()-1, 15, 30, 0, 0, mustLoc(t, "America/Denver")), ++ expectedRenewalTime: time.Date(denverMST.Year(), denverMST.Month(), denverMST.Day()-1, 0, 0, 0, 0, mustLoc(t, "America/Denver")).Add((35*time.Hour + 0*time.Minute)).UTC(), ++ notBefore: midnightUTC(denverMDT.AddDate(0, 0, -10)), ++ renewalSpec: &apiv1.CertificateRenewal{ ++ Policy: apiv1.CertificateRenewalPolicyRenewBefore, ++ Windows: []apiv1.CertificateRenewalWindows{ ++ { ++ Timezone: "America/Denver", ++ Cron: "0 10 * * *", ++ WindowDuration: &metav1.Duration{Duration: time.Hour * 2}, ++ }, ++ }, ++ }, ++ }, ++ "single window, renewal time outside of windows": { ++ notAfter: future.Add(24 * time.Hour), ++ targetRenewalTime: future.Add(13*time.Hour + 30*time.Minute), ++ expectedRenewalTime: future.Add(13*time.Hour + 30*time.Minute), ++ notBefore: midnightUTC(now.AddDate(0, 0, -10)), ++ wantErr: true, ++ renewalSpec: &apiv1.CertificateRenewal{ ++ Policy: apiv1.CertificateRenewalPolicyRenewBefore, ++ Windows: []apiv1.CertificateRenewalWindows{ ++ { ++ Timezone: time.UTC.String(), ++ Cron: "0 10 * * *", ++ WindowDuration: &metav1.Duration{Duration: time.Hour * 2}, ++ }, ++ }, ++ }, ++ }, ++ } ++ ++ for name, te := range tests { ++ renewBefore := te.notAfter.Sub(te.targetRenewalTime) ++ ++ res, err := RenewalTime(te.notBefore, te.notAfter, &metav1.Duration{Duration: renewBefore}, nil, te.renewalSpec) ++ ++ if te.wantErr { ++ assert.NotNil(t, err) ++ assert.Error(t, err) ++ ++ assert.Equal(t, te.expectedRenewalTime, res.Time, name) ++ return ++ } ++ ++ assert.Nil(t, err) ++ assert.Equal(t, te.expectedRenewalTime, res.Time, name) ++ } ++} ++ ++func TestRenewalWithDisable(t *testing.T) { ++ now := time.Now() ++ notAfter := now.Add(time.Hour * 24) ++ ++ res, err := RenewalTime(now, notAfter, &metav1.Duration{Duration: 20 * time.Hour}, nil, &apiv1.CertificateRenewal{ ++ Policy: apiv1.CertificateRenewalPolicyDisabled, ++ }) ++ ++ assert.Nil(t, err) ++ assert.Nil(t, res) ++} +diff --git a/test/unit/gen/certificate.go b/test/unit/gen/certificate.go +index 149857cf5..94dbf2570 100644 +--- a/test/unit/gen/certificate.go ++++ b/test/unit/gen/certificate.go +@@ -252,6 +252,17 @@ func AddCertificateAnnotations(annotations map[string]string) CertificateModifie + } + } + ++func SetCertificateRenewalWindows(windows []v1.CertificateRenewalWindows) CertificateModifier { ++ return func(crt *v1.Certificate) { ++ if crt.Spec.Renewal == nil { ++ crt.Spec.Renewal = new(v1.CertificateRenewal) ++ } ++ ++ crt.Spec.Renewal.Policy = v1.CertificateRenewalPolicyRenewBefore ++ crt.Spec.Renewal.Windows = windows ++ } ++} ++ + func AddCertificateLabels(labels map[string]string) CertificateModifier { + return func(crt *v1.Certificate) { + if crt.Labels == nil { diff --git a/cert-manager_1/tests/private/eval_tests_aug.patch b/cert-manager_1/tests/private/eval_tests_aug.patch new file mode 100644 index 0000000000000000000000000000000000000000..b20eb0e79965bb9506d01cfb546e3b7b8110f552 --- /dev/null +++ b/cert-manager_1/tests/private/eval_tests_aug.patch @@ -0,0 +1,878 @@ +diff --git a/internal/apis/certmanager/validation/certificate_renewal_aug_test.go b/internal/apis/certmanager/validation/certificate_renewal_aug_test.go +new file mode 100644 +index 000000000..111111111 +--- /dev/null ++++ b/internal/apis/certmanager/validation/certificate_renewal_aug_test.go +@@ -0,0 +1,128 @@ ++/* ++Copyright 2026 The cert-manager Authors. ++ ++Licensed under the Apache License, Version 2.0 (the "License"); ++you may not use this file except in compliance with the License. ++You may obtain a copy of the License at ++ ++ http://www.apache.org/licenses/LICENSE-2.0 ++ ++Unless required by applicable law or agreed to in writing, software ++distributed under the License is distributed on an "AS IS" BASIS, ++WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ++See the License for the specific language governing permissions and ++limitations under the License. ++*/ ++ ++package validation ++ ++import ( ++ "strings" ++ "testing" ++ "time" ++ ++ metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" ++ ++ internalcmapi "github.com/cert-manager/cert-manager/internal/apis/certmanager" ++) ++ ++func TestAugmentedValidateCertificateRenewalRules(t *testing.T) { ++ tests := map[string]struct { ++ renewal *internalcmapi.CertificateRenewal ++ want []string ++ }{ ++ "disabled policy rejects windows": { ++ renewal: &internalcmapi.CertificateRenewal{ ++ Policy: internalcmapi.Disabled, ++ Windows: []internalcmapi.CertificateRenewalWindows{{ ++ WindowDuration: &metav1.Duration{Duration: 2 * time.Hour}, ++ Cron: "0 23 * * 1-5", ++ Timezone: "UTC", ++ }}, ++ }, ++ want: []string{ ++ "spec.renewal.windows: Forbidden", ++ "windows cannot be set when `renewal.policy` is set to Disabled", ++ }, ++ }, ++ "unknown policy is rejected": { ++ renewal: &internalcmapi.CertificateRenewal{ ++ Policy: internalcmapi.CertificateRenewalPolicy("Always"), ++ }, ++ want: []string{ ++ "spec.renewal.policy: Unsupported value", ++ "Always", ++ }, ++ }, ++ "window duration is required": { ++ renewal: &internalcmapi.CertificateRenewal{ ++ Policy: internalcmapi.RenewBefore, ++ Windows: []internalcmapi.CertificateRenewalWindows{{ ++ Cron: "0 23 * * 1-5", ++ Timezone: "UTC", ++ }}, ++ }, ++ want: []string{ ++ "spec.renewal.windows[0].windowDuration: Required value", ++ "windowDuration must be specified", ++ }, ++ }, ++ "invalid timezone is rejected": { ++ renewal: &internalcmapi.CertificateRenewal{ ++ Policy: internalcmapi.RenewBefore, ++ Windows: []internalcmapi.CertificateRenewalWindows{{ ++ WindowDuration: &metav1.Duration{Duration: 2 * time.Hour}, ++ Cron: "0 23 * * 1-5", ++ Timezone: "Mars/Base", ++ }}, ++ }, ++ want: []string{ ++ "spec.renewal.windows[0].timezone: Invalid value", ++ "timezone must be IANA compliant", ++ }, ++ }, ++ "invalid cron is rejected": { ++ renewal: &internalcmapi.CertificateRenewal{ ++ Policy: internalcmapi.RenewBefore, ++ Windows: []internalcmapi.CertificateRenewalWindows{{ ++ WindowDuration: &metav1.Duration{Duration: 2 * time.Hour}, ++ Cron: "not a cron", ++ Timezone: "UTC", ++ }}, ++ }, ++ want: []string{ ++ "spec.renewal.windows[0].cron: Invalid value", ++ "invalid cron syntax", ++ }, ++ }, ++ } ++ ++ for name, test := range tests { ++ t.Run(name, func(t *testing.T) { ++ errs, warnings := ValidateCertificate(someAdmissionRequest, certificateWithRenewal(test.renewal)) ++ if len(warnings) != 0 { ++ t.Fatalf("unexpected warnings: %v", warnings) ++ } ++ got := errs.ToAggregate().Error() ++ for _, want := range test.want { ++ if !strings.Contains(got, want) { ++ t.Fatalf("expected validation error to contain %q, got %q", want, got) ++ } ++ } ++ }) ++ } ++} ++ ++func certificateWithRenewal(renewal *internalcmapi.CertificateRenewal) *internalcmapi.Certificate { ++ return &internalcmapi.Certificate{ ++ Spec: internalcmapi.CertificateSpec{ ++ CommonName: "example.com", ++ SecretName: "example-tls", ++ IssuerRef: validIssuerRef, ++ PrivateKey: &internalcmapi.CertificatePrivateKey{ ++ RotationPolicy: internalcmapi.RotationPolicyNever, ++ }, ++ Renewal: renewal, ++ }, ++ } ++} +diff --git a/internal/controller/certificates/policies/checks_renewal_aug_test.go b/internal/controller/certificates/policies/checks_renewal_aug_test.go +new file mode 100644 +index 000000000..111111111 +--- /dev/null ++++ b/internal/controller/certificates/policies/checks_renewal_aug_test.go +@@ -0,0 +1,81 @@ ++/* ++Copyright 2026 The cert-manager Authors. ++ ++Licensed under the Apache License, Version 2.0 (the "License"); ++you may not use this file except in compliance with the License. ++You may obtain a copy of the License at ++ ++ http://www.apache.org/licenses/LICENSE-2.0 ++ ++Unless required by applicable law or agreed to in writing, software ++distributed under the License is distributed on an "AS IS" BASIS, ++WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ++See the License for the specific language governing permissions and ++limitations under the License. ++*/ ++ ++package policies ++ ++import ( ++ "strings" ++ "testing" ++ "time" ++ ++ corev1 "k8s.io/api/core/v1" ++ metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" ++ fakeclock "k8s.io/utils/clock/testing" ++ ++ cmapi "github.com/cert-manager/cert-manager/pkg/apis/certmanager/v1" ++ cmmeta "github.com/cert-manager/cert-manager/pkg/apis/meta/v1" ++ testcrypto "github.com/cert-manager/cert-manager/test/unit/crypto" ++) ++ ++func TestAugmentedCurrentCertificateNearingExpiryHonorsRenewalWindows(t *testing.T) { ++ now := time.Date(2026, time.January, 1, 12, 0, 0, 0, time.UTC) ++ clock := fakeclock.NewFakeClock(now) ++ key := testcrypto.MustCreatePEMPrivateKey(t) ++ certificate := &cmapi.Certificate{ ++ Spec: cmapi.CertificateSpec{ ++ CommonName: "example.com", ++ IssuerRef: cmmeta.IssuerReference{ ++ Name: "testissuer", ++ Kind: "IssuerKind", ++ Group: "group.example.com", ++ }, ++ RenewBefore: &metav1.Duration{Duration: time.Hour}, ++ Renewal: &cmapi.CertificateRenewal{ ++ Policy: cmapi.CertificateRenewalPolicyRenewBefore, ++ Windows: []cmapi.CertificateRenewalWindows{{ ++ Timezone: "UTC", ++ WindowDuration: &metav1.Duration{Duration: 10 * time.Minute}, ++ Cron: "0 0 * * *", ++ }}, ++ }, ++ }, ++ Status: cmapi.CertificateStatus{ ++ RenewalTime: &metav1.Time{Time: now.Add(-30 * time.Minute)}, ++ }, ++ } ++ secret := &corev1.Secret{ ++ Data: map[string][]byte{ ++ corev1.TLSPrivateKeyKey: key, ++ corev1.TLSCertKey: testcrypto.MustCreateCertWithNotBeforeAfter(t, key, ++ &cmapi.Certificate{Spec: cmapi.CertificateSpec{CommonName: "example.com"}}, ++ now.Add(-time.Hour), ++ now.Add(30*time.Minute), ++ ), ++ }, ++ } ++ ++ reason, message, reissue := CurrentCertificateNearingExpiry(clock)(Input{ ++ Certificate: certificate, ++ Secret: secret, ++ }) ++ ++ if reason != WindowError || !reissue { ++ t.Fatalf("expected WindowError reissue, got reason=%q reissue=%v message=%q", reason, reissue, message) ++ } ++ if !strings.Contains(message, "cannot find a time with the given windows") { ++ t.Fatalf("expected window calculation error, got %q", message) ++ } ++} +diff --git a/pkg/api/util/names_aug_test.go b/pkg/api/util/names_aug_test.go +new file mode 100644 +index 000000000..111111111 +--- /dev/null ++++ b/pkg/api/util/names_aug_test.go +@@ -0,0 +1,34 @@ ++/* ++Copyright 2026 The cert-manager Authors. ++ ++Licensed under the Apache License, Version 2.0 (the "License"); ++you may not use this file except in compliance with the License. ++You may obtain a copy of the License at ++ ++ http://www.apache.org/licenses/LICENSE-2.0 ++ ++Unless required by applicable law or agreed to in writing, software ++distributed under the License is distributed on an "AS IS" BASIS, ++WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ++See the License for the specific language governing permissions and ++limitations under the License. ++*/ ++ ++package util ++ ++import "testing" ++ ++func TestAugmentedDNSSafeShortenToNCharacters(t *testing.T) { ++ if got := DNSSafeShortenToNCharacters("abc.def", 4); got != "abc" { ++ t.Fatalf("expected trailing separator to be trimmed, got %q", got) ++ } ++ if got := DNSSafeShortenToNCharacters("abc", 10); got != "abc" { ++ t.Fatalf("expected short name to remain unchanged, got %q", got) ++ } ++} ++ ++func TestAugmentedSecureNameRejectsTooShortLimit(t *testing.T) { ++ if _, err := ComputeSecureUniqueDeterministicNameFromData("stable-name", 63); err == nil { ++ t.Fatal("expected maxNameLength below hash length to be rejected") ++ } ++} +diff --git a/pkg/util/pki/renewaltime_aug_test.go b/pkg/util/pki/renewaltime_aug_test.go +new file mode 100644 +index 000000000..111111111 +--- /dev/null ++++ b/pkg/util/pki/renewaltime_aug_test.go +@@ -0,0 +1,145 @@ ++/* ++Copyright 2026 The cert-manager Authors. ++ ++Licensed under the Apache License, Version 2.0 (the "License"); ++you may not use this file except in compliance with the License. ++You may obtain a copy of the License at ++ ++ http://www.apache.org/licenses/LICENSE-2.0 ++ ++Unless required by applicable law or agreed to in writing, software ++distributed under the License is distributed on an "AS IS" BASIS, ++WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ++See the License for the specific language governing permissions and ++limitations under the License. ++*/ ++ ++package pki ++ ++import ( ++ "strings" ++ "testing" ++ "time" ++ ++ metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" ++ ++ apiv1 "github.com/cert-manager/cert-manager/pkg/apis/certmanager/v1" ++) ++ ++func TestAugmentedRenewalTimeWindowBoundaries(t *testing.T) { ++ tests := map[string]struct { ++ notBefore time.Time ++ notAfter time.Time ++ desired time.Time ++ windows []apiv1.CertificateRenewalWindows ++ want time.Time ++ }{ ++ "desired exactly at previous window end is accepted": { ++ notBefore: utc(2026, time.January, 1, 0, 0), ++ notAfter: utc(2026, time.January, 1, 5, 0), ++ desired: utc(2026, time.January, 1, 2, 0), ++ windows: []apiv1.CertificateRenewalWindows{{ ++ Timezone: "UTC", ++ WindowDuration: &metav1.Duration{Duration: time.Hour}, ++ Cron: "0 1 * * *", ++ }}, ++ want: utc(2026, time.January, 1, 2, 0), ++ }, ++ "previous compliant boundary is preferred over a later window": { ++ notBefore: utc(2026, time.January, 1, 0, 0), ++ notAfter: utc(2026, time.January, 1, 5, 0), ++ desired: utc(2026, time.January, 1, 2, 0), ++ windows: []apiv1.CertificateRenewalWindows{ ++ { ++ Timezone: "UTC", ++ WindowDuration: &metav1.Duration{Duration: time.Hour}, ++ Cron: "0 1 * * *", ++ }, ++ { ++ Timezone: "UTC", ++ WindowDuration: &metav1.Duration{Duration: time.Hour}, ++ Cron: "0 4 * * *", ++ }, ++ }, ++ want: utc(2026, time.January, 1, 2, 0), ++ }, ++ "desired exactly at window start is accepted": { ++ notBefore: utc(2026, time.January, 1, 0, 0), ++ notAfter: utc(2026, time.January, 1, 6, 0), ++ desired: utc(2026, time.January, 1, 3, 0), ++ windows: []apiv1.CertificateRenewalWindows{{ ++ Timezone: "UTC", ++ WindowDuration: &metav1.Duration{Duration: time.Hour}, ++ Cron: "0 3 * * *", ++ }}, ++ want: utc(2026, time.January, 1, 3, 0), ++ }, ++ "desired exactly at recurring window start is accepted": { ++ notBefore: utc(2026, time.January, 1, 0, 0), ++ notAfter: utc(2026, time.January, 1, 6, 0), ++ desired: utc(2026, time.January, 1, 3, 0), ++ windows: []apiv1.CertificateRenewalWindows{{ ++ Timezone: "UTC", ++ WindowDuration: &metav1.Duration{Duration: 10 * time.Minute}, ++ Cron: "0 * * * *", ++ }}, ++ want: utc(2026, time.January, 1, 3, 0), ++ }, ++ "timezone windows are evaluated in the configured location": { ++ notBefore: utc(2026, time.January, 1, 0, 0), ++ notAfter: utc(2026, time.January, 1, 18, 0), ++ desired: utc(2026, time.January, 1, 14, 0), ++ windows: []apiv1.CertificateRenewalWindows{{ ++ Timezone: "America/New_York", ++ WindowDuration: &metav1.Duration{Duration: 2 * time.Hour}, ++ Cron: "0 9 * * *", ++ }}, ++ want: utc(2026, time.January, 1, 14, 0), ++ }, ++ } ++ ++ for name, test := range tests { ++ t.Run(name, func(t *testing.T) { ++ got, err := RenewalTime(test.notBefore, test.notAfter, renewBeforeFor(test.notAfter, test.desired), nil, &apiv1.CertificateRenewal{ ++ Policy: apiv1.CertificateRenewalPolicyRenewBefore, ++ Windows: test.windows, ++ }) ++ if err != nil { ++ t.Fatalf("unexpected renewal error: %v", err) ++ } ++ if got == nil || !got.Time.Equal(test.want) { ++ t.Fatalf("expected renewal at %s, got %v", test.want, got) ++ } ++ }) ++ } ++} ++ ++func TestAugmentedRenewalTimeDisabledAndUnsupportedPolicy(t *testing.T) { ++ notBefore := utc(2026, time.January, 1, 0, 0) ++ notAfter := utc(2026, time.January, 2, 0, 0) ++ ++ got, err := RenewalTime(notBefore, notAfter, &metav1.Duration{Duration: time.Hour}, nil, &apiv1.CertificateRenewal{ ++ Policy: apiv1.CertificateRenewalPolicyDisabled, ++ }) ++ if err != nil { ++ t.Fatalf("disabled renewal returned error: %v", err) ++ } ++ if got != nil { ++ t.Fatalf("disabled renewal should not schedule a renewal time, got %v", got) ++ } ++ ++ got, err = RenewalTime(notBefore, notAfter, &metav1.Duration{Duration: time.Hour}, nil, &apiv1.CertificateRenewal{ ++ Policy: apiv1.CertificateRenewalPolicy("Always"), ++ }) ++ if err == nil || !strings.Contains(err.Error(), "unsupported renewal policy: Always") { ++ t.Fatalf("expected unsupported policy error, got time=%v err=%v", got, err) ++ } ++} ++ ++func utc(year int, month time.Month, day, hour, minute int) time.Time { ++ return time.Date(year, month, day, hour, minute, 0, 0, time.UTC) ++} ++ ++func renewBeforeFor(notAfter, desired time.Time) *metav1.Duration { ++ return &metav1.Duration{Duration: notAfter.Sub(desired)} ++} +diff --git a/internal/apis/certmanager/conversion_renewal_aug_test.go b/internal/apis/certmanager/conversion_renewal_aug_test.go +new file mode 100644 +index 0000000..07bd041 +--- /dev/null ++++ b/internal/apis/certmanager/conversion_renewal_aug_test.go +@@ -0,0 +1,78 @@ ++/* ++Copyright 2026 The cert-manager Authors. ++ ++Licensed under the Apache License, Version 2.0 (the "License"); ++you may not use this file except in compliance with the License. ++You may obtain a copy of the License at ++ ++ http://www.apache.org/licenses/LICENSE-2.0 ++ ++Unless required by applicable law or agreed to in writing, software ++distributed under the License is distributed on an "AS IS" BASIS, ++WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ++See the License for the specific language governing permissions and ++limitations under the License. ++*/ ++ ++package certmanager_test ++ ++// Augmented suite extension (lolbench-aug). The renewal spec is part of the ++// public Certificate API: converting a v1 Certificate to the internal hub ++// version and back must preserve the renewal policy and windows untouched. ++ ++import ( ++ "reflect" ++ "testing" ++ "time" ++ ++ metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" ++ ++ internalcm "github.com/cert-manager/cert-manager/internal/apis/certmanager" ++ internalv1 "github.com/cert-manager/cert-manager/internal/apis/certmanager/v1" ++ cmmeta "github.com/cert-manager/cert-manager/pkg/apis/meta/v1" ++ apiv1 "github.com/cert-manager/cert-manager/pkg/apis/certmanager/v1" ++) ++ ++func TestAugmentedRenewalSpecConvertsRoundTrip(t *testing.T) { ++ in := &apiv1.Certificate{ ++ ObjectMeta: metav1.ObjectMeta{Name: "aug-conv"}, ++ Spec: apiv1.CertificateSpec{ ++ SecretName: "aug-conv-secret", ++ IssuerRef: cmmeta.IssuerReference{Name: "issuer"}, ++ CommonName: "example.test", ++ DNSNames: []string{"a.example.test", "b.example.test"}, ++ Duration: &metav1.Duration{Duration: 90 * 24 * time.Hour}, ++ Renewal: &apiv1.CertificateRenewal{ ++ Policy: apiv1.CertificateRenewalPolicyRenewBefore, ++ Windows: []apiv1.CertificateRenewalWindows{ ++ { ++ Timezone: "UTC", ++ WindowDuration: &metav1.Duration{Duration: 2 * time.Hour}, ++ Cron: "0 1 * * *", ++ }, ++ { ++ Timezone: "Asia/Shanghai", ++ WindowDuration: &metav1.Duration{Duration: 30 * time.Minute}, ++ Cron: "*/15 8-18 * * MON-FRI", ++ }, ++ }, ++ }, ++ }, ++ } ++ ++ internal := &internalcm.Certificate{} ++ if err := internalv1.Convert_v1_Certificate_To_certmanager_Certificate(in, internal, nil); err != nil { ++ t.Fatalf("v1 -> internal: %v", err) ++ } ++ if internal.Spec.Renewal == nil || len(internal.Spec.Renewal.Windows) != 2 { ++ t.Fatalf("internal renewal not converted: %+v", internal.Spec.Renewal) ++ } ++ ++ out := &apiv1.Certificate{} ++ if err := internalv1.Convert_certmanager_Certificate_To_v1_Certificate(internal, out, nil); err != nil { ++ t.Fatalf("internal -> v1: %v", err) ++ } ++ if !reflect.DeepEqual(in.Spec.Renewal, out.Spec.Renewal) { ++ t.Fatalf("renewal spec did not round-trip:\n in: %+v\nout: %+v", in.Spec.Renewal, out.Spec.Renewal) ++ } ++} +diff --git a/pkg/apis/certmanager/v1/deepcopy_renewal_aug_test.go b/pkg/apis/certmanager/v1/deepcopy_renewal_aug_test.go +new file mode 100644 +index 0000000..47e9696 +--- /dev/null ++++ b/pkg/apis/certmanager/v1/deepcopy_renewal_aug_test.go +@@ -0,0 +1,88 @@ ++/* ++Copyright 2026 The cert-manager Authors. ++ ++Licensed under the Apache License, Version 2.0 (the "License"); ++you may not use this file except in compliance with the License. ++You may obtain a copy of the License at ++ ++ http://www.apache.org/licenses/LICENSE-2.0 ++ ++Unless required by applicable law or agreed to in writing, software ++distributed under the License is distributed on an "AS IS" BASIS, ++WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ++See the License for the specific language governing permissions and ++limitations under the License. ++*/ ++ ++package v1_test ++ ++// Augmented suite extension (lolbench-aug). Deep copies of the public renewal ++// API types must be equal to and independent of their originals. ++ ++import ( ++ "reflect" ++ "testing" ++ "time" ++ ++ metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" ++ ++ apiv1 "github.com/cert-manager/cert-manager/pkg/apis/certmanager/v1" ++) ++ ++func TestAugmentedRenewalDeepCopyIsEqualAndIndependent(t *testing.T) { ++ orig := &apiv1.CertificateRenewal{ ++ Policy: apiv1.CertificateRenewalPolicyRenewBefore, ++ Windows: []apiv1.CertificateRenewalWindows{ ++ { ++ Timezone: "UTC", ++ WindowDuration: &metav1.Duration{Duration: time.Hour}, ++ Cron: "0 2 * * *", ++ }, ++ }, ++ } ++ ++ cp := orig.DeepCopy() ++ if !reflect.DeepEqual(orig, cp) { ++ t.Fatalf("deep copy differs:\norig: %+v\ncopy: %+v", orig, cp) ++ } ++ ++ // Mutating the copy must not affect the original. ++ cp.Policy = apiv1.CertificateRenewalPolicyDisabled ++ cp.Windows[0].Cron = "@daily" ++ cp.Windows[0].WindowDuration.Duration = 5 * time.Minute ++ if orig.Policy != apiv1.CertificateRenewalPolicyRenewBefore || orig.Windows[0].Cron != "0 2 * * *" || ++ orig.Windows[0].WindowDuration.Duration != time.Hour { ++ t.Fatalf("deep copy is not independent: %+v", orig) ++ } ++ ++ // Certificate-level deep copy carries the renewal subtree. ++ cert := &apiv1.Certificate{Spec: apiv1.CertificateSpec{Renewal: orig}} ++ certCopy := cert.DeepCopy() ++ if !reflect.DeepEqual(cert.Spec.Renewal, certCopy.Spec.Renewal) { ++ t.Fatalf("certificate deep copy lost renewal: %+v", certCopy.Spec.Renewal) ++ } ++ certCopy.Spec.Renewal.Windows[0].Timezone = "Asia/Shanghai" ++ if cert.Spec.Renewal.Windows[0].Timezone != "UTC" { ++ t.Fatalf("certificate deep copy is not independent") ++ } ++} ++ ++func TestAugmentedRenewalDeepCopyHandlesSparseShapes(t *testing.T) { ++ // Nil window duration, empty windows and a nil renewal all copy safely. ++ sparse := &apiv1.CertificateRenewal{ ++ Policy: apiv1.CertificateRenewalPolicyDisabled, ++ Windows: []apiv1.CertificateRenewalWindows{{Timezone: "UTC", Cron: "@daily"}}, ++ } ++ cp := sparse.DeepCopy() ++ if !reflect.DeepEqual(sparse, cp) { ++ t.Fatalf("sparse deep copy differs: %+v vs %+v", sparse, cp) ++ } ++ empty := &apiv1.CertificateRenewal{Policy: apiv1.CertificateRenewalPolicyRenewBefore} ++ if got := empty.DeepCopy(); !reflect.DeepEqual(empty, got) { ++ t.Fatalf("empty deep copy differs") ++ } ++ cert := &apiv1.Certificate{} ++ if got := cert.DeepCopy(); got.Spec.Renewal != nil { ++ t.Fatalf("nil renewal must stay nil, got %+v", got.Spec.Renewal) ++ } ++} +diff --git a/pkg/util/pki/renewaltime_cron_matrix_aug_test.go b/pkg/util/pki/renewaltime_cron_matrix_aug_test.go +new file mode 100644 +index 0000000..d939d25 +--- /dev/null ++++ b/pkg/util/pki/renewaltime_cron_matrix_aug_test.go +@@ -0,0 +1,282 @@ ++/* ++Copyright 2026 The cert-manager Authors. ++ ++Licensed under the Apache License, Version 2.0 (the "License"); ++you may not use this file except in compliance with the License. ++You may obtain a copy of the License at ++ ++ http://www.apache.org/licenses/LICENSE-2.0 ++ ++Unless required by applicable law or agreed to in writing, software ++distributed under the License is distributed on an "AS IS" BASIS, ++WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ++See the License for the specific language governing permissions and ++limitations under the License. ++*/ ++ ++package pki ++ ++// Augmented suite extension (lolbench-aug). The requirement's renewal windows ++// accept standard cron expressions with descriptors, names, ranges, steps, ++// lists, day-of-month/day-of-week combinations and IANA timezones; the renewal ++// time keeps the desired time when it falls inside a window and otherwise ++// delays to the next window opening after it (never renewing earlier); ++// boundaries beyond the certificate lifetime are an error. This matrix drives those grammar and scheduling behaviors through the ++// same public RenewalTime surface used by the existing augmented tests. ++ ++import ( ++ "testing" ++ "time" ++ ++ metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" ++ ++ apiv1 "github.com/cert-manager/cert-manager/pkg/apis/certmanager/v1" ++) ++ ++func mxUTC(year int, month time.Month, day, hour, minute int) time.Time { ++ return time.Date(year, month, day, hour, minute, 0, 0, time.UTC) ++} ++ ++func mxWindow(cron, tz string, d time.Duration) apiv1.CertificateRenewalWindows { ++ return apiv1.CertificateRenewalWindows{ ++ Timezone: tz, ++ WindowDuration: &metav1.Duration{Duration: d}, ++ Cron: cron, ++ } ++} ++ ++// mxRenewBefore yields a renewBefore that puts the desired renewal time at ++// the given instant for the given notAfter. ++func mxRenewBefore(notAfter, desired time.Time) *metav1.Duration { ++ return &metav1.Duration{Duration: notAfter.Sub(desired)} ++} ++ ++func TestAugmentedCronMatrixGrammarBoundaries(t *testing.T) { ++ day := 24 * time.Hour ++ tests := map[string]struct { ++ notBefore time.Time ++ notAfter time.Time ++ desired time.Time ++ window apiv1.CertificateRenewalWindows ++ want time.Time ++ }{ ++ "descriptor @daily delays to the next midnight": { ++ notBefore: mxUTC(2026, time.March, 1, 0, 0), ++ notAfter: mxUTC(2026, time.March, 20, 0, 0), ++ desired: mxUTC(2026, time.March, 10, 15, 30), ++ window: mxWindow("@daily", "UTC", 2*time.Hour), ++ want: mxUTC(2026, time.March, 11, 0, 0), ++ }, ++ "descriptor @hourly picks previous hour": { ++ notBefore: mxUTC(2026, time.March, 1, 0, 0), ++ notAfter: mxUTC(2026, time.March, 20, 0, 0), ++ desired: mxUTC(2026, time.March, 10, 15, 30), ++ window: mxWindow("@hourly", "UTC", 30*time.Minute), ++ want: mxUTC(2026, time.March, 10, 15, 30), ++ }, ++ "descriptor @weekly delays to the next Sunday": { ++ notBefore: mxUTC(2026, time.March, 1, 0, 0), ++ notAfter: mxUTC(2026, time.April, 1, 0, 0), ++ desired: mxUTC(2026, time.March, 11, 12, 0), // Wednesday ++ window: mxWindow("@weekly", "UTC", 6 * time.Hour), ++ want: mxUTC(2026, time.March, 15, 0, 0), // next Sunday start ++ }, ++ "descriptor @monthly delays to the next month start": { ++ notBefore: mxUTC(2026, time.January, 1, 0, 0), ++ notAfter: mxUTC(2026, time.June, 1, 0, 0), ++ desired: mxUTC(2026, time.March, 15, 0, 0), ++ window: mxWindow("@monthly", "UTC", day), ++ want: mxUTC(2026, time.April, 1, 0, 0), ++ }, ++ "descriptor @yearly delays to the next January first": { ++ notBefore: mxUTC(2025, time.June, 1, 0, 0), ++ notAfter: mxUTC(2027, time.June, 1, 0, 0), ++ desired: mxUTC(2026, time.August, 15, 0, 0), ++ window: mxWindow("@yearly", "UTC", 7 * day), ++ want: mxUTC(2027, time.January, 1, 0, 0), ++ }, ++ "named month and weekday with range": { ++ notBefore: mxUTC(2026, time.January, 1, 0, 0), ++ notAfter: mxUTC(2026, time.December, 1, 0, 0), ++ // 09:00 on Mon-Fri in March; desired Saturday noon delays to Monday 09:00. ++ desired: mxUTC(2026, time.March, 14, 12, 0), ++ window: mxWindow("0 9 * MAR MON-FRI", "UTC", 4*time.Hour), ++ want: mxUTC(2026, time.March, 16, 9, 0), ++ }, ++ "step minutes within hour": { ++ notBefore: mxUTC(2026, time.March, 1, 0, 0), ++ notAfter: mxUTC(2026, time.March, 20, 0, 0), ++ desired: mxUTC(2026, time.March, 10, 10, 23), ++ window: mxWindow("*/15 * * * *", "UTC", 10*time.Minute), ++ want: mxUTC(2026, time.March, 10, 10, 23), ++ }, ++ "stepped range of hours": { ++ notBefore: mxUTC(2026, time.March, 1, 0, 0), ++ notAfter: mxUTC(2026, time.March, 20, 0, 0), ++ desired: mxUTC(2026, time.March, 10, 13, 0), ++ window: mxWindow("0 8-18/4 * * *", "UTC", time.Hour), ++ want: mxUTC(2026, time.March, 10, 13, 0), ++ }, ++ "list of days of month": { ++ notBefore: mxUTC(2026, time.January, 1, 0, 0), ++ notAfter: mxUTC(2026, time.June, 1, 0, 0), ++ desired: mxUTC(2026, time.March, 20, 0, 0), ++ window: mxWindow("0 6 1,15,28 * *", "UTC", 12*time.Hour), ++ want: mxUTC(2026, time.March, 28, 6, 0), ++ }, ++ "dom OR dow semantics picks the closest of either": { ++ notBefore: mxUTC(2026, time.January, 1, 0, 0), ++ notAfter: mxUTC(2026, time.June, 1, 0, 0), ++ // 2026-03-12 is a Thursday; spec fires on the 1st OR on Mondays, so the ++ // next boundary is Monday 2026-03-16. ++ desired: mxUTC(2026, time.March, 12, 12, 0), ++ window: mxWindow("0 0 1 * MON", "UTC", 6*time.Hour), ++ want: mxUTC(2026, time.March, 16, 0, 0), ++ }, ++ "end of month wrap to previous month": { ++ notBefore: mxUTC(2026, time.January, 1, 0, 0), ++ notAfter: mxUTC(2026, time.June, 1, 0, 0), ++ // Day 31 does not exist in April; the next boundary after May 5th is May 31st. ++ desired: mxUTC(2026, time.May, 5, 0, 0), ++ window: mxWindow("0 0 31 * *", "UTC", 24*time.Hour), ++ want: mxUTC(2026, time.May, 31, 0, 0), ++ }, ++ ++ "IANA timezone shifts the boundary": { ++ notBefore: mxUTC(2026, time.March, 1, 0, 0), ++ notAfter: mxUTC(2026, time.March, 20, 0, 0), ++ // 00:00 in Shanghai == 16:00 UTC the previous day; next boundary after the desired time. ++ desired: mxUTC(2026, time.March, 10, 20, 0), ++ window: mxWindow("0 0 * * *", "Asia/Shanghai", 2*time.Hour), ++ want: mxUTC(2026, time.March, 11, 16, 0), ++ }, ++ "DST spring-forward day in New York": { ++ notBefore: mxUTC(2026, time.March, 1, 0, 0), ++ notAfter: mxUTC(2026, time.March, 20, 0, 0), ++ // On the spring-forward day the 01:30 window [06:30,07:30] UTC ends before ++ // the desired 09:00 UTC; the next 01:30 boundary is in EDT = 05:30 UTC. ++ desired: mxUTC(2026, time.March, 8, 9, 0), ++ window: mxWindow("30 1 * * *", "America/New_York", time.Hour), ++ want: mxUTC(2026, time.March, 9, 5, 30), ++ }, ++ } ++ for name, test := range tests { ++ t.Run(name, func(t *testing.T) { ++ renewal := &apiv1.CertificateRenewal{ ++ Policy: apiv1.CertificateRenewalPolicyRenewBefore, ++ Windows: []apiv1.CertificateRenewalWindows{test.window}, ++ } ++ got, err := RenewalTime(test.notBefore, test.notAfter, mxRenewBefore(test.notAfter, test.desired), nil, renewal) ++ if err != nil { ++ t.Fatalf("unexpected error: %v", err) ++ } ++ if got == nil { ++ t.Fatalf("expected a renewal time, got nil") ++ } ++ if !got.Time.Equal(test.want) { ++ t.Fatalf("want %v, got %v", test.want, got.Time) ++ } ++ }) ++ } ++} ++ ++func TestAugmentedCronMatrixMultiWindowSelection(t *testing.T) { ++ // With several windows, the latest compliant boundary across all of them ++ // wins; windows whose boundaries all fall outside the certificate ++ // lifetime contribute nothing. ++ notBefore := mxUTC(2026, time.March, 1, 0, 0) ++ notAfter := mxUTC(2026, time.March, 20, 0, 0) ++ desired := mxUTC(2026, time.March, 10, 11, 45) ++ renewal := &apiv1.CertificateRenewal{ ++ Policy: apiv1.CertificateRenewalPolicyRenewBefore, ++ Windows: []apiv1.CertificateRenewalWindows{ ++ mxWindow("0 3 * * *", "UTC", time.Hour), // 03:00 daily ++ mxWindow("30 11 * * *", "UTC", time.Hour), // 11:30 daily <- latest before 11:45 ++ mxWindow("0 9 * * MON", "UTC", time.Hour), // Mondays 09:00 ++ mxWindow("0 0 1 JAN *", "UTC", time.Hour), // outside lifetime ++ }, ++ } ++ got, err := RenewalTime(notBefore, notAfter, mxRenewBefore(notAfter, desired), nil, renewal) ++ if err != nil { ++ t.Fatalf("unexpected error: %v", err) ++ } ++ want := mxUTC(2026, time.March, 10, 11, 45) // desired sits inside the 11:30+1h window ++ if got == nil || !got.Time.Equal(want) { ++ t.Fatalf("want %v, got %v", want, got) ++ } ++} ++ ++func TestAugmentedCronMatrixBoundaryBeyondLifetimeErrors(t *testing.T) { ++ // The only boundary of this spec (Dec 25) lies beyond the certificate ++ // lifetime relative to the desired time, so no compliant renewal time ++ // exists and the calculation must error. ++ notBefore := mxUTC(2025, time.June, 1, 0, 0) ++ notAfter := mxUTC(2026, time.June, 1, 0, 0) ++ desired := mxUTC(2026, time.January, 10, 0, 0) ++ renewal := &apiv1.CertificateRenewal{ ++ Policy: apiv1.CertificateRenewalPolicyRenewBefore, ++ Windows: []apiv1.CertificateRenewalWindows{mxWindow("0 12 25 DEC *", "UTC", 24*time.Hour)}, ++ } ++ if _, err := RenewalTime(notBefore, notAfter, mxRenewBefore(notAfter, desired), nil, renewal); err == nil { ++ t.Fatalf("expected an error for a window with no boundary inside the lifetime") ++ } ++} ++ ++func TestAugmentedCronMatrixExactNextBoundaryIsUsed(t *testing.T) { ++ // A desired time falling just before a window opening must move exactly to ++ // that opening (not skip past it), and a desired time exactly at a window ++ // opening is already compliant. ++ notBefore := mxUTC(2026, time.March, 1, 0, 0) ++ notAfter := mxUTC(2026, time.March, 20, 0, 0) ++ renewal := &apiv1.CertificateRenewal{ ++ Policy: apiv1.CertificateRenewalPolicyRenewBefore, ++ Windows: []apiv1.CertificateRenewalWindows{mxWindow("@daily", "UTC", 10*time.Minute)}, ++ } ++ ++ justBefore := mxUTC(2026, time.March, 9, 23, 59) ++ got, err := RenewalTime(notBefore, notAfter, mxRenewBefore(notAfter, justBefore), nil, renewal) ++ if err != nil { ++ t.Fatalf("unexpected error: %v", err) ++ } ++ if want := mxUTC(2026, time.March, 10, 0, 0); got == nil || !got.Time.Equal(want) { ++ t.Fatalf("want %v, got %v", want, got) ++ } ++ ++ atBoundary := mxUTC(2026, time.March, 10, 0, 0) ++ got2, err := RenewalTime(notBefore, notAfter, mxRenewBefore(notAfter, atBoundary), nil, renewal) ++ if err != nil { ++ t.Fatalf("unexpected error: %v", err) ++ } ++ if got2 == nil || !got2.Time.Equal(atBoundary) { ++ t.Fatalf("want %v, got %v", atBoundary, got2) ++ } ++} ++ ++func TestAugmentedCronMatrixInvalidWindowsError(t *testing.T) { ++ notBefore := mxUTC(2026, time.March, 1, 0, 0) ++ notAfter := mxUTC(2026, time.March, 20, 0, 0) ++ desired := mxUTC(2026, time.March, 10, 12, 0) ++ cases := map[string]apiv1.CertificateRenewalWindows{ ++ "too few cron fields": mxWindow("0 1 * *", "UTC", time.Hour), ++ "too many cron fields": mxWindow("0 0 1 * * 7", "UTC", time.Hour), ++ "minute out of range": mxWindow("99 * * * *", "UTC", time.Hour), ++ "bad range order": mxWindow("0 18-8 * * *", "UTC", time.Hour), ++ "bad step": mxWindow("*/0 * * * *", "UTC", time.Hour), ++ "unknown name": mxWindow("0 0 * FOO *", "UTC", time.Hour), ++ "unknown descriptor": mxWindow("@fortnightly", "UTC", time.Hour), ++ "garbage timezone": mxWindow("0 1 * * *", "Not/AZone", time.Hour), ++ "missing window duration": {Timezone: "UTC", Cron: "0 1 * * *"}, ++ "non-positive duration": {Timezone: "UTC", WindowDuration: &metav1.Duration{Duration: 0}, Cron: "0 1 * * *"}, ++ } ++ for name, w := range cases { ++ t.Run(name, func(t *testing.T) { ++ renewal := &apiv1.CertificateRenewal{ ++ Policy: apiv1.CertificateRenewalPolicyRenewBefore, ++ Windows: []apiv1.CertificateRenewalWindows{w}, ++ } ++ if _, err := RenewalTime(notBefore, notAfter, mxRenewBefore(notAfter, desired), nil, renewal); err == nil { ++ t.Fatalf("expected an error for %q", name) ++ } ++ }) ++ } ++} diff --git a/cert-manager_1/tests/private/f2p.txt b/cert-manager_1/tests/private/f2p.txt new file mode 100644 index 0000000000000000000000000000000000000000..6f21115fa6c5043a4cfbbdacf6b89d4c2e003bf4 --- /dev/null +++ b/cert-manager_1/tests/private/f2p.txt @@ -0,0 +1,4 @@ +github.com/cert-manager/cert-manager/pkg/util/pki::TestRenewalTime +github.com/cert-manager/cert-manager/pkg/util/pki::TestRenewalWithWindowsForRenewBefore +github.com/cert-manager/cert-manager/pkg/util/pki::TestRenewalWithDisable +github.com/cert-manager/cert-manager/internal/apis/certmanager/validation::TestValidateCertificate diff --git a/cert-manager_1/tests/private/f2p_aug.txt b/cert-manager_1/tests/private/f2p_aug.txt new file mode 100644 index 0000000000000000000000000000000000000000..f0c267c1f8467ef3a6103c8877d9e777cc738e71 --- /dev/null +++ b/cert-manager_1/tests/private/f2p_aug.txt @@ -0,0 +1,12 @@ +github.com/cert-manager/cert-manager/pkg/util/pki::TestAugmentedRenewalTimeWindowBoundaries +github.com/cert-manager/cert-manager/pkg/util/pki::TestAugmentedRenewalTimeDisabledAndUnsupportedPolicy +github.com/cert-manager/cert-manager/internal/apis/certmanager/validation::TestAugmentedValidateCertificateRenewalRules +github.com/cert-manager/cert-manager/internal/controller/certificates/policies::TestAugmentedCurrentCertificateNearingExpiryHonorsRenewalWindows +github.com/cert-manager/cert-manager/pkg/util/pki::TestAugmentedCronMatrixGrammarBoundaries +github.com/cert-manager/cert-manager/pkg/util/pki::TestAugmentedCronMatrixMultiWindowSelection +github.com/cert-manager/cert-manager/pkg/util/pki::TestAugmentedCronMatrixBoundaryBeyondLifetimeErrors +github.com/cert-manager/cert-manager/internal/apis/certmanager::TestAugmentedRenewalSpecConvertsRoundTrip +github.com/cert-manager/cert-manager/pkg/apis/certmanager/v1::TestAugmentedRenewalDeepCopyIsEqualAndIndependent +github.com/cert-manager/cert-manager/pkg/util/pki::TestAugmentedCronMatrixExactNextBoundaryIsUsed +github.com/cert-manager/cert-manager/pkg/util/pki::TestAugmentedCronMatrixInvalidWindowsError +github.com/cert-manager/cert-manager/pkg/apis/certmanager/v1::TestAugmentedRenewalDeepCopyHandlesSparseShapes diff --git a/cert-manager_1/tests/private/omitted.patch b/cert-manager_1/tests/private/omitted.patch new file mode 100644 index 0000000000000000000000000000000000000000..4f483c0d5c9b5475ced97b94b41e63c0e5bf5373 --- /dev/null +++ b/cert-manager_1/tests/private/omitted.patch @@ -0,0 +1,8 @@ +# omitted: LICENSES +# omitted: cmd/cainjector/LICENSES +# omitted: cmd/controller/LICENSES +# omitted: cmd/startupapicheck/LICENSES +# omitted: cmd/webhook/LICENSES +# omitted: deploy/charts/cert-manager/templates/crd-cert-manager.io_certificates.yaml +# omitted: deploy/crds/cert-manager.io_certificates.yaml +# omitted: internal/cron/LICENSE diff --git a/cert-manager_1/tests/private/p2p.txt b/cert-manager_1/tests/private/p2p.txt new file mode 100644 index 0000000000000000000000000000000000000000..0c955d05e591331e1bec1af5259628c6366e2403 --- /dev/null +++ b/cert-manager_1/tests/private/p2p.txt @@ -0,0 +1,48 @@ +github.com/cert-manager/cert-manager/pkg/api/util::TestComputeName +github.com/cert-manager/cert-manager/pkg/api/util::TestDNSSafeShortenToNCharacters +github.com/cert-manager/cert-manager/pkg/api/util::TestComputeSecureUniqueDeterministicNameFromData +github.com/cert-manager/cert-manager/internal/apis/certmanager/install::TestRoundTripTypes +github.com/cert-manager/cert-manager/internal/controller/certificaterequests::Test_serializeApply +github.com/cert-manager/cert-manager/internal/controller/certificaterequests::Test_serializeApplyStatus +github.com/cert-manager/cert-manager/internal/controller/certificates::Test_serializeApply +github.com/cert-manager/cert-manager/internal/controller/certificates::Test_serializeApplyStatus +github.com/cert-manager/cert-manager/internal/controller/certificates::TestCertificateOwnsSecret +github.com/cert-manager/cert-manager/internal/controller/certificates::Test_AnnotationsForCertificateSecret +github.com/cert-manager/cert-manager/internal/controller/issuers::Test_serializeApplyIssuerStatus +github.com/cert-manager/cert-manager/internal/controller/issuers::Test_serializeApplyClusterIssuerStatus +github.com/cert-manager/cert-manager/internal/controller/orders::Test_serializeApplyStatus +github.com/cert-manager/cert-manager/pkg/controller::Test_NewContextFactory +github.com/cert-manager/cert-manager/pkg/controller::TestBuildAnnotationsToCopy +github.com/cert-manager/cert-manager/pkg/controller::TestOnlyUpdateWhenResourceChanged +github.com/cert-manager/cert-manager/pkg/controller::TestBlockingEventHandler +github.com/cert-manager/cert-manager/pkg/controller::TestQueuingEventHandler +github.com/cert-manager/cert-manager/pkg/controller::TestFilterEventHandler +github.com/cert-manager/cert-manager/pkg/controller/certificates/keymanager::TestProcessItem +github.com/cert-manager/cert-manager/pkg/acme/accounts::TestRegistry_AddClient +github.com/cert-manager/cert-manager/pkg/acme/accounts::TestRegistry_RemoveClient +github.com/cert-manager/cert-manager/pkg/acme/accounts::TestRegistry_RemoveClient_EmptyRegistry +github.com/cert-manager/cert-manager/pkg/acme/accounts::TestRegistry_ListClients +github.com/cert-manager/cert-manager/pkg/acme/accounts::TestRegistry_AddClient_UpdatesExistingWhenPrivateKeyChanges +github.com/cert-manager/cert-manager/pkg/acme/accounts::TestRegistry_AddClient_UpdatesClientPKChecksum +github.com/cert-manager/cert-manager/pkg/acme/client::TestInstrumentedRoundTripper_LabelsAndAccumulation +github.com/cert-manager/cert-manager/pkg/acme/util::TestRetryBackoff +github.com/cert-manager/cert-manager/pkg/acme/webhook/apiserver::TestNewChallengeServer +github.com/cert-manager/cert-manager/pkg/cainjector/configfile::TestFSLoader_Load +github.com/cert-manager/cert-manager/pkg/webhook/admission::TestHandler +github.com/cert-manager/cert-manager/pkg/webhook/admission::TestChainHandles +github.com/cert-manager/cert-manager/pkg/webhook/admission::TestChainDoesntHandle +github.com/cert-manager/cert-manager/pkg/webhook/admission::TestChainValidate +github.com/cert-manager/cert-manager/pkg/webhook/admission::TestChainValidate_Fails +github.com/cert-manager/cert-manager/pkg/webhook/admission::TestChainMutate +github.com/cert-manager/cert-manager/pkg/webhook/admission::TestChainMutate_Fails +github.com/cert-manager/cert-manager/pkg/controller/acmeorders/selectors::TestDNSZones +github.com/cert-manager/cert-manager/pkg/util/predicate::TestCertificateSecretName +github.com/cert-manager/cert-manager/pkg/util/predicate::TestCertificateNextPrivateKeySecretName +github.com/cert-manager/cert-manager/pkg/util::Test_RestConfigWithUserAgent +github.com/cert-manager/cert-manager/pkg/util::Test_PrefixFromUserAgent +github.com/cert-manager/cert-manager/pkg/util::TestEqualUnsorted +github.com/cert-manager/cert-manager/pkg/util::TestEqualURLsUnsorted +github.com/cert-manager/cert-manager/pkg/util::TestEqualIPsUnsorted +github.com/cert-manager/cert-manager/pkg/util::TestEqualIPsUnsorted_RawIPs +github.com/cert-manager/cert-manager/pkg/util::TestContains +github.com/cert-manager/cert-manager/pkg/util::TestVersion diff --git a/cert-manager_1/tests/private/p2p_aug.txt b/cert-manager_1/tests/private/p2p_aug.txt new file mode 100644 index 0000000000000000000000000000000000000000..9ccd10ab68a07c3e15627f5df73c557612c23b96 --- /dev/null +++ b/cert-manager_1/tests/private/p2p_aug.txt @@ -0,0 +1,2 @@ +github.com/cert-manager/cert-manager/pkg/api/util::TestAugmentedDNSSafeShortenToNCharacters +github.com/cert-manager/cert-manager/pkg/api/util::TestAugmentedSecureNameRejectsTooShortLimit diff --git a/cert-manager_1/tests/private/run_tests.sh b/cert-manager_1/tests/private/run_tests.sh new file mode 100644 index 0000000000000000000000000000000000000000..ccccc9ae506ca18433e60bc392b1440d67255bc3 --- /dev/null +++ b/cert-manager_1/tests/private/run_tests.sh @@ -0,0 +1,194 @@ +#!/usr/bin/env bash +set -uo pipefail +PRIV=/opt/lolbench/private; SRC=/workspace/cert-manager; MODE=${LOLBENCH_MODE:-eval}; SUITE=${LOLBENCH_SUITE:-orig} +INSTANCE_ID="cert-manager_certificate-renewal-control_PR-8258" +F2P_SELECTED=/tmp/lolbench_f2p_selected.txt +P2P_SELECTED=/tmp/lolbench_p2p_selected.txt +APPLY_AUG=0 +export GOFLAGS=${GOFLAGS:-} +export PATH=/usr/local/go/bin:$PATH +read_selectors(){ + for file in "$@"; do + [ -f "$file" ] || continue + grep -v '^[[:space:]]*$' "$file" || true + done +} +select_suite(){ + case "$SUITE" in + orig) + read_selectors "$PRIV/f2p.txt" > "$F2P_SELECTED" + read_selectors "$PRIV/p2p.txt" > "$P2P_SELECTED" + ;; + aug) + read_selectors "$PRIV/f2p_aug.txt" > "$F2P_SELECTED" + read_selectors "$PRIV/p2p_aug.txt" > "$P2P_SELECTED" + APPLY_AUG=1 + ;; + union) + read_selectors "$PRIV/f2p.txt" "$PRIV/f2p_aug.txt" > "$F2P_SELECTED" + read_selectors "$PRIV/p2p.txt" "$PRIV/p2p_aug.txt" > "$P2P_SELECTED" + APPLY_AUG=1 + ;; + *) SUITE=orig; read_selectors "$PRIV/f2p.txt" > "$F2P_SELECTED"; read_selectors "$PRIV/p2p.txt" > "$P2P_SELECTED";; + esac +} +select_suite +emit_error(){ python3 - "$1" "$2" "$3" "$INSTANCE_ID" "$F2P_SELECTED" "$P2P_SELECTED" <<'P' >/out/agent_report.json +import json,sys +cat,ap,bs,inst,fp,pp=sys.argv[1:7] +fn=sum(1 for l in open(fp) if l.strip()); pn=sum(1 for l in open(pp) if l.strip()) +print(json.dumps({"instance_id":inst,"applied":ap.lower()=="true","build":{"status":bs},"f2p":{"passed":0,"failed":0,"errored":fn,"skipped":0,"total":fn},"p2p":{"passed":0,"failed":0,"errored":pn,"skipped":0,"total":pn},"resolved":False,"error_categories":[cat]},indent=2)) +P +} +case "$MODE" in + validate_pre) SRC_PATCH="";; + validate_post) + if [ -f /solution/solution.patch ]; then + SRC_PATCH=/solution/solution.patch + else + SRC_PATCH="$PRIV/solution.patch" + fi ;; + eval) [ -f /in/solution.patch ] || { emit_error missing_solution_patch false skipped; exit 0; }; AGENT_PATCH=/tmp/lolbench_agent_patch.diff; cp /in/solution.patch "$AGENT_PATCH"; chmod 0600 "$AGENT_PATCH"; SRC_PATCH="$AGENT_PATCH";; + *) emit_error harness_error false skipped; exit 0;; +esac +cd "$SRC"; git config --global --add safe.directory "$SRC"; git reset --hard >/dev/null 2>&1; git clean -fd >/dev/null 2>&1 +if [ -n "$SRC_PATCH" ]; then git apply --binary --check "$SRC_PATCH" 2>/tmp/e || { emit_error patch_apply_failure false skipped; exit 0; }; git apply --binary "$SRC_PATCH"; fi +if [ -n "$SRC_PATCH" ]; then + # LoLBench eval-patch-collision guard (re-verify remediation): if the agent patch touched files the + # eval test patches own (test fixtures the agent must not modify), restore + # those paths (both sides of every diff/rename) to the base state so + # eval_tests(.aug).patch always applies. Agent source changes are preserved. + for _lb_ep in "$PRIV/eval_helpers.patch" "$PRIV/eval_tests.patch" "$PRIV/eval_tests_aug.patch"; do + [ -f "$_lb_ep" ] || continue + { sed -n 's|^diff --git a/\(.*\) b/\(.*\)$|\1\n\2|p' "$_lb_ep" + sed -n 's|^rename from \(.*\)$|\1|p' "$_lb_ep" + sed -n 's|^rename to \(.*\)$|\1|p' "$_lb_ep"; } | sort -u | while read -r _lb_f; do + [ -n "$_lb_f" ] || continue + git checkout HEAD -- "$_lb_f" >/dev/null 2>&1 || rm -f "$_lb_f" >/dev/null 2>&1 || true + done + done +fi +git apply --binary --check "$PRIV/eval_tests.patch" 2>/tmp/e || { cat /tmp/e>&2; emit_error eval_patch_apply_failure true skipped; exit 0; } +git apply --binary "$PRIV/eval_tests.patch" +if [ "$APPLY_AUG" -eq 1 ]; then + git apply --binary --check "$PRIV/eval_tests_aug.patch" 2>/tmp/e || { cat /tmp/e>&2; emit_error eval_aug_patch_apply_failure true skipped; exit 0; } + git apply --binary "$PRIV/eval_tests_aug.patch" +fi +run(){ python3 - "$1" "$2" "$SRC" "$3" <<'P' +import json,subprocess,sys +sf,lf,src,failfast=sys.argv[1:5] +sels=[l.strip() for l in open(sf) if l.strip()]; g={} +for s in sels: pkg,_,t=s.partition("::"); g.setdefault(pkg,[]).append(t) +with open(lf,"w") as o: + for pkg,tests in g.items(): + rx="^("+"|".join(tests)+")$" + cmd=["go","test","-count=1","-timeout=20m","-json","-run",rx,pkg] + o.write(f"### CMD {pkg}\n"); o.flush() + p=subprocess.run(cmd,cwd=src,stdout=subprocess.PIPE,stderr=subprocess.STDOUT,text=True) + o.write(p.stdout); o.write(f"\n### EXIT {p.returncode}\n") + if failfast == "1" and p.returncode != 0: + break +P +} +run "$F2P_SELECTED" /workspace/.f2p "${LOLBENCH_F2P_FAIL_FAST:-0}" +if [ "${LOLBENCH_F2P_FAIL_FAST:-0}" = "1" ]; then +python3 - "$F2P_SELECTED" "$P2P_SELECTED" /workspace/.f2p "$INSTANCE_ID" "$MODE" "$SUITE" <<'P' +import json,sys +ff,pf,fl,inst,mode,suite=sys.argv[1:7] +fids=[l.strip() for l in open(ff) if l.strip()] +pids=[l.strip() for l in open(pf) if l.strip()] +def parse(path): + out={}; cur=None + for line in open(path,errors="replace"): + line=line.rstrip("\n") + if line.startswith("### CMD"): cur=line.split()[-1]; out.setdefault(cur,{}); continue + if line.startswith("### EXIT"): continue + try: ev=json.loads(line) + except: + if "build failed" in line and cur: out[cur]["__c__"]="failed" + continue + pkg=ev.get("Package") or cur + if not pkg: continue + out.setdefault(pkg,{}) + a=ev.get("Action") + if a=="build-fail" or (a=="fail" and ev.get("FailedBuild")): out[pkg]["__c__"]="failed" + if a=="output" and "[build failed]" in (ev.get("Output") or ""): out[pkg]["__c__"]="failed" + t=ev.get("Test") + if t and a in ("pass","fail","skip"): out[pkg][t]=a.upper() + return out +fr=parse(fl) +def st(sel,rep): + pkg,_,t=sel.partition("::"); d=rep.get(pkg,{}) + if d.get("__c__")=="failed": return "ERROR" + return {"PASS":"PASSED","FAIL":"FAILED","SKIP":"SKIPPED"}.get(d.get(t),"ERROR") +def bucket(ids,rep): + out={"PASSED":[],"FAILED":[],"ERROR":[],"SKIPPED":[]} + for i in ids: + out[st(i,rep)].append(i) + return out +def cnts(d,ids): + return {"passed":len(d["PASSED"]),"failed":len(d["FAILED"]),"errored":len(d["ERROR"]),"skipped":len(d["SKIPPED"]),"total":len(ids)} +f=bucket(fids,fr) +if len(f["PASSED"]) != len(fids): + p={"PASSED":[],"FAILED":[],"ERROR":[],"SKIPPED":list(pids)} + p_agent={"passed":len(pids),"failed":0,"errored":0,"skipped":0,"total":len(pids)} + grader={"instance_id":inst,"mode":mode,"suite":suite,"applied":True,"build":{"status":"ok"},"f2p":f,"p2p":p,"resolved":False,"mutation_fail_fast":True} + agent={"instance_id":inst,"suite":suite,"applied":True,"build":{"status":"ok"},"f2p":cnts(f,fids),"p2p":p_agent,"resolved":False,"error_categories":[],"mutation_fail_fast":True} + json.dump(grader,open("/out/grader_report.json","w"),indent=2) + json.dump(agent,open("/out/agent_report.json","w"),indent=2) + print(json.dumps(grader,indent=2)) + sys.exit(42) +sys.exit(0) +P + rc=$? + if [ "$rc" -eq 42 ]; then + exit 0 + fi + if [ "$rc" -ne 0 ]; then + exit "$rc" + fi +fi +run "$P2P_SELECTED" /workspace/.p2p 0 +python3 - "$F2P_SELECTED" "$P2P_SELECTED" /workspace/.f2p /workspace/.p2p "$INSTANCE_ID" "$MODE" "$SUITE" <<'P' +import json,sys +ff,pf,fl,pl,inst,mode,suite=sys.argv[1:8] +fids=[l.strip() for l in open(ff) if l.strip()]; pids=[l.strip() for l in open(pf) if l.strip()] +def parse(path): + out={}; cur=None + for line in open(path,errors="replace"): + line=line.rstrip("\n") + if line.startswith("### CMD"): cur=line.split()[-1]; out.setdefault(cur,{}); continue + if line.startswith("### EXIT"): continue + try: ev=json.loads(line) + except: + if "build failed" in line and cur: out[cur]["__c__"]="failed" + continue + pkg=ev.get("Package") or cur + if not pkg: continue + out.setdefault(pkg,{}) + a=ev.get("Action") + if a=="build-fail" or (a=="fail" and ev.get("FailedBuild")): out[pkg]["__c__"]="failed" + if a=="output" and "[build failed]" in (ev.get("Output") or ""): out[pkg]["__c__"]="failed" + t=ev.get("Test") + if t and a in ("pass","fail","skip"): out[pkg][t]=a.upper() + return out +fr=parse(fl); pr=parse(pl) +def st(sel,rep): + pkg,_,t=sel.partition("::"); d=rep.get(pkg,{}) + if d.get("__c__")=="failed": return "ERROR" + return {"PASS":"PASSED","FAIL":"FAILED","SKIP":"SKIPPED"}.get(d.get(t),"ERROR") +def bucket(ids,rep): + out={"PASSED":[],"FAILED":[],"ERROR":[],"SKIPPED":[]} + for i in ids: + out[st(i,rep)].append(i) + return out +f=bucket(fids,fr); p=bucket(pids,pr) +resolved=len(f["PASSED"])==len(fids) and len(p["PASSED"])==len(pids) +grader={"instance_id":inst,"mode":mode,"suite":suite,"applied":True,"build":{"status":"ok"},"f2p":f,"p2p":p,"resolved":resolved} +def cnts(d,ids): + return {"passed":len(d["PASSED"]),"failed":len(d["FAILED"]),"errored":len(d["ERROR"]),"skipped":len(d["SKIPPED"]),"total":len(ids)} +agent={"instance_id":inst,"suite":suite,"applied":True,"build":{"status":"ok"},"f2p":cnts(f,fids),"p2p":cnts(p,pids),"resolved":resolved,"error_categories":[]} +json.dump(grader,open("/out/grader_report.json","w"),indent=2) +json.dump(agent,open("/out/agent_report.json","w"),indent=2) +print(json.dumps(grader,indent=2)) +P diff --git a/cert-manager_1/tests/private/spec.json b/cert-manager_1/tests/private/spec.json new file mode 100644 index 0000000000000000000000000000000000000000..371960395a1b155c94177185b655864ca5cd717f --- /dev/null +++ b/cert-manager_1/tests/private/spec.json @@ -0,0 +1,457 @@ +{ + "instance_id": "cert-manager_certificate-renewal-control_PR-8258", + "repo": "cert-manager/cert-manager", + "language": "Go", + "image": "lolbench/cert-manager-pr-8258:1", + "base_commit": "788c2f25fe3542e0163cd8d295efd215b3ccbe3b", + "pr_head_sha": "1756a823b00d337d33058c528a8a3c349388e93f", + "pr_link": "https://github.com/cert-manager/cert-manager/pull/8258", + "test_framework": "go_test", + "test_level": "system", + "fail_to_pass": [ + "github.com/cert-manager/cert-manager/pkg/util/pki::TestRenewalTime", + "github.com/cert-manager/cert-manager/pkg/util/pki::TestRenewalWithWindowsForRenewBefore", + "github.com/cert-manager/cert-manager/pkg/util/pki::TestRenewalWithDisable", + "github.com/cert-manager/cert-manager/internal/apis/certmanager/validation::TestValidateCertificate" + ], + "pass_to_pass": [ + "github.com/cert-manager/cert-manager/pkg/api/util::TestComputeName", + "github.com/cert-manager/cert-manager/pkg/api/util::TestDNSSafeShortenToNCharacters", + "github.com/cert-manager/cert-manager/pkg/api/util::TestComputeSecureUniqueDeterministicNameFromData", + "github.com/cert-manager/cert-manager/internal/apis/certmanager/install::TestRoundTripTypes", + "github.com/cert-manager/cert-manager/internal/controller/certificaterequests::Test_serializeApply", + "github.com/cert-manager/cert-manager/internal/controller/certificaterequests::Test_serializeApplyStatus", + "github.com/cert-manager/cert-manager/internal/controller/certificates::Test_serializeApply", + "github.com/cert-manager/cert-manager/internal/controller/certificates::Test_serializeApplyStatus", + "github.com/cert-manager/cert-manager/internal/controller/certificates::TestCertificateOwnsSecret", + "github.com/cert-manager/cert-manager/internal/controller/certificates::Test_AnnotationsForCertificateSecret", + "github.com/cert-manager/cert-manager/internal/controller/issuers::Test_serializeApplyIssuerStatus", + "github.com/cert-manager/cert-manager/internal/controller/issuers::Test_serializeApplyClusterIssuerStatus", + "github.com/cert-manager/cert-manager/internal/controller/orders::Test_serializeApplyStatus", + "github.com/cert-manager/cert-manager/pkg/controller::Test_NewContextFactory", + "github.com/cert-manager/cert-manager/pkg/controller::TestBuildAnnotationsToCopy", + "github.com/cert-manager/cert-manager/pkg/controller::TestOnlyUpdateWhenResourceChanged", + "github.com/cert-manager/cert-manager/pkg/controller::TestBlockingEventHandler", + "github.com/cert-manager/cert-manager/pkg/controller::TestQueuingEventHandler", + "github.com/cert-manager/cert-manager/pkg/controller::TestFilterEventHandler", + "github.com/cert-manager/cert-manager/pkg/controller/certificates/keymanager::TestProcessItem", + "github.com/cert-manager/cert-manager/pkg/acme/accounts::TestRegistry_AddClient", + "github.com/cert-manager/cert-manager/pkg/acme/accounts::TestRegistry_RemoveClient", + "github.com/cert-manager/cert-manager/pkg/acme/accounts::TestRegistry_RemoveClient_EmptyRegistry", + "github.com/cert-manager/cert-manager/pkg/acme/accounts::TestRegistry_ListClients", + "github.com/cert-manager/cert-manager/pkg/acme/accounts::TestRegistry_AddClient_UpdatesExistingWhenPrivateKeyChanges", + "github.com/cert-manager/cert-manager/pkg/acme/accounts::TestRegistry_AddClient_UpdatesClientPKChecksum", + "github.com/cert-manager/cert-manager/pkg/acme/client::TestInstrumentedRoundTripper_LabelsAndAccumulation", + "github.com/cert-manager/cert-manager/pkg/acme/util::TestRetryBackoff", + "github.com/cert-manager/cert-manager/pkg/acme/webhook/apiserver::TestNewChallengeServer", + "github.com/cert-manager/cert-manager/pkg/cainjector/configfile::TestFSLoader_Load", + "github.com/cert-manager/cert-manager/pkg/webhook/admission::TestHandler", + "github.com/cert-manager/cert-manager/pkg/webhook/admission::TestChainHandles", + "github.com/cert-manager/cert-manager/pkg/webhook/admission::TestChainDoesntHandle", + "github.com/cert-manager/cert-manager/pkg/webhook/admission::TestChainValidate", + "github.com/cert-manager/cert-manager/pkg/webhook/admission::TestChainValidate_Fails", + "github.com/cert-manager/cert-manager/pkg/webhook/admission::TestChainMutate", + "github.com/cert-manager/cert-manager/pkg/webhook/admission::TestChainMutate_Fails", + "github.com/cert-manager/cert-manager/pkg/controller/acmeorders/selectors::TestDNSZones", + "github.com/cert-manager/cert-manager/pkg/util/predicate::TestCertificateSecretName", + "github.com/cert-manager/cert-manager/pkg/util/predicate::TestCertificateNextPrivateKeySecretName", + "github.com/cert-manager/cert-manager/pkg/util::Test_RestConfigWithUserAgent", + "github.com/cert-manager/cert-manager/pkg/util::Test_PrefixFromUserAgent", + "github.com/cert-manager/cert-manager/pkg/util::TestEqualUnsorted", + "github.com/cert-manager/cert-manager/pkg/util::TestEqualURLsUnsorted", + "github.com/cert-manager/cert-manager/pkg/util::TestEqualIPsUnsorted", + "github.com/cert-manager/cert-manager/pkg/util::TestEqualIPsUnsorted_RawIPs", + "github.com/cert-manager/cert-manager/pkg/util::TestContains", + "github.com/cert-manager/cert-manager/pkg/util::TestVersion" + ], + "solution_patch_sha256": "9f402dbe8f297b61b29efe77ad86008f2e27a9a96efed2a1fdc6c84201809097", + "eval_tests_patch_sha256": "bd157873f49b8b797c87703ee32026f7d5bb8c1cf70ed98aab700853e3f4643d", + "omitted_patch_sha256": "264aa796e4b53647993cfe00f170a912fac2b45193adf67a8a883364e94a3774", + "validation_status": "validated_augmented_coverage_exception", + "env": { + "go": "1.25.0" + }, + "platform": "linux/amd64,linux/arm64", + "validated_at": "2026-06-16", + "diff_source": "local_git_diff(base..head per PR file)", + "triage": { + "fail_to_pass": { + "github.com/cert-manager/cert-manager/pkg/util/pki::TestRenewalTime": { + "system_reason": "Public RenewalTime() (pre-existing, sig changed); \u00a76 PASS per Codex." + }, + "github.com/cert-manager/cert-manager/pkg/util/pki::TestRenewalWithWindowsForRenewBefore": { + "system_reason": "Public RenewalTime() with documented CertificateRenewal windows; covers renewaltime.go + cron parser. \u00a76 PASS per Codex." + }, + "github.com/cert-manager/cert-manager/pkg/util/pki::TestRenewalWithDisable": { + "system_reason": "Public RenewalTime() disabled-policy path. \u00a76 PASS per Codex." + }, + "github.com/cert-manager/cert-manager/internal/apis/certmanager/validation::TestValidateCertificate": { + "system_reason": "Public ValidateCertificate() with documented Renewal cases; covers the new validateCertificateRenewal/Windows validators indirectly. \u00a76-clean (same basis as Codex-reviewed pki tests)." + } + }, + "pass_to_pass": { + "github.com/cert-manager/cert-manager/pkg/api/util::TestComputeName": { + "system_reason": "Uncontaminated." + }, + "github.com/cert-manager/cert-manager/pkg/api/util::TestDNSSafeShortenToNCharacters": { + "system_reason": "Uncontaminated." + }, + "github.com/cert-manager/cert-manager/pkg/api/util::TestComputeSecureUniqueDeterministicNameFromData": { + "system_reason": "Uncontaminated." + }, + "github.com/cert-manager/cert-manager/internal/apis/certmanager/install::TestRoundTripTypes": { + "system_reason": "Uncontaminated fuzz API roundtrip; covers generated conversion/deepcopy of the new renewal types." + }, + "github.com/cert-manager/cert-manager/internal/controller/certificaterequests::Test_serializeApply": { + "system_reason": "Pre-existing upstream controller test at base_commit; guards unchanged controller infrastructure behavior outside the renewal requirement surface." + }, + "github.com/cert-manager/cert-manager/internal/controller/certificaterequests::Test_serializeApplyStatus": { + "system_reason": "Pre-existing upstream controller test at base_commit; guards unchanged controller infrastructure behavior outside the renewal requirement surface." + }, + "github.com/cert-manager/cert-manager/internal/controller/certificates::Test_serializeApply": { + "system_reason": "Pre-existing upstream certificate-controller test at base_commit; guards unchanged certificate controller behavior adjacent to the renewal readiness/trigger/policy changes without asserting renewal-window semantics." + }, + "github.com/cert-manager/cert-manager/internal/controller/certificates::Test_serializeApplyStatus": { + "system_reason": "Pre-existing upstream certificate-controller test at base_commit; guards unchanged certificate controller behavior adjacent to the renewal readiness/trigger/policy changes without asserting renewal-window semantics." + }, + "github.com/cert-manager/cert-manager/internal/controller/certificates::TestCertificateOwnsSecret": { + "system_reason": "Pre-existing upstream certificate-controller test at base_commit; guards unchanged certificate controller behavior adjacent to the renewal readiness/trigger/policy changes without asserting renewal-window semantics." + }, + "github.com/cert-manager/cert-manager/internal/controller/certificates::Test_AnnotationsForCertificateSecret": { + "system_reason": "Pre-existing upstream certificate-controller test at base_commit; guards unchanged certificate controller behavior adjacent to the renewal readiness/trigger/policy changes without asserting renewal-window semantics." + }, + "github.com/cert-manager/cert-manager/internal/controller/issuers::Test_serializeApplyIssuerStatus": { + "system_reason": "Pre-existing upstream controller test at base_commit; guards unchanged controller infrastructure behavior outside the renewal requirement surface." + }, + "github.com/cert-manager/cert-manager/internal/controller/issuers::Test_serializeApplyClusterIssuerStatus": { + "system_reason": "Pre-existing upstream controller test at base_commit; guards unchanged controller infrastructure behavior outside the renewal requirement surface." + }, + "github.com/cert-manager/cert-manager/internal/controller/orders::Test_serializeApplyStatus": { + "system_reason": "Pre-existing upstream controller test at base_commit; guards unchanged controller infrastructure behavior outside the renewal requirement surface." + }, + "github.com/cert-manager/cert-manager/pkg/controller::Test_NewContextFactory": { + "system_reason": "Pre-existing upstream controller test at base_commit; guards unchanged controller infrastructure behavior outside the renewal requirement surface." + }, + "github.com/cert-manager/cert-manager/pkg/controller::TestBuildAnnotationsToCopy": { + "system_reason": "Pre-existing upstream controller test at base_commit; guards unchanged controller infrastructure behavior outside the renewal requirement surface." + }, + "github.com/cert-manager/cert-manager/pkg/controller::TestOnlyUpdateWhenResourceChanged": { + "system_reason": "Pre-existing upstream controller test at base_commit; guards unchanged controller infrastructure behavior outside the renewal requirement surface." + }, + "github.com/cert-manager/cert-manager/pkg/controller::TestBlockingEventHandler": { + "system_reason": "Pre-existing upstream controller test at base_commit; guards unchanged controller infrastructure behavior outside the renewal requirement surface." + }, + "github.com/cert-manager/cert-manager/pkg/controller::TestQueuingEventHandler": { + "system_reason": "Pre-existing upstream controller test at base_commit; guards unchanged controller infrastructure behavior outside the renewal requirement surface." + }, + "github.com/cert-manager/cert-manager/pkg/controller::TestFilterEventHandler": { + "system_reason": "Pre-existing upstream controller test at base_commit; guards unchanged controller infrastructure behavior outside the renewal requirement surface." + }, + "github.com/cert-manager/cert-manager/pkg/controller/certificates/keymanager::TestProcessItem": { + "system_reason": "Pre-existing upstream certificate-controller test at base_commit; guards unchanged certificate controller behavior adjacent to the renewal readiness/trigger/policy changes without asserting renewal-window semantics." + }, + "github.com/cert-manager/cert-manager/pkg/acme/accounts::TestRegistry_AddClient": { + "system_reason": "Pre-existing upstream ACME/controller-adjacent test at base_commit; guards unchanged issuer/account/challenge behavior outside the certificate-renewal requirement surface." + }, + "github.com/cert-manager/cert-manager/pkg/acme/accounts::TestRegistry_RemoveClient": { + "system_reason": "Pre-existing upstream ACME/controller-adjacent test at base_commit; guards unchanged issuer/account/challenge behavior outside the certificate-renewal requirement surface." + }, + "github.com/cert-manager/cert-manager/pkg/acme/accounts::TestRegistry_RemoveClient_EmptyRegistry": { + "system_reason": "Pre-existing upstream ACME/controller-adjacent test at base_commit; guards unchanged issuer/account/challenge behavior outside the certificate-renewal requirement surface." + }, + "github.com/cert-manager/cert-manager/pkg/acme/accounts::TestRegistry_ListClients": { + "system_reason": "Pre-existing upstream ACME/controller-adjacent test at base_commit; guards unchanged issuer/account/challenge behavior outside the certificate-renewal requirement surface." + }, + "github.com/cert-manager/cert-manager/pkg/acme/accounts::TestRegistry_AddClient_UpdatesExistingWhenPrivateKeyChanges": { + "system_reason": "Pre-existing upstream ACME/controller-adjacent test at base_commit; guards unchanged issuer/account/challenge behavior outside the certificate-renewal requirement surface." + }, + "github.com/cert-manager/cert-manager/pkg/acme/accounts::TestRegistry_AddClient_UpdatesClientPKChecksum": { + "system_reason": "Pre-existing upstream ACME/controller-adjacent test at base_commit; guards unchanged issuer/account/challenge behavior outside the certificate-renewal requirement surface." + }, + "github.com/cert-manager/cert-manager/pkg/acme/client::TestInstrumentedRoundTripper_LabelsAndAccumulation": { + "system_reason": "Pre-existing upstream ACME/controller-adjacent test at base_commit; guards unchanged issuer/account/challenge behavior outside the certificate-renewal requirement surface." + }, + "github.com/cert-manager/cert-manager/pkg/acme/util::TestRetryBackoff": { + "system_reason": "Pre-existing upstream ACME/controller-adjacent test at base_commit; guards unchanged issuer/account/challenge behavior outside the certificate-renewal requirement surface." + }, + "github.com/cert-manager/cert-manager/pkg/acme/webhook/apiserver::TestNewChallengeServer": { + "system_reason": "Pre-existing upstream ACME/controller-adjacent test at base_commit; guards unchanged issuer/account/challenge behavior outside the certificate-renewal requirement surface." + }, + "github.com/cert-manager/cert-manager/pkg/cainjector/configfile::TestFSLoader_Load": { + "system_reason": "Pre-existing upstream configfile loader test at base_commit; guards unchanged config loading behavior outside the renewal requirement surface." + }, + "github.com/cert-manager/cert-manager/pkg/webhook/admission::TestHandler": { + "system_reason": "Pre-existing upstream webhook admission-chain test at base_commit; guards unchanged admission infrastructure behavior outside the certificate-renewal requirement surface." + }, + "github.com/cert-manager/cert-manager/pkg/webhook/admission::TestChainHandles": { + "system_reason": "Pre-existing upstream webhook admission-chain test at base_commit; guards unchanged admission infrastructure behavior outside the certificate-renewal requirement surface." + }, + "github.com/cert-manager/cert-manager/pkg/webhook/admission::TestChainDoesntHandle": { + "system_reason": "Pre-existing upstream webhook admission-chain test at base_commit; guards unchanged admission infrastructure behavior outside the certificate-renewal requirement surface." + }, + "github.com/cert-manager/cert-manager/pkg/webhook/admission::TestChainValidate": { + "system_reason": "Pre-existing upstream webhook admission-chain test at base_commit; guards unchanged admission infrastructure behavior outside the certificate-renewal requirement surface." + }, + "github.com/cert-manager/cert-manager/pkg/webhook/admission::TestChainValidate_Fails": { + "system_reason": "Pre-existing upstream webhook admission-chain test at base_commit; guards unchanged admission infrastructure behavior outside the certificate-renewal requirement surface." + }, + "github.com/cert-manager/cert-manager/pkg/webhook/admission::TestChainMutate": { + "system_reason": "Pre-existing upstream webhook admission-chain test at base_commit; guards unchanged admission infrastructure behavior outside the certificate-renewal requirement surface." + }, + "github.com/cert-manager/cert-manager/pkg/webhook/admission::TestChainMutate_Fails": { + "system_reason": "Pre-existing upstream webhook admission-chain test at base_commit; guards unchanged admission infrastructure behavior outside the certificate-renewal requirement surface." + }, + "github.com/cert-manager/cert-manager/pkg/controller/acmeorders/selectors::TestDNSZones": { + "system_reason": "Pre-existing upstream ACME controller test at base_commit; guards unchanged controller behavior outside the renewal readiness/trigger requirement surface." + }, + "github.com/cert-manager/cert-manager/pkg/util/predicate::TestCertificateSecretName": { + "system_reason": "Pre-existing upstream predicate utility test at base_commit; guards unchanged certificate resource helper behavior outside the renewal requirement surface." + }, + "github.com/cert-manager/cert-manager/pkg/util/predicate::TestCertificateNextPrivateKeySecretName": { + "system_reason": "Pre-existing upstream predicate utility test at base_commit; guards unchanged certificate resource helper behavior outside the renewal requirement surface." + }, + "github.com/cert-manager/cert-manager/pkg/util::Test_RestConfigWithUserAgent": { + "system_reason": "Pre-existing upstream pkg/util test at base_commit; guards unchanged shared utility behavior outside the renewal requirement surface." + }, + "github.com/cert-manager/cert-manager/pkg/util::Test_PrefixFromUserAgent": { + "system_reason": "Pre-existing upstream pkg/util test at base_commit; guards unchanged shared utility behavior outside the renewal requirement surface." + }, + "github.com/cert-manager/cert-manager/pkg/util::TestEqualUnsorted": { + "system_reason": "Pre-existing upstream pkg/util test at base_commit; guards unchanged shared utility behavior outside the renewal requirement surface." + }, + "github.com/cert-manager/cert-manager/pkg/util::TestEqualURLsUnsorted": { + "system_reason": "Pre-existing upstream pkg/util test at base_commit; guards unchanged shared utility behavior outside the renewal requirement surface." + }, + "github.com/cert-manager/cert-manager/pkg/util::TestEqualIPsUnsorted": { + "system_reason": "Pre-existing upstream pkg/util test at base_commit; guards unchanged shared utility behavior outside the renewal requirement surface." + }, + "github.com/cert-manager/cert-manager/pkg/util::TestEqualIPsUnsorted_RawIPs": { + "system_reason": "Pre-existing upstream pkg/util test at base_commit; guards unchanged shared utility behavior outside the renewal requirement surface." + }, + "github.com/cert-manager/cert-manager/pkg/util::TestContains": { + "system_reason": "Pre-existing upstream pkg/util test at base_commit; guards unchanged shared utility behavior outside the renewal requirement surface." + }, + "github.com/cert-manager/cert-manager/pkg/util::TestVersion": { + "system_reason": "Pre-existing upstream pkg/util test at base_commit; guards unchanged shared utility behavior outside the renewal requirement surface." + } + } + }, + "augmented": { + "fail_to_pass": [ + "github.com/cert-manager/cert-manager/pkg/util/pki::TestAugmentedRenewalTimeWindowBoundaries", + "github.com/cert-manager/cert-manager/pkg/util/pki::TestAugmentedRenewalTimeDisabledAndUnsupportedPolicy", + "github.com/cert-manager/cert-manager/internal/apis/certmanager/validation::TestAugmentedValidateCertificateRenewalRules", + "github.com/cert-manager/cert-manager/internal/controller/certificates/policies::TestAugmentedCurrentCertificateNearingExpiryHonorsRenewalWindows", + "github.com/cert-manager/cert-manager/pkg/util/pki::TestAugmentedCronMatrixGrammarBoundaries", + "github.com/cert-manager/cert-manager/pkg/util/pki::TestAugmentedCronMatrixMultiWindowSelection", + "github.com/cert-manager/cert-manager/pkg/util/pki::TestAugmentedCronMatrixBoundaryBeyondLifetimeErrors", + "github.com/cert-manager/cert-manager/internal/apis/certmanager::TestAugmentedRenewalSpecConvertsRoundTrip", + "github.com/cert-manager/cert-manager/pkg/apis/certmanager/v1::TestAugmentedRenewalDeepCopyIsEqualAndIndependent", + "github.com/cert-manager/cert-manager/pkg/util/pki::TestAugmentedCronMatrixExactNextBoundaryIsUsed", + "github.com/cert-manager/cert-manager/pkg/util/pki::TestAugmentedCronMatrixInvalidWindowsError", + "github.com/cert-manager/cert-manager/pkg/apis/certmanager/v1::TestAugmentedRenewalDeepCopyHandlesSparseShapes" + ], + "pass_to_pass": [ + "github.com/cert-manager/cert-manager/pkg/api/util::TestAugmentedDNSSafeShortenToNCharacters", + "github.com/cert-manager/cert-manager/pkg/api/util::TestAugmentedSecureNameRejectsTooShortLimit" + ], + "eval_tests_aug_patch_sha256": "146a534e749b8215bca251a16849ce63fde514b339c34426a9cd3681ee6bb263", + "f2p_aug_sha256": "ef4798f273f3116ab76a4de47c9135a2223bb1ea78e23381929e262cf1d57808", + "p2p_aug_sha256": "388cc7c5b6fb7a4efe096faf23fc2d87e0a533412ad7aaed5c3a6a225b0ff8fc", + "coverage_report_aug_sha256": "af87c5195b0ad01cb2532fa4ec5387a2d4c59ea9bac179c0cc3e5364befc8cf2", + "coverage_report_union_sha256": "3320798de83555c59389b93ded62a4b32e45edc8dc9a95ac709b3032c1cfbb8d", + "validation_status": "validated", + "validated_at": "2026-06-12", + "triage": { + "test_level_policy": "Augmented F2P drives documented renewal behavior through pre-existing public/module surfaces: RenewalTime, ValidateCertificate, and CurrentCertificateNearingExpiry. Augmented P2P exercises unchanged pkg/api/util name helpers. No augmented selector directly invokes a PR-added helper such as findAfterDesired, validateCertificateRenewal, CronParse, or generated apply-configuration builders.", + "fail_to_pass": { + "github.com/cert-manager/cert-manager/pkg/util/pki::TestAugmentedRenewalTimeWindowBoundaries": { + "requirement_sections": [ + "Controller logic > Updated behavior" + ], + "public_surface": "pkg/util/pki RenewalTime called with documented renewal.policy=RenewBefore windows.", + "mutants_targeted": [ + "mutant_004_after_window_preferred_over_before", + "mutant_005_before_window_uses_start_not_end", + "mutant_011_cron_parse_ignores_timezone" + ], + "rationale": "Pins backward/forward window choice, inclusive window-start/end boundaries, and timezone-aware cron evaluation through the public renewal-time calculator." + }, + "github.com/cert-manager/cert-manager/pkg/util/pki::TestAugmentedRenewalTimeDisabledAndUnsupportedPolicy": { + "requirement_sections": [ + "Controller logic > Updated behavior", + "Proposed API" + ], + "public_surface": "pkg/util/pki RenewalTime called with documented Disabled and policy enum behavior.", + "mutants_targeted": [ + "mutant_001_disabled_policy_renews_normally", + "mutant_001_disabled_policy_still_renews", + "mutant_002_renew_before_policy_ignores_windows", + "mutant_003_unknown_policy_falls_back_to_default", + "mutant_008_unknown_policy_allowed", + "mutant_012_policy_check_ignores_renewal_spec" + ], + "rationale": "Asserts Disabled schedules no renewal and unsupported policies surface an error rather than silently falling back to legacy renew-before behavior." + }, + "github.com/cert-manager/cert-manager/internal/apis/certmanager/validation::TestAugmentedValidateCertificateRenewalRules": { + "requirement_sections": [ + "Validation and Admission", + "Proposed API" + ], + "public_surface": "internal/apis/certmanager/validation ValidateCertificate admission surface.", + "mutants_targeted": [ + "mutant_002_disabled_policy_allows_windows", + "mutant_003_invalid_timezone_allowed", + "mutant_004_invalid_cron_allowed", + "mutant_007_disabled_policy_allows_windows", + "mutant_009_window_duration_not_required", + "mutant_010_invalid_timezone_allowed" + ], + "rationale": "Checks admission rejects Disabled windows, unknown policies, missing windowDuration, invalid timezone, and invalid cron syntax through the existing ValidateCertificate entry point." + }, + "github.com/cert-manager/cert-manager/internal/controller/certificates/policies::TestAugmentedCurrentCertificateNearingExpiryHonorsRenewalWindows": { + "requirement_sections": [ + "Controller logic > Updated behavior", + "Status changes and Conditions" + ], + "public_surface": "certificate policy check CurrentCertificateNearingExpiry over a Certificate and Secret flow.", + "mutants_targeted": [ + "mutant_002_renew_before_policy_ignores_windows" + ], + "rationale": "Exercises the controller policy path that converts an unsatisfied renewal window into the WindowError reason used by readiness/trigger flows." + }, + "github.com/cert-manager/cert-manager/pkg/util/pki::TestAugmentedCronMatrixGrammarBoundaries": { + "requirement_sections": [ + "Controller logic > Updated behavior", + "Proposed API" + ], + "public_surface": "pkg/util/pki RenewalTime called with documented renewal.policy=RenewBefore windows.", + "mutants_targeted": [ + "mutant_011_cron_parse_ignores_timezone" + ], + "rationale": "Cron grammar matrix (descriptors, names, ranges, steps, lists, dom-or-dow, month/day wraps, IANA timezones incl. a DST transition) through the public renewal-time surface: desired time is kept when inside a window and otherwise delayed to the next window opening." + }, + "github.com/cert-manager/cert-manager/pkg/util/pki::TestAugmentedCronMatrixMultiWindowSelection": { + "requirement_sections": [ + "Controller logic > Updated behavior" + ], + "public_surface": "pkg/util/pki RenewalTime called with documented renewal.policy=RenewBefore windows.", + "mutants_targeted": [ + "mutant_004_after_window_preferred_over_before" + ], + "rationale": "With several windows the desired time inside any window wins; windows outside the lifetime contribute nothing." + }, + "github.com/cert-manager/cert-manager/pkg/util/pki::TestAugmentedCronMatrixBoundaryBeyondLifetimeErrors": { + "requirement_sections": [ + "Controller logic > Updated behavior" + ], + "public_surface": "pkg/util/pki RenewalTime called with documented renewal.policy=RenewBefore windows.", + "mutants_targeted": [], + "rationale": "A window whose only boundary lies beyond the certificate lifetime yields an error rather than a silent renewal time." + }, + "github.com/cert-manager/cert-manager/internal/apis/certmanager::TestAugmentedRenewalSpecConvertsRoundTrip": { + "requirement_sections": [ + "Proposed API" + ], + "public_surface": "Generated v1<->internal Certificate conversion functions (pre-existing exported converters extended by codegen).", + "mutants_targeted": [], + "rationale": "The renewal policy and windows of the public API must round-trip the internal hub conversion untouched." + }, + "github.com/cert-manager/cert-manager/pkg/apis/certmanager/v1::TestAugmentedRenewalDeepCopyIsEqualAndIndependent": { + "requirement_sections": [ + "Proposed API" + ], + "public_surface": "DeepCopy on the public renewal API types.", + "mutants_targeted": [], + "rationale": "Deep copies of CertificateRenewal/Windows are equal to and independent of their originals, including through Certificate.Spec." + }, + "github.com/cert-manager/cert-manager/pkg/util/pki::TestAugmentedCronMatrixExactNextBoundaryIsUsed": { + "requirement_sections": [ + "Controller logic > Updated behavior" + ], + "public_surface": "pkg/util/pki RenewalTime called with documented renewal.policy=RenewBefore windows.", + "mutants_targeted": [], + "rationale": "Pins exact-boundary handling: a desired time just before a window opening moves exactly to that opening; a desired time exactly at an opening is already compliant. (mutant_006 remains classified equivalent per test_augmentation/equivalent_mutants.csv \u2014 probes corroborated the before-arm masking.)" + }, + "github.com/cert-manager/cert-manager/pkg/util/pki::TestAugmentedCronMatrixInvalidWindowsError": { + "requirement_sections": [ + "Controller logic > Updated behavior", + "Proposed API" + ], + "public_surface": "pkg/util/pki RenewalTime called with documented renewal.policy=RenewBefore windows.", + "mutants_targeted": [ + "mutant_009_window_duration_not_required", + "mutant_010_invalid_timezone_allowed" + ], + "rationale": "Invalid cron grammar (field counts, ranges, steps, names, descriptors), invalid timezones and missing/non-positive window durations surface as calculation errors through the public surface." + }, + "github.com/cert-manager/cert-manager/pkg/apis/certmanager/v1::TestAugmentedRenewalDeepCopyHandlesSparseShapes": { + "requirement_sections": [ + "Proposed API" + ], + "public_surface": "DeepCopy on the public renewal API types.", + "mutants_targeted": [], + "rationale": "Sparse shapes (nil window duration, empty windows, nil renewal) deep-copy safely and faithfully." + } + }, + "pass_to_pass": { + "github.com/cert-manager/cert-manager/pkg/api/util::TestAugmentedDNSSafeShortenToNCharacters": { + "requirement_sections": [ + "Motivation > Goals" + ], + "public_surface": "unchanged pkg/api/util public DNS-safe name helper.", + "rationale": "Guards adjacent unchanged name-shortening behavior promised by the backward-compatible API extension." + }, + "github.com/cert-manager/cert-manager/pkg/api/util::TestAugmentedSecureNameRejectsTooShortLimit": { + "requirement_sections": [ + "Motivation > Goals" + ], + "public_surface": "unchanged pkg/api/util public secure deterministic name helper.", + "rationale": "Guards adjacent unchanged secure-name validation behavior outside the renewal implementation surface." + } + } + }, + "equivalent_mutants": [], + "mutant_set_revision": { + "date": "2026-06-16", + "removed": [ + "mutant_006_exact_boundary_after_window_missed" + ], + "reason": "equivalent", + "note": "1 equivalent mutant(s) removed from mutations/ per the 2026-06-16 mutant-kill audit (no \u00a76-clean test can kill an equivalent mutant); union now kills all 11 remaining mutants.", + "new_total": 11, + "union_kills_all_remaining": true + } + }, + "validation_summary": { + "pre": { + "f2p": "all FAIL/ERROR", + "p2p": "all PASS" + }, + "post": { + "f2p": "all PASS", + "p2p": "all PASS", + "resolved": true + }, + "coverage_pct": 56.78, + "coverage_report": "coverage_out/coverage_report_union.json", + "coverage_report_aug": "coverage_out/coverage_report_aug.json", + "coverage_exception": "Union coverage remains below 80% after the documented coverage-improvement attempts. Current refreshed reports after P2P expansion are orig 41.58% (405/974), aug 54.31% (529/974), and union 56.78% (553/974). The remaining denominator is dominated by vendored robfig/cron scheduler files not used by the renewal feature (cron.go, option.go, constantdelay.go, much of logger.go) plus generated/apply-configuration code whose direct tests would be synthetic or would invoke PR-added generated source symbols not named in the requirement doc. Behavioral feature code remains well covered: validation/certificate.go 100%, checks.go 100%, renewaltime.go 89.86%, and util.go 100% in the final union report.", + "codex_review": "Augmented selectors obey the new-source-symbol rule: they do not call PR-added private helpers such as findAfterDesired or validateCertificateRenewal, and the only equivalent mutant is documented in test_augmentation/equivalent_mutants.csv.", + "p2p_expansion": "2026-06-16: expanded p2p.txt to 48 pre-existing original upstream selectors; p2p_aug.txt remains unchanged with 2 synthesized selectors, so union P2P is 50. Orig pre/post and union pre/post validation passed the P2P gate." + }, + "merge_commit_sha": "1756a823b00d337d33058c528a8a3c349388e93f", + "test_cmd_template": "go test -count=1 -timeout=20m -json -run ", + "log_parser": "go_test_json", + "agent_contract": { + "input": "/in/solution.patch", + "output": "/out/agent_report.json", + "invocation": "docker run --rm -v $(pwd)/solution.patch:/in/solution.patch:ro -v $(pwd)/out:/out lolbench/cert-manager-pr-8258:1" + }, + "coverage": { + "orig": 41.58, + "aug": 54.31, + "union": 56.78, + "denominator": "union_executable_lines" + } +} \ No newline at end of file diff --git a/cert-manager_1/tests/report_to_reward.py b/cert-manager_1/tests/report_to_reward.py new file mode 100644 index 0000000000000000000000000000000000000000..b1144e45515947fc82904fa267adecc040ac7adc --- /dev/null +++ b/cert-manager_1/tests/report_to_reward.py @@ -0,0 +1,73 @@ +#!/usr/bin/env python3 +import argparse +import json +from pathlib import Path + + +def rate(bucket): + total = float(bucket.get("total", 0) or 0) + if total <= 0: + return 0.0 + return float(bucket.get("passed", 0) or 0) / total + + +def write_json(path, payload): + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(json.dumps(payload, indent=2, sort_keys=True) + "\n") + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument("--suite", default="union") + parser.add_argument("--missing-patch") + parser.add_argument("--invalid-suite", action="store_true") + parser.add_argument("--runner-rc", type=int, default=0) + parser.add_argument("agent_report") + parser.add_argument("reward_file") + args = parser.parse_args() + + report_path = Path(args.agent_report) + reward_path = Path(args.reward_file) + + if args.invalid_suite: + reward = {"reward": 0.0, "resolved": 0.0, "applied": 0.0, "build_ok": 0.0, "f2p_pass_rate": 0.0, "p2p_pass_rate": 0.0, "harness_ok": 1.0} + sanitized = {"instance_id": "cert-manager_1", "suite": args.suite, "applied": False, "resolved": False, "error_categories": ["invalid_lolbench_suite"]} + write_json(report_path, sanitized) + write_json(reward_path, reward) + print(f"LoLBench reward=0 invalid suite {args.suite!r}") + return 0 + + if args.missing_patch: + reward = {"reward": 0.0, "resolved": 0.0, "applied": 0.0, "build_ok": 0.0, "f2p_pass_rate": 0.0, "p2p_pass_rate": 0.0, "harness_ok": 1.0} + sanitized = {"instance_id": "cert-manager_1", "suite": args.suite, "applied": False, "resolved": False, "error_categories": ["missing_solution_patch"]} + write_json(report_path, sanitized) + write_json(reward_path, reward) + print("LoLBench reward=0 missing solution patch") + return 0 + + if not report_path.exists(): + reward = {"reward": 0.0, "resolved": 0.0, "applied": 0.0, "build_ok": 0.0, "f2p_pass_rate": 0.0, "p2p_pass_rate": 0.0, "harness_ok": 0.0} + write_json(reward_path, reward) + print(f"LoLBench reward=0 no agent_report.json runner_rc={args.runner_rc}") + return 0 + + report = json.loads(report_path.read_text()) + build_status = report.get("build", {}).get("status") + resolved = bool(report.get("resolved")) + applied = bool(report.get("applied")) + reward = { + "reward": 1.0 if resolved else 0.0, + "resolved": 1.0 if resolved else 0.0, + "applied": 1.0 if applied else 0.0, + "build_ok": 1.0 if build_status == "ok" else 0.0, + "f2p_pass_rate": rate(report.get("f2p", {})), + "p2p_pass_rate": rate(report.get("p2p", {})), + "harness_ok": 1.0 if args.runner_rc == 0 else 0.0, + } + write_json(reward_path, reward) + print("LoLBench reward={reward} resolved={resolved} f2p={f2p_pass_rate:.3f} p2p={p2p_pass_rate:.3f}".format(**reward)) + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/cert-manager_1/tests/test.sh b/cert-manager_1/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..45ba2abd4f682d021752e6966a772a0ee2edb9f5 --- /dev/null +++ b/cert-manager_1/tests/test.sh @@ -0,0 +1,43 @@ +#!/usr/bin/env bash +set -euo pipefail + +suite=${LOLBENCH_SUITE:-union} +mode=${LOLBENCH_MODE:-eval} +patch=${LOLBENCH_SOLUTION_PATCH:-/logs/artifacts/solution.patch} +private_log=/tmp/lolbench-private-run.log + +mkdir -p /logs/verifier /logs/artifacts /in /out + +case "$suite" in + orig|aug|union) ;; + *) + python3 /tests/report_to_reward.py --suite "$suite" --invalid-suite /out/agent_report.json /logs/verifier/reward.json + exit 0 + ;; +esac + +if [ "$mode" = "eval" ] && [ ! -s "$patch" ]; then + python3 /tests/report_to_reward.py --suite "$suite" --missing-patch "$patch" /out/agent_report.json /logs/verifier/reward.json + exit 0 +fi + +if [ "$mode" = "eval" ]; then + cp "$patch" /in/solution.patch + chmod 0400 /in/solution.patch +fi + +set +e +LOLBENCH_MODE="$mode" LOLBENCH_SUITE="$suite" /opt/lolbench/private/run_tests.sh >"$private_log" 2>&1 +runner_rc=$? +set -e + +cp "$private_log" /logs/verifier/private_run.log +if [ -f /out/grader_report.json ]; then + cp /out/grader_report.json /logs/verifier/grader_report.json +fi + +python3 /tests/report_to_reward.py --suite "$suite" --runner-rc "$runner_rc" /out/agent_report.json /logs/verifier/reward.json + +if [ -f /out/agent_report.json ]; then + cp /out/agent_report.json /logs/verifier/agent_report.json +fi diff --git a/cpython_1/README.md b/cpython_1/README.md new file mode 100644 index 0000000000000000000000000000000000000000..8748b354c4006ba1cee5ff51f5b5114a4bfb3158 --- /dev/null +++ b/cpython_1/README.md @@ -0,0 +1,87 @@ +# LoLBench Harbor Task: cpython_1 + +This is a Harbor-format LoLBench task generated from `CPython_PEP-617_New-PEG-parser-for-CPython_PR-19503`. + +Selected source instance: + +- Harbor ID: `cpython_1` +- PR: `python/cpython#19503` +- Base commit: `a81849b0315277bb3937271174aaaa5059c0b445` +- Test modes: `orig, aug, union` +- Default/canonical mode: `union` +- Harbor image: `smartdub26/lolbench-linux:cpython_1-1.0.0` +- Docker Hub image: `smartdub26/lolbench-linux:cpython_1-1.0.0` + +## Image Setup + +Prefer the published Docker Hub image when it is available. Harbor refers to +the image as `smartdub26/lolbench-linux:cpython_1-1.0.0`, so Docker can pull it +directly when it is not present locally: + +```bash +docker pull smartdub26/lolbench-linux:cpython_1-1.0.0 +``` + +Only if the Docker Hub image is unavailable, build the single task image +locally: + +```bash +docker build -t lolbench/cpython_1:1.0.0 harbor_tasks/cpython_1/environment +docker tag lolbench/cpython_1:1.0.0 smartdub26/lolbench-linux:cpython_1-1.0.0 +``` + +The image contains the processed source tree at the base commit under +`/workspace/cpython`. Harbor must not mount a host source checkout +for the agent. + +## Run an Agent + +```bash +.harbor-venv/bin/harbor run \ + -p harbor_tasks/cpython_1 \ + -a codex \ + -m "" \ + --job-name cpython_1_agent_union \ + --jobs-dir harbor_runs/cpython_1 \ + --no-delete \ + --n-concurrent 1 \ + --ve LOLBENCH_SUITE=union +``` + +After implementing the requirement, the agent must clean any test-file edits +and run: + +```bash +lolbench-submit +``` + +## Evaluate a Patch + +Choose one mode with `LOLBENCH_SUITE=orig`, `aug`, or `union`; if unset, the +task defaults to `union`. + +```bash +PATCH="$(pwd)/path/to/solution.patch" + +.harbor-venv/bin/harbor run \ + -p harbor_tasks/cpython_1 \ + -a oracle \ + --job-name cpython_1_eval_union \ + --jobs-dir harbor_runs/cpython_1 \ + --no-delete \ + --n-concurrent 1 \ + --mounts '[{"type":"bind","source":"'"$PATCH"'","target":"/candidate/solution.patch","read_only":true}]' \ + --ae LOLBENCH_ORACLE_PATCH=/candidate/solution.patch \ + --ve LOLBENCH_SUITE=union +``` + +Outputs: + +```bash +find harbor_runs/cpython_1/cpython_1_eval_union -path '*/verifier/agent_report.json' -print +find harbor_runs/cpython_1/cpython_1_eval_union -path '*/verifier/reward.json' -print +``` + +`tests/docker-compose.yaml` is a verifier-only Harbor overlay. It mounts +`tests/`, `tests/private/`, and `solution/` into the separate verifier +container; none of those paths are mounted into the agent container. diff --git a/cpython_1/environment/Dockerfile b/cpython_1/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..71b633f7bbc0838b51793d54dc015ab32977cddb --- /dev/null +++ b/cpython_1/environment/Dockerfile @@ -0,0 +1,157 @@ +# LoLBench eval image: CPython PR-19503 (PEP 617: New PEG parser for CPython) +# Requirement: https://peps.python.org/pep-0617/ +# base_commit: a81849b0315277bb3937271174aaaa5059c0b445 (2020-03-20, +# parent of merge commit c5fc1568 — see spec.json +# base_commit_note for why this overrides the CSV value) +# +# Agent-facing contract (the agent does NOT run anything inside this image; +# the evaluator runs the container after the agent submits a solution.patch): +# +# docker run --rm \ +# --network=none \ +# -v $(pwd)/solution.patch:/in/solution.patch:ro \ +# -v $(pwd)/out:/out \ +# lolbench/cpython-pr-19503:1 +# +# Unlike the PEP-768 instance, this PR (PEP 617's new PEG parser) does +# NOT need --cap-add=SYS_PTRACE: the new parser runs entirely in-process, +# no cross-process attach. The container stays --network=none with the +# default seccomp profile. +# +# Because the agent's code never executes here, the container runs every +# step as root — no agent UID, no chown of /usr/local, no runuser dance. +# +# Layered build per docs/executable_environment_plan.md §4: +# layer 1: ubuntu:22.04 +# layer 2: lolbench/cpython-base:1 (toolchain + stdlib build deps) +# layer 3: THIS image (cpython @ base_commit + built python + private bundle) + +ARG BASE_IMAGE=lolbench/cpython-base:1 +FROM ${BASE_IMAGE} + +ARG BASE_COMMIT=a81849b0315277bb3937271174aaaa5059c0b445 + +# ---- Per-instance dirs ------------------------------------------------ +# /opt/lolbench/private/ holds the eval-side artifacts (eval_tests.patch, +# selectors, golden solution.patch, run_tests.sh). We keep the path +# name `private` to document intent; perms are default since the +# container is only ever run by the trusted evaluator. +RUN mkdir -p /opt/lolbench/private /in /out /workspace + +# ---- Source tree at base_commit --------------------------------------- +# After fetching at the exact base_commit, we reset git history so +# `git log` inside the container does not reveal the SHA (kept for +# tidiness; the evaluator already knows the base, the agent never +# sees the container). +WORKDIR /workspace +RUN git init cpython && \ + cd cpython && \ + git remote add origin https://github.com/python/cpython.git && \ + git fetch --no-tags origin ${BASE_COMMIT} && \ + git checkout ${BASE_COMMIT} && \ + git config user.email lolbench@local && \ + git config user.name lolbench && \ + if ! git diff --quiet || ! git diff --cached --quiet || [ -n "$(git ls-files --others --exclude-standard)" ]; then \ + git add -A && git -c commit.gpgsign=false commit -q -m "LoLBench environment overlay"; \ + fi && \ + git tag -f base && git tag -f lolbench-base && \ + git for-each-ref --format='%(refname)' refs/heads refs/remotes refs/tags | \ + while read ref; do \ + case "$ref" in refs/tags/base|refs/tags/lolbench-base) ;; *) git update-ref -d "$ref" ;; esac; \ + done && \ + ( git remote remove origin 2>/dev/null || true ) && \ + rm -f .git/FETCH_HEAD && \ + git reflog expire --expire=now --all && \ + git repack -Ad && \ + git prune --expire=now && \ + git config --global --add safe.directory /workspace/cpython + +# ---- Pre-build CPython at base_commit --------------------------------- +# A single full build at base_commit warms the build tree so that +# applying solution.patch at eval time only triggers an incremental +# rebuild (Make handles the dependency graph). We deliberately do NOT +# pre-apply the patch — the eval/validate dispatcher decides which +# patch to apply per run. +# +# Build flags rationale: +# --prefix=/usr/local : keep system layout; we use ./python, not the +# installed binary, so the install step is omitted +# --with-pydebug : OFF (default). Enabling pydebug doubles test +# duration and changes ABI in ways unrelated to +# PEP 617. We build the release configuration. +# --enable-shared : OFF (default). The static interpreter is what +# regrtest expects. +# PEP 617 build : no extra configure flags; the new PEG parser is +# compiled in when Parser/pegen/*.c and +# Modules/_peg_parser.c are present (added by +# solution.patch). At pre-state those files are +# absent → base build is plain old-parser +# CPython 3.9.0a5 from a81849b0. +# `set -o pipefail` so `make ... | tee log` propagates make's non-zero +# exit; otherwise a broken CPython build could ship as a green image +# (the pipeline's exit status would be tee's exit status, which is 0). +SHELL ["/bin/bash", "-o", "pipefail", "-c"] +RUN cd /workspace/cpython && \ + ./configure --prefix=/usr/local --enable-optimizations=no && \ + jobs=$(awk '$1!="max"{printf("%d", ($1+$2-1)/$2)}' /sys/fs/cgroup/cpu.max 2>/dev/null); \ + : "${jobs:=$(nproc)}"; \ + [ "$jobs" -lt 1 ] && jobs=1; \ + make -j"$jobs" 2>&1 | tee /tmp/cpython-build.log | tail -400 + +# ---- Eval bundle ------------------------------------------------------ +# All eval-side files live in the instance directory root. The +# Dockerfile bakes them into /opt/lolbench/private/ inside the +# container; the path name is just a stable tooling convention since +# the container runs as root throughout (the agent/evaluator boundary +# is the eval API, not Unix permissions). + +# Harbor runtime adapter: keep the image public/agent-safe. +RUN mkdir -p /opt/lolbench /logs/artifacts /logs/agent /logs/verifier /in /out && \ + if ! id -u agent >/dev/null 2>&1; then useradd -m -s /bin/bash agent; fi +COPY metadata.json /opt/lolbench/metadata.json +COPY lolbench-submit /usr/local/bin/lolbench-submit +RUN chmod +x /usr/local/bin/lolbench-submit && \ + git config --global --add safe.directory /workspace/cpython && \ + if [ -d /workspace/cpython/.git ]; then \ + cd /workspace/cpython && git ls-files --others --exclude-standard | sort > /opt/lolbench/base_untracked.txt; \ + else \ + : > /opt/lolbench/base_untracked.txt; \ + fi && \ + chown -R agent:agent /workspace/cpython /logs +# Local-reference hardening: retain only the approved base history. +RUN cd /workspace/cpython && \ + git for-each-ref --format='%(refname)' refs/heads refs/remotes refs/tags | \ + while read ref; do \ + case "$ref" in refs/tags/base|refs/tags/lolbench-base) ;; *) git update-ref -d "$ref" ;; esac; \ + done && \ + ( git remote remove origin 2>/dev/null || true ) && \ + rm -f .git/FETCH_HEAD && \ + git reflog expire --expire=now --all && \ + git repack -Ad && \ + git prune --expire=now && \ + unreachable=$(git fsck --unreachable --no-reflogs) && \ + test -z "$unreachable" && \ + chown -R agent:agent .git +# Remove installed Python source copies/backports and package caches. +RUN for root in /usr/local/lib /usr/lib; do \ + [ ! -d "$root" ] || find "$root" -type d \ + \( -path '*/site-packages/pip' -o -path '*/dist-packages/pip' -o \ + -name ensurepip -o -name tomllib -o -name zoneinfo -o \ + -path '*/site-packages/tomli*' -o -path '*/dist-packages/tomli*' -o \ + -path '*/site-packages/typing_extensions*' -o -path '*/dist-packages/typing_extensions*' -o \ + -path '*/site-packages/exceptiongroup*' -o -path '*/dist-packages/exceptiongroup*' \) \ + -prune -exec rm -rf '{}' +; \ + [ ! -d "$root" ] || find "$root" -type f \ + \( -name 'tomli*.py' -o -name 'typing_extensions*.py' -o -name 'exceptiongroup*.py' \) -delete; \ + done && \ + rm -rf /usr/share/python-wheels /usr/share/python3-wheels \ + /root/.cache/pip /root/.cache/uv /home/agent/.cache/pip /home/agent/.cache/uv && \ + rm -f /usr/local/bin/pip /usr/local/bin/pip3 /usr/local/bin/pip3.* \ + /usr/bin/pip /usr/bin/pip3 /usr/bin/pip3.* && \ + for p in /usr/local/lib/python*/site-packages /usr/lib/python*/dist-packages; do \ + [ ! -d "$p" ] || { chown -R root:root "$p"; chmod -R go-w "$p"; chmod 0711 "$p"; }; \ + done +USER agent +WORKDIR /workspace/cpython +ENV LOLBENCH_INSTANCE_ID=cpython_1 +ENV LOLBENCH_SOURCE_SLUG=CPython_PEP-617_New-PEG-parser-for-CPython_PR-19503 diff --git a/cpython_1/environment/docker-compose.yaml b/cpython_1/environment/docker-compose.yaml new file mode 100644 index 0000000000000000000000000000000000000000..7ed45f87dc9faf9df284f5b10d6d2289781ff254 --- /dev/null +++ b/cpython_1/environment/docker-compose.yaml @@ -0,0 +1,3 @@ +services: + main: + pull_policy: missing diff --git a/cpython_1/environment/lolbench-submit b/cpython_1/environment/lolbench-submit new file mode 100644 index 0000000000000000000000000000000000000000..0f89163f3f975ed8856ef411059c188c40e2eabc --- /dev/null +++ b/cpython_1/environment/lolbench-submit @@ -0,0 +1,32 @@ +#!/usr/bin/env bash +set -euo pipefail + +repo=${1:-$PWD} +out=${LOLBENCH_PATCH_OUT:-/logs/artifacts/solution.patch} + +mkdir -p "$(dirname "$out")" +cd "$repo" + +baseline=/opt/lolbench/base_untracked.txt +current=$(mktemp) +new_files=$(mktemp) +trap 'rm -f "$current" "$new_files"' EXIT + +git ls-files --others --exclude-standard | sort > "$current" +if [ -f "$baseline" ]; then + comm -13 "$baseline" "$current" > "$new_files" +else + cp "$current" "$new_files" +fi + +if [ -s "$new_files" ]; then + xargs -r git add -N -- < "$new_files" +fi + +git diff --binary > "$out" + +if [ ! -s "$out" ]; then + echo "warning: wrote an empty solution patch to $out" >&2 +else + echo "wrote solution patch to $out" +fi diff --git a/cpython_1/environment/metadata.json b/cpython_1/environment/metadata.json new file mode 100644 index 0000000000000000000000000000000000000000..8859a05ef33981e237968784e89addfc0547bf1f --- /dev/null +++ b/cpython_1/environment/metadata.json @@ -0,0 +1,22 @@ +{ + "instance_id": "cpython_1", + "source_instance_id": "CPython_PEP-617_New-PEG-parser-for-CPython_PR-19503", + "source_slug": "CPython_PEP-617_New-PEG-parser-for-CPython_PR-19503", + "docker_slug": "CPython_PEP-617_New-PEG-parser-for-CPython_PR-19503", + "dockerhub_image": "smartdub26/lolbench-linux:cpython_1-1.0.0", + "project": "cpython", + "repo": "python/cpython", + "requirement_doc": "https://peps.python.org/pep-0617/", + "pr_link": "https://github.com/python/cpython/pull/19503", + "base_commit": "a81849b0315277bb3937271174aaaa5059c0b445", + "merge_commit": "c5fc15685202cda73f7c3f5c6f299b0945f58508", + "source_history_policy": "ancestors-only", + "lolbench_test_modes": [ + "orig", + "aug", + "union" + ], + "default_lolbench_suite": "union", + "canonical_lolbench_suite": "union", + "augmentation_available": true +} diff --git a/cpython_1/environment/source_audit.json b/cpython_1/environment/source_audit.json new file mode 100644 index 0000000000000000000000000000000000000000..1490740fb24191608b0240427029f8201b79e031 --- /dev/null +++ b/cpython_1/environment/source_audit.json @@ -0,0 +1,7 @@ +{ + "source_policy": "dockerfile_fetch_pruned_ancestor_history", + "local_reference_policy": "auxiliary_sources_removed_execute_only", + "base_commit": "a81849b0315277bb3937271174aaaa5059c0b445", + "repo": "python/cpython", + "note": "The Dockerfile fetches only the declared base history, removes refs/remotes/reflogs, repacks and prunes unreachable objects, asserts that git fsck finds no unreachable object, removes auxiliary reference sources, and makes remaining auxiliary toolchains root-owned and non-enumerable to the agent." +} diff --git a/cpython_1/instruction.md b/cpython_1/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..aa773dc843a6578732bb53d5f3cef65dfdc4fea1 --- /dev/null +++ b/cpython_1/instruction.md @@ -0,0 +1,722 @@ +You are working in `/workspace/cpython`, a source tree checked out at +the base commit for this task. Implement the requested behavior in the source +tree, then run: + +```bash +lolbench-submit +``` + +Do not stop after editing files, running tests, or describing the solution. The +task is complete only when `lolbench-submit` has created +`/logs/artifacts/solution.patch`. If that file does not exist, continue +working and run `lolbench-submit` again. + +That command writes your implementation diff to +`/logs/artifacts/solution.patch`, which is the artifact the Harbor verifier +will grade. Before running `lolbench-submit`, clean or revert any test files +you created or modified; test files must not be included in the final +`solution.patch`. + +This environment has no outbound internet access — `curl`/`wget`, `git fetch`/`clone`, package installs, and web fetch/search will all fail. Implement the requirements using only the code already in the workspace and your own knowledge; do not attempt to fetch or search external resources. + +Now please implement the following requirements in the source tree: + +--- + +# PEP 617: New PEG parser for CPython + +## Overview +This PEP proposes replacing the current LL(1)-based parser of CPython +with a new PEG-based parser. This new parser would allow the elimination of multiple +"hacks" that exist in the current grammar to circumvent the LL(1)-limitation. +It would substantially reduce the maintenance costs in some areas related to the +compiling pipeline such as the grammar, the parser and the AST generation. The new PEG +parser will also lift the LL(1) restriction on the current Python grammar. + +## Background on LL(1) parsers +The current Python grammar is an LL(1)-based grammar. A grammar can be said to be +LL(1) if it can be parsed by an LL(1) parser, which in turn is defined as a +top-down parser that parses the input from left to right, performing leftmost +derivation of the sentence, with just one token of lookahead. +The traditional approach to constructing or generating an LL(1) parser is to +produce a *parse table* which encodes the possible transitions between all possible +states of the parser. These tables are normally constructed from the *first sets* +and the *follow sets* of the grammar: + +* Given a rule, the *first set* is the collection of all terminals that can occur + first in a full derivation of that rule. Intuitively, this helps the parser decide + among the alternatives in a rule. For + instance, given the rule: + +``` +rule: A | B +``` + if only `A` can start with the terminal *a* and only `B` can start with the + terminal *b* and the parser sees the token *b* when parsing this rule, it knows + that it needs to follow the non-terminal `B`. + +* An extension to this simple idea is needed when a rule may expand to the empty string. + Given a rule, the *follow set* is the collection of terminals that can appear + immediately to the right of that rule in a partial derivation. Intuitively, this + solves the problem of the empty alternative. For instance, + given this rule: + +``` +rule: A 'b' +``` + if the parser has the token *b* and the non-terminal `A` can only start + with the token *a*, then the parser can tell that this is an invalid program. + But if `A` could expand to the empty string (called an ε-production), + then the parser would recognise a valid empty `A`, + since the next token *b* is in the *follow set* of `A`. + +The current Python grammar does not contain ε-productions, so the *follow sets* are not +needed when creating the parse tables. Currently, in CPython, a parser generator +program reads the grammar and produces a parsing table representing a set of +deterministic finite automata (DFA) that can be included in a C program, the +parser. The parser is a pushdown automaton that uses this data to produce a Concrete +Syntax Tree (CST) sometimes known directly as a "parse tree". In this process, the +*first sets* are used indirectly when generating the DFAs. + +LL(1) parsers and grammars are usually efficient and simple to implement +and generate. However, it is not possible, under the LL(1) restriction, +to express certain common constructs in a way natural to the language +designer and the reader. This includes some in the Python language. + +As LL(1) parsers can only look one token ahead to distinguish +possibilities, some rules in the grammar may be ambiguous. For instance the rule: + +``` +rule: A | B +``` +is ambiguous if the *first sets* of both `A` and `B` have some elements in +common. When the parser sees a token in the input +program that both *A* and *B* can start with, it is impossible for it to deduce +which option to expand, as no further token of the program can be examined to +disambiguate. +The rule may be transformed to equivalent LL(1) rules, but then it may +be harder for a human reader to grasp its meaning. +Examples later in this document show that the current LL(1)-based +grammar suffers a lot from this scenario. + +Another broad class of rules precluded by LL(1) is left-recursive rules. +A rule is left-recursive if it can derive to a +sentential form with itself as the leftmost symbol. For instance this rule: + +``` +rule: rule 'a' +``` +is left-recursive because the rule can be expanded to an expression that starts +with itself. As will be described later, left-recursion is the natural way to +express certain desired language properties directly in the grammar. + +## Background on PEG parsers +A PEG (Parsing Expression Grammar) grammar differs from a context-free grammar +(like the current one) in the fact that the way it is written more closely +reflects how the parser will operate when parsing it. The fundamental technical +difference is that the choice operator is ordered. This means that when writing: + +``` +rule: A | B | C +``` +a context-free-grammar parser (like an LL(1) parser) will generate constructions +that given an input string will *deduce* which alternative (`A`, `B` or `C`) +must be expanded, while a PEG parser will check if the first alternative succeeds +and only if it fails, will it continue with the second or the third one in the +order in which they are written. This makes the choice operator not commutative. + +Unlike LL(1) parsers, PEG-based parsers cannot be ambiguous: if a string parses, +it has exactly one valid parse tree. This means that a PEG-based parser cannot +suffer from the ambiguity problems described in the previous section. + +PEG parsers are usually constructed as a recursive descent parser in which every +rule in the grammar corresponds to a function in the program implementing the +parser and the parsing expression (the "expansion" or "definition" of the rule) +represents the "code" in said function. Each parsing function conceptually takes +an input string as its argument, and yields one of the following results: + +* A "success" result. This result indicates that the expression can be parsed by + that rule and the function may optionally move forward or consume one or more + characters of the input string supplied to it. +* A "failure" result, in which case no input is consumed. + +Notice that "failure" results do not imply that the program is incorrect or a +parsing failure because as the choice operator is ordered, a "failure" result +merely indicates "try the following option". A direct implementation of a PEG +parser as a recursive descent parser will present exponential time performance in +the worst case as compared with LL(1) parsers, because PEG parsers have infinite lookahead +(this means that they can consider an arbitrary number of tokens before deciding +for a rule). Usually, PEG parsers avoid this exponential time complexity with a +technique called "packrat parsing" [1]_ which not only loads the entire +program in memory before parsing it but also allows the parser to backtrack +arbitrarily. This is made efficient by memoizing the rules already matched for +each position. The cost of the memoization cache is that the parser will naturally +use more memory than a simple LL(1) parser, which normally are table-based. We +will explain later in this document why we consider this cost acceptable. + +## Rationale +In this section, we describe a list of problems that are present in the current parser +machinery in CPython that motivates the need for a new parser. + +### Some rules are not actually LL(1) +Although the Python grammar is technically an LL(1) grammar (because it is parsed by +an LL(1) parser) several rules are not LL(1) and several workarounds are +implemented in the grammar and in other parts of CPython to deal with this. For +example, consider the rule for assignment expressions: + +``` +namedexpr_test: [NAME ':='] test +``` +This simple rule is not compatible with the Python grammar as *NAME* is among the +elements of the *first set* of the rule *test*. To work around this limitation the +actual rule that appears in the current grammar is: + +``` +namedexpr_test: test [':=' test] +``` +Which is a much broader rule than the previous one allowing constructs like ``[x +for x in y] := [1,2,3]``. The way the rule is limited to its desired form is by +disallowing these unwanted constructions when transforming the parse tree to the +abstract syntax tree. This is not only inelegant but a considerable maintenance +burden as it forces the AST creation routines and the compiler into a situation in +which they need to know how to separate valid programs from invalid programs, +which should be a responsibility solely of the parser. This also leads to the +actual grammar file not reflecting correctly what the *actual* grammar is (that +is, the collection of all valid Python programs). + +Similar workarounds appear in multiple other rules of the current grammar. +Sometimes this problem is unsolvable. For instance, [bpo-12782: Multiple context expressions do not support parentheses for continuation across lines](https://github.com/python/cpython/issues/56991) shows how making an LL(1) rule that supports +writing: + +``` +with ( + open("a_really_long_foo") as foo, + open("a_really_long_baz") as baz, + open("a_really_long_bar") as bar +): + ... +``` +is not possible since the first sets of the grammar items that can +appear as context managers include the open parenthesis, making the rule +ambiguous. This rule is not only consistent with other parts of the language (like +the rule for multiple imports), but is also very useful to auto-formatting tools, +as parenthesized groups are normally used to group elements to be +formatted together (in the same way the tools operate on the contents of lists, +sets...). + +### Complicated AST parsing +Another problem of the current parser is that there is a huge coupling between the +AST generation routines and the particular shape of the produced parse trees. This +makes the code for generating the AST especially complicated as many actions and +choices are implicit. For instance, the AST generation code knows what +alternatives of a certain rule are produced based on the number of child nodes +present in a given parse node. This makes the code difficult to follow as this +property is not directly related to the grammar file and is influenced by +implementation details. As a result of this, a considerable amount of the AST +generation code needs to deal with inspecting and reasoning about the particular +shape of the parse trees that it receives. + +### Lack of left recursion +As described previously, a limitation of LL(1) grammars is that they cannot allow +left-recursion. This makes writing some rules very unnatural and far from how +programmers normally think about the program. For instance this construct (a simpler +variation of several rules present in the current grammar): + +``` +expr: expr '+' term | term +``` +cannot be parsed by an LL(1) parser. The traditional remedy is to rewrite the +grammar to circumvent the problem: + +``` +expr: term ('+' term)* +``` +The problem that appears with this form is that the parse tree is forced to have a +very unnatural shape. This is because with this rule, for the input program ``a + +b + c` the parse tree will be flattened (`['a', '+', 'b', '+', 'c']``) and must +be post-processed to construct a left-recursive parse tree (``[['a', '+', 'b'], +'+', 'c']``). Being forced to write the second rule not only leads to the parse +tree not correctly reflecting the desired associativity, but also imposes further +pressure on later compilation stages to detect and post-process these cases. + +### Intermediate parse tree +The last problem present in the current parser is the intermediate creation of a +parse tree or Concrete Syntax Tree that is later transformed to an Abstract Syntax +Tree. Although the construction of a CST is very common in parser and compiler +pipelines, in CPython this intermediate CST is not used by anything else (it is +only indirectly exposed by the *parser* module and a surprisingly small part of +the code in the CST production is reused in the module). Which is worse: the whole +tree is kept in memory, keeping many branches that consist of chains of nodes with +a single child. This has been shown to consume a considerable amount of memory (for +instance in [bpo-26415: Excessive peak memory consumption by the Python parser](https://github.com/python/cpython/issues/70603)). + +Having to produce an intermediate result between the grammar and the AST is not only +undesirable but also makes the AST generation step much more complicated, raising +considerably the maintenance burden. + +## The new proposed PEG parser +The new proposed PEG parser contains the following pieces: + +* A parser generator that can read a grammar file and produce a PEG parser + written in Python or C that can parse said grammar. + +* A PEG meta-grammar that automatically generates a Python parser that is used + for the parser generator itself (this means that there are no manually-written + parsers). + +* A generated parser (using the parser generator) that can directly produce C and + Python AST objects. + +On the implementation side, the Python parser generator exposes these steps as `parse_string`, which runs a parser class over grammar source text; `generate_parser`, which turns a parsed `Grammar` into a parser class; and `make_parser`, which composes the two to build a parser directly from grammar source. +Expose the parser-generator package under `Tools/peg_generator/pegen/`; in +particular, provide `pegen.grammar_parser.GeneratedParser` (commonly used as +`GrammarParser`), `pegen.testutil.parse_string`, +`pegen.testutil.generate_parser`, `pegen.testutil.make_parser`, +`pegen.testutil.generate_parser_c_extension`, +`pegen.testutil.generate_c_parser_source`, `pegen.grammar.Grammar`, +`pegen.grammar.GrammarError`, `pegen.grammar.GrammarVisitor`, and +`pegen.first_sets.FirstSetCalculator`. + +### Left recursion +PEG parsers normally do not support left recursion but we have implemented a +technique similar to the one described in Medeiros et al. [2]_ but using the +memoization cache instead of static variables. This approach is closer to the one +described in Warth et al. [3]_. This allows us to write not only simple left-recursive +rules but also more complicated rules that involve indirect left-recursion like: + +``` +rule1: rule2 | 'a' +rule2: rule3 | 'b' +rule3: rule1 | 'c' +``` +and "hidden left-recursion" like: + +``` +rule: 'optional'? rule '@' some_other_rule +``` +### Syntax +The grammar consists of a sequence of rules of the form: + +``` +rule_name: expression +``` +Optionally, a type can be included right after the rule name, which +specifies the return type of the C or Python function corresponding to +the rule: + +``` +rule_name[return_type]: expression +``` +If the return type is omitted, then a `void *` is returned in C and an +`Any` in Python. + +#### Grammar Expressions +`# comment` +''''''''''''' + +Python-style comments. + +`e1 e2` +''''''''' + +Match e1, then match e2. + +```PEG +rule_name: first_rule second_rule +``` +`e1 | e2` +''''''''''' + +Match e1 or e2. + +The first alternative can also appear on the line after the rule name +for formatting purposes. In that case, a \| must be used before the +first alternative, like so: + +```PEG +rule_name[return_type]: + | first_alt + | second_alt +``` +`( e )` +''''''''' + +Match e. + +```PEG +rule_name: (e) +``` +A slightly more complex and useful example includes using the grouping +operator together with the repeat operators: + +```PEG +rule_name: (e1 e2)* +``` +`[ e ] or e?` +''''''''''''''' + +Optionally match e. + +```PEG +rule_name: [e] +``` +A more useful example includes defining that a trailing comma is +optional: + +```PEG +rule_name: e (',' e)* [','] +``` +`e*` +'''''' + +Match zero or more occurrences of e. + +```PEG +rule_name: (e1 e2)* +``` +`e+` +'''''' + +Match one or more occurrences of e. + +```PEG +rule_name: (e1 e2)+ +``` +`s.e+` +'''''''' + +Match one or more occurrences of e, separated by s. The generated parse +tree does not include the separator. This is otherwise identical to +`(e (s e)*)`. + +```PEG +rule_name: ','.e+ +``` +`&e` +'''''' + +Succeed if e can be parsed, without consuming any input. + +`!e` +'''''' + +Fail if e can be parsed, without consuming any input. + +An example taken from the proposed Python grammar specifies that a primary +consists of an atom, which is not followed by a `.` or a `(` or a +`[`: + +```PEG +primary: atom !'.' !'(' !'[' +``` +`~` +'''''' + +Commit to the current alternative, even if it fails to parse. + +```PEG +rule_name: '(' ~ some_rule ')' | some_alt +``` +In this example, if a left parenthesis is parsed, then the other +alternative won’t be considered, even if some_rule or ‘)’ fail to be +parsed. + +#### Variables in the Grammar +A subexpression can be named by preceding it with an identifier and an +`=` sign. The name can then be used in the action (see below), like this: + +``` +rule_name[return_type]: '(' a=some_other_rule ')' { a } +``` +### Grammar actions +To avoid the intermediate steps that obscure the relationship between the +grammar and the AST generation the proposed PEG parser allows directly +generating AST nodes for a rule via grammar actions. Grammar actions are +language-specific expressions that are evaluated when a grammar rule is +successfully parsed. These expressions can be written in Python or C +depending on the desired output of the parser generator. This means that if +one would want to generate a parser in Python and another in C, two grammar +files should be written, each one with a different set of actions, keeping +everything else apart from said actions identical in both files. As an +example of a grammar with Python actions, the piece of the parser generator +that parses grammar files is bootstrapped from a meta-grammar file with +Python actions that generate the grammar tree as a result of the parsing. + +In the specific case of the new proposed PEG grammar for Python, having +actions allows directly describing how the AST is composed in the grammar +itself, making it more clear and maintainable. This AST generation process is +supported by the use of some helper functions that factor out common AST +object manipulations and some other required operations that are not directly +related to the grammar. + +To indicate these actions each alternative can be followed by the action code +inside curly-braces, which specifies the return value of the alternative: + +``` +rule_name[return_type]: + | first_alt1 first_alt2 { first_alt1 } + | second_alt1 second_alt2 { second_alt1 } +``` +If the action is omitted and C code is being generated, then there are two +different possibilities: + +1. If there’s a single name in the alternative, this gets returned. +2. If not, a dummy name object gets returned (this case should be avoided). + +If the action is omitted and Python code is being generated, then a list +with all the parsed expressions gets returned (this is meant for debugging). + +The full meta-grammar for the grammars supported by the PEG generator is: + +```PEG +start[Grammar]: grammar ENDMARKER { grammar } + +grammar[Grammar]: + | metas rules { Grammar(rules, metas) } + | rules { Grammar(rules, []) } + +metas[MetaList]: + | meta metas { [meta] + metas } + | meta { [meta] } + +meta[MetaTuple]: + | "@" NAME NEWLINE { (name.string, None) } + | "@" a=NAME b=NAME NEWLINE { (a.string, b.string) } + | "@" NAME STRING NEWLINE { (name.string, literal_eval(string.string)) } + +rules[RuleList]: + | rule rules { [rule] + rules } + | rule { [rule] } + +rule[Rule]: + | rulename ":" alts NEWLINE INDENT more_alts DEDENT { + Rule(rulename[0], rulename[1], Rhs(alts.alts + more_alts.alts)) } + | rulename ":" NEWLINE INDENT more_alts DEDENT { Rule(rulename[0], rulename[1], more_alts) } + | rulename ":" alts NEWLINE { Rule(rulename[0], rulename[1], alts) } + +rulename[RuleName]: + | NAME '[' type=NAME '*' ']' {(name.string, type.string+"*")} + | NAME '[' type=NAME ']' {(name.string, type.string)} + | NAME {(name.string, None)} + +alts[Rhs]: + | alt "|" alts { Rhs([alt] + alts.alts)} + | alt { Rhs([alt]) } + +more_alts[Rhs]: + | "|" alts NEWLINE more_alts { Rhs(alts.alts + more_alts.alts) } + | "|" alts NEWLINE { Rhs(alts.alts) } + +alt[Alt]: + | items '$' action { Alt(items + [NamedItem(None, NameLeaf('ENDMARKER'))], action=action) } + | items '$' { Alt(items + [NamedItem(None, NameLeaf('ENDMARKER'))], action=None) } + | items action { Alt(items, action=action) } + | items { Alt(items, action=None) } + +items[NamedItemList]: + | named_item items { [named_item] + items } + | named_item { [named_item] } + +named_item[NamedItem]: + | NAME '=' ~ item {NamedItem(name.string, item)} + | item {NamedItem(None, item)} + | it=lookahead {NamedItem(None, it)} + +lookahead[LookaheadOrCut]: + | '&' ~ atom {PositiveLookahead(atom)} + | '!' ~ atom {NegativeLookahead(atom)} + | '~' {Cut()} + +item[Item]: + | '[' ~ alts ']' {Opt(alts)} + | atom '?' {Opt(atom)} + | atom '*' {Repeat0(atom)} + | atom '+' {Repeat1(atom)} + | sep=atom '.' node=atom '+' {Gather(sep, node)} + | atom {atom} + +atom[Plain]: + | '(' ~ alts ')' {Group(alts)} + | NAME {NameLeaf(name.string) } + | STRING {StringLeaf(string.string)} + +## Mini-grammar for the actions + +action[str]: "{" ~ target_atoms "}" { target_atoms } + +target_atoms[str]: + | target_atom target_atoms { target_atom + " " + target_atoms } + | target_atom { target_atom } + +target_atom[str]: + | "{" ~ target_atoms "}" { "{" + target_atoms + "}" } + | NAME { name.string } + | NUMBER { number.string } + | STRING { string.string } + | "?" { "?" } + | ":" { ":" } +``` +As an illustrative example this simple grammar file allows directly +generating a full parser that can parse simple arithmetic expressions and that +returns a valid C-based Python AST: + +```PEG +start[mod_ty]: a=expr_stmt* $ { Module(a, NULL, p->arena) } +expr_stmt[stmt_ty]: a=expr NEWLINE { _Py_Expr(a, EXTRA) } +expr[expr_ty]: + | l=expr '+' r=term { _Py_BinOp(l, Add, r, EXTRA) } + | l=expr '-' r=term { _Py_BinOp(l, Sub, r, EXTRA) } + | t=term { t } + +term[expr_ty]: + | l=term '*' r=factor { _Py_BinOp(l, Mult, r, EXTRA) } + | l=term '/' r=factor { _Py_BinOp(l, Div, r, EXTRA) } + | f=factor { f } + +factor[expr_ty]: + | '(' e=expr ')' { e } + | a=atom { a } + +atom[expr_ty]: + | n=NAME { n } + | n=NUMBER { n } + | s=STRING { s } +``` +Here `EXTRA` is a macro that expands to ``start_lineno, start_col_offset, +end_lineno, end_col_offset, p->arena``, those being variables automatically +injected by the parser; `p` points to an object that holds on to all state +for the parser. + +A similar grammar written to target Python AST objects: + +```PEG +start: expr NEWLINE? ENDMARKER { ast.Expression(expr) } +expr: + | expr '+' term { ast.BinOp(expr, ast.Add(), term) } + | expr '-' term { ast.BinOp(expr, ast.Sub(), term) } + | term { term } + +term: + | l=term '*' r=factor { ast.BinOp(l, ast.Mult(), r) } + | term '/' factor { ast.BinOp(term, ast.Div(), factor) } + | factor { factor } + +factor: + | '(' expr ')' { expr } + | atom { atom } + +atom: + | NAME { ast.Name(id=name.string, ctx=ast.Load()) } + | NUMBER { ast.Constant(value=ast.literal_eval(number.string)) } +``` +## Migration plan +This section describes the migration plan when porting to the new PEG-based parser +if this PEP is accepted. The migration will be executed in a series of steps that allow +initially to fallback to the previous parser if needed: + +1. Starting with Python 3.9 alpha 6, include the new PEG-based parser machinery in CPython + with a command-line flag and environment variable that allows switching between + the new and the old parsers together with explicit APIs that allow invoking the + new and the old parsers independently. At this step, all Python APIs like `ast.parse` + and `compile` will use the parser set by the flags or the environment variable and + the default parser will be the new PEG-based parser. Which parser is active is + observable at runtime through `sys.flags.use_peg`, a new member of the `sys.flags` + struct sequence that is nonzero while the PEG parser is in effect. + +2. Between Python 3.9 and Python 3.10, the old parser and related code (like the + "parser" module) will be kept until a new Python release happens (Python 3.10). In + the meanwhile and until the old parser is removed, **no new Python Grammar + addition will be added that requires the PEG parser**. This means that the grammar + will be kept LL(1) until the old parser is removed. + +3. In Python 3.10, remove the old parser, the command-line flag, the environment + variable and the "parser" module and related code. + +## Performance and validation +We have done extensive timing and validation of the new parser, and +this gives us confidence that the new parser is of high enough quality +to replace the current parser. + +### Performance +We have tuned the performance of the new parser to come within 10% of +the current parser both in speed and memory consumption. While the +PEG/packrat parsing algorithm inherently consumes more memory than the +current LL(1) parser, we have an advantage because we don't construct +an intermediate CST. + +Below are some benchmarks. These are focused on compiling source code +to bytecode, because this is the most realistic situation. Returning +an AST to Python code is not as representative, because the process to +convert the *internal* AST (only accessible to C code) to an +*external* AST (an instance of `ast.AST`) takes more time than the +parser itself. + +All measurements reported here are done on a recent MacBook Pro, +taking the median of three runs. No particular care was taken to stop +other applications running on the same machine. + +The first timings are for our canonical test file, which has 100,000 +lines endlessly repeating the following three lines: + +```python +1 + 2 + 4 + 5 + 6 + 7 + 8 + 9 + 10 + ((((((11 * 12 * 13 * 14 * 15 + 16 * 17 + 18 * 19 * 20)))))) +2*3 + 4*5*6 +12 + (2 * 3 * 4 * 5 + 6 + 7 * 8) +``` +- Just parsing and throwing away the internal AST takes 1.16 seconds + with a max RSS of 681 MiB. + +- Parsing and converting to `ast.AST` takes 6.34 seconds, max RSS + 1029 MiB. + +- Parsing and compiling to bytecode takes 1.28 seconds, max RSS 681 + MiB. + +- With the current parser, parsing and compiling takes 1.44 seconds, + max RSS 836 MiB. + +For this particular test file, the new parser is faster and uses less +memory than the current parser (compare the last two bullets). + +We also did timings with a more realistic payload, the entire Python +3.8 stdlib. This payload consists of 1,641 files, 749,570 lines, +27,622,497 bytes. (Though 11 files can't be compiled by any Python 3 +parser due to encoding issues, sometimes intentional.) + +- Compiling and throwing away the internal AST took 2.141 seconds. + That's 350,040 lines/sec, or 12,899,367 bytes/sec. The max RSS was + 74 MiB (the largest file in the stdlib is much smaller than our + canonical test file). + +- Compiling to bytecode took 3.290 seconds. That's 227,861 lines/sec, + or 8,396,942 bytes/sec. Max RSS 77 MiB. + +- Compiling to bytecode using the current parser took 3.367 seconds. + That's 222,620 lines/sec, or 8,203,780 bytes/sec. Max RSS 70 MiB. + +Comparing the last two bullets we find that the new parser is slightly +faster but uses slightly (about 10%) more memory. We believe this is +acceptable. (Also, there are probably some more tweaks we can make to +reduce memory usage.) + +## Rejected Alternatives +We did not seriously consider alternative ways to implement the new +parser, but here's a brief discussion of LALR(1). + +Thirty years ago the first author decided to go his own way with +Python's parser rather than using LALR(1), which was the industry +standard at the time (e.g. Bison and Yacc). The reasons were +primarily emotional (gut feelings, intuition), based on past experience +using Yacc in other projects, where grammar development took more +effort than anticipated (in part due to shift-reduce conflicts). A +specific criticism of Bison and Yacc that still holds is that their +meta-grammar (the notation used to feed the grammar into the parser +generator) does not support EBNF conveniences like +`[optional_clause]` or `(repeated_clause)*`. Using a custom +parser generator, a syntax tree matching the structure of the grammar +could be generated automatically, and with EBNF that tree could match +the "human-friendly" structure of the grammar. + +Other variants of LR were not considered, nor was LL (e.g. ANTLR). +PEG was selected because it was easy to understand given a basic +understanding of recursive-descent parsing. diff --git a/cpython_1/solution/solution.patch b/cpython_1/solution/solution.patch new file mode 100644 index 0000000000000000000000000000000000000000..f1ca39f114c6f61fac3c33d74cdde828038b20fd --- /dev/null +++ b/cpython_1/solution/solution.patch @@ -0,0 +1,24879 @@ +diff --git a/Grammar/python.gram b/Grammar/python.gram +new file mode 100644 +--- /dev/null ++++ b/Grammar/python.gram +@@ -0,0 +1,555 @@ ++# Simplified grammar for Python ++ ++@bytecode True ++@trailer ''' ++void * ++_PyPegen_parse(Parser *p) ++{ ++ // Initialize keywords ++ p->keywords = reserved_keywords; ++ p->n_keyword_lists = n_keyword_lists; ++ ++ // Run parser ++ void *result = NULL; ++ if (p->start_rule == Py_file_input) { ++ result = file_rule(p); ++ } else if (p->start_rule == Py_single_input) { ++ result = interactive_rule(p); ++ } else if (p->start_rule == Py_eval_input) { ++ result = eval_rule(p); ++ } else if (p->start_rule == Py_fstring_input) { ++ result = fstring_rule(p); ++ } ++ ++ return result; ++} ++ ++// The end ++''' ++file[mod_ty]: a=[statements] ENDMARKER { Module(a, NULL, p->arena) } ++interactive[mod_ty]: a=statement_newline { Interactive(a, p->arena) } ++eval[mod_ty]: a=expressions NEWLINE* ENDMARKER { Expression(a, p->arena) } ++fstring[expr_ty]: star_expressions ++ ++statements[asdl_seq*]: a=statement+ { _PyPegen_seq_flatten(p, a) } ++statement[asdl_seq*]: a=compound_stmt { _PyPegen_singleton_seq(p, a) } | simple_stmt ++statement_newline[asdl_seq*]: ++ | a=compound_stmt NEWLINE { _PyPegen_singleton_seq(p, a) } ++ | simple_stmt ++ | NEWLINE { _PyPegen_singleton_seq(p, CHECK(_Py_Pass(EXTRA))) } ++ | ENDMARKER { _PyPegen_interactive_exit(p) } ++simple_stmt[asdl_seq*]: ++ | a=small_stmt !';' NEWLINE { _PyPegen_singleton_seq(p, a) } # Not needed, there for speedup ++ | a=';'.small_stmt+ [';'] NEWLINE { a } ++# NOTE: assignment MUST precede expression, else parsing a simple assignment ++# will throw a SyntaxError. ++small_stmt[stmt_ty] (memo): ++ | assignment ++ | e=star_expressions { _Py_Expr(e, EXTRA) } ++ | &'return' return_stmt ++ | &('import' | 'from') import_stmt ++ | &'raise' raise_stmt ++ | 'pass' { _Py_Pass(EXTRA) } ++ | &'del' del_stmt ++ | &'yield' yield_stmt ++ | &'assert' assert_stmt ++ | 'break' { _Py_Break(EXTRA) } ++ | 'continue' { _Py_Continue(EXTRA) } ++ | &'global' global_stmt ++ | &'nonlocal' nonlocal_stmt ++compound_stmt[stmt_ty]: ++ | &('def' | '@' | ASYNC) function_def ++ | &'if' if_stmt ++ | &('class' | '@') class_def ++ | &('with' | ASYNC) with_stmt ++ | &('for' | ASYNC) for_stmt ++ | &'try' try_stmt ++ | &'while' while_stmt ++ ++# NOTE: annotated_rhs may start with 'yield'; yield_expr must start with 'yield' ++assignment: ++ | a=NAME ':' b=expression c=['=' d=annotated_rhs { d }] { ++ _Py_AnnAssign(CHECK(_PyPegen_set_expr_context(p, a, Store)), b, c, 1, EXTRA) } ++ | a=('(' b=inside_paren_ann_assign_target ')' { b } ++ | ann_assign_subscript_attribute_target) ':' b=expression c=['=' d=annotated_rhs { d }] { ++ _Py_AnnAssign(a, b, c, 0, EXTRA)} ++ | a=(z=star_targets '=' { z })+ b=(yield_expr | star_expressions) { ++ _Py_Assign(a, b, NULL, EXTRA) } ++ | a=target b=augassign c=(yield_expr | star_expressions) { ++ _Py_AugAssign(a, b->kind, c, EXTRA) } ++ | invalid_assignment ++ ++augassign[AugOperator*]: ++ | '+=' {_PyPegen_augoperator(p, Add)} ++ | '-=' {_PyPegen_augoperator(p, Sub)} ++ | '*=' {_PyPegen_augoperator(p, Mult)} ++ | '@=' {_PyPegen_augoperator(p, MatMult)} ++ | '/=' {_PyPegen_augoperator(p, Div)} ++ | '%=' {_PyPegen_augoperator(p, Mod)} ++ | '&=' {_PyPegen_augoperator(p, BitAnd)} ++ | '|=' {_PyPegen_augoperator(p, BitOr)} ++ | '^=' {_PyPegen_augoperator(p, BitXor)} ++ | '<<=' {_PyPegen_augoperator(p, LShift)} ++ | '>>=' {_PyPegen_augoperator(p, RShift)} ++ | '**=' {_PyPegen_augoperator(p, Pow)} ++ | '//=' {_PyPegen_augoperator(p, FloorDiv)} ++ ++global_stmt[stmt_ty]: 'global' a=','.NAME+ { ++ _Py_Global(CHECK(_PyPegen_map_names_to_ids(p, a)), EXTRA) } ++nonlocal_stmt[stmt_ty]: 'nonlocal' a=','.NAME+ { ++ _Py_Nonlocal(CHECK(_PyPegen_map_names_to_ids(p, a)), EXTRA) } ++ ++yield_stmt[stmt_ty]: y=yield_expr { _Py_Expr(y, EXTRA) } ++ ++assert_stmt[stmt_ty]: 'assert' a=expression b=[',' z=expression { z }] { _Py_Assert(a, b, EXTRA) } ++ ++del_stmt[stmt_ty]: 'del' a=del_targets { _Py_Delete(a, EXTRA) } ++ ++import_stmt[stmt_ty]: import_name | import_from ++import_name[stmt_ty]: 'import' a=dotted_as_names { _Py_Import(a, EXTRA) } ++# note below: the ('.' | '...') is necessary because '...' is tokenized as ELLIPSIS ++import_from[stmt_ty]: ++ | 'from' a=('.' | '...')* b=dotted_name 'import' c=import_from_targets { ++ _Py_ImportFrom(b->v.Name.id, c, _PyPegen_seq_count_dots(a), EXTRA) } ++ | 'from' a=('.' | '...')+ 'import' b=import_from_targets { ++ _Py_ImportFrom(NULL, b, _PyPegen_seq_count_dots(a), EXTRA) } ++import_from_targets[asdl_seq*]: ++ | '(' a=import_from_as_names [','] ')' { a } ++ | import_from_as_names ++ | '*' { _PyPegen_singleton_seq(p, CHECK(_PyPegen_alias_for_star(p))) } ++import_from_as_names[asdl_seq*]: ++ | a=','.import_from_as_name+ { a } ++import_from_as_name[alias_ty]: ++ | a=NAME b=['as' z=NAME { z }] { _Py_alias(a->v.Name.id, ++ (b) ? ((expr_ty) b)->v.Name.id : NULL, ++ p->arena) } ++dotted_as_names[asdl_seq*]: ++ | a=','.dotted_as_name+ { a } ++dotted_as_name[alias_ty]: ++ | a=dotted_name b=['as' z=NAME { z }] { _Py_alias(a->v.Name.id, ++ (b) ? ((expr_ty) b)->v.Name.id : NULL, ++ p->arena) } ++dotted_name[expr_ty]: ++ | a=dotted_name '.' b=NAME { _PyPegen_join_names_with_dot(p, a, b) } ++ | NAME ++ ++if_stmt[stmt_ty]: ++ | 'if' a=named_expression ':' b=block c=elif_stmt { _Py_If(a, b, CHECK(_PyPegen_singleton_seq(p, c)), EXTRA) } ++ | 'if' a=named_expression ':' b=block c=[else_block] { _Py_If(a, b, c, EXTRA) } ++elif_stmt[stmt_ty]: ++ | 'elif' a=named_expression ':' b=block c=elif_stmt { _Py_If(a, b, CHECK(_PyPegen_singleton_seq(p, c)), EXTRA) } ++ | 'elif' a=named_expression ':' b=block c=[else_block] { _Py_If(a, b, c, EXTRA) } ++else_block[asdl_seq*]: 'else' ':' b=block { b } ++ ++while_stmt[stmt_ty]: ++ | 'while' a=named_expression ':' b=block c=[else_block] { _Py_While(a, b, c, EXTRA) } ++ ++for_stmt[stmt_ty]: ++ | is_async=[ASYNC] 'for' t=star_targets 'in' ex=star_expressions ':' b=block el=[else_block] { ++ (is_async ? _Py_AsyncFor : _Py_For)(t, ex, b, el, NULL, EXTRA) } ++ ++with_stmt[stmt_ty]: ++ | is_async=[ASYNC] 'with' '(' a=','.with_item+ ')' ':' b=block { ++ (is_async ? _Py_AsyncWith : _Py_With)(a, b, NULL, EXTRA) } ++ | is_async=[ASYNC] 'with' a=','.with_item+ ':' b=block { ++ (is_async ? _Py_AsyncWith : _Py_With)(a, b, NULL, EXTRA) } ++with_item[withitem_ty]: ++ | e=expression o=['as' t=target { t }] { _Py_withitem(e, o, p->arena) } ++ ++try_stmt[stmt_ty]: ++ | 'try' ':' b=block f=finally_block { _Py_Try(b, NULL, NULL, f, EXTRA) } ++ | 'try' ':' b=block ex=except_block+ el=[else_block] f=[finally_block] { _Py_Try(b, ex, el, f, EXTRA) } ++except_block[excepthandler_ty]: ++ | 'except' e=expression t=['as' z=target { z }] ':' b=block { ++ _Py_ExceptHandler(e, (t) ? ((expr_ty) t)->v.Name.id : NULL, b, EXTRA) } ++ | 'except' ':' b=block { _Py_ExceptHandler(NULL, NULL, b, EXTRA) } ++finally_block[asdl_seq*]: 'finally' ':' a=block { a } ++ ++return_stmt[stmt_ty]: ++ | 'return' a=[star_expressions] { _Py_Return(a, EXTRA) } ++ ++raise_stmt[stmt_ty]: ++ | 'raise' a=expression b=['from' z=expression { z }] { _Py_Raise(a, b, EXTRA) } ++ | 'raise' { _Py_Raise(NULL, NULL, EXTRA) } ++ ++function_def[stmt_ty]: ++ | d=decorators f=function_def_raw { _PyPegen_function_def_decorators(p, d, f) } ++ | function_def_raw ++ ++function_def_raw[stmt_ty]: ++ | is_async=[ASYNC] 'def' n=NAME '(' params=[params] ')' a=['->' z=annotation { z }] ':' b=block { ++ (is_async ? _Py_AsyncFunctionDef : _Py_FunctionDef)(n->v.Name.id, ++ (params) ? params : CHECK(_PyPegen_empty_arguments(p)), ++ b, NULL, a, NULL, EXTRA) } ++ ++params[arguments_ty]: ++ | invalid_parameters ++ | parameters ++parameters[arguments_ty]: ++ | a=slash_without_default b=[',' x=plain_names { x }] c=[',' y=names_with_default { y }] d=[',' z=[star_etc] { z }] { ++ _PyPegen_make_arguments(p, a, NULL, b, c, d) } ++ | a=slash_with_default b=[',' y=names_with_default { y }] c=[',' z=[star_etc] { z }] { ++ _PyPegen_make_arguments(p, NULL, a, NULL, b, c) } ++ | a=plain_names b=[',' y=names_with_default { y }] c=[',' z=[star_etc] { z }] { ++ _PyPegen_make_arguments(p, NULL, NULL, a, b, c) } ++ | a=names_with_default b=[',' z=[star_etc] { z }] { _PyPegen_make_arguments(p, NULL, NULL, NULL, a, b)} ++ | a=star_etc { _PyPegen_make_arguments(p, NULL, NULL, NULL, NULL, a) } ++slash_without_default[asdl_seq*]: a=plain_names ',' '/' { a } ++slash_with_default[SlashWithDefault*]: a=[n=plain_names ',' { n }] b=names_with_default ',' '/' { ++ _PyPegen_slash_with_default(p, a, b) } ++star_etc[StarEtc*]: ++ | '*' a=plain_name b=name_with_optional_default* c=[',' d=kwds { d }] [','] { ++ _PyPegen_star_etc(p, a, b, c) } ++ | '*' b=name_with_optional_default+ c=[',' d=kwds { d }] [','] { ++ _PyPegen_star_etc(p, NULL, b, c) } ++ | a=kwds [','] { _PyPegen_star_etc(p, NULL, NULL, a) } ++name_with_optional_default[NameDefaultPair*]: ++ | ',' a=plain_name b=['=' e=expression { e }] { _PyPegen_name_default_pair(p, a, b) } ++names_with_default[asdl_seq*]: a=','.name_with_default+ { a } ++name_with_default[NameDefaultPair*]: ++ | n=plain_name '=' e=expression { _PyPegen_name_default_pair(p, n, e) } ++plain_names[asdl_seq*] (memo): a=','.(plain_name !'=')+ { a } ++plain_name[arg_ty]: ++ | a=NAME b=[':' z=annotation { z }] { _Py_arg(a->v.Name.id, b, NULL, EXTRA) } ++kwds[arg_ty]: ++ | '**' a=plain_name { a } ++annotation[expr_ty]: expression ++ ++decorators[asdl_seq*]: a=('@' f=named_expression NEWLINE { f })+ { a } ++ ++class_def[stmt_ty]: ++ | a=decorators b=class_def_raw { _PyPegen_class_def_decorators(p, a, b) } ++ | class_def_raw ++class_def_raw[stmt_ty]: ++ | 'class' a=NAME b=['(' z=[arguments] ')' { z }] ':' c=block { ++ _Py_ClassDef(a->v.Name.id, ++ (b) ? ((expr_ty) b)->v.Call.args : NULL, ++ (b) ? ((expr_ty) b)->v.Call.keywords : NULL, ++ c, NULL, EXTRA) } ++ ++block[asdl_seq*] (memo): ++ | NEWLINE INDENT a=statements DEDENT { a } ++ | simple_stmt ++ | invalid_block ++ ++expressions_list[asdl_seq*]: a=','.star_expression+ [','] { a } ++star_expressions[expr_ty]: ++ | a=star_expression b=(',' c=star_expression { c })+ [','] { ++ _Py_Tuple(CHECK(_PyPegen_seq_insert_in_front(p, a, b)), Load, EXTRA) } ++ | a=star_expression ',' { _Py_Tuple(CHECK(_PyPegen_singleton_seq(p, a)), Load, EXTRA) } ++ | star_expression ++star_expression[expr_ty] (memo): ++ | '*' a=bitwise_or { _Py_Starred(a, Load, EXTRA) } ++ | expression ++ ++star_named_expressions[asdl_seq*]: a=','.star_named_expression+ [','] { a } ++star_named_expression[expr_ty]: ++ | '*' a=bitwise_or { _Py_Starred(a, Load, EXTRA) } ++ | named_expression ++named_expression[expr_ty]: ++ | a=NAME ':=' b=expression { _Py_NamedExpr(CHECK(_PyPegen_set_expr_context(p, a, Store)), b, EXTRA) } ++ | expression !':=' ++ | invalid_named_expression ++ ++annotated_rhs[expr_ty]: yield_expr | star_expressions ++ ++expressions[expr_ty]: ++ | a=expression b=(',' c=expression { c })+ [','] { ++ _Py_Tuple(CHECK(_PyPegen_seq_insert_in_front(p, a, b)), Load, EXTRA) } ++ | a=expression ',' { _Py_Tuple(CHECK(_PyPegen_singleton_seq(p, a)), Load, EXTRA) } ++ | expression ++expression[expr_ty] (memo): ++ | a=disjunction 'if' b=disjunction 'else' c=expression { _Py_IfExp(b, a, c, EXTRA) } ++ | disjunction ++ | lambdef ++ ++lambdef[expr_ty]: ++ | 'lambda' a=[lambda_parameters] ':' b=expression { _Py_Lambda((a) ? a : CHECK(_PyPegen_empty_arguments(p)), b, EXTRA) } ++lambda_parameters[arguments_ty]: ++ | a=lambda_slash_without_default b=[',' x=lambda_plain_names { x }] c=[',' y=lambda_names_with_default { y }] d=[',' z=[lambda_star_etc] { z }] { ++ _PyPegen_make_arguments(p, a, NULL, b, c, d) } ++ | a=lambda_slash_with_default b=[',' y=lambda_names_with_default { y }] c=[',' z=[lambda_star_etc] { z }] { ++ _PyPegen_make_arguments(p, NULL, a, NULL, b, c) } ++ | a=lambda_plain_names b=[',' y=lambda_names_with_default { y }] c=[',' z=[lambda_star_etc] { z }] { ++ _PyPegen_make_arguments(p, NULL, NULL, a, b, c) } ++ | a=lambda_names_with_default b=[',' z=[lambda_star_etc] { z }] { _PyPegen_make_arguments(p, NULL, NULL, NULL, a, b)} ++ | a=lambda_star_etc { _PyPegen_make_arguments(p, NULL, NULL, NULL, NULL, a) } ++lambda_slash_without_default[asdl_seq*]: a=lambda_plain_names ',' '/' { a } ++lambda_slash_with_default[SlashWithDefault*]: a=[n=lambda_plain_names ',' { n }] b=lambda_names_with_default ',' '/' { ++ _PyPegen_slash_with_default(p, a, b) } ++lambda_star_etc[StarEtc*]: ++ | '*' a=lambda_plain_name b=lambda_name_with_optional_default* c=[',' d=lambda_kwds { d }] [','] { ++ _PyPegen_star_etc(p, a, b, c) } ++ | '*' b=lambda_name_with_optional_default+ c=[',' d=lambda_kwds { d }] [','] { ++ _PyPegen_star_etc(p, NULL, b, c) } ++ | a=lambda_kwds [','] { _PyPegen_star_etc(p, NULL, NULL, a) } ++lambda_name_with_optional_default[NameDefaultPair*]: ++ | ',' a=lambda_plain_name b=['=' e=expression { e }] { _PyPegen_name_default_pair(p, a, b) } ++lambda_names_with_default[asdl_seq*]: a=','.lambda_name_with_default+ { a } ++lambda_name_with_default[NameDefaultPair*]: ++ | n=lambda_plain_name '=' e=expression { _PyPegen_name_default_pair(p, n, e) } ++lambda_plain_names[asdl_seq*]: a=','.(lambda_plain_name !'=')+ { a } ++lambda_plain_name[arg_ty]: a=NAME { _Py_arg(a->v.Name.id, NULL, NULL, EXTRA) } ++lambda_kwds[arg_ty]: '**' a=lambda_plain_name { a } ++ ++disjunction[expr_ty] (memo): ++ | a=conjunction b=('or' c=conjunction { c })+ { _Py_BoolOp( ++ Or, ++ CHECK(_PyPegen_seq_insert_in_front(p, a, b)), ++ EXTRA) } ++ | conjunction ++conjunction[expr_ty] (memo): ++ | a=inversion b=('and' c=inversion { c })+ { _Py_BoolOp( ++ And, ++ CHECK(_PyPegen_seq_insert_in_front(p, a, b)), ++ EXTRA) } ++ | inversion ++inversion[expr_ty] (memo): ++ | 'not' a=inversion { _Py_UnaryOp(Not, a, EXTRA) } ++ | comparison ++comparison[expr_ty]: ++ | a=bitwise_or b=compare_op_bitwise_or_pair+ { ++ _Py_Compare(a, CHECK(_PyPegen_get_cmpops(p, b)), CHECK(_PyPegen_get_exprs(p, b)), EXTRA) } ++ | bitwise_or ++compare_op_bitwise_or_pair[CmpopExprPair*]: ++ | eq_bitwise_or ++ | noteq_bitwise_or ++ | lte_bitwise_or ++ | lt_bitwise_or ++ | gte_bitwise_or ++ | gt_bitwise_or ++ | notin_bitwise_or ++ | in_bitwise_or ++ | isnot_bitwise_or ++ | is_bitwise_or ++eq_bitwise_or[CmpopExprPair*]: '==' a=bitwise_or { _PyPegen_cmpop_expr_pair(p, Eq, a) } ++noteq_bitwise_or[CmpopExprPair*]: '!=' a=bitwise_or { _PyPegen_cmpop_expr_pair(p, NotEq, a) } ++lte_bitwise_or[CmpopExprPair*]: '<=' a=bitwise_or { _PyPegen_cmpop_expr_pair(p, LtE, a) } ++lt_bitwise_or[CmpopExprPair*]: '<' a=bitwise_or { _PyPegen_cmpop_expr_pair(p, Lt, a) } ++gte_bitwise_or[CmpopExprPair*]: '>=' a=bitwise_or { _PyPegen_cmpop_expr_pair(p, GtE, a) } ++gt_bitwise_or[CmpopExprPair*]: '>' a=bitwise_or { _PyPegen_cmpop_expr_pair(p, Gt, a) } ++notin_bitwise_or[CmpopExprPair*]: 'not' 'in' a=bitwise_or { _PyPegen_cmpop_expr_pair(p, NotIn, a) } ++in_bitwise_or[CmpopExprPair*]: 'in' a=bitwise_or { _PyPegen_cmpop_expr_pair(p, In, a) } ++isnot_bitwise_or[CmpopExprPair*]: 'is' 'not' a=bitwise_or { _PyPegen_cmpop_expr_pair(p, IsNot, a) } ++is_bitwise_or[CmpopExprPair*]: 'is' a=bitwise_or { _PyPegen_cmpop_expr_pair(p, Is, a) } ++ ++bitwise_or[expr_ty]: ++ | a=bitwise_or '|' b=bitwise_xor { _Py_BinOp(a, BitOr, b, EXTRA) } ++ | bitwise_xor ++bitwise_xor[expr_ty]: ++ | a=bitwise_xor '^' b=bitwise_and { _Py_BinOp(a, BitXor, b, EXTRA) } ++ | bitwise_and ++bitwise_and[expr_ty]: ++ | a=bitwise_and '&' b=shift_expr { _Py_BinOp(a, BitAnd, b, EXTRA) } ++ | shift_expr ++shift_expr[expr_ty]: ++ | a=shift_expr '<<' b=sum { _Py_BinOp(a, LShift, b, EXTRA) } ++ | a=shift_expr '>>' b=sum { _Py_BinOp(a, RShift, b, EXTRA) } ++ | sum ++ ++sum[expr_ty]: ++ | a=sum '+' b=term { _Py_BinOp(a, Add, b, EXTRA) } ++ | a=sum '-' b=term { _Py_BinOp(a, Sub, b, EXTRA) } ++ | term ++term[expr_ty]: ++ | a=term '*' b=factor { _Py_BinOp(a, Mult, b, EXTRA) } ++ | a=term '/' b=factor { _Py_BinOp(a, Div, b, EXTRA) } ++ | a=term '//' b=factor { _Py_BinOp(a, FloorDiv, b, EXTRA) } ++ | a=term '%' b=factor { _Py_BinOp(a, Mod, b, EXTRA) } ++ | a=term '@' b=factor { _Py_BinOp(a, MatMult, b, EXTRA) } ++ | factor ++factor[expr_ty] (memo): ++ | '+' a=factor { _Py_UnaryOp(UAdd, a, EXTRA) } ++ | '-' a=factor { _Py_UnaryOp(USub, a, EXTRA) } ++ | '~' a=factor { _Py_UnaryOp(Invert, a, EXTRA) } ++ | power ++power[expr_ty]: ++ | a=await_primary '**' b=factor { _Py_BinOp(a, Pow, b, EXTRA) } ++ | await_primary ++await_primary[expr_ty] (memo): ++ | AWAIT a=primary { _Py_Await(a, EXTRA) } ++ | primary ++primary[expr_ty]: ++ | a=primary '.' b=NAME { _Py_Attribute(a, b->v.Name.id, Load, EXTRA) } ++ | a=primary b=genexp { _Py_Call(a, CHECK(_PyPegen_singleton_seq(p, b)), NULL, EXTRA) } ++ | a=primary '(' b=[arguments] ')' { ++ _Py_Call(a, ++ (b) ? ((expr_ty) b)->v.Call.args : NULL, ++ (b) ? ((expr_ty) b)->v.Call.keywords : NULL, ++ EXTRA) } ++ | a=primary '[' b=slices ']' { _Py_Subscript(a, b, Load, EXTRA) } ++ | atom ++ ++slices[expr_ty]: ++ | a=slice !',' { a } ++ | a=','.slice+ [','] { _Py_Tuple(a, Load, EXTRA) } ++slice[expr_ty]: ++ | a=[expression] ':' b=[expression] c=[':' d=[expression] { d }] { _Py_Slice(a, b, c, EXTRA) } ++ | a=expression { a } ++atom[expr_ty]: ++ | NAME ++ | 'True' { _Py_Constant(Py_True, NULL, EXTRA) } ++ | 'False' { _Py_Constant(Py_False, NULL, EXTRA) } ++ | 'None' { _Py_Constant(Py_None, NULL, EXTRA) } ++ | '__new_parser__' { RAISE_SYNTAX_ERROR("You found it!") } ++ | &STRING strings ++ | NUMBER ++ | &'(' (tuple | group | genexp) ++ | &'[' (list | listcomp) ++ | &'{' (dict | set | dictcomp | setcomp) ++ | '...' { _Py_Constant(Py_Ellipsis, NULL, EXTRA) } ++ ++strings[expr_ty] (memo): a=STRING+ { _PyPegen_concatenate_strings(p, a) } ++list[expr_ty]: ++ | '[' a=[star_named_expressions] ']' { _Py_List(a, Load, EXTRA) } ++listcomp[expr_ty]: ++ | '[' a=named_expression b=for_if_clauses ']' { _Py_ListComp(a, b, EXTRA) } ++ | invalid_comprehension ++tuple[expr_ty]: ++ | '(' a=[y=star_named_expression ',' z=[star_named_expressions] { _PyPegen_seq_insert_in_front(p, y, z) } ] ')' { ++ _Py_Tuple(a, Load, EXTRA) } ++group[expr_ty]: '(' a=(yield_expr | named_expression) ')' { a } ++genexp[expr_ty]: ++ | '(' a=expression b=for_if_clauses ')' { _Py_GeneratorExp(a, b, EXTRA) } ++ | invalid_comprehension ++set[expr_ty]: '{' a=expressions_list '}' { _Py_Set(a, EXTRA) } ++setcomp[expr_ty]: ++ | '{' a=expression b=for_if_clauses '}' { _Py_SetComp(a, b, EXTRA) } ++ | invalid_comprehension ++dict[expr_ty]: ++ | '{' a=[kvpairs] '}' { _Py_Dict(CHECK(_PyPegen_get_keys(p, a)), ++ CHECK(_PyPegen_get_values(p, a)), EXTRA) } ++dictcomp[expr_ty]: ++ | '{' a=kvpair b=for_if_clauses '}' { _Py_DictComp(a->key, a->value, b, EXTRA) } ++kvpairs[asdl_seq*]: a=','.kvpair+ [','] { a } ++kvpair[KeyValuePair*]: ++ | '**' a=bitwise_or { _PyPegen_key_value_pair(p, NULL, a) } ++ | a=expression ':' b=expression { _PyPegen_key_value_pair(p, a, b) } ++for_if_clauses[asdl_seq*]: ++ | a=(y=[ASYNC] 'for' a=star_targets 'in' b=disjunction c=('if' z=disjunction { z })* ++ { _Py_comprehension(a, b, c, y != NULL, p->arena) })+ { a } ++ ++yield_expr[expr_ty]: ++ | 'yield' 'from' a=expression { _Py_YieldFrom(a, EXTRA) } ++ | 'yield' a=[star_expressions] { _Py_Yield(a, EXTRA) } ++ ++arguments[expr_ty] (memo): ++ | a=args [','] &')' { a } ++ | incorrect_arguments ++args[expr_ty]: ++ | a=starred_expression b=[',' c=args { c }] { ++ _Py_Call(_PyPegen_dummy_name(p), ++ (b) ? CHECK(_PyPegen_seq_insert_in_front(p, a, ((expr_ty) b)->v.Call.args)) ++ : CHECK(_PyPegen_singleton_seq(p, a)), ++ (b) ? ((expr_ty) b)->v.Call.keywords : NULL, ++ EXTRA) } ++ | a=kwargs { _Py_Call(_PyPegen_dummy_name(p), ++ CHECK_NULL_ALLOWED(_PyPegen_seq_extract_starred_exprs(p, a)), ++ CHECK_NULL_ALLOWED(_PyPegen_seq_delete_starred_exprs(p, a)), ++ EXTRA) } ++ | a=named_expression b=[',' c=args { c }] { ++ _Py_Call(_PyPegen_dummy_name(p), ++ (b) ? CHECK(_PyPegen_seq_insert_in_front(p, a, ((expr_ty) b)->v.Call.args)) ++ : CHECK(_PyPegen_singleton_seq(p, a)), ++ (b) ? ((expr_ty) b)->v.Call.keywords : NULL, ++ EXTRA) } ++kwargs[asdl_seq*]: ++ | a=','.kwarg_or_starred+ ',' b=','.kwarg_or_double_starred+ { _PyPegen_join_sequences(p, a, b) } ++ | ','.kwarg_or_starred+ ++ | ','.kwarg_or_double_starred+ ++starred_expression[expr_ty]: ++ | '*' a=expression { _Py_Starred(a, Load, EXTRA) } ++kwarg_or_starred[KeywordOrStarred*]: ++ | a=NAME '=' b=expression { ++ _PyPegen_keyword_or_starred(p, CHECK(_Py_keyword(a->v.Name.id, b, EXTRA)), 1) } ++ | a=starred_expression { _PyPegen_keyword_or_starred(p, a, 0) } ++kwarg_or_double_starred[KeywordOrStarred*]: ++ | a=NAME '=' b=expression { ++ _PyPegen_keyword_or_starred(p, CHECK(_Py_keyword(a->v.Name.id, b, EXTRA)), 1) } ++ | '**' a=expression { _PyPegen_keyword_or_starred(p, CHECK(_Py_keyword(NULL, a, EXTRA)), 1) } ++ ++# NOTE: star_targets may contain *bitwise_or, targets may not. ++star_targets[expr_ty]: ++ | a=star_target !',' { a } ++ | a=star_target b=(',' c=star_target { c })* [','] { ++ _Py_Tuple(CHECK(_PyPegen_seq_insert_in_front(p, a, b)), Store, EXTRA) } ++star_targets_seq[asdl_seq*]: a=','.star_target+ [','] { a } ++star_target[expr_ty] (memo): ++ | '*' a=(!'*' star_target) { ++ _Py_Starred(CHECK(_PyPegen_set_expr_context(p, a, Store)), Store, EXTRA) } ++ | a=t_primary '.' b=NAME !t_lookahead { _Py_Attribute(a, b->v.Name.id, Store, EXTRA) } ++ | a=t_primary '[' b=slices ']' !t_lookahead { _Py_Subscript(a, b, Store, EXTRA) } ++ | star_atom ++star_atom[expr_ty]: ++ | a=NAME { _PyPegen_set_expr_context(p, a, Store) } ++ | '(' a=star_target ')' { _PyPegen_set_expr_context(p, a, Store) } ++ | '(' a=[star_targets_seq] ')' { _Py_Tuple(a, Store, EXTRA) } ++ | '[' a=[star_targets_seq] ']' { _Py_List(a, Store, EXTRA) } ++ ++inside_paren_ann_assign_target[expr_ty]: ++ | ann_assign_subscript_attribute_target ++ | a=NAME { _PyPegen_set_expr_context(p, a, Store) } ++ | '(' a=inside_paren_ann_assign_target ')' { a } ++ ++ann_assign_subscript_attribute_target[expr_ty]: ++ | a=t_primary '.' b=NAME !t_lookahead { _Py_Attribute(a, b->v.Name.id, Store, EXTRA) } ++ | a=t_primary '[' b=slices ']' !t_lookahead { _Py_Subscript(a, b, Store, EXTRA) } ++ ++del_targets[asdl_seq*]: a=','.del_target+ [','] { a } ++del_target[expr_ty] (memo): ++ | a=t_primary '.' b=NAME !t_lookahead { _Py_Attribute(a, b->v.Name.id, Del, EXTRA) } ++ | a=t_primary '[' b=slices ']' !t_lookahead { _Py_Subscript(a, b, Del, EXTRA) } ++ | del_t_atom ++del_t_atom[expr_ty]: ++ | a=NAME { _PyPegen_set_expr_context(p, a, Del) } ++ | '(' a=del_target ')' { _PyPegen_set_expr_context(p, a, Del) } ++ | '(' a=[del_targets] ')' { _Py_Tuple(a, Del, EXTRA) } ++ | '[' a=[del_targets] ']' { _Py_List(a, Del, EXTRA) } ++ ++targets[asdl_seq*]: a=','.target+ [','] { a } ++target[expr_ty] (memo): ++ | a=t_primary '.' b=NAME !t_lookahead { _Py_Attribute(a, b->v.Name.id, Store, EXTRA) } ++ | a=t_primary '[' b=slices ']' !t_lookahead { _Py_Subscript(a, b, Store, EXTRA) } ++ | t_atom ++t_primary[expr_ty]: ++ | a=t_primary '.' b=NAME &t_lookahead { _Py_Attribute(a, b->v.Name.id, Load, EXTRA) } ++ | a=t_primary '[' b=slices ']' &t_lookahead { _Py_Subscript(a, b, Load, EXTRA) } ++ | a=t_primary b=genexp &t_lookahead { _Py_Call(a, CHECK(_PyPegen_singleton_seq(p, b)), NULL, EXTRA) } ++ | a=t_primary '(' b=[arguments] ')' &t_lookahead { ++ _Py_Call(a, ++ (b) ? ((expr_ty) b)->v.Call.args : NULL, ++ (b) ? ((expr_ty) b)->v.Call.keywords : NULL, ++ EXTRA) } ++ | a=atom &t_lookahead { a } ++t_lookahead: '(' | '[' | '.' ++t_atom[expr_ty]: ++ | a=NAME { _PyPegen_set_expr_context(p, a, Store) } ++ | '(' a=target ')' { _PyPegen_set_expr_context(p, a, Store) } ++ | '(' b=[targets] ')' { _Py_Tuple(b, Store, EXTRA) } ++ | '[' b=[targets] ']' { _Py_List(b, Store, EXTRA) } ++ ++ ++# From here on, there are rules for invalid syntax with specialised error messages ++incorrect_arguments: ++ | args ',' '*' { RAISE_SYNTAX_ERROR("iterable argument unpacking follows keyword argument unpacking") } ++ | expression for_if_clauses ',' [args | expression for_if_clauses] { ++ RAISE_SYNTAX_ERROR("Generator expression must be parenthesized") } ++ | a=args ',' args { _PyPegen_arguments_parsing_error(p, a) } ++invalid_named_expression: ++ | a=expression ':=' expression { ++ RAISE_SYNTAX_ERROR("cannot use assignment expressions with %s", _PyPegen_get_expr_name(a)) } ++invalid_assignment: ++ | list ':' { RAISE_SYNTAX_ERROR("only single target (not list) can be annotated") } ++ | tuple ':' { RAISE_SYNTAX_ERROR("only single target (not tuple) can be annotated") } ++ | expression ':' expression ['=' annotated_rhs] { ++ RAISE_SYNTAX_ERROR("illegal target for annotation") } ++ | a=expression ('=' | augassign) (yield_expr | star_expressions) { ++ RAISE_SYNTAX_ERROR("cannot assign to %s", _PyPegen_get_expr_name(a)) } ++invalid_block: ++ | NEWLINE !INDENT { RAISE_INDENTATION_ERROR("expected an indented block") } ++invalid_comprehension: ++ | ('[' | '(' | '{') '*' expression for_if_clauses { ++ RAISE_SYNTAX_ERROR("iterable unpacking cannot be used in comprehension") } ++invalid_parameters: ++ | [plain_names ','] (slash_with_default | names_with_default) ',' plain_names { ++ RAISE_SYNTAX_ERROR("non-default argument follows default argument") } +diff --git a/Include/compile.h b/Include/compile.h +--- a/Include/compile.h ++++ b/Include/compile.h +@@ -102,4 +102,7 @@ PyAPI_FUNC(int) _PyAST_Optimize(struct _mod *, PyArena *arena, _PyASTOptimizeSta + #define Py_eval_input 258 + #define Py_func_type_input 345 + ++/* This doesn't need to match anything */ ++#define Py_fstring_input 800 ++ + #endif /* !Py_COMPILE_H */ +diff --git a/Include/cpython/initconfig.h b/Include/cpython/initconfig.h +--- a/Include/cpython/initconfig.h ++++ b/Include/cpython/initconfig.h +@@ -147,6 +147,10 @@ typedef struct { + Set to 1 by -X faulthandler and PYTHONFAULTHANDLER. -1 means unset. */ + int faulthandler; + ++ /* Enable PEG parser? ++ 1 by default, set to 0 by -X oldparser and PYTHONOLDPARSER */ ++ int use_peg; ++ + /* Enable tracemalloc? + Set by -X tracemalloc=N and PYTHONTRACEMALLOC. -1 means unset */ + int tracemalloc; +diff --git a/Include/pegen_interface.h b/Include/pegen_interface.h +new file mode 100644 +--- /dev/null ++++ b/Include/pegen_interface.h +@@ -0,0 +1,32 @@ ++#ifndef Py_LIMITED_API ++#ifndef Py_PEGENINTERFACE ++#define Py_PEGENINTERFACE ++#ifdef __cplusplus ++extern "C" { ++#endif ++ ++#include "Python.h" ++#include "Python-ast.h" ++ ++PyAPI_FUNC(mod_ty) PyPegen_ASTFromFile(const char *filename, int mode, PyArena *arena); ++PyAPI_FUNC(mod_ty) PyPegen_ASTFromString(const char *str, int mode, PyCompilerFlags *flags, ++ PyArena *arena); ++PyAPI_FUNC(mod_ty) PyPegen_ASTFromStringObject(const char *str, PyObject* filename, int mode, ++ PyCompilerFlags *flags, PyArena *arena); ++PyAPI_FUNC(mod_ty) PyPegen_ASTFromFileObject(FILE *fp, PyObject *filename_ob, ++ int mode, const char *enc, const char *ps1, ++ const char *ps2, int *errcode, PyArena *arena); ++PyAPI_FUNC(PyCodeObject *) PyPegen_CodeObjectFromFile(const char *filename, int mode); ++PyAPI_FUNC(PyCodeObject *) PyPegen_CodeObjectFromString(const char *str, int mode, ++ PyCompilerFlags *flags); ++PyAPI_FUNC(PyCodeObject *) PyPegen_CodeObjectFromFileObject(FILE *, PyObject *filename_ob, ++ int mode, const char *enc, ++ const char *ps1, ++ const char *ps2, ++ int *errcode); ++ ++#ifdef __cplusplus ++} ++#endif ++#endif /* !Py_PEGENINTERFACE*/ ++#endif /* !Py_LIMITED_API */ +diff --git a/Makefile.pre.in b/Makefile.pre.in +--- a/Makefile.pre.in ++++ b/Makefile.pre.in +@@ -244,7 +244,7 @@ LIBOBJS= @LIBOBJS@ + PYTHON= python$(EXE) + BUILDPYTHON= python$(BUILDEXE) + +-PYTHON_FOR_REGEN=@PYTHON_FOR_REGEN@ ++PYTHON_FOR_REGEN?=@PYTHON_FOR_REGEN@ + UPDATE_FILE=@PYTHON_FOR_REGEN@ $(srcdir)/Tools/scripts/update_file.py + PYTHON_FOR_BUILD=@PYTHON_FOR_BUILD@ + _PYTHON_HOST_PLATFORM=@_PYTHON_HOST_PLATFORM@ +@@ -295,6 +295,19 @@ LIBFFI_INCLUDEDIR= @LIBFFI_INCLUDEDIR@ + + ########################################################################## + # Parser ++ ++PEGEN_OBJS= \ ++ Parser/pegen/pegen.o \ ++ Parser/pegen/parse.o \ ++ Parser/pegen/parse_string.o \ ++ Parser/pegen/peg_api.o ++ ++ ++PEGEN_HEADERS= \ ++ $(srcdir)/Include/pegen_interface.h \ ++ $(srcdir)/Parser/pegen/pegen.h \ ++ $(srcdir)/Parser/pegen/parse_string.h ++ + POBJS= \ + Parser/acceler.o \ + Parser/grammar1.o \ +@@ -303,9 +316,10 @@ POBJS= \ + Parser/parser.o \ + Parser/token.o \ + +-PARSER_OBJS= $(POBJS) Parser/myreadline.o Parser/parsetok.o Parser/tokenizer.o ++PARSER_OBJS= $(POBJS) $(PEGEN_OBJS) Parser/myreadline.o Parser/parsetok.o Parser/tokenizer.o + + PARSER_HEADERS= \ ++ $(PEGEN_HEADERS) \ + $(srcdir)/Include/grammar.h \ + $(srcdir)/Include/parsetok.h \ + $(srcdir)/Parser/parser.h \ +@@ -731,7 +745,7 @@ regen-importlib: Programs/_freeze_importlib + ############################################################################ + # Regenerate all generated files + +-regen-all: regen-opcode regen-opcode-targets regen-typeslots regen-grammar \ ++regen-all: regen-opcode regen-opcode-targets regen-typeslots regen-grammar regen-pegen \ + regen-token regen-keyword regen-symbol regen-ast regen-importlib clinic + + ############################################################################ +@@ -806,6 +820,12 @@ regen-grammar: regen-token + $(UPDATE_FILE) $(srcdir)/Include/graminit.h $(srcdir)/Include/graminit.h.new + $(UPDATE_FILE) $(srcdir)/Python/graminit.c $(srcdir)/Python/graminit.c.new + ++.PHONY: regen-pegen ++regen-pegen: ++ PYTHONPATH=$(srcdir)/Tools/peg_generator $(PYTHON_FOR_REGEN) -m pegen -c -q $(srcdir)/Grammar/python.gram \ ++ -o $(srcdir)/Parser/pegen/parse.new.c ++ $(UPDATE_FILE) $(srcdir)/Parser/pegen/parse.c $(srcdir)/Parser/pegen/parse.new.c ++ + .PHONY=regen-ast + regen-ast: + # Regenerate Include/Python-ast.h using Parser/asdl_c.py -h +diff --git a/Modules/Setup b/Modules/Setup +--- a/Modules/Setup ++++ b/Modules/Setup +@@ -134,6 +134,9 @@ faulthandler faulthandler.c + # can call _PyTraceMalloc_NewReference(). + _tracemalloc _tracemalloc.c hashtable.c + ++# PEG-based parser module -- slated to be *the* parser ++_peg_parser _peg_parser.c ++ + # The rest of the modules listed in this file are all commented out by + # default. Usually they can be detected and built as dynamically + # loaded modules by the new setup.py script added in Python 2.1. If +diff --git a/Modules/_peg_parser.c b/Modules/_peg_parser.c +new file mode 100644 +--- /dev/null ++++ b/Modules/_peg_parser.c +@@ -0,0 +1,107 @@ ++#include ++#include ++ ++PyObject * ++_Py_parse_file(PyObject *self, PyObject *args, PyObject *kwds) ++{ ++ static char *keywords[] = {"file", "mode", NULL}; ++ char *filename; ++ char *mode_str = "exec"; ++ ++ if (!PyArg_ParseTupleAndKeywords(args, kwds, "s|s", keywords, &filename, &mode_str)) { ++ return NULL; ++ } ++ ++ int mode; ++ if (strcmp(mode_str, "exec") == 0) { ++ mode = Py_file_input; ++ } ++ else if (strcmp(mode_str, "single") == 0) { ++ mode = Py_single_input; ++ } ++ else { ++ return PyErr_Format(PyExc_ValueError, "mode must be either 'exec' or 'single'"); ++ } ++ ++ PyArena *arena = PyArena_New(); ++ if (arena == NULL) { ++ return NULL; ++ } ++ ++ PyObject *result = NULL; ++ ++ mod_ty res = PyPegen_ASTFromFile(filename, mode, arena); ++ if (res == NULL) { ++ goto error; ++ } ++ result = PyAST_mod2obj(res); ++ ++error: ++ PyArena_Free(arena); ++ return result; ++} ++ ++PyObject * ++_Py_parse_string(PyObject *self, PyObject *args, PyObject *kwds) ++{ ++ static char *keywords[] = {"string", "mode", NULL}; ++ char *the_string; ++ char *mode_str = "exec"; ++ ++ if (!PyArg_ParseTupleAndKeywords(args, kwds, "s|s", keywords, &the_string, &mode_str)) { ++ return NULL; ++ } ++ ++ int mode; ++ if (strcmp(mode_str, "exec") == 0) { ++ mode = Py_file_input; ++ } ++ else if (strcmp(mode_str, "eval") == 0) { ++ mode = Py_eval_input; ++ } ++ else if (strcmp(mode_str, "single") == 0) { ++ mode = Py_single_input; ++ } ++ else { ++ return PyErr_Format(PyExc_ValueError, "mode must be either 'exec' or 'eval' or 'single'"); ++ } ++ ++ PyArena *arena = PyArena_New(); ++ if (arena == NULL) { ++ return NULL; ++ } ++ ++ PyObject *result = NULL; ++ ++ PyCompilerFlags flags = _PyCompilerFlags_INIT; ++ flags.cf_flags = PyCF_IGNORE_COOKIE; ++ ++ mod_ty res = PyPegen_ASTFromString(the_string, mode, &flags, arena); ++ if (res == NULL) { ++ goto error; ++ } ++ result = PyAST_mod2obj(res); ++ ++error: ++ PyArena_Free(arena); ++ return result; ++} ++ ++static PyMethodDef ParseMethods[] = { ++ {"parse_file", (PyCFunction)(void (*)(void))_Py_parse_file, METH_VARARGS|METH_KEYWORDS, "Parse a file."}, ++ {"parse_string", (PyCFunction)(void (*)(void))_Py_parse_string, METH_VARARGS|METH_KEYWORDS,"Parse a string."}, ++ {NULL, NULL, 0, NULL} /* Sentinel */ ++}; ++ ++static struct PyModuleDef parsemodule = { ++ PyModuleDef_HEAD_INIT, ++ .m_name = "peg_parser", ++ .m_doc = "A parser.", ++ .m_methods = ParseMethods, ++}; ++ ++PyMODINIT_FUNC ++PyInit__peg_parser(void) ++{ ++ return PyModule_Create(&parsemodule); ++} +diff --git a/PC/config.c b/PC/config.c +--- a/PC/config.c ++++ b/PC/config.c +@@ -75,6 +75,8 @@ extern PyObject* PyInit__opcode(void); + + extern PyObject* PyInit__contextvars(void); + ++extern PyObject* PyInit__peg_parser(void); ++ + /* tools/freeze/makeconfig.py marker for additional "extern" */ + /* -- ADDMODULE MARKER 1 -- */ + +@@ -169,6 +171,7 @@ struct _inittab _PyImport_Inittab[] = { + {"_opcode", PyInit__opcode}, + + {"_contextvars", PyInit__contextvars}, ++ {"_peg_parser", PyInit__peg_parser}, + + /* Sentinel */ + {0, 0} +diff --git a/PCbuild/pythoncore.vcxproj b/PCbuild/pythoncore.vcxproj +--- a/PCbuild/pythoncore.vcxproj ++++ b/PCbuild/pythoncore.vcxproj +@@ -213,6 +213,8 @@ + + + ++ ++ + + + +@@ -276,6 +278,8 @@ + + + ++ ++ + + + +@@ -338,6 +342,7 @@ + + + ++ + + + +@@ -419,6 +424,10 @@ + + + ++ ++ ++ ++ + + + +diff --git a/PCbuild/pythoncore.vcxproj.filters b/PCbuild/pythoncore.vcxproj.filters +--- a/PCbuild/pythoncore.vcxproj.filters ++++ b/PCbuild/pythoncore.vcxproj.filters +@@ -902,6 +902,18 @@ + + Parser + ++ ++ Parser ++ ++ ++ Parser ++ ++ ++ Parser ++ ++ ++ Parser ++ + + Parser + +diff --git a/PCbuild/regen.vcxproj b/PCbuild/regen.vcxproj +--- a/PCbuild/regen.vcxproj ++++ b/PCbuild/regen.vcxproj +@@ -166,6 +166,14 @@ + + + ++ ++ ++ ++ ++ ++ ++ ++ + + + +@@ -222,4 +230,4 @@ + + + +- +\ No newline at end of file ++ +diff --git a/Parser/pegen/parse.c b/Parser/pegen/parse.c +new file mode 100644 +--- /dev/null ++++ b/Parser/pegen/parse.c +@@ -0,0 +1,15391 @@ ++// @generated by pegen.py from ./Grammar/python.gram ++#include "pegen.h" ++static const int n_keyword_lists = 15; ++static KeywordToken *reserved_keywords[] = { ++ NULL, ++ NULL, ++ (KeywordToken[]) { ++ {"if", 510}, ++ {"in", 518}, ++ {"is", 526}, ++ {"as", 531}, ++ {"or", 532}, ++ {NULL, -1}, ++ }, ++ (KeywordToken[]) { ++ {"del", 503}, ++ {"try", 511}, ++ {"for", 517}, ++ {"def", 522}, ++ {"not", 525}, ++ {"and", 533}, ++ {NULL, -1}, ++ }, ++ (KeywordToken[]) { ++ {"pass", 502}, ++ {"from", 514}, ++ {"elif", 515}, ++ {"else", 516}, ++ {"with", 519}, ++ {"True", 527}, ++ {"None", 529}, ++ {NULL, -1}, ++ }, ++ (KeywordToken[]) { ++ {"raise", 501}, ++ {"yield", 504}, ++ {"break", 506}, ++ {"while", 512}, ++ {"class", 523}, ++ {"False", 528}, ++ {NULL, -1}, ++ }, ++ (KeywordToken[]) { ++ {"return", 500}, ++ {"assert", 505}, ++ {"global", 508}, ++ {"import", 513}, ++ {"except", 520}, ++ {"lambda", 524}, ++ {NULL, -1}, ++ }, ++ (KeywordToken[]) { ++ {"finally", 521}, ++ {NULL, -1}, ++ }, ++ (KeywordToken[]) { ++ {"continue", 507}, ++ {"nonlocal", 509}, ++ {NULL, -1}, ++ }, ++ NULL, ++ NULL, ++ NULL, ++ NULL, ++ NULL, ++ (KeywordToken[]) { ++ {"__new_parser__", 530}, ++ {NULL, -1}, ++ }, ++}; ++#define file_type 1000 ++#define interactive_type 1001 ++#define eval_type 1002 ++#define fstring_type 1003 ++#define statements_type 1004 ++#define statement_type 1005 ++#define statement_newline_type 1006 ++#define simple_stmt_type 1007 ++#define small_stmt_type 1008 ++#define compound_stmt_type 1009 ++#define assignment_type 1010 ++#define augassign_type 1011 ++#define global_stmt_type 1012 ++#define nonlocal_stmt_type 1013 ++#define yield_stmt_type 1014 ++#define assert_stmt_type 1015 ++#define del_stmt_type 1016 ++#define import_stmt_type 1017 ++#define import_name_type 1018 ++#define import_from_type 1019 ++#define import_from_targets_type 1020 ++#define import_from_as_names_type 1021 ++#define import_from_as_name_type 1022 ++#define dotted_as_names_type 1023 ++#define dotted_as_name_type 1024 ++#define dotted_name_type 1025 // Left-recursive ++#define if_stmt_type 1026 ++#define elif_stmt_type 1027 ++#define else_block_type 1028 ++#define while_stmt_type 1029 ++#define for_stmt_type 1030 ++#define with_stmt_type 1031 ++#define with_item_type 1032 ++#define try_stmt_type 1033 ++#define except_block_type 1034 ++#define finally_block_type 1035 ++#define return_stmt_type 1036 ++#define raise_stmt_type 1037 ++#define function_def_type 1038 ++#define function_def_raw_type 1039 ++#define params_type 1040 ++#define parameters_type 1041 ++#define slash_without_default_type 1042 ++#define slash_with_default_type 1043 ++#define star_etc_type 1044 ++#define name_with_optional_default_type 1045 ++#define names_with_default_type 1046 ++#define name_with_default_type 1047 ++#define plain_names_type 1048 ++#define plain_name_type 1049 ++#define kwds_type 1050 ++#define annotation_type 1051 ++#define decorators_type 1052 ++#define class_def_type 1053 ++#define class_def_raw_type 1054 ++#define block_type 1055 ++#define expressions_list_type 1056 ++#define star_expressions_type 1057 ++#define star_expression_type 1058 ++#define star_named_expressions_type 1059 ++#define star_named_expression_type 1060 ++#define named_expression_type 1061 ++#define annotated_rhs_type 1062 ++#define expressions_type 1063 ++#define expression_type 1064 ++#define lambdef_type 1065 ++#define lambda_parameters_type 1066 ++#define lambda_slash_without_default_type 1067 ++#define lambda_slash_with_default_type 1068 ++#define lambda_star_etc_type 1069 ++#define lambda_name_with_optional_default_type 1070 ++#define lambda_names_with_default_type 1071 ++#define lambda_name_with_default_type 1072 ++#define lambda_plain_names_type 1073 ++#define lambda_plain_name_type 1074 ++#define lambda_kwds_type 1075 ++#define disjunction_type 1076 ++#define conjunction_type 1077 ++#define inversion_type 1078 ++#define comparison_type 1079 ++#define compare_op_bitwise_or_pair_type 1080 ++#define eq_bitwise_or_type 1081 ++#define noteq_bitwise_or_type 1082 ++#define lte_bitwise_or_type 1083 ++#define lt_bitwise_or_type 1084 ++#define gte_bitwise_or_type 1085 ++#define gt_bitwise_or_type 1086 ++#define notin_bitwise_or_type 1087 ++#define in_bitwise_or_type 1088 ++#define isnot_bitwise_or_type 1089 ++#define is_bitwise_or_type 1090 ++#define bitwise_or_type 1091 // Left-recursive ++#define bitwise_xor_type 1092 // Left-recursive ++#define bitwise_and_type 1093 // Left-recursive ++#define shift_expr_type 1094 // Left-recursive ++#define sum_type 1095 // Left-recursive ++#define term_type 1096 // Left-recursive ++#define factor_type 1097 ++#define power_type 1098 ++#define await_primary_type 1099 ++#define primary_type 1100 // Left-recursive ++#define slices_type 1101 ++#define slice_type 1102 ++#define atom_type 1103 ++#define strings_type 1104 ++#define list_type 1105 ++#define listcomp_type 1106 ++#define tuple_type 1107 ++#define group_type 1108 ++#define genexp_type 1109 ++#define set_type 1110 ++#define setcomp_type 1111 ++#define dict_type 1112 ++#define dictcomp_type 1113 ++#define kvpairs_type 1114 ++#define kvpair_type 1115 ++#define for_if_clauses_type 1116 ++#define yield_expr_type 1117 ++#define arguments_type 1118 ++#define args_type 1119 ++#define kwargs_type 1120 ++#define starred_expression_type 1121 ++#define kwarg_or_starred_type 1122 ++#define kwarg_or_double_starred_type 1123 ++#define star_targets_type 1124 ++#define star_targets_seq_type 1125 ++#define star_target_type 1126 ++#define star_atom_type 1127 ++#define inside_paren_ann_assign_target_type 1128 ++#define ann_assign_subscript_attribute_target_type 1129 ++#define del_targets_type 1130 ++#define del_target_type 1131 ++#define del_t_atom_type 1132 ++#define targets_type 1133 ++#define target_type 1134 ++#define t_primary_type 1135 // Left-recursive ++#define t_lookahead_type 1136 ++#define t_atom_type 1137 ++#define incorrect_arguments_type 1138 ++#define invalid_named_expression_type 1139 ++#define invalid_assignment_type 1140 ++#define invalid_block_type 1141 ++#define invalid_comprehension_type 1142 ++#define invalid_parameters_type 1143 ++#define _loop0_1_type 1144 ++#define _loop1_2_type 1145 ++#define _loop0_4_type 1146 ++#define _gather_3_type 1147 ++#define _tmp_5_type 1148 ++#define _tmp_6_type 1149 ++#define _tmp_7_type 1150 ++#define _tmp_8_type 1151 ++#define _tmp_9_type 1152 ++#define _tmp_10_type 1153 ++#define _tmp_11_type 1154 ++#define _tmp_12_type 1155 ++#define _loop1_13_type 1156 ++#define _tmp_14_type 1157 ++#define _tmp_15_type 1158 ++#define _loop0_17_type 1159 ++#define _gather_16_type 1160 ++#define _loop0_19_type 1161 ++#define _gather_18_type 1162 ++#define _tmp_20_type 1163 ++#define _loop0_21_type 1164 ++#define _loop1_22_type 1165 ++#define _loop0_24_type 1166 ++#define _gather_23_type 1167 ++#define _tmp_25_type 1168 ++#define _loop0_27_type 1169 ++#define _gather_26_type 1170 ++#define _tmp_28_type 1171 ++#define _loop0_30_type 1172 ++#define _gather_29_type 1173 ++#define _loop0_32_type 1174 ++#define _gather_31_type 1175 ++#define _tmp_33_type 1176 ++#define _loop1_34_type 1177 ++#define _tmp_35_type 1178 ++#define _tmp_36_type 1179 ++#define _tmp_37_type 1180 ++#define _tmp_38_type 1181 ++#define _tmp_39_type 1182 ++#define _tmp_40_type 1183 ++#define _tmp_41_type 1184 ++#define _tmp_42_type 1185 ++#define _tmp_43_type 1186 ++#define _tmp_44_type 1187 ++#define _tmp_45_type 1188 ++#define _tmp_46_type 1189 ++#define _loop0_47_type 1190 ++#define _tmp_48_type 1191 ++#define _loop1_49_type 1192 ++#define _tmp_50_type 1193 ++#define _tmp_51_type 1194 ++#define _loop0_53_type 1195 ++#define _gather_52_type 1196 ++#define _loop0_55_type 1197 ++#define _gather_54_type 1198 ++#define _tmp_56_type 1199 ++#define _loop1_57_type 1200 ++#define _tmp_58_type 1201 ++#define _loop0_60_type 1202 ++#define _gather_59_type 1203 ++#define _loop1_61_type 1204 ++#define _loop0_63_type 1205 ++#define _gather_62_type 1206 ++#define _loop1_64_type 1207 ++#define _tmp_65_type 1208 ++#define _tmp_66_type 1209 ++#define _tmp_67_type 1210 ++#define _tmp_68_type 1211 ++#define _tmp_69_type 1212 ++#define _tmp_70_type 1213 ++#define _tmp_71_type 1214 ++#define _tmp_72_type 1215 ++#define _tmp_73_type 1216 ++#define _loop0_74_type 1217 ++#define _tmp_75_type 1218 ++#define _loop1_76_type 1219 ++#define _tmp_77_type 1220 ++#define _tmp_78_type 1221 ++#define _loop0_80_type 1222 ++#define _gather_79_type 1223 ++#define _loop0_82_type 1224 ++#define _gather_81_type 1225 ++#define _loop1_83_type 1226 ++#define _loop1_84_type 1227 ++#define _loop1_85_type 1228 ++#define _loop0_87_type 1229 ++#define _gather_86_type 1230 ++#define _tmp_88_type 1231 ++#define _tmp_89_type 1232 ++#define _tmp_90_type 1233 ++#define _tmp_91_type 1234 ++#define _loop1_92_type 1235 ++#define _tmp_93_type 1236 ++#define _tmp_94_type 1237 ++#define _loop0_96_type 1238 ++#define _gather_95_type 1239 ++#define _loop1_97_type 1240 ++#define _tmp_98_type 1241 ++#define _tmp_99_type 1242 ++#define _loop0_101_type 1243 ++#define _gather_100_type 1244 ++#define _loop0_103_type 1245 ++#define _gather_102_type 1246 ++#define _loop0_105_type 1247 ++#define _gather_104_type 1248 ++#define _loop0_107_type 1249 ++#define _gather_106_type 1250 ++#define _loop0_108_type 1251 ++#define _loop0_110_type 1252 ++#define _gather_109_type 1253 ++#define _tmp_111_type 1254 ++#define _loop0_113_type 1255 ++#define _gather_112_type 1256 ++#define _loop0_115_type 1257 ++#define _gather_114_type 1258 ++#define _tmp_116_type 1259 ++#define _tmp_117_type 1260 ++#define _tmp_118_type 1261 ++#define _tmp_119_type 1262 ++#define _tmp_120_type 1263 ++#define _tmp_121_type 1264 ++#define _tmp_122_type 1265 ++#define _tmp_123_type 1266 ++#define _tmp_124_type 1267 ++#define _tmp_125_type 1268 ++#define _tmp_126_type 1269 ++#define _tmp_127_type 1270 ++#define _tmp_128_type 1271 ++#define _tmp_129_type 1272 ++#define _tmp_130_type 1273 ++#define _tmp_131_type 1274 ++#define _tmp_132_type 1275 ++#define _tmp_133_type 1276 ++#define _tmp_134_type 1277 ++#define _loop0_135_type 1278 ++#define _tmp_136_type 1279 ++ ++static mod_ty file_rule(Parser *p); ++static mod_ty interactive_rule(Parser *p); ++static mod_ty eval_rule(Parser *p); ++static expr_ty fstring_rule(Parser *p); ++static asdl_seq* statements_rule(Parser *p); ++static asdl_seq* statement_rule(Parser *p); ++static asdl_seq* statement_newline_rule(Parser *p); ++static asdl_seq* simple_stmt_rule(Parser *p); ++static stmt_ty small_stmt_rule(Parser *p); ++static stmt_ty compound_stmt_rule(Parser *p); ++static void *assignment_rule(Parser *p); ++static AugOperator* augassign_rule(Parser *p); ++static stmt_ty global_stmt_rule(Parser *p); ++static stmt_ty nonlocal_stmt_rule(Parser *p); ++static stmt_ty yield_stmt_rule(Parser *p); ++static stmt_ty assert_stmt_rule(Parser *p); ++static stmt_ty del_stmt_rule(Parser *p); ++static stmt_ty import_stmt_rule(Parser *p); ++static stmt_ty import_name_rule(Parser *p); ++static stmt_ty import_from_rule(Parser *p); ++static asdl_seq* import_from_targets_rule(Parser *p); ++static asdl_seq* import_from_as_names_rule(Parser *p); ++static alias_ty import_from_as_name_rule(Parser *p); ++static asdl_seq* dotted_as_names_rule(Parser *p); ++static alias_ty dotted_as_name_rule(Parser *p); ++static expr_ty dotted_name_rule(Parser *p); ++static stmt_ty if_stmt_rule(Parser *p); ++static stmt_ty elif_stmt_rule(Parser *p); ++static asdl_seq* else_block_rule(Parser *p); ++static stmt_ty while_stmt_rule(Parser *p); ++static stmt_ty for_stmt_rule(Parser *p); ++static stmt_ty with_stmt_rule(Parser *p); ++static withitem_ty with_item_rule(Parser *p); ++static stmt_ty try_stmt_rule(Parser *p); ++static excepthandler_ty except_block_rule(Parser *p); ++static asdl_seq* finally_block_rule(Parser *p); ++static stmt_ty return_stmt_rule(Parser *p); ++static stmt_ty raise_stmt_rule(Parser *p); ++static stmt_ty function_def_rule(Parser *p); ++static stmt_ty function_def_raw_rule(Parser *p); ++static arguments_ty params_rule(Parser *p); ++static arguments_ty parameters_rule(Parser *p); ++static asdl_seq* slash_without_default_rule(Parser *p); ++static SlashWithDefault* slash_with_default_rule(Parser *p); ++static StarEtc* star_etc_rule(Parser *p); ++static NameDefaultPair* name_with_optional_default_rule(Parser *p); ++static asdl_seq* names_with_default_rule(Parser *p); ++static NameDefaultPair* name_with_default_rule(Parser *p); ++static asdl_seq* plain_names_rule(Parser *p); ++static arg_ty plain_name_rule(Parser *p); ++static arg_ty kwds_rule(Parser *p); ++static expr_ty annotation_rule(Parser *p); ++static asdl_seq* decorators_rule(Parser *p); ++static stmt_ty class_def_rule(Parser *p); ++static stmt_ty class_def_raw_rule(Parser *p); ++static asdl_seq* block_rule(Parser *p); ++static asdl_seq* expressions_list_rule(Parser *p); ++static expr_ty star_expressions_rule(Parser *p); ++static expr_ty star_expression_rule(Parser *p); ++static asdl_seq* star_named_expressions_rule(Parser *p); ++static expr_ty star_named_expression_rule(Parser *p); ++static expr_ty named_expression_rule(Parser *p); ++static expr_ty annotated_rhs_rule(Parser *p); ++static expr_ty expressions_rule(Parser *p); ++static expr_ty expression_rule(Parser *p); ++static expr_ty lambdef_rule(Parser *p); ++static arguments_ty lambda_parameters_rule(Parser *p); ++static asdl_seq* lambda_slash_without_default_rule(Parser *p); ++static SlashWithDefault* lambda_slash_with_default_rule(Parser *p); ++static StarEtc* lambda_star_etc_rule(Parser *p); ++static NameDefaultPair* lambda_name_with_optional_default_rule(Parser *p); ++static asdl_seq* lambda_names_with_default_rule(Parser *p); ++static NameDefaultPair* lambda_name_with_default_rule(Parser *p); ++static asdl_seq* lambda_plain_names_rule(Parser *p); ++static arg_ty lambda_plain_name_rule(Parser *p); ++static arg_ty lambda_kwds_rule(Parser *p); ++static expr_ty disjunction_rule(Parser *p); ++static expr_ty conjunction_rule(Parser *p); ++static expr_ty inversion_rule(Parser *p); ++static expr_ty comparison_rule(Parser *p); ++static CmpopExprPair* compare_op_bitwise_or_pair_rule(Parser *p); ++static CmpopExprPair* eq_bitwise_or_rule(Parser *p); ++static CmpopExprPair* noteq_bitwise_or_rule(Parser *p); ++static CmpopExprPair* lte_bitwise_or_rule(Parser *p); ++static CmpopExprPair* lt_bitwise_or_rule(Parser *p); ++static CmpopExprPair* gte_bitwise_or_rule(Parser *p); ++static CmpopExprPair* gt_bitwise_or_rule(Parser *p); ++static CmpopExprPair* notin_bitwise_or_rule(Parser *p); ++static CmpopExprPair* in_bitwise_or_rule(Parser *p); ++static CmpopExprPair* isnot_bitwise_or_rule(Parser *p); ++static CmpopExprPair* is_bitwise_or_rule(Parser *p); ++static expr_ty bitwise_or_rule(Parser *p); ++static expr_ty bitwise_xor_rule(Parser *p); ++static expr_ty bitwise_and_rule(Parser *p); ++static expr_ty shift_expr_rule(Parser *p); ++static expr_ty sum_rule(Parser *p); ++static expr_ty term_rule(Parser *p); ++static expr_ty factor_rule(Parser *p); ++static expr_ty power_rule(Parser *p); ++static expr_ty await_primary_rule(Parser *p); ++static expr_ty primary_rule(Parser *p); ++static expr_ty slices_rule(Parser *p); ++static expr_ty slice_rule(Parser *p); ++static expr_ty atom_rule(Parser *p); ++static expr_ty strings_rule(Parser *p); ++static expr_ty list_rule(Parser *p); ++static expr_ty listcomp_rule(Parser *p); ++static expr_ty tuple_rule(Parser *p); ++static expr_ty group_rule(Parser *p); ++static expr_ty genexp_rule(Parser *p); ++static expr_ty set_rule(Parser *p); ++static expr_ty setcomp_rule(Parser *p); ++static expr_ty dict_rule(Parser *p); ++static expr_ty dictcomp_rule(Parser *p); ++static asdl_seq* kvpairs_rule(Parser *p); ++static KeyValuePair* kvpair_rule(Parser *p); ++static asdl_seq* for_if_clauses_rule(Parser *p); ++static expr_ty yield_expr_rule(Parser *p); ++static expr_ty arguments_rule(Parser *p); ++static expr_ty args_rule(Parser *p); ++static asdl_seq* kwargs_rule(Parser *p); ++static expr_ty starred_expression_rule(Parser *p); ++static KeywordOrStarred* kwarg_or_starred_rule(Parser *p); ++static KeywordOrStarred* kwarg_or_double_starred_rule(Parser *p); ++static expr_ty star_targets_rule(Parser *p); ++static asdl_seq* star_targets_seq_rule(Parser *p); ++static expr_ty star_target_rule(Parser *p); ++static expr_ty star_atom_rule(Parser *p); ++static expr_ty inside_paren_ann_assign_target_rule(Parser *p); ++static expr_ty ann_assign_subscript_attribute_target_rule(Parser *p); ++static asdl_seq* del_targets_rule(Parser *p); ++static expr_ty del_target_rule(Parser *p); ++static expr_ty del_t_atom_rule(Parser *p); ++static asdl_seq* targets_rule(Parser *p); ++static expr_ty target_rule(Parser *p); ++static expr_ty t_primary_rule(Parser *p); ++static void *t_lookahead_rule(Parser *p); ++static expr_ty t_atom_rule(Parser *p); ++static void *incorrect_arguments_rule(Parser *p); ++static void *invalid_named_expression_rule(Parser *p); ++static void *invalid_assignment_rule(Parser *p); ++static void *invalid_block_rule(Parser *p); ++static void *invalid_comprehension_rule(Parser *p); ++static void *invalid_parameters_rule(Parser *p); ++static asdl_seq *_loop0_1_rule(Parser *p); ++static asdl_seq *_loop1_2_rule(Parser *p); ++static asdl_seq *_loop0_4_rule(Parser *p); ++static asdl_seq *_gather_3_rule(Parser *p); ++static void *_tmp_5_rule(Parser *p); ++static void *_tmp_6_rule(Parser *p); ++static void *_tmp_7_rule(Parser *p); ++static void *_tmp_8_rule(Parser *p); ++static void *_tmp_9_rule(Parser *p); ++static void *_tmp_10_rule(Parser *p); ++static void *_tmp_11_rule(Parser *p); ++static void *_tmp_12_rule(Parser *p); ++static asdl_seq *_loop1_13_rule(Parser *p); ++static void *_tmp_14_rule(Parser *p); ++static void *_tmp_15_rule(Parser *p); ++static asdl_seq *_loop0_17_rule(Parser *p); ++static asdl_seq *_gather_16_rule(Parser *p); ++static asdl_seq *_loop0_19_rule(Parser *p); ++static asdl_seq *_gather_18_rule(Parser *p); ++static void *_tmp_20_rule(Parser *p); ++static asdl_seq *_loop0_21_rule(Parser *p); ++static asdl_seq *_loop1_22_rule(Parser *p); ++static asdl_seq *_loop0_24_rule(Parser *p); ++static asdl_seq *_gather_23_rule(Parser *p); ++static void *_tmp_25_rule(Parser *p); ++static asdl_seq *_loop0_27_rule(Parser *p); ++static asdl_seq *_gather_26_rule(Parser *p); ++static void *_tmp_28_rule(Parser *p); ++static asdl_seq *_loop0_30_rule(Parser *p); ++static asdl_seq *_gather_29_rule(Parser *p); ++static asdl_seq *_loop0_32_rule(Parser *p); ++static asdl_seq *_gather_31_rule(Parser *p); ++static void *_tmp_33_rule(Parser *p); ++static asdl_seq *_loop1_34_rule(Parser *p); ++static void *_tmp_35_rule(Parser *p); ++static void *_tmp_36_rule(Parser *p); ++static void *_tmp_37_rule(Parser *p); ++static void *_tmp_38_rule(Parser *p); ++static void *_tmp_39_rule(Parser *p); ++static void *_tmp_40_rule(Parser *p); ++static void *_tmp_41_rule(Parser *p); ++static void *_tmp_42_rule(Parser *p); ++static void *_tmp_43_rule(Parser *p); ++static void *_tmp_44_rule(Parser *p); ++static void *_tmp_45_rule(Parser *p); ++static void *_tmp_46_rule(Parser *p); ++static asdl_seq *_loop0_47_rule(Parser *p); ++static void *_tmp_48_rule(Parser *p); ++static asdl_seq *_loop1_49_rule(Parser *p); ++static void *_tmp_50_rule(Parser *p); ++static void *_tmp_51_rule(Parser *p); ++static asdl_seq *_loop0_53_rule(Parser *p); ++static asdl_seq *_gather_52_rule(Parser *p); ++static asdl_seq *_loop0_55_rule(Parser *p); ++static asdl_seq *_gather_54_rule(Parser *p); ++static void *_tmp_56_rule(Parser *p); ++static asdl_seq *_loop1_57_rule(Parser *p); ++static void *_tmp_58_rule(Parser *p); ++static asdl_seq *_loop0_60_rule(Parser *p); ++static asdl_seq *_gather_59_rule(Parser *p); ++static asdl_seq *_loop1_61_rule(Parser *p); ++static asdl_seq *_loop0_63_rule(Parser *p); ++static asdl_seq *_gather_62_rule(Parser *p); ++static asdl_seq *_loop1_64_rule(Parser *p); ++static void *_tmp_65_rule(Parser *p); ++static void *_tmp_66_rule(Parser *p); ++static void *_tmp_67_rule(Parser *p); ++static void *_tmp_68_rule(Parser *p); ++static void *_tmp_69_rule(Parser *p); ++static void *_tmp_70_rule(Parser *p); ++static void *_tmp_71_rule(Parser *p); ++static void *_tmp_72_rule(Parser *p); ++static void *_tmp_73_rule(Parser *p); ++static asdl_seq *_loop0_74_rule(Parser *p); ++static void *_tmp_75_rule(Parser *p); ++static asdl_seq *_loop1_76_rule(Parser *p); ++static void *_tmp_77_rule(Parser *p); ++static void *_tmp_78_rule(Parser *p); ++static asdl_seq *_loop0_80_rule(Parser *p); ++static asdl_seq *_gather_79_rule(Parser *p); ++static asdl_seq *_loop0_82_rule(Parser *p); ++static asdl_seq *_gather_81_rule(Parser *p); ++static asdl_seq *_loop1_83_rule(Parser *p); ++static asdl_seq *_loop1_84_rule(Parser *p); ++static asdl_seq *_loop1_85_rule(Parser *p); ++static asdl_seq *_loop0_87_rule(Parser *p); ++static asdl_seq *_gather_86_rule(Parser *p); ++static void *_tmp_88_rule(Parser *p); ++static void *_tmp_89_rule(Parser *p); ++static void *_tmp_90_rule(Parser *p); ++static void *_tmp_91_rule(Parser *p); ++static asdl_seq *_loop1_92_rule(Parser *p); ++static void *_tmp_93_rule(Parser *p); ++static void *_tmp_94_rule(Parser *p); ++static asdl_seq *_loop0_96_rule(Parser *p); ++static asdl_seq *_gather_95_rule(Parser *p); ++static asdl_seq *_loop1_97_rule(Parser *p); ++static void *_tmp_98_rule(Parser *p); ++static void *_tmp_99_rule(Parser *p); ++static asdl_seq *_loop0_101_rule(Parser *p); ++static asdl_seq *_gather_100_rule(Parser *p); ++static asdl_seq *_loop0_103_rule(Parser *p); ++static asdl_seq *_gather_102_rule(Parser *p); ++static asdl_seq *_loop0_105_rule(Parser *p); ++static asdl_seq *_gather_104_rule(Parser *p); ++static asdl_seq *_loop0_107_rule(Parser *p); ++static asdl_seq *_gather_106_rule(Parser *p); ++static asdl_seq *_loop0_108_rule(Parser *p); ++static asdl_seq *_loop0_110_rule(Parser *p); ++static asdl_seq *_gather_109_rule(Parser *p); ++static void *_tmp_111_rule(Parser *p); ++static asdl_seq *_loop0_113_rule(Parser *p); ++static asdl_seq *_gather_112_rule(Parser *p); ++static asdl_seq *_loop0_115_rule(Parser *p); ++static asdl_seq *_gather_114_rule(Parser *p); ++static void *_tmp_116_rule(Parser *p); ++static void *_tmp_117_rule(Parser *p); ++static void *_tmp_118_rule(Parser *p); ++static void *_tmp_119_rule(Parser *p); ++static void *_tmp_120_rule(Parser *p); ++static void *_tmp_121_rule(Parser *p); ++static void *_tmp_122_rule(Parser *p); ++static void *_tmp_123_rule(Parser *p); ++static void *_tmp_124_rule(Parser *p); ++static void *_tmp_125_rule(Parser *p); ++static void *_tmp_126_rule(Parser *p); ++static void *_tmp_127_rule(Parser *p); ++static void *_tmp_128_rule(Parser *p); ++static void *_tmp_129_rule(Parser *p); ++static void *_tmp_130_rule(Parser *p); ++static void *_tmp_131_rule(Parser *p); ++static void *_tmp_132_rule(Parser *p); ++static void *_tmp_133_rule(Parser *p); ++static void *_tmp_134_rule(Parser *p); ++static asdl_seq *_loop0_135_rule(Parser *p); ++static void *_tmp_136_rule(Parser *p); ++ ++ ++// file: statements? $ ++static mod_ty ++file_rule(Parser *p) ++{ ++ if (p->error_indicator) { ++ return NULL; ++ } ++ mod_ty res = NULL; ++ int mark = p->mark; ++ { // statements? $ ++ void *a; ++ void *endmarker_var; ++ if ( ++ (a = statements_rule(p), 1) ++ && ++ (endmarker_var = _PyPegen_endmarker_token(p)) ++ ) ++ { ++ res = Module ( a , NULL , p -> arena ); ++ if (res == NULL && PyErr_Occurred()) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ goto done; ++ } ++ p->mark = mark; ++ } ++ res = NULL; ++ done: ++ return res; ++} ++ ++// interactive: statement_newline ++static mod_ty ++interactive_rule(Parser *p) ++{ ++ if (p->error_indicator) { ++ return NULL; ++ } ++ mod_ty res = NULL; ++ int mark = p->mark; ++ { // statement_newline ++ asdl_seq* a; ++ if ( ++ (a = statement_newline_rule(p)) ++ ) ++ { ++ res = Interactive ( a , p -> arena ); ++ if (res == NULL && PyErr_Occurred()) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ goto done; ++ } ++ p->mark = mark; ++ } ++ res = NULL; ++ done: ++ return res; ++} ++ ++// eval: expressions NEWLINE* $ ++static mod_ty ++eval_rule(Parser *p) ++{ ++ if (p->error_indicator) { ++ return NULL; ++ } ++ mod_ty res = NULL; ++ int mark = p->mark; ++ { // expressions NEWLINE* $ ++ asdl_seq * _loop0_1_var; ++ expr_ty a; ++ void *endmarker_var; ++ if ( ++ (a = expressions_rule(p)) ++ && ++ (_loop0_1_var = _loop0_1_rule(p)) ++ && ++ (endmarker_var = _PyPegen_endmarker_token(p)) ++ ) ++ { ++ res = Expression ( a , p -> arena ); ++ if (res == NULL && PyErr_Occurred()) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ goto done; ++ } ++ p->mark = mark; ++ } ++ res = NULL; ++ done: ++ return res; ++} ++ ++// fstring: star_expressions ++static expr_ty ++fstring_rule(Parser *p) ++{ ++ if (p->error_indicator) { ++ return NULL; ++ } ++ expr_ty res = NULL; ++ int mark = p->mark; ++ { // star_expressions ++ expr_ty star_expressions_var; ++ if ( ++ (star_expressions_var = star_expressions_rule(p)) ++ ) ++ { ++ res = star_expressions_var; ++ goto done; ++ } ++ p->mark = mark; ++ } ++ res = NULL; ++ done: ++ return res; ++} ++ ++// statements: statement+ ++static asdl_seq* ++statements_rule(Parser *p) ++{ ++ if (p->error_indicator) { ++ return NULL; ++ } ++ asdl_seq* res = NULL; ++ int mark = p->mark; ++ { // statement+ ++ asdl_seq * a; ++ if ( ++ (a = _loop1_2_rule(p)) ++ ) ++ { ++ res = _PyPegen_seq_flatten ( p , a ); ++ if (res == NULL && PyErr_Occurred()) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ goto done; ++ } ++ p->mark = mark; ++ } ++ res = NULL; ++ done: ++ return res; ++} ++ ++// statement: compound_stmt | simple_stmt ++static asdl_seq* ++statement_rule(Parser *p) ++{ ++ if (p->error_indicator) { ++ return NULL; ++ } ++ asdl_seq* res = NULL; ++ int mark = p->mark; ++ { // compound_stmt ++ stmt_ty a; ++ if ( ++ (a = compound_stmt_rule(p)) ++ ) ++ { ++ res = _PyPegen_singleton_seq ( p , a ); ++ if (res == NULL && PyErr_Occurred()) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ goto done; ++ } ++ p->mark = mark; ++ } ++ { // simple_stmt ++ asdl_seq* simple_stmt_var; ++ if ( ++ (simple_stmt_var = simple_stmt_rule(p)) ++ ) ++ { ++ res = simple_stmt_var; ++ goto done; ++ } ++ p->mark = mark; ++ } ++ res = NULL; ++ done: ++ return res; ++} ++ ++// statement_newline: compound_stmt NEWLINE | simple_stmt | NEWLINE | $ ++static asdl_seq* ++statement_newline_rule(Parser *p) ++{ ++ if (p->error_indicator) { ++ return NULL; ++ } ++ asdl_seq* res = NULL; ++ int mark = p->mark; ++ if (p->mark == p->fill && _PyPegen_fill_token(p) < 0) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ int start_lineno = p->tokens[mark]->lineno; ++ UNUSED(start_lineno); // Only used by EXTRA macro ++ int start_col_offset = p->tokens[mark]->col_offset; ++ UNUSED(start_col_offset); // Only used by EXTRA macro ++ { // compound_stmt NEWLINE ++ stmt_ty a; ++ void *newline_var; ++ if ( ++ (a = compound_stmt_rule(p)) ++ && ++ (newline_var = _PyPegen_newline_token(p)) ++ ) ++ { ++ res = _PyPegen_singleton_seq ( p , a ); ++ if (res == NULL && PyErr_Occurred()) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ goto done; ++ } ++ p->mark = mark; ++ } ++ { // simple_stmt ++ asdl_seq* simple_stmt_var; ++ if ( ++ (simple_stmt_var = simple_stmt_rule(p)) ++ ) ++ { ++ res = simple_stmt_var; ++ goto done; ++ } ++ p->mark = mark; ++ } ++ { // NEWLINE ++ void *newline_var; ++ if ( ++ (newline_var = _PyPegen_newline_token(p)) ++ ) ++ { ++ Token *token = _PyPegen_get_last_nonnwhitespace_token(p); ++ if (token == NULL) { ++ return NULL; ++ } ++ int end_lineno = token->end_lineno; ++ UNUSED(end_lineno); // Only used by EXTRA macro ++ int end_col_offset = token->end_col_offset; ++ UNUSED(end_col_offset); // Only used by EXTRA macro ++ res = _PyPegen_singleton_seq ( p , CHECK ( _Py_Pass ( EXTRA ) ) ); ++ if (res == NULL && PyErr_Occurred()) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ goto done; ++ } ++ p->mark = mark; ++ } ++ { // $ ++ void *endmarker_var; ++ if ( ++ (endmarker_var = _PyPegen_endmarker_token(p)) ++ ) ++ { ++ res = _PyPegen_interactive_exit ( p ); ++ if (res == NULL && PyErr_Occurred()) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ goto done; ++ } ++ p->mark = mark; ++ } ++ res = NULL; ++ done: ++ return res; ++} ++ ++// simple_stmt: small_stmt !';' NEWLINE | ';'.small_stmt+ ';'? NEWLINE ++static asdl_seq* ++simple_stmt_rule(Parser *p) ++{ ++ if (p->error_indicator) { ++ return NULL; ++ } ++ asdl_seq* res = NULL; ++ int mark = p->mark; ++ { // small_stmt !';' NEWLINE ++ stmt_ty a; ++ void *newline_var; ++ if ( ++ (a = small_stmt_rule(p)) ++ && ++ _PyPegen_lookahead_with_int(0, _PyPegen_expect_token, p, 13) ++ && ++ (newline_var = _PyPegen_newline_token(p)) ++ ) ++ { ++ res = _PyPegen_singleton_seq ( p , a ); ++ if (res == NULL && PyErr_Occurred()) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ goto done; ++ } ++ p->mark = mark; ++ } ++ { // ';'.small_stmt+ ';'? NEWLINE ++ asdl_seq * a; ++ void *newline_var; ++ void *opt_var; ++ UNUSED(opt_var); // Silence compiler warnings ++ if ( ++ (a = _gather_3_rule(p)) ++ && ++ (opt_var = _PyPegen_expect_token(p, 13), 1) ++ && ++ (newline_var = _PyPegen_newline_token(p)) ++ ) ++ { ++ res = a; ++ if (res == NULL && PyErr_Occurred()) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ goto done; ++ } ++ p->mark = mark; ++ } ++ res = NULL; ++ done: ++ return res; ++} ++ ++// small_stmt: ++// | assignment ++// | star_expressions ++// | &'return' return_stmt ++// | &('import' | 'from') import_stmt ++// | &'raise' raise_stmt ++// | 'pass' ++// | &'del' del_stmt ++// | &'yield' yield_stmt ++// | &'assert' assert_stmt ++// | 'break' ++// | 'continue' ++// | &'global' global_stmt ++// | &'nonlocal' nonlocal_stmt ++static stmt_ty ++small_stmt_rule(Parser *p) ++{ ++ if (p->error_indicator) { ++ return NULL; ++ } ++ stmt_ty res = NULL; ++ if (_PyPegen_is_memoized(p, small_stmt_type, &res)) ++ return res; ++ int mark = p->mark; ++ if (p->mark == p->fill && _PyPegen_fill_token(p) < 0) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ int start_lineno = p->tokens[mark]->lineno; ++ UNUSED(start_lineno); // Only used by EXTRA macro ++ int start_col_offset = p->tokens[mark]->col_offset; ++ UNUSED(start_col_offset); // Only used by EXTRA macro ++ { // assignment ++ void *assignment_var; ++ if ( ++ (assignment_var = assignment_rule(p)) ++ ) ++ { ++ res = assignment_var; ++ goto done; ++ } ++ p->mark = mark; ++ } ++ { // star_expressions ++ expr_ty e; ++ if ( ++ (e = star_expressions_rule(p)) ++ ) ++ { ++ Token *token = _PyPegen_get_last_nonnwhitespace_token(p); ++ if (token == NULL) { ++ return NULL; ++ } ++ int end_lineno = token->end_lineno; ++ UNUSED(end_lineno); // Only used by EXTRA macro ++ int end_col_offset = token->end_col_offset; ++ UNUSED(end_col_offset); // Only used by EXTRA macro ++ res = _Py_Expr ( e , EXTRA ); ++ if (res == NULL && PyErr_Occurred()) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ goto done; ++ } ++ p->mark = mark; ++ } ++ { // &'return' return_stmt ++ stmt_ty return_stmt_var; ++ if ( ++ _PyPegen_lookahead_with_int(1, _PyPegen_expect_token, p, 500) ++ && ++ (return_stmt_var = return_stmt_rule(p)) ++ ) ++ { ++ res = return_stmt_var; ++ goto done; ++ } ++ p->mark = mark; ++ } ++ { // &('import' | 'from') import_stmt ++ stmt_ty import_stmt_var; ++ if ( ++ _PyPegen_lookahead(1, _tmp_5_rule, p) ++ && ++ (import_stmt_var = import_stmt_rule(p)) ++ ) ++ { ++ res = import_stmt_var; ++ goto done; ++ } ++ p->mark = mark; ++ } ++ { // &'raise' raise_stmt ++ stmt_ty raise_stmt_var; ++ if ( ++ _PyPegen_lookahead_with_int(1, _PyPegen_expect_token, p, 501) ++ && ++ (raise_stmt_var = raise_stmt_rule(p)) ++ ) ++ { ++ res = raise_stmt_var; ++ goto done; ++ } ++ p->mark = mark; ++ } ++ { // 'pass' ++ void *keyword; ++ if ( ++ (keyword = _PyPegen_expect_token(p, 502)) ++ ) ++ { ++ Token *token = _PyPegen_get_last_nonnwhitespace_token(p); ++ if (token == NULL) { ++ return NULL; ++ } ++ int end_lineno = token->end_lineno; ++ UNUSED(end_lineno); // Only used by EXTRA macro ++ int end_col_offset = token->end_col_offset; ++ UNUSED(end_col_offset); // Only used by EXTRA macro ++ res = _Py_Pass ( EXTRA ); ++ if (res == NULL && PyErr_Occurred()) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ goto done; ++ } ++ p->mark = mark; ++ } ++ { // &'del' del_stmt ++ stmt_ty del_stmt_var; ++ if ( ++ _PyPegen_lookahead_with_int(1, _PyPegen_expect_token, p, 503) ++ && ++ (del_stmt_var = del_stmt_rule(p)) ++ ) ++ { ++ res = del_stmt_var; ++ goto done; ++ } ++ p->mark = mark; ++ } ++ { // &'yield' yield_stmt ++ stmt_ty yield_stmt_var; ++ if ( ++ _PyPegen_lookahead_with_int(1, _PyPegen_expect_token, p, 504) ++ && ++ (yield_stmt_var = yield_stmt_rule(p)) ++ ) ++ { ++ res = yield_stmt_var; ++ goto done; ++ } ++ p->mark = mark; ++ } ++ { // &'assert' assert_stmt ++ stmt_ty assert_stmt_var; ++ if ( ++ _PyPegen_lookahead_with_int(1, _PyPegen_expect_token, p, 505) ++ && ++ (assert_stmt_var = assert_stmt_rule(p)) ++ ) ++ { ++ res = assert_stmt_var; ++ goto done; ++ } ++ p->mark = mark; ++ } ++ { // 'break' ++ void *keyword; ++ if ( ++ (keyword = _PyPegen_expect_token(p, 506)) ++ ) ++ { ++ Token *token = _PyPegen_get_last_nonnwhitespace_token(p); ++ if (token == NULL) { ++ return NULL; ++ } ++ int end_lineno = token->end_lineno; ++ UNUSED(end_lineno); // Only used by EXTRA macro ++ int end_col_offset = token->end_col_offset; ++ UNUSED(end_col_offset); // Only used by EXTRA macro ++ res = _Py_Break ( EXTRA ); ++ if (res == NULL && PyErr_Occurred()) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ goto done; ++ } ++ p->mark = mark; ++ } ++ { // 'continue' ++ void *keyword; ++ if ( ++ (keyword = _PyPegen_expect_token(p, 507)) ++ ) ++ { ++ Token *token = _PyPegen_get_last_nonnwhitespace_token(p); ++ if (token == NULL) { ++ return NULL; ++ } ++ int end_lineno = token->end_lineno; ++ UNUSED(end_lineno); // Only used by EXTRA macro ++ int end_col_offset = token->end_col_offset; ++ UNUSED(end_col_offset); // Only used by EXTRA macro ++ res = _Py_Continue ( EXTRA ); ++ if (res == NULL && PyErr_Occurred()) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ goto done; ++ } ++ p->mark = mark; ++ } ++ { // &'global' global_stmt ++ stmt_ty global_stmt_var; ++ if ( ++ _PyPegen_lookahead_with_int(1, _PyPegen_expect_token, p, 508) ++ && ++ (global_stmt_var = global_stmt_rule(p)) ++ ) ++ { ++ res = global_stmt_var; ++ goto done; ++ } ++ p->mark = mark; ++ } ++ { // &'nonlocal' nonlocal_stmt ++ stmt_ty nonlocal_stmt_var; ++ if ( ++ _PyPegen_lookahead_with_int(1, _PyPegen_expect_token, p, 509) ++ && ++ (nonlocal_stmt_var = nonlocal_stmt_rule(p)) ++ ) ++ { ++ res = nonlocal_stmt_var; ++ goto done; ++ } ++ p->mark = mark; ++ } ++ res = NULL; ++ done: ++ _PyPegen_insert_memo(p, mark, small_stmt_type, res); ++ return res; ++} ++ ++// compound_stmt: ++// | &('def' | '@' | ASYNC) function_def ++// | &'if' if_stmt ++// | &('class' | '@') class_def ++// | &('with' | ASYNC) with_stmt ++// | &('for' | ASYNC) for_stmt ++// | &'try' try_stmt ++// | &'while' while_stmt ++static stmt_ty ++compound_stmt_rule(Parser *p) ++{ ++ if (p->error_indicator) { ++ return NULL; ++ } ++ stmt_ty res = NULL; ++ int mark = p->mark; ++ { // &('def' | '@' | ASYNC) function_def ++ stmt_ty function_def_var; ++ if ( ++ _PyPegen_lookahead(1, _tmp_6_rule, p) ++ && ++ (function_def_var = function_def_rule(p)) ++ ) ++ { ++ res = function_def_var; ++ goto done; ++ } ++ p->mark = mark; ++ } ++ { // &'if' if_stmt ++ stmt_ty if_stmt_var; ++ if ( ++ _PyPegen_lookahead_with_int(1, _PyPegen_expect_token, p, 510) ++ && ++ (if_stmt_var = if_stmt_rule(p)) ++ ) ++ { ++ res = if_stmt_var; ++ goto done; ++ } ++ p->mark = mark; ++ } ++ { // &('class' | '@') class_def ++ stmt_ty class_def_var; ++ if ( ++ _PyPegen_lookahead(1, _tmp_7_rule, p) ++ && ++ (class_def_var = class_def_rule(p)) ++ ) ++ { ++ res = class_def_var; ++ goto done; ++ } ++ p->mark = mark; ++ } ++ { // &('with' | ASYNC) with_stmt ++ stmt_ty with_stmt_var; ++ if ( ++ _PyPegen_lookahead(1, _tmp_8_rule, p) ++ && ++ (with_stmt_var = with_stmt_rule(p)) ++ ) ++ { ++ res = with_stmt_var; ++ goto done; ++ } ++ p->mark = mark; ++ } ++ { // &('for' | ASYNC) for_stmt ++ stmt_ty for_stmt_var; ++ if ( ++ _PyPegen_lookahead(1, _tmp_9_rule, p) ++ && ++ (for_stmt_var = for_stmt_rule(p)) ++ ) ++ { ++ res = for_stmt_var; ++ goto done; ++ } ++ p->mark = mark; ++ } ++ { // &'try' try_stmt ++ stmt_ty try_stmt_var; ++ if ( ++ _PyPegen_lookahead_with_int(1, _PyPegen_expect_token, p, 511) ++ && ++ (try_stmt_var = try_stmt_rule(p)) ++ ) ++ { ++ res = try_stmt_var; ++ goto done; ++ } ++ p->mark = mark; ++ } ++ { // &'while' while_stmt ++ stmt_ty while_stmt_var; ++ if ( ++ _PyPegen_lookahead_with_int(1, _PyPegen_expect_token, p, 512) ++ && ++ (while_stmt_var = while_stmt_rule(p)) ++ ) ++ { ++ res = while_stmt_var; ++ goto done; ++ } ++ p->mark = mark; ++ } ++ res = NULL; ++ done: ++ return res; ++} ++ ++// assignment: ++// | NAME ':' expression ['=' annotated_rhs] ++// | ('(' inside_paren_ann_assign_target ')' | ann_assign_subscript_attribute_target) ':' expression ['=' annotated_rhs] ++// | ((star_targets '='))+ (yield_expr | star_expressions) ++// | target augassign (yield_expr | star_expressions) ++// | invalid_assignment ++static void * ++assignment_rule(Parser *p) ++{ ++ if (p->error_indicator) { ++ return NULL; ++ } ++ void * res = NULL; ++ int mark = p->mark; ++ if (p->mark == p->fill && _PyPegen_fill_token(p) < 0) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ int start_lineno = p->tokens[mark]->lineno; ++ UNUSED(start_lineno); // Only used by EXTRA macro ++ int start_col_offset = p->tokens[mark]->col_offset; ++ UNUSED(start_col_offset); // Only used by EXTRA macro ++ { // NAME ':' expression ['=' annotated_rhs] ++ expr_ty a; ++ expr_ty b; ++ void *c; ++ void *literal; ++ if ( ++ (a = _PyPegen_name_token(p)) ++ && ++ (literal = _PyPegen_expect_token(p, 11)) ++ && ++ (b = expression_rule(p)) ++ && ++ (c = _tmp_10_rule(p), 1) ++ ) ++ { ++ Token *token = _PyPegen_get_last_nonnwhitespace_token(p); ++ if (token == NULL) { ++ return NULL; ++ } ++ int end_lineno = token->end_lineno; ++ UNUSED(end_lineno); // Only used by EXTRA macro ++ int end_col_offset = token->end_col_offset; ++ UNUSED(end_col_offset); // Only used by EXTRA macro ++ res = _Py_AnnAssign ( CHECK ( _PyPegen_set_expr_context ( p , a , Store ) ) , b , c , 1 , EXTRA ); ++ if (res == NULL && PyErr_Occurred()) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ goto done; ++ } ++ p->mark = mark; ++ } ++ { // ('(' inside_paren_ann_assign_target ')' | ann_assign_subscript_attribute_target) ':' expression ['=' annotated_rhs] ++ void *a; ++ expr_ty b; ++ void *c; ++ void *literal; ++ if ( ++ (a = _tmp_11_rule(p)) ++ && ++ (literal = _PyPegen_expect_token(p, 11)) ++ && ++ (b = expression_rule(p)) ++ && ++ (c = _tmp_12_rule(p), 1) ++ ) ++ { ++ Token *token = _PyPegen_get_last_nonnwhitespace_token(p); ++ if (token == NULL) { ++ return NULL; ++ } ++ int end_lineno = token->end_lineno; ++ UNUSED(end_lineno); // Only used by EXTRA macro ++ int end_col_offset = token->end_col_offset; ++ UNUSED(end_col_offset); // Only used by EXTRA macro ++ res = _Py_AnnAssign ( a , b , c , 0 , EXTRA ); ++ if (res == NULL && PyErr_Occurred()) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ goto done; ++ } ++ p->mark = mark; ++ } ++ { // ((star_targets '='))+ (yield_expr | star_expressions) ++ asdl_seq * a; ++ void *b; ++ if ( ++ (a = _loop1_13_rule(p)) ++ && ++ (b = _tmp_14_rule(p)) ++ ) ++ { ++ Token *token = _PyPegen_get_last_nonnwhitespace_token(p); ++ if (token == NULL) { ++ return NULL; ++ } ++ int end_lineno = token->end_lineno; ++ UNUSED(end_lineno); // Only used by EXTRA macro ++ int end_col_offset = token->end_col_offset; ++ UNUSED(end_col_offset); // Only used by EXTRA macro ++ res = _Py_Assign ( a , b , NULL , EXTRA ); ++ if (res == NULL && PyErr_Occurred()) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ goto done; ++ } ++ p->mark = mark; ++ } ++ { // target augassign (yield_expr | star_expressions) ++ expr_ty a; ++ AugOperator* b; ++ void *c; ++ if ( ++ (a = target_rule(p)) ++ && ++ (b = augassign_rule(p)) ++ && ++ (c = _tmp_15_rule(p)) ++ ) ++ { ++ Token *token = _PyPegen_get_last_nonnwhitespace_token(p); ++ if (token == NULL) { ++ return NULL; ++ } ++ int end_lineno = token->end_lineno; ++ UNUSED(end_lineno); // Only used by EXTRA macro ++ int end_col_offset = token->end_col_offset; ++ UNUSED(end_col_offset); // Only used by EXTRA macro ++ res = _Py_AugAssign ( a , b -> kind , c , EXTRA ); ++ if (res == NULL && PyErr_Occurred()) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ goto done; ++ } ++ p->mark = mark; ++ } ++ { // invalid_assignment ++ void *invalid_assignment_var; ++ if ( ++ (invalid_assignment_var = invalid_assignment_rule(p)) ++ ) ++ { ++ res = invalid_assignment_var; ++ goto done; ++ } ++ p->mark = mark; ++ } ++ res = NULL; ++ done: ++ return res; ++} ++ ++// augassign: ++// | '+=' ++// | '-=' ++// | '*=' ++// | '@=' ++// | '/=' ++// | '%=' ++// | '&=' ++// | '|=' ++// | '^=' ++// | '<<=' ++// | '>>=' ++// | '**=' ++// | '//=' ++static AugOperator* ++augassign_rule(Parser *p) ++{ ++ if (p->error_indicator) { ++ return NULL; ++ } ++ AugOperator* res = NULL; ++ int mark = p->mark; ++ { // '+=' ++ void *literal; ++ if ( ++ (literal = _PyPegen_expect_token(p, 36)) ++ ) ++ { ++ res = _PyPegen_augoperator ( p , Add ); ++ if (res == NULL && PyErr_Occurred()) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ goto done; ++ } ++ p->mark = mark; ++ } ++ { // '-=' ++ void *literal; ++ if ( ++ (literal = _PyPegen_expect_token(p, 37)) ++ ) ++ { ++ res = _PyPegen_augoperator ( p , Sub ); ++ if (res == NULL && PyErr_Occurred()) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ goto done; ++ } ++ p->mark = mark; ++ } ++ { // '*=' ++ void *literal; ++ if ( ++ (literal = _PyPegen_expect_token(p, 38)) ++ ) ++ { ++ res = _PyPegen_augoperator ( p , Mult ); ++ if (res == NULL && PyErr_Occurred()) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ goto done; ++ } ++ p->mark = mark; ++ } ++ { // '@=' ++ void *literal; ++ if ( ++ (literal = _PyPegen_expect_token(p, 50)) ++ ) ++ { ++ res = _PyPegen_augoperator ( p , MatMult ); ++ if (res == NULL && PyErr_Occurred()) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ goto done; ++ } ++ p->mark = mark; ++ } ++ { // '/=' ++ void *literal; ++ if ( ++ (literal = _PyPegen_expect_token(p, 39)) ++ ) ++ { ++ res = _PyPegen_augoperator ( p , Div ); ++ if (res == NULL && PyErr_Occurred()) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ goto done; ++ } ++ p->mark = mark; ++ } ++ { // '%=' ++ void *literal; ++ if ( ++ (literal = _PyPegen_expect_token(p, 40)) ++ ) ++ { ++ res = _PyPegen_augoperator ( p , Mod ); ++ if (res == NULL && PyErr_Occurred()) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ goto done; ++ } ++ p->mark = mark; ++ } ++ { // '&=' ++ void *literal; ++ if ( ++ (literal = _PyPegen_expect_token(p, 41)) ++ ) ++ { ++ res = _PyPegen_augoperator ( p , BitAnd ); ++ if (res == NULL && PyErr_Occurred()) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ goto done; ++ } ++ p->mark = mark; ++ } ++ { // '|=' ++ void *literal; ++ if ( ++ (literal = _PyPegen_expect_token(p, 42)) ++ ) ++ { ++ res = _PyPegen_augoperator ( p , BitOr ); ++ if (res == NULL && PyErr_Occurred()) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ goto done; ++ } ++ p->mark = mark; ++ } ++ { // '^=' ++ void *literal; ++ if ( ++ (literal = _PyPegen_expect_token(p, 43)) ++ ) ++ { ++ res = _PyPegen_augoperator ( p , BitXor ); ++ if (res == NULL && PyErr_Occurred()) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ goto done; ++ } ++ p->mark = mark; ++ } ++ { // '<<=' ++ void *literal; ++ if ( ++ (literal = _PyPegen_expect_token(p, 44)) ++ ) ++ { ++ res = _PyPegen_augoperator ( p , LShift ); ++ if (res == NULL && PyErr_Occurred()) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ goto done; ++ } ++ p->mark = mark; ++ } ++ { // '>>=' ++ void *literal; ++ if ( ++ (literal = _PyPegen_expect_token(p, 45)) ++ ) ++ { ++ res = _PyPegen_augoperator ( p , RShift ); ++ if (res == NULL && PyErr_Occurred()) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ goto done; ++ } ++ p->mark = mark; ++ } ++ { // '**=' ++ void *literal; ++ if ( ++ (literal = _PyPegen_expect_token(p, 46)) ++ ) ++ { ++ res = _PyPegen_augoperator ( p , Pow ); ++ if (res == NULL && PyErr_Occurred()) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ goto done; ++ } ++ p->mark = mark; ++ } ++ { // '//=' ++ void *literal; ++ if ( ++ (literal = _PyPegen_expect_token(p, 48)) ++ ) ++ { ++ res = _PyPegen_augoperator ( p , FloorDiv ); ++ if (res == NULL && PyErr_Occurred()) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ goto done; ++ } ++ p->mark = mark; ++ } ++ res = NULL; ++ done: ++ return res; ++} ++ ++// global_stmt: 'global' ','.NAME+ ++static stmt_ty ++global_stmt_rule(Parser *p) ++{ ++ if (p->error_indicator) { ++ return NULL; ++ } ++ stmt_ty res = NULL; ++ int mark = p->mark; ++ if (p->mark == p->fill && _PyPegen_fill_token(p) < 0) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ int start_lineno = p->tokens[mark]->lineno; ++ UNUSED(start_lineno); // Only used by EXTRA macro ++ int start_col_offset = p->tokens[mark]->col_offset; ++ UNUSED(start_col_offset); // Only used by EXTRA macro ++ { // 'global' ','.NAME+ ++ asdl_seq * a; ++ void *keyword; ++ if ( ++ (keyword = _PyPegen_expect_token(p, 508)) ++ && ++ (a = _gather_16_rule(p)) ++ ) ++ { ++ Token *token = _PyPegen_get_last_nonnwhitespace_token(p); ++ if (token == NULL) { ++ return NULL; ++ } ++ int end_lineno = token->end_lineno; ++ UNUSED(end_lineno); // Only used by EXTRA macro ++ int end_col_offset = token->end_col_offset; ++ UNUSED(end_col_offset); // Only used by EXTRA macro ++ res = _Py_Global ( CHECK ( _PyPegen_map_names_to_ids ( p , a ) ) , EXTRA ); ++ if (res == NULL && PyErr_Occurred()) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ goto done; ++ } ++ p->mark = mark; ++ } ++ res = NULL; ++ done: ++ return res; ++} ++ ++// nonlocal_stmt: 'nonlocal' ','.NAME+ ++static stmt_ty ++nonlocal_stmt_rule(Parser *p) ++{ ++ if (p->error_indicator) { ++ return NULL; ++ } ++ stmt_ty res = NULL; ++ int mark = p->mark; ++ if (p->mark == p->fill && _PyPegen_fill_token(p) < 0) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ int start_lineno = p->tokens[mark]->lineno; ++ UNUSED(start_lineno); // Only used by EXTRA macro ++ int start_col_offset = p->tokens[mark]->col_offset; ++ UNUSED(start_col_offset); // Only used by EXTRA macro ++ { // 'nonlocal' ','.NAME+ ++ asdl_seq * a; ++ void *keyword; ++ if ( ++ (keyword = _PyPegen_expect_token(p, 509)) ++ && ++ (a = _gather_18_rule(p)) ++ ) ++ { ++ Token *token = _PyPegen_get_last_nonnwhitespace_token(p); ++ if (token == NULL) { ++ return NULL; ++ } ++ int end_lineno = token->end_lineno; ++ UNUSED(end_lineno); // Only used by EXTRA macro ++ int end_col_offset = token->end_col_offset; ++ UNUSED(end_col_offset); // Only used by EXTRA macro ++ res = _Py_Nonlocal ( CHECK ( _PyPegen_map_names_to_ids ( p , a ) ) , EXTRA ); ++ if (res == NULL && PyErr_Occurred()) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ goto done; ++ } ++ p->mark = mark; ++ } ++ res = NULL; ++ done: ++ return res; ++} ++ ++// yield_stmt: yield_expr ++static stmt_ty ++yield_stmt_rule(Parser *p) ++{ ++ if (p->error_indicator) { ++ return NULL; ++ } ++ stmt_ty res = NULL; ++ int mark = p->mark; ++ if (p->mark == p->fill && _PyPegen_fill_token(p) < 0) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ int start_lineno = p->tokens[mark]->lineno; ++ UNUSED(start_lineno); // Only used by EXTRA macro ++ int start_col_offset = p->tokens[mark]->col_offset; ++ UNUSED(start_col_offset); // Only used by EXTRA macro ++ { // yield_expr ++ expr_ty y; ++ if ( ++ (y = yield_expr_rule(p)) ++ ) ++ { ++ Token *token = _PyPegen_get_last_nonnwhitespace_token(p); ++ if (token == NULL) { ++ return NULL; ++ } ++ int end_lineno = token->end_lineno; ++ UNUSED(end_lineno); // Only used by EXTRA macro ++ int end_col_offset = token->end_col_offset; ++ UNUSED(end_col_offset); // Only used by EXTRA macro ++ res = _Py_Expr ( y , EXTRA ); ++ if (res == NULL && PyErr_Occurred()) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ goto done; ++ } ++ p->mark = mark; ++ } ++ res = NULL; ++ done: ++ return res; ++} ++ ++// assert_stmt: 'assert' expression [',' expression] ++static stmt_ty ++assert_stmt_rule(Parser *p) ++{ ++ if (p->error_indicator) { ++ return NULL; ++ } ++ stmt_ty res = NULL; ++ int mark = p->mark; ++ if (p->mark == p->fill && _PyPegen_fill_token(p) < 0) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ int start_lineno = p->tokens[mark]->lineno; ++ UNUSED(start_lineno); // Only used by EXTRA macro ++ int start_col_offset = p->tokens[mark]->col_offset; ++ UNUSED(start_col_offset); // Only used by EXTRA macro ++ { // 'assert' expression [',' expression] ++ expr_ty a; ++ void *b; ++ void *keyword; ++ if ( ++ (keyword = _PyPegen_expect_token(p, 505)) ++ && ++ (a = expression_rule(p)) ++ && ++ (b = _tmp_20_rule(p), 1) ++ ) ++ { ++ Token *token = _PyPegen_get_last_nonnwhitespace_token(p); ++ if (token == NULL) { ++ return NULL; ++ } ++ int end_lineno = token->end_lineno; ++ UNUSED(end_lineno); // Only used by EXTRA macro ++ int end_col_offset = token->end_col_offset; ++ UNUSED(end_col_offset); // Only used by EXTRA macro ++ res = _Py_Assert ( a , b , EXTRA ); ++ if (res == NULL && PyErr_Occurred()) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ goto done; ++ } ++ p->mark = mark; ++ } ++ res = NULL; ++ done: ++ return res; ++} ++ ++// del_stmt: 'del' del_targets ++static stmt_ty ++del_stmt_rule(Parser *p) ++{ ++ if (p->error_indicator) { ++ return NULL; ++ } ++ stmt_ty res = NULL; ++ int mark = p->mark; ++ if (p->mark == p->fill && _PyPegen_fill_token(p) < 0) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ int start_lineno = p->tokens[mark]->lineno; ++ UNUSED(start_lineno); // Only used by EXTRA macro ++ int start_col_offset = p->tokens[mark]->col_offset; ++ UNUSED(start_col_offset); // Only used by EXTRA macro ++ { // 'del' del_targets ++ asdl_seq* a; ++ void *keyword; ++ if ( ++ (keyword = _PyPegen_expect_token(p, 503)) ++ && ++ (a = del_targets_rule(p)) ++ ) ++ { ++ Token *token = _PyPegen_get_last_nonnwhitespace_token(p); ++ if (token == NULL) { ++ return NULL; ++ } ++ int end_lineno = token->end_lineno; ++ UNUSED(end_lineno); // Only used by EXTRA macro ++ int end_col_offset = token->end_col_offset; ++ UNUSED(end_col_offset); // Only used by EXTRA macro ++ res = _Py_Delete ( a , EXTRA ); ++ if (res == NULL && PyErr_Occurred()) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ goto done; ++ } ++ p->mark = mark; ++ } ++ res = NULL; ++ done: ++ return res; ++} ++ ++// import_stmt: import_name | import_from ++static stmt_ty ++import_stmt_rule(Parser *p) ++{ ++ if (p->error_indicator) { ++ return NULL; ++ } ++ stmt_ty res = NULL; ++ int mark = p->mark; ++ { // import_name ++ stmt_ty import_name_var; ++ if ( ++ (import_name_var = import_name_rule(p)) ++ ) ++ { ++ res = import_name_var; ++ goto done; ++ } ++ p->mark = mark; ++ } ++ { // import_from ++ stmt_ty import_from_var; ++ if ( ++ (import_from_var = import_from_rule(p)) ++ ) ++ { ++ res = import_from_var; ++ goto done; ++ } ++ p->mark = mark; ++ } ++ res = NULL; ++ done: ++ return res; ++} ++ ++// import_name: 'import' dotted_as_names ++static stmt_ty ++import_name_rule(Parser *p) ++{ ++ if (p->error_indicator) { ++ return NULL; ++ } ++ stmt_ty res = NULL; ++ int mark = p->mark; ++ if (p->mark == p->fill && _PyPegen_fill_token(p) < 0) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ int start_lineno = p->tokens[mark]->lineno; ++ UNUSED(start_lineno); // Only used by EXTRA macro ++ int start_col_offset = p->tokens[mark]->col_offset; ++ UNUSED(start_col_offset); // Only used by EXTRA macro ++ { // 'import' dotted_as_names ++ asdl_seq* a; ++ void *keyword; ++ if ( ++ (keyword = _PyPegen_expect_token(p, 513)) ++ && ++ (a = dotted_as_names_rule(p)) ++ ) ++ { ++ Token *token = _PyPegen_get_last_nonnwhitespace_token(p); ++ if (token == NULL) { ++ return NULL; ++ } ++ int end_lineno = token->end_lineno; ++ UNUSED(end_lineno); // Only used by EXTRA macro ++ int end_col_offset = token->end_col_offset; ++ UNUSED(end_col_offset); // Only used by EXTRA macro ++ res = _Py_Import ( a , EXTRA ); ++ if (res == NULL && PyErr_Occurred()) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ goto done; ++ } ++ p->mark = mark; ++ } ++ res = NULL; ++ done: ++ return res; ++} ++ ++// import_from: ++// | 'from' (('.' | '...'))* dotted_name 'import' import_from_targets ++// | 'from' (('.' | '...'))+ 'import' import_from_targets ++static stmt_ty ++import_from_rule(Parser *p) ++{ ++ if (p->error_indicator) { ++ return NULL; ++ } ++ stmt_ty res = NULL; ++ int mark = p->mark; ++ if (p->mark == p->fill && _PyPegen_fill_token(p) < 0) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ int start_lineno = p->tokens[mark]->lineno; ++ UNUSED(start_lineno); // Only used by EXTRA macro ++ int start_col_offset = p->tokens[mark]->col_offset; ++ UNUSED(start_col_offset); // Only used by EXTRA macro ++ { // 'from' (('.' | '...'))* dotted_name 'import' import_from_targets ++ asdl_seq * a; ++ expr_ty b; ++ asdl_seq* c; ++ void *keyword; ++ void *keyword_1; ++ if ( ++ (keyword = _PyPegen_expect_token(p, 514)) ++ && ++ (a = _loop0_21_rule(p)) ++ && ++ (b = dotted_name_rule(p)) ++ && ++ (keyword_1 = _PyPegen_expect_token(p, 513)) ++ && ++ (c = import_from_targets_rule(p)) ++ ) ++ { ++ Token *token = _PyPegen_get_last_nonnwhitespace_token(p); ++ if (token == NULL) { ++ return NULL; ++ } ++ int end_lineno = token->end_lineno; ++ UNUSED(end_lineno); // Only used by EXTRA macro ++ int end_col_offset = token->end_col_offset; ++ UNUSED(end_col_offset); // Only used by EXTRA macro ++ res = _Py_ImportFrom ( b -> v . Name . id , c , _PyPegen_seq_count_dots ( a ) , EXTRA ); ++ if (res == NULL && PyErr_Occurred()) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ goto done; ++ } ++ p->mark = mark; ++ } ++ { // 'from' (('.' | '...'))+ 'import' import_from_targets ++ asdl_seq * a; ++ asdl_seq* b; ++ void *keyword; ++ void *keyword_1; ++ if ( ++ (keyword = _PyPegen_expect_token(p, 514)) ++ && ++ (a = _loop1_22_rule(p)) ++ && ++ (keyword_1 = _PyPegen_expect_token(p, 513)) ++ && ++ (b = import_from_targets_rule(p)) ++ ) ++ { ++ Token *token = _PyPegen_get_last_nonnwhitespace_token(p); ++ if (token == NULL) { ++ return NULL; ++ } ++ int end_lineno = token->end_lineno; ++ UNUSED(end_lineno); // Only used by EXTRA macro ++ int end_col_offset = token->end_col_offset; ++ UNUSED(end_col_offset); // Only used by EXTRA macro ++ res = _Py_ImportFrom ( NULL , b , _PyPegen_seq_count_dots ( a ) , EXTRA ); ++ if (res == NULL && PyErr_Occurred()) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ goto done; ++ } ++ p->mark = mark; ++ } ++ res = NULL; ++ done: ++ return res; ++} ++ ++// import_from_targets: '(' import_from_as_names ','? ')' | import_from_as_names | '*' ++static asdl_seq* ++import_from_targets_rule(Parser *p) ++{ ++ if (p->error_indicator) { ++ return NULL; ++ } ++ asdl_seq* res = NULL; ++ int mark = p->mark; ++ { // '(' import_from_as_names ','? ')' ++ asdl_seq* a; ++ void *literal; ++ void *literal_1; ++ void *opt_var; ++ UNUSED(opt_var); // Silence compiler warnings ++ if ( ++ (literal = _PyPegen_expect_token(p, 7)) ++ && ++ (a = import_from_as_names_rule(p)) ++ && ++ (opt_var = _PyPegen_expect_token(p, 12), 1) ++ && ++ (literal_1 = _PyPegen_expect_token(p, 8)) ++ ) ++ { ++ res = a; ++ if (res == NULL && PyErr_Occurred()) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ goto done; ++ } ++ p->mark = mark; ++ } ++ { // import_from_as_names ++ asdl_seq* import_from_as_names_var; ++ if ( ++ (import_from_as_names_var = import_from_as_names_rule(p)) ++ ) ++ { ++ res = import_from_as_names_var; ++ goto done; ++ } ++ p->mark = mark; ++ } ++ { // '*' ++ void *literal; ++ if ( ++ (literal = _PyPegen_expect_token(p, 16)) ++ ) ++ { ++ res = _PyPegen_singleton_seq ( p , CHECK ( _PyPegen_alias_for_star ( p ) ) ); ++ if (res == NULL && PyErr_Occurred()) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ goto done; ++ } ++ p->mark = mark; ++ } ++ res = NULL; ++ done: ++ return res; ++} ++ ++// import_from_as_names: ','.import_from_as_name+ ++static asdl_seq* ++import_from_as_names_rule(Parser *p) ++{ ++ if (p->error_indicator) { ++ return NULL; ++ } ++ asdl_seq* res = NULL; ++ int mark = p->mark; ++ { // ','.import_from_as_name+ ++ asdl_seq * a; ++ if ( ++ (a = _gather_23_rule(p)) ++ ) ++ { ++ res = a; ++ if (res == NULL && PyErr_Occurred()) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ goto done; ++ } ++ p->mark = mark; ++ } ++ res = NULL; ++ done: ++ return res; ++} ++ ++// import_from_as_name: NAME ['as' NAME] ++static alias_ty ++import_from_as_name_rule(Parser *p) ++{ ++ if (p->error_indicator) { ++ return NULL; ++ } ++ alias_ty res = NULL; ++ int mark = p->mark; ++ { // NAME ['as' NAME] ++ expr_ty a; ++ void *b; ++ if ( ++ (a = _PyPegen_name_token(p)) ++ && ++ (b = _tmp_25_rule(p), 1) ++ ) ++ { ++ res = _Py_alias ( a -> v . Name . id , ( b ) ? ( ( expr_ty ) b ) -> v . Name . id : NULL , p -> arena ); ++ if (res == NULL && PyErr_Occurred()) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ goto done; ++ } ++ p->mark = mark; ++ } ++ res = NULL; ++ done: ++ return res; ++} ++ ++// dotted_as_names: ','.dotted_as_name+ ++static asdl_seq* ++dotted_as_names_rule(Parser *p) ++{ ++ if (p->error_indicator) { ++ return NULL; ++ } ++ asdl_seq* res = NULL; ++ int mark = p->mark; ++ { // ','.dotted_as_name+ ++ asdl_seq * a; ++ if ( ++ (a = _gather_26_rule(p)) ++ ) ++ { ++ res = a; ++ if (res == NULL && PyErr_Occurred()) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ goto done; ++ } ++ p->mark = mark; ++ } ++ res = NULL; ++ done: ++ return res; ++} ++ ++// dotted_as_name: dotted_name ['as' NAME] ++static alias_ty ++dotted_as_name_rule(Parser *p) ++{ ++ if (p->error_indicator) { ++ return NULL; ++ } ++ alias_ty res = NULL; ++ int mark = p->mark; ++ { // dotted_name ['as' NAME] ++ expr_ty a; ++ void *b; ++ if ( ++ (a = dotted_name_rule(p)) ++ && ++ (b = _tmp_28_rule(p), 1) ++ ) ++ { ++ res = _Py_alias ( a -> v . Name . id , ( b ) ? ( ( expr_ty ) b ) -> v . Name . id : NULL , p -> arena ); ++ if (res == NULL && PyErr_Occurred()) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ goto done; ++ } ++ p->mark = mark; ++ } ++ res = NULL; ++ done: ++ return res; ++} ++ ++// Left-recursive ++// dotted_name: dotted_name '.' NAME | NAME ++static expr_ty dotted_name_raw(Parser *); ++static expr_ty ++dotted_name_rule(Parser *p) ++{ ++ expr_ty res = NULL; ++ if (_PyPegen_is_memoized(p, dotted_name_type, &res)) ++ return res; ++ int mark = p->mark; ++ int resmark = p->mark; ++ while (1) { ++ int tmpvar_0 = _PyPegen_update_memo(p, mark, dotted_name_type, res); ++ if (tmpvar_0) { ++ return res; ++ } ++ p->mark = mark; ++ void *raw = dotted_name_raw(p); ++ if (raw == NULL || p->mark <= resmark) ++ break; ++ resmark = p->mark; ++ res = raw; ++ } ++ p->mark = resmark; ++ return res; ++} ++static expr_ty ++dotted_name_raw(Parser *p) ++{ ++ if (p->error_indicator) { ++ return NULL; ++ } ++ expr_ty res = NULL; ++ int mark = p->mark; ++ { // dotted_name '.' NAME ++ expr_ty a; ++ expr_ty b; ++ void *literal; ++ if ( ++ (a = dotted_name_rule(p)) ++ && ++ (literal = _PyPegen_expect_token(p, 23)) ++ && ++ (b = _PyPegen_name_token(p)) ++ ) ++ { ++ res = _PyPegen_join_names_with_dot ( p , a , b ); ++ if (res == NULL && PyErr_Occurred()) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ goto done; ++ } ++ p->mark = mark; ++ } ++ { // NAME ++ expr_ty name_var; ++ if ( ++ (name_var = _PyPegen_name_token(p)) ++ ) ++ { ++ res = name_var; ++ goto done; ++ } ++ p->mark = mark; ++ } ++ res = NULL; ++ done: ++ return res; ++} ++ ++// if_stmt: ++// | 'if' named_expression ':' block elif_stmt ++// | 'if' named_expression ':' block else_block? ++static stmt_ty ++if_stmt_rule(Parser *p) ++{ ++ if (p->error_indicator) { ++ return NULL; ++ } ++ stmt_ty res = NULL; ++ int mark = p->mark; ++ if (p->mark == p->fill && _PyPegen_fill_token(p) < 0) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ int start_lineno = p->tokens[mark]->lineno; ++ UNUSED(start_lineno); // Only used by EXTRA macro ++ int start_col_offset = p->tokens[mark]->col_offset; ++ UNUSED(start_col_offset); // Only used by EXTRA macro ++ { // 'if' named_expression ':' block elif_stmt ++ expr_ty a; ++ asdl_seq* b; ++ stmt_ty c; ++ void *keyword; ++ void *literal; ++ if ( ++ (keyword = _PyPegen_expect_token(p, 510)) ++ && ++ (a = named_expression_rule(p)) ++ && ++ (literal = _PyPegen_expect_token(p, 11)) ++ && ++ (b = block_rule(p)) ++ && ++ (c = elif_stmt_rule(p)) ++ ) ++ { ++ Token *token = _PyPegen_get_last_nonnwhitespace_token(p); ++ if (token == NULL) { ++ return NULL; ++ } ++ int end_lineno = token->end_lineno; ++ UNUSED(end_lineno); // Only used by EXTRA macro ++ int end_col_offset = token->end_col_offset; ++ UNUSED(end_col_offset); // Only used by EXTRA macro ++ res = _Py_If ( a , b , CHECK ( _PyPegen_singleton_seq ( p , c ) ) , EXTRA ); ++ if (res == NULL && PyErr_Occurred()) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ goto done; ++ } ++ p->mark = mark; ++ } ++ { // 'if' named_expression ':' block else_block? ++ expr_ty a; ++ asdl_seq* b; ++ void *c; ++ void *keyword; ++ void *literal; ++ if ( ++ (keyword = _PyPegen_expect_token(p, 510)) ++ && ++ (a = named_expression_rule(p)) ++ && ++ (literal = _PyPegen_expect_token(p, 11)) ++ && ++ (b = block_rule(p)) ++ && ++ (c = else_block_rule(p), 1) ++ ) ++ { ++ Token *token = _PyPegen_get_last_nonnwhitespace_token(p); ++ if (token == NULL) { ++ return NULL; ++ } ++ int end_lineno = token->end_lineno; ++ UNUSED(end_lineno); // Only used by EXTRA macro ++ int end_col_offset = token->end_col_offset; ++ UNUSED(end_col_offset); // Only used by EXTRA macro ++ res = _Py_If ( a , b , c , EXTRA ); ++ if (res == NULL && PyErr_Occurred()) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ goto done; ++ } ++ p->mark = mark; ++ } ++ res = NULL; ++ done: ++ return res; ++} ++ ++// elif_stmt: ++// | 'elif' named_expression ':' block elif_stmt ++// | 'elif' named_expression ':' block else_block? ++static stmt_ty ++elif_stmt_rule(Parser *p) ++{ ++ if (p->error_indicator) { ++ return NULL; ++ } ++ stmt_ty res = NULL; ++ int mark = p->mark; ++ if (p->mark == p->fill && _PyPegen_fill_token(p) < 0) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ int start_lineno = p->tokens[mark]->lineno; ++ UNUSED(start_lineno); // Only used by EXTRA macro ++ int start_col_offset = p->tokens[mark]->col_offset; ++ UNUSED(start_col_offset); // Only used by EXTRA macro ++ { // 'elif' named_expression ':' block elif_stmt ++ expr_ty a; ++ asdl_seq* b; ++ stmt_ty c; ++ void *keyword; ++ void *literal; ++ if ( ++ (keyword = _PyPegen_expect_token(p, 515)) ++ && ++ (a = named_expression_rule(p)) ++ && ++ (literal = _PyPegen_expect_token(p, 11)) ++ && ++ (b = block_rule(p)) ++ && ++ (c = elif_stmt_rule(p)) ++ ) ++ { ++ Token *token = _PyPegen_get_last_nonnwhitespace_token(p); ++ if (token == NULL) { ++ return NULL; ++ } ++ int end_lineno = token->end_lineno; ++ UNUSED(end_lineno); // Only used by EXTRA macro ++ int end_col_offset = token->end_col_offset; ++ UNUSED(end_col_offset); // Only used by EXTRA macro ++ res = _Py_If ( a , b , CHECK ( _PyPegen_singleton_seq ( p , c ) ) , EXTRA ); ++ if (res == NULL && PyErr_Occurred()) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ goto done; ++ } ++ p->mark = mark; ++ } ++ { // 'elif' named_expression ':' block else_block? ++ expr_ty a; ++ asdl_seq* b; ++ void *c; ++ void *keyword; ++ void *literal; ++ if ( ++ (keyword = _PyPegen_expect_token(p, 515)) ++ && ++ (a = named_expression_rule(p)) ++ && ++ (literal = _PyPegen_expect_token(p, 11)) ++ && ++ (b = block_rule(p)) ++ && ++ (c = else_block_rule(p), 1) ++ ) ++ { ++ Token *token = _PyPegen_get_last_nonnwhitespace_token(p); ++ if (token == NULL) { ++ return NULL; ++ } ++ int end_lineno = token->end_lineno; ++ UNUSED(end_lineno); // Only used by EXTRA macro ++ int end_col_offset = token->end_col_offset; ++ UNUSED(end_col_offset); // Only used by EXTRA macro ++ res = _Py_If ( a , b , c , EXTRA ); ++ if (res == NULL && PyErr_Occurred()) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ goto done; ++ } ++ p->mark = mark; ++ } ++ res = NULL; ++ done: ++ return res; ++} ++ ++// else_block: 'else' ':' block ++static asdl_seq* ++else_block_rule(Parser *p) ++{ ++ if (p->error_indicator) { ++ return NULL; ++ } ++ asdl_seq* res = NULL; ++ int mark = p->mark; ++ { // 'else' ':' block ++ asdl_seq* b; ++ void *keyword; ++ void *literal; ++ if ( ++ (keyword = _PyPegen_expect_token(p, 516)) ++ && ++ (literal = _PyPegen_expect_token(p, 11)) ++ && ++ (b = block_rule(p)) ++ ) ++ { ++ res = b; ++ if (res == NULL && PyErr_Occurred()) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ goto done; ++ } ++ p->mark = mark; ++ } ++ res = NULL; ++ done: ++ return res; ++} ++ ++// while_stmt: 'while' named_expression ':' block else_block? ++static stmt_ty ++while_stmt_rule(Parser *p) ++{ ++ if (p->error_indicator) { ++ return NULL; ++ } ++ stmt_ty res = NULL; ++ int mark = p->mark; ++ if (p->mark == p->fill && _PyPegen_fill_token(p) < 0) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ int start_lineno = p->tokens[mark]->lineno; ++ UNUSED(start_lineno); // Only used by EXTRA macro ++ int start_col_offset = p->tokens[mark]->col_offset; ++ UNUSED(start_col_offset); // Only used by EXTRA macro ++ { // 'while' named_expression ':' block else_block? ++ expr_ty a; ++ asdl_seq* b; ++ void *c; ++ void *keyword; ++ void *literal; ++ if ( ++ (keyword = _PyPegen_expect_token(p, 512)) ++ && ++ (a = named_expression_rule(p)) ++ && ++ (literal = _PyPegen_expect_token(p, 11)) ++ && ++ (b = block_rule(p)) ++ && ++ (c = else_block_rule(p), 1) ++ ) ++ { ++ Token *token = _PyPegen_get_last_nonnwhitespace_token(p); ++ if (token == NULL) { ++ return NULL; ++ } ++ int end_lineno = token->end_lineno; ++ UNUSED(end_lineno); // Only used by EXTRA macro ++ int end_col_offset = token->end_col_offset; ++ UNUSED(end_col_offset); // Only used by EXTRA macro ++ res = _Py_While ( a , b , c , EXTRA ); ++ if (res == NULL && PyErr_Occurred()) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ goto done; ++ } ++ p->mark = mark; ++ } ++ res = NULL; ++ done: ++ return res; ++} ++ ++// for_stmt: ASYNC? 'for' star_targets 'in' star_expressions ':' block else_block? ++static stmt_ty ++for_stmt_rule(Parser *p) ++{ ++ if (p->error_indicator) { ++ return NULL; ++ } ++ stmt_ty res = NULL; ++ int mark = p->mark; ++ if (p->mark == p->fill && _PyPegen_fill_token(p) < 0) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ int start_lineno = p->tokens[mark]->lineno; ++ UNUSED(start_lineno); // Only used by EXTRA macro ++ int start_col_offset = p->tokens[mark]->col_offset; ++ UNUSED(start_col_offset); // Only used by EXTRA macro ++ { // ASYNC? 'for' star_targets 'in' star_expressions ':' block else_block? ++ asdl_seq* b; ++ void *el; ++ expr_ty ex; ++ void *is_async; ++ void *keyword; ++ void *keyword_1; ++ void *literal; ++ expr_ty t; ++ if ( ++ (is_async = _PyPegen_async_token(p), 1) ++ && ++ (keyword = _PyPegen_expect_token(p, 517)) ++ && ++ (t = star_targets_rule(p)) ++ && ++ (keyword_1 = _PyPegen_expect_token(p, 518)) ++ && ++ (ex = star_expressions_rule(p)) ++ && ++ (literal = _PyPegen_expect_token(p, 11)) ++ && ++ (b = block_rule(p)) ++ && ++ (el = else_block_rule(p), 1) ++ ) ++ { ++ Token *token = _PyPegen_get_last_nonnwhitespace_token(p); ++ if (token == NULL) { ++ return NULL; ++ } ++ int end_lineno = token->end_lineno; ++ UNUSED(end_lineno); // Only used by EXTRA macro ++ int end_col_offset = token->end_col_offset; ++ UNUSED(end_col_offset); // Only used by EXTRA macro ++ res = ( is_async ? _Py_AsyncFor : _Py_For ) ( t , ex , b , el , NULL , EXTRA ); ++ if (res == NULL && PyErr_Occurred()) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ goto done; ++ } ++ p->mark = mark; ++ } ++ res = NULL; ++ done: ++ return res; ++} ++ ++// with_stmt: ++// | ASYNC? 'with' '(' ','.with_item+ ')' ':' block ++// | ASYNC? 'with' ','.with_item+ ':' block ++static stmt_ty ++with_stmt_rule(Parser *p) ++{ ++ if (p->error_indicator) { ++ return NULL; ++ } ++ stmt_ty res = NULL; ++ int mark = p->mark; ++ if (p->mark == p->fill && _PyPegen_fill_token(p) < 0) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ int start_lineno = p->tokens[mark]->lineno; ++ UNUSED(start_lineno); // Only used by EXTRA macro ++ int start_col_offset = p->tokens[mark]->col_offset; ++ UNUSED(start_col_offset); // Only used by EXTRA macro ++ { // ASYNC? 'with' '(' ','.with_item+ ')' ':' block ++ asdl_seq * a; ++ asdl_seq* b; ++ void *is_async; ++ void *keyword; ++ void *literal; ++ void *literal_1; ++ void *literal_2; ++ if ( ++ (is_async = _PyPegen_async_token(p), 1) ++ && ++ (keyword = _PyPegen_expect_token(p, 519)) ++ && ++ (literal = _PyPegen_expect_token(p, 7)) ++ && ++ (a = _gather_29_rule(p)) ++ && ++ (literal_1 = _PyPegen_expect_token(p, 8)) ++ && ++ (literal_2 = _PyPegen_expect_token(p, 11)) ++ && ++ (b = block_rule(p)) ++ ) ++ { ++ Token *token = _PyPegen_get_last_nonnwhitespace_token(p); ++ if (token == NULL) { ++ return NULL; ++ } ++ int end_lineno = token->end_lineno; ++ UNUSED(end_lineno); // Only used by EXTRA macro ++ int end_col_offset = token->end_col_offset; ++ UNUSED(end_col_offset); // Only used by EXTRA macro ++ res = ( is_async ? _Py_AsyncWith : _Py_With ) ( a , b , NULL , EXTRA ); ++ if (res == NULL && PyErr_Occurred()) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ goto done; ++ } ++ p->mark = mark; ++ } ++ { // ASYNC? 'with' ','.with_item+ ':' block ++ asdl_seq * a; ++ asdl_seq* b; ++ void *is_async; ++ void *keyword; ++ void *literal; ++ if ( ++ (is_async = _PyPegen_async_token(p), 1) ++ && ++ (keyword = _PyPegen_expect_token(p, 519)) ++ && ++ (a = _gather_31_rule(p)) ++ && ++ (literal = _PyPegen_expect_token(p, 11)) ++ && ++ (b = block_rule(p)) ++ ) ++ { ++ Token *token = _PyPegen_get_last_nonnwhitespace_token(p); ++ if (token == NULL) { ++ return NULL; ++ } ++ int end_lineno = token->end_lineno; ++ UNUSED(end_lineno); // Only used by EXTRA macro ++ int end_col_offset = token->end_col_offset; ++ UNUSED(end_col_offset); // Only used by EXTRA macro ++ res = ( is_async ? _Py_AsyncWith : _Py_With ) ( a , b , NULL , EXTRA ); ++ if (res == NULL && PyErr_Occurred()) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ goto done; ++ } ++ p->mark = mark; ++ } ++ res = NULL; ++ done: ++ return res; ++} ++ ++// with_item: expression ['as' target] ++static withitem_ty ++with_item_rule(Parser *p) ++{ ++ if (p->error_indicator) { ++ return NULL; ++ } ++ withitem_ty res = NULL; ++ int mark = p->mark; ++ { // expression ['as' target] ++ expr_ty e; ++ void *o; ++ if ( ++ (e = expression_rule(p)) ++ && ++ (o = _tmp_33_rule(p), 1) ++ ) ++ { ++ res = _Py_withitem ( e , o , p -> arena ); ++ if (res == NULL && PyErr_Occurred()) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ goto done; ++ } ++ p->mark = mark; ++ } ++ res = NULL; ++ done: ++ return res; ++} ++ ++// try_stmt: ++// | 'try' ':' block finally_block ++// | 'try' ':' block except_block+ else_block? finally_block? ++static stmt_ty ++try_stmt_rule(Parser *p) ++{ ++ if (p->error_indicator) { ++ return NULL; ++ } ++ stmt_ty res = NULL; ++ int mark = p->mark; ++ if (p->mark == p->fill && _PyPegen_fill_token(p) < 0) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ int start_lineno = p->tokens[mark]->lineno; ++ UNUSED(start_lineno); // Only used by EXTRA macro ++ int start_col_offset = p->tokens[mark]->col_offset; ++ UNUSED(start_col_offset); // Only used by EXTRA macro ++ { // 'try' ':' block finally_block ++ asdl_seq* b; ++ asdl_seq* f; ++ void *keyword; ++ void *literal; ++ if ( ++ (keyword = _PyPegen_expect_token(p, 511)) ++ && ++ (literal = _PyPegen_expect_token(p, 11)) ++ && ++ (b = block_rule(p)) ++ && ++ (f = finally_block_rule(p)) ++ ) ++ { ++ Token *token = _PyPegen_get_last_nonnwhitespace_token(p); ++ if (token == NULL) { ++ return NULL; ++ } ++ int end_lineno = token->end_lineno; ++ UNUSED(end_lineno); // Only used by EXTRA macro ++ int end_col_offset = token->end_col_offset; ++ UNUSED(end_col_offset); // Only used by EXTRA macro ++ res = _Py_Try ( b , NULL , NULL , f , EXTRA ); ++ if (res == NULL && PyErr_Occurred()) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ goto done; ++ } ++ p->mark = mark; ++ } ++ { // 'try' ':' block except_block+ else_block? finally_block? ++ asdl_seq* b; ++ void *el; ++ asdl_seq * ex; ++ void *f; ++ void *keyword; ++ void *literal; ++ if ( ++ (keyword = _PyPegen_expect_token(p, 511)) ++ && ++ (literal = _PyPegen_expect_token(p, 11)) ++ && ++ (b = block_rule(p)) ++ && ++ (ex = _loop1_34_rule(p)) ++ && ++ (el = else_block_rule(p), 1) ++ && ++ (f = finally_block_rule(p), 1) ++ ) ++ { ++ Token *token = _PyPegen_get_last_nonnwhitespace_token(p); ++ if (token == NULL) { ++ return NULL; ++ } ++ int end_lineno = token->end_lineno; ++ UNUSED(end_lineno); // Only used by EXTRA macro ++ int end_col_offset = token->end_col_offset; ++ UNUSED(end_col_offset); // Only used by EXTRA macro ++ res = _Py_Try ( b , ex , el , f , EXTRA ); ++ if (res == NULL && PyErr_Occurred()) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ goto done; ++ } ++ p->mark = mark; ++ } ++ res = NULL; ++ done: ++ return res; ++} ++ ++// except_block: 'except' expression ['as' target] ':' block | 'except' ':' block ++static excepthandler_ty ++except_block_rule(Parser *p) ++{ ++ if (p->error_indicator) { ++ return NULL; ++ } ++ excepthandler_ty res = NULL; ++ int mark = p->mark; ++ if (p->mark == p->fill && _PyPegen_fill_token(p) < 0) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ int start_lineno = p->tokens[mark]->lineno; ++ UNUSED(start_lineno); // Only used by EXTRA macro ++ int start_col_offset = p->tokens[mark]->col_offset; ++ UNUSED(start_col_offset); // Only used by EXTRA macro ++ { // 'except' expression ['as' target] ':' block ++ asdl_seq* b; ++ expr_ty e; ++ void *keyword; ++ void *literal; ++ void *t; ++ if ( ++ (keyword = _PyPegen_expect_token(p, 520)) ++ && ++ (e = expression_rule(p)) ++ && ++ (t = _tmp_35_rule(p), 1) ++ && ++ (literal = _PyPegen_expect_token(p, 11)) ++ && ++ (b = block_rule(p)) ++ ) ++ { ++ Token *token = _PyPegen_get_last_nonnwhitespace_token(p); ++ if (token == NULL) { ++ return NULL; ++ } ++ int end_lineno = token->end_lineno; ++ UNUSED(end_lineno); // Only used by EXTRA macro ++ int end_col_offset = token->end_col_offset; ++ UNUSED(end_col_offset); // Only used by EXTRA macro ++ res = _Py_ExceptHandler ( e , ( t ) ? ( ( expr_ty ) t ) -> v . Name . id : NULL , b , EXTRA ); ++ if (res == NULL && PyErr_Occurred()) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ goto done; ++ } ++ p->mark = mark; ++ } ++ { // 'except' ':' block ++ asdl_seq* b; ++ void *keyword; ++ void *literal; ++ if ( ++ (keyword = _PyPegen_expect_token(p, 520)) ++ && ++ (literal = _PyPegen_expect_token(p, 11)) ++ && ++ (b = block_rule(p)) ++ ) ++ { ++ Token *token = _PyPegen_get_last_nonnwhitespace_token(p); ++ if (token == NULL) { ++ return NULL; ++ } ++ int end_lineno = token->end_lineno; ++ UNUSED(end_lineno); // Only used by EXTRA macro ++ int end_col_offset = token->end_col_offset; ++ UNUSED(end_col_offset); // Only used by EXTRA macro ++ res = _Py_ExceptHandler ( NULL , NULL , b , EXTRA ); ++ if (res == NULL && PyErr_Occurred()) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ goto done; ++ } ++ p->mark = mark; ++ } ++ res = NULL; ++ done: ++ return res; ++} ++ ++// finally_block: 'finally' ':' block ++static asdl_seq* ++finally_block_rule(Parser *p) ++{ ++ if (p->error_indicator) { ++ return NULL; ++ } ++ asdl_seq* res = NULL; ++ int mark = p->mark; ++ { // 'finally' ':' block ++ asdl_seq* a; ++ void *keyword; ++ void *literal; ++ if ( ++ (keyword = _PyPegen_expect_token(p, 521)) ++ && ++ (literal = _PyPegen_expect_token(p, 11)) ++ && ++ (a = block_rule(p)) ++ ) ++ { ++ res = a; ++ if (res == NULL && PyErr_Occurred()) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ goto done; ++ } ++ p->mark = mark; ++ } ++ res = NULL; ++ done: ++ return res; ++} ++ ++// return_stmt: 'return' star_expressions? ++static stmt_ty ++return_stmt_rule(Parser *p) ++{ ++ if (p->error_indicator) { ++ return NULL; ++ } ++ stmt_ty res = NULL; ++ int mark = p->mark; ++ if (p->mark == p->fill && _PyPegen_fill_token(p) < 0) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ int start_lineno = p->tokens[mark]->lineno; ++ UNUSED(start_lineno); // Only used by EXTRA macro ++ int start_col_offset = p->tokens[mark]->col_offset; ++ UNUSED(start_col_offset); // Only used by EXTRA macro ++ { // 'return' star_expressions? ++ void *a; ++ void *keyword; ++ if ( ++ (keyword = _PyPegen_expect_token(p, 500)) ++ && ++ (a = star_expressions_rule(p), 1) ++ ) ++ { ++ Token *token = _PyPegen_get_last_nonnwhitespace_token(p); ++ if (token == NULL) { ++ return NULL; ++ } ++ int end_lineno = token->end_lineno; ++ UNUSED(end_lineno); // Only used by EXTRA macro ++ int end_col_offset = token->end_col_offset; ++ UNUSED(end_col_offset); // Only used by EXTRA macro ++ res = _Py_Return ( a , EXTRA ); ++ if (res == NULL && PyErr_Occurred()) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ goto done; ++ } ++ p->mark = mark; ++ } ++ res = NULL; ++ done: ++ return res; ++} ++ ++// raise_stmt: 'raise' expression ['from' expression] | 'raise' ++static stmt_ty ++raise_stmt_rule(Parser *p) ++{ ++ if (p->error_indicator) { ++ return NULL; ++ } ++ stmt_ty res = NULL; ++ int mark = p->mark; ++ if (p->mark == p->fill && _PyPegen_fill_token(p) < 0) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ int start_lineno = p->tokens[mark]->lineno; ++ UNUSED(start_lineno); // Only used by EXTRA macro ++ int start_col_offset = p->tokens[mark]->col_offset; ++ UNUSED(start_col_offset); // Only used by EXTRA macro ++ { // 'raise' expression ['from' expression] ++ expr_ty a; ++ void *b; ++ void *keyword; ++ if ( ++ (keyword = _PyPegen_expect_token(p, 501)) ++ && ++ (a = expression_rule(p)) ++ && ++ (b = _tmp_36_rule(p), 1) ++ ) ++ { ++ Token *token = _PyPegen_get_last_nonnwhitespace_token(p); ++ if (token == NULL) { ++ return NULL; ++ } ++ int end_lineno = token->end_lineno; ++ UNUSED(end_lineno); // Only used by EXTRA macro ++ int end_col_offset = token->end_col_offset; ++ UNUSED(end_col_offset); // Only used by EXTRA macro ++ res = _Py_Raise ( a , b , EXTRA ); ++ if (res == NULL && PyErr_Occurred()) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ goto done; ++ } ++ p->mark = mark; ++ } ++ { // 'raise' ++ void *keyword; ++ if ( ++ (keyword = _PyPegen_expect_token(p, 501)) ++ ) ++ { ++ Token *token = _PyPegen_get_last_nonnwhitespace_token(p); ++ if (token == NULL) { ++ return NULL; ++ } ++ int end_lineno = token->end_lineno; ++ UNUSED(end_lineno); // Only used by EXTRA macro ++ int end_col_offset = token->end_col_offset; ++ UNUSED(end_col_offset); // Only used by EXTRA macro ++ res = _Py_Raise ( NULL , NULL , EXTRA ); ++ if (res == NULL && PyErr_Occurred()) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ goto done; ++ } ++ p->mark = mark; ++ } ++ res = NULL; ++ done: ++ return res; ++} ++ ++// function_def: decorators function_def_raw | function_def_raw ++static stmt_ty ++function_def_rule(Parser *p) ++{ ++ if (p->error_indicator) { ++ return NULL; ++ } ++ stmt_ty res = NULL; ++ int mark = p->mark; ++ { // decorators function_def_raw ++ asdl_seq* d; ++ stmt_ty f; ++ if ( ++ (d = decorators_rule(p)) ++ && ++ (f = function_def_raw_rule(p)) ++ ) ++ { ++ res = _PyPegen_function_def_decorators ( p , d , f ); ++ if (res == NULL && PyErr_Occurred()) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ goto done; ++ } ++ p->mark = mark; ++ } ++ { // function_def_raw ++ stmt_ty function_def_raw_var; ++ if ( ++ (function_def_raw_var = function_def_raw_rule(p)) ++ ) ++ { ++ res = function_def_raw_var; ++ goto done; ++ } ++ p->mark = mark; ++ } ++ res = NULL; ++ done: ++ return res; ++} ++ ++// function_def_raw: ASYNC? 'def' NAME '(' params? ')' ['->' annotation] ':' block ++static stmt_ty ++function_def_raw_rule(Parser *p) ++{ ++ if (p->error_indicator) { ++ return NULL; ++ } ++ stmt_ty res = NULL; ++ int mark = p->mark; ++ if (p->mark == p->fill && _PyPegen_fill_token(p) < 0) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ int start_lineno = p->tokens[mark]->lineno; ++ UNUSED(start_lineno); // Only used by EXTRA macro ++ int start_col_offset = p->tokens[mark]->col_offset; ++ UNUSED(start_col_offset); // Only used by EXTRA macro ++ { // ASYNC? 'def' NAME '(' params? ')' ['->' annotation] ':' block ++ void *a; ++ asdl_seq* b; ++ void *is_async; ++ void *keyword; ++ void *literal; ++ void *literal_1; ++ void *literal_2; ++ expr_ty n; ++ void *params; ++ if ( ++ (is_async = _PyPegen_async_token(p), 1) ++ && ++ (keyword = _PyPegen_expect_token(p, 522)) ++ && ++ (n = _PyPegen_name_token(p)) ++ && ++ (literal = _PyPegen_expect_token(p, 7)) ++ && ++ (params = params_rule(p), 1) ++ && ++ (literal_1 = _PyPegen_expect_token(p, 8)) ++ && ++ (a = _tmp_37_rule(p), 1) ++ && ++ (literal_2 = _PyPegen_expect_token(p, 11)) ++ && ++ (b = block_rule(p)) ++ ) ++ { ++ Token *token = _PyPegen_get_last_nonnwhitespace_token(p); ++ if (token == NULL) { ++ return NULL; ++ } ++ int end_lineno = token->end_lineno; ++ UNUSED(end_lineno); // Only used by EXTRA macro ++ int end_col_offset = token->end_col_offset; ++ UNUSED(end_col_offset); // Only used by EXTRA macro ++ res = ( is_async ? _Py_AsyncFunctionDef : _Py_FunctionDef ) ( n -> v . Name . id , ( params ) ? params : CHECK ( _PyPegen_empty_arguments ( p ) ) , b , NULL , a , NULL , EXTRA ); ++ if (res == NULL && PyErr_Occurred()) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ goto done; ++ } ++ p->mark = mark; ++ } ++ res = NULL; ++ done: ++ return res; ++} ++ ++// params: invalid_parameters | parameters ++static arguments_ty ++params_rule(Parser *p) ++{ ++ if (p->error_indicator) { ++ return NULL; ++ } ++ arguments_ty res = NULL; ++ int mark = p->mark; ++ { // invalid_parameters ++ void *invalid_parameters_var; ++ if ( ++ (invalid_parameters_var = invalid_parameters_rule(p)) ++ ) ++ { ++ res = invalid_parameters_var; ++ goto done; ++ } ++ p->mark = mark; ++ } ++ { // parameters ++ arguments_ty parameters_var; ++ if ( ++ (parameters_var = parameters_rule(p)) ++ ) ++ { ++ res = parameters_var; ++ goto done; ++ } ++ p->mark = mark; ++ } ++ res = NULL; ++ done: ++ return res; ++} ++ ++// parameters: ++// | slash_without_default [',' plain_names] [',' names_with_default] [',' star_etc?] ++// | slash_with_default [',' names_with_default] [',' star_etc?] ++// | plain_names [',' names_with_default] [',' star_etc?] ++// | names_with_default [',' star_etc?] ++// | star_etc ++static arguments_ty ++parameters_rule(Parser *p) ++{ ++ if (p->error_indicator) { ++ return NULL; ++ } ++ arguments_ty res = NULL; ++ int mark = p->mark; ++ { // slash_without_default [',' plain_names] [',' names_with_default] [',' star_etc?] ++ asdl_seq* a; ++ void *b; ++ void *c; ++ void *d; ++ if ( ++ (a = slash_without_default_rule(p)) ++ && ++ (b = _tmp_38_rule(p), 1) ++ && ++ (c = _tmp_39_rule(p), 1) ++ && ++ (d = _tmp_40_rule(p), 1) ++ ) ++ { ++ res = _PyPegen_make_arguments ( p , a , NULL , b , c , d ); ++ if (res == NULL && PyErr_Occurred()) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ goto done; ++ } ++ p->mark = mark; ++ } ++ { // slash_with_default [',' names_with_default] [',' star_etc?] ++ SlashWithDefault* a; ++ void *b; ++ void *c; ++ if ( ++ (a = slash_with_default_rule(p)) ++ && ++ (b = _tmp_41_rule(p), 1) ++ && ++ (c = _tmp_42_rule(p), 1) ++ ) ++ { ++ res = _PyPegen_make_arguments ( p , NULL , a , NULL , b , c ); ++ if (res == NULL && PyErr_Occurred()) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ goto done; ++ } ++ p->mark = mark; ++ } ++ { // plain_names [',' names_with_default] [',' star_etc?] ++ asdl_seq* a; ++ void *b; ++ void *c; ++ if ( ++ (a = plain_names_rule(p)) ++ && ++ (b = _tmp_43_rule(p), 1) ++ && ++ (c = _tmp_44_rule(p), 1) ++ ) ++ { ++ res = _PyPegen_make_arguments ( p , NULL , NULL , a , b , c ); ++ if (res == NULL && PyErr_Occurred()) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ goto done; ++ } ++ p->mark = mark; ++ } ++ { // names_with_default [',' star_etc?] ++ asdl_seq* a; ++ void *b; ++ if ( ++ (a = names_with_default_rule(p)) ++ && ++ (b = _tmp_45_rule(p), 1) ++ ) ++ { ++ res = _PyPegen_make_arguments ( p , NULL , NULL , NULL , a , b ); ++ if (res == NULL && PyErr_Occurred()) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ goto done; ++ } ++ p->mark = mark; ++ } ++ { // star_etc ++ StarEtc* a; ++ if ( ++ (a = star_etc_rule(p)) ++ ) ++ { ++ res = _PyPegen_make_arguments ( p , NULL , NULL , NULL , NULL , a ); ++ if (res == NULL && PyErr_Occurred()) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ goto done; ++ } ++ p->mark = mark; ++ } ++ res = NULL; ++ done: ++ return res; ++} ++ ++// slash_without_default: plain_names ',' '/' ++static asdl_seq* ++slash_without_default_rule(Parser *p) ++{ ++ if (p->error_indicator) { ++ return NULL; ++ } ++ asdl_seq* res = NULL; ++ int mark = p->mark; ++ { // plain_names ',' '/' ++ asdl_seq* a; ++ void *literal; ++ void *literal_1; ++ if ( ++ (a = plain_names_rule(p)) ++ && ++ (literal = _PyPegen_expect_token(p, 12)) ++ && ++ (literal_1 = _PyPegen_expect_token(p, 17)) ++ ) ++ { ++ res = a; ++ if (res == NULL && PyErr_Occurred()) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ goto done; ++ } ++ p->mark = mark; ++ } ++ res = NULL; ++ done: ++ return res; ++} ++ ++// slash_with_default: [plain_names ','] names_with_default ',' '/' ++static SlashWithDefault* ++slash_with_default_rule(Parser *p) ++{ ++ if (p->error_indicator) { ++ return NULL; ++ } ++ SlashWithDefault* res = NULL; ++ int mark = p->mark; ++ { // [plain_names ','] names_with_default ',' '/' ++ void *a; ++ asdl_seq* b; ++ void *literal; ++ void *literal_1; ++ if ( ++ (a = _tmp_46_rule(p), 1) ++ && ++ (b = names_with_default_rule(p)) ++ && ++ (literal = _PyPegen_expect_token(p, 12)) ++ && ++ (literal_1 = _PyPegen_expect_token(p, 17)) ++ ) ++ { ++ res = _PyPegen_slash_with_default ( p , a , b ); ++ if (res == NULL && PyErr_Occurred()) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ goto done; ++ } ++ p->mark = mark; ++ } ++ res = NULL; ++ done: ++ return res; ++} ++ ++// star_etc: ++// | '*' plain_name name_with_optional_default* [',' kwds] ','? ++// | '*' name_with_optional_default+ [',' kwds] ','? ++// | kwds ','? ++static StarEtc* ++star_etc_rule(Parser *p) ++{ ++ if (p->error_indicator) { ++ return NULL; ++ } ++ StarEtc* res = NULL; ++ int mark = p->mark; ++ { // '*' plain_name name_with_optional_default* [',' kwds] ','? ++ arg_ty a; ++ asdl_seq * b; ++ void *c; ++ void *literal; ++ void *opt_var; ++ UNUSED(opt_var); // Silence compiler warnings ++ if ( ++ (literal = _PyPegen_expect_token(p, 16)) ++ && ++ (a = plain_name_rule(p)) ++ && ++ (b = _loop0_47_rule(p)) ++ && ++ (c = _tmp_48_rule(p), 1) ++ && ++ (opt_var = _PyPegen_expect_token(p, 12), 1) ++ ) ++ { ++ res = _PyPegen_star_etc ( p , a , b , c ); ++ if (res == NULL && PyErr_Occurred()) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ goto done; ++ } ++ p->mark = mark; ++ } ++ { // '*' name_with_optional_default+ [',' kwds] ','? ++ asdl_seq * b; ++ void *c; ++ void *literal; ++ void *opt_var; ++ UNUSED(opt_var); // Silence compiler warnings ++ if ( ++ (literal = _PyPegen_expect_token(p, 16)) ++ && ++ (b = _loop1_49_rule(p)) ++ && ++ (c = _tmp_50_rule(p), 1) ++ && ++ (opt_var = _PyPegen_expect_token(p, 12), 1) ++ ) ++ { ++ res = _PyPegen_star_etc ( p , NULL , b , c ); ++ if (res == NULL && PyErr_Occurred()) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ goto done; ++ } ++ p->mark = mark; ++ } ++ { // kwds ','? ++ arg_ty a; ++ void *opt_var; ++ UNUSED(opt_var); // Silence compiler warnings ++ if ( ++ (a = kwds_rule(p)) ++ && ++ (opt_var = _PyPegen_expect_token(p, 12), 1) ++ ) ++ { ++ res = _PyPegen_star_etc ( p , NULL , NULL , a ); ++ if (res == NULL && PyErr_Occurred()) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ goto done; ++ } ++ p->mark = mark; ++ } ++ res = NULL; ++ done: ++ return res; ++} ++ ++// name_with_optional_default: ',' plain_name ['=' expression] ++static NameDefaultPair* ++name_with_optional_default_rule(Parser *p) ++{ ++ if (p->error_indicator) { ++ return NULL; ++ } ++ NameDefaultPair* res = NULL; ++ int mark = p->mark; ++ { // ',' plain_name ['=' expression] ++ arg_ty a; ++ void *b; ++ void *literal; ++ if ( ++ (literal = _PyPegen_expect_token(p, 12)) ++ && ++ (a = plain_name_rule(p)) ++ && ++ (b = _tmp_51_rule(p), 1) ++ ) ++ { ++ res = _PyPegen_name_default_pair ( p , a , b ); ++ if (res == NULL && PyErr_Occurred()) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ goto done; ++ } ++ p->mark = mark; ++ } ++ res = NULL; ++ done: ++ return res; ++} ++ ++// names_with_default: ','.name_with_default+ ++static asdl_seq* ++names_with_default_rule(Parser *p) ++{ ++ if (p->error_indicator) { ++ return NULL; ++ } ++ asdl_seq* res = NULL; ++ int mark = p->mark; ++ { // ','.name_with_default+ ++ asdl_seq * a; ++ if ( ++ (a = _gather_52_rule(p)) ++ ) ++ { ++ res = a; ++ if (res == NULL && PyErr_Occurred()) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ goto done; ++ } ++ p->mark = mark; ++ } ++ res = NULL; ++ done: ++ return res; ++} ++ ++// name_with_default: plain_name '=' expression ++static NameDefaultPair* ++name_with_default_rule(Parser *p) ++{ ++ if (p->error_indicator) { ++ return NULL; ++ } ++ NameDefaultPair* res = NULL; ++ int mark = p->mark; ++ { // plain_name '=' expression ++ expr_ty e; ++ void *literal; ++ arg_ty n; ++ if ( ++ (n = plain_name_rule(p)) ++ && ++ (literal = _PyPegen_expect_token(p, 22)) ++ && ++ (e = expression_rule(p)) ++ ) ++ { ++ res = _PyPegen_name_default_pair ( p , n , e ); ++ if (res == NULL && PyErr_Occurred()) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ goto done; ++ } ++ p->mark = mark; ++ } ++ res = NULL; ++ done: ++ return res; ++} ++ ++// plain_names: ','.(plain_name !'=')+ ++static asdl_seq* ++plain_names_rule(Parser *p) ++{ ++ if (p->error_indicator) { ++ return NULL; ++ } ++ asdl_seq* res = NULL; ++ if (_PyPegen_is_memoized(p, plain_names_type, &res)) ++ return res; ++ int mark = p->mark; ++ { // ','.(plain_name !'=')+ ++ asdl_seq * a; ++ if ( ++ (a = _gather_54_rule(p)) ++ ) ++ { ++ res = a; ++ if (res == NULL && PyErr_Occurred()) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ goto done; ++ } ++ p->mark = mark; ++ } ++ res = NULL; ++ done: ++ _PyPegen_insert_memo(p, mark, plain_names_type, res); ++ return res; ++} ++ ++// plain_name: NAME [':' annotation] ++static arg_ty ++plain_name_rule(Parser *p) ++{ ++ if (p->error_indicator) { ++ return NULL; ++ } ++ arg_ty res = NULL; ++ int mark = p->mark; ++ if (p->mark == p->fill && _PyPegen_fill_token(p) < 0) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ int start_lineno = p->tokens[mark]->lineno; ++ UNUSED(start_lineno); // Only used by EXTRA macro ++ int start_col_offset = p->tokens[mark]->col_offset; ++ UNUSED(start_col_offset); // Only used by EXTRA macro ++ { // NAME [':' annotation] ++ expr_ty a; ++ void *b; ++ if ( ++ (a = _PyPegen_name_token(p)) ++ && ++ (b = _tmp_56_rule(p), 1) ++ ) ++ { ++ Token *token = _PyPegen_get_last_nonnwhitespace_token(p); ++ if (token == NULL) { ++ return NULL; ++ } ++ int end_lineno = token->end_lineno; ++ UNUSED(end_lineno); // Only used by EXTRA macro ++ int end_col_offset = token->end_col_offset; ++ UNUSED(end_col_offset); // Only used by EXTRA macro ++ res = _Py_arg ( a -> v . Name . id , b , NULL , EXTRA ); ++ if (res == NULL && PyErr_Occurred()) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ goto done; ++ } ++ p->mark = mark; ++ } ++ res = NULL; ++ done: ++ return res; ++} ++ ++// kwds: '**' plain_name ++static arg_ty ++kwds_rule(Parser *p) ++{ ++ if (p->error_indicator) { ++ return NULL; ++ } ++ arg_ty res = NULL; ++ int mark = p->mark; ++ { // '**' plain_name ++ arg_ty a; ++ void *literal; ++ if ( ++ (literal = _PyPegen_expect_token(p, 35)) ++ && ++ (a = plain_name_rule(p)) ++ ) ++ { ++ res = a; ++ if (res == NULL && PyErr_Occurred()) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ goto done; ++ } ++ p->mark = mark; ++ } ++ res = NULL; ++ done: ++ return res; ++} ++ ++// annotation: expression ++static expr_ty ++annotation_rule(Parser *p) ++{ ++ if (p->error_indicator) { ++ return NULL; ++ } ++ expr_ty res = NULL; ++ int mark = p->mark; ++ { // expression ++ expr_ty expression_var; ++ if ( ++ (expression_var = expression_rule(p)) ++ ) ++ { ++ res = expression_var; ++ goto done; ++ } ++ p->mark = mark; ++ } ++ res = NULL; ++ done: ++ return res; ++} ++ ++// decorators: (('@' named_expression NEWLINE))+ ++static asdl_seq* ++decorators_rule(Parser *p) ++{ ++ if (p->error_indicator) { ++ return NULL; ++ } ++ asdl_seq* res = NULL; ++ int mark = p->mark; ++ { // (('@' named_expression NEWLINE))+ ++ asdl_seq * a; ++ if ( ++ (a = _loop1_57_rule(p)) ++ ) ++ { ++ res = a; ++ if (res == NULL && PyErr_Occurred()) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ goto done; ++ } ++ p->mark = mark; ++ } ++ res = NULL; ++ done: ++ return res; ++} ++ ++// class_def: decorators class_def_raw | class_def_raw ++static stmt_ty ++class_def_rule(Parser *p) ++{ ++ if (p->error_indicator) { ++ return NULL; ++ } ++ stmt_ty res = NULL; ++ int mark = p->mark; ++ { // decorators class_def_raw ++ asdl_seq* a; ++ stmt_ty b; ++ if ( ++ (a = decorators_rule(p)) ++ && ++ (b = class_def_raw_rule(p)) ++ ) ++ { ++ res = _PyPegen_class_def_decorators ( p , a , b ); ++ if (res == NULL && PyErr_Occurred()) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ goto done; ++ } ++ p->mark = mark; ++ } ++ { // class_def_raw ++ stmt_ty class_def_raw_var; ++ if ( ++ (class_def_raw_var = class_def_raw_rule(p)) ++ ) ++ { ++ res = class_def_raw_var; ++ goto done; ++ } ++ p->mark = mark; ++ } ++ res = NULL; ++ done: ++ return res; ++} ++ ++// class_def_raw: 'class' NAME ['(' arguments? ')'] ':' block ++static stmt_ty ++class_def_raw_rule(Parser *p) ++{ ++ if (p->error_indicator) { ++ return NULL; ++ } ++ stmt_ty res = NULL; ++ int mark = p->mark; ++ if (p->mark == p->fill && _PyPegen_fill_token(p) < 0) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ int start_lineno = p->tokens[mark]->lineno; ++ UNUSED(start_lineno); // Only used by EXTRA macro ++ int start_col_offset = p->tokens[mark]->col_offset; ++ UNUSED(start_col_offset); // Only used by EXTRA macro ++ { // 'class' NAME ['(' arguments? ')'] ':' block ++ expr_ty a; ++ void *b; ++ asdl_seq* c; ++ void *keyword; ++ void *literal; ++ if ( ++ (keyword = _PyPegen_expect_token(p, 523)) ++ && ++ (a = _PyPegen_name_token(p)) ++ && ++ (b = _tmp_58_rule(p), 1) ++ && ++ (literal = _PyPegen_expect_token(p, 11)) ++ && ++ (c = block_rule(p)) ++ ) ++ { ++ Token *token = _PyPegen_get_last_nonnwhitespace_token(p); ++ if (token == NULL) { ++ return NULL; ++ } ++ int end_lineno = token->end_lineno; ++ UNUSED(end_lineno); // Only used by EXTRA macro ++ int end_col_offset = token->end_col_offset; ++ UNUSED(end_col_offset); // Only used by EXTRA macro ++ res = _Py_ClassDef ( a -> v . Name . id , ( b ) ? ( ( expr_ty ) b ) -> v . Call . args : NULL , ( b ) ? ( ( expr_ty ) b ) -> v . Call . keywords : NULL , c , NULL , EXTRA ); ++ if (res == NULL && PyErr_Occurred()) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ goto done; ++ } ++ p->mark = mark; ++ } ++ res = NULL; ++ done: ++ return res; ++} ++ ++// block: NEWLINE INDENT statements DEDENT | simple_stmt | invalid_block ++static asdl_seq* ++block_rule(Parser *p) ++{ ++ if (p->error_indicator) { ++ return NULL; ++ } ++ asdl_seq* res = NULL; ++ if (_PyPegen_is_memoized(p, block_type, &res)) ++ return res; ++ int mark = p->mark; ++ { // NEWLINE INDENT statements DEDENT ++ asdl_seq* a; ++ void *dedent_var; ++ void *indent_var; ++ void *newline_var; ++ if ( ++ (newline_var = _PyPegen_newline_token(p)) ++ && ++ (indent_var = _PyPegen_indent_token(p)) ++ && ++ (a = statements_rule(p)) ++ && ++ (dedent_var = _PyPegen_dedent_token(p)) ++ ) ++ { ++ res = a; ++ if (res == NULL && PyErr_Occurred()) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ goto done; ++ } ++ p->mark = mark; ++ } ++ { // simple_stmt ++ asdl_seq* simple_stmt_var; ++ if ( ++ (simple_stmt_var = simple_stmt_rule(p)) ++ ) ++ { ++ res = simple_stmt_var; ++ goto done; ++ } ++ p->mark = mark; ++ } ++ { // invalid_block ++ void *invalid_block_var; ++ if ( ++ (invalid_block_var = invalid_block_rule(p)) ++ ) ++ { ++ res = invalid_block_var; ++ goto done; ++ } ++ p->mark = mark; ++ } ++ res = NULL; ++ done: ++ _PyPegen_insert_memo(p, mark, block_type, res); ++ return res; ++} ++ ++// expressions_list: ','.star_expression+ ','? ++static asdl_seq* ++expressions_list_rule(Parser *p) ++{ ++ if (p->error_indicator) { ++ return NULL; ++ } ++ asdl_seq* res = NULL; ++ int mark = p->mark; ++ { // ','.star_expression+ ','? ++ asdl_seq * a; ++ void *opt_var; ++ UNUSED(opt_var); // Silence compiler warnings ++ if ( ++ (a = _gather_59_rule(p)) ++ && ++ (opt_var = _PyPegen_expect_token(p, 12), 1) ++ ) ++ { ++ res = a; ++ if (res == NULL && PyErr_Occurred()) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ goto done; ++ } ++ p->mark = mark; ++ } ++ res = NULL; ++ done: ++ return res; ++} ++ ++// star_expressions: ++// | star_expression ((',' star_expression))+ ','? ++// | star_expression ',' ++// | star_expression ++static expr_ty ++star_expressions_rule(Parser *p) ++{ ++ if (p->error_indicator) { ++ return NULL; ++ } ++ expr_ty res = NULL; ++ int mark = p->mark; ++ if (p->mark == p->fill && _PyPegen_fill_token(p) < 0) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ int start_lineno = p->tokens[mark]->lineno; ++ UNUSED(start_lineno); // Only used by EXTRA macro ++ int start_col_offset = p->tokens[mark]->col_offset; ++ UNUSED(start_col_offset); // Only used by EXTRA macro ++ { // star_expression ((',' star_expression))+ ','? ++ expr_ty a; ++ asdl_seq * b; ++ void *opt_var; ++ UNUSED(opt_var); // Silence compiler warnings ++ if ( ++ (a = star_expression_rule(p)) ++ && ++ (b = _loop1_61_rule(p)) ++ && ++ (opt_var = _PyPegen_expect_token(p, 12), 1) ++ ) ++ { ++ Token *token = _PyPegen_get_last_nonnwhitespace_token(p); ++ if (token == NULL) { ++ return NULL; ++ } ++ int end_lineno = token->end_lineno; ++ UNUSED(end_lineno); // Only used by EXTRA macro ++ int end_col_offset = token->end_col_offset; ++ UNUSED(end_col_offset); // Only used by EXTRA macro ++ res = _Py_Tuple ( CHECK ( _PyPegen_seq_insert_in_front ( p , a , b ) ) , Load , EXTRA ); ++ if (res == NULL && PyErr_Occurred()) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ goto done; ++ } ++ p->mark = mark; ++ } ++ { // star_expression ',' ++ expr_ty a; ++ void *literal; ++ if ( ++ (a = star_expression_rule(p)) ++ && ++ (literal = _PyPegen_expect_token(p, 12)) ++ ) ++ { ++ Token *token = _PyPegen_get_last_nonnwhitespace_token(p); ++ if (token == NULL) { ++ return NULL; ++ } ++ int end_lineno = token->end_lineno; ++ UNUSED(end_lineno); // Only used by EXTRA macro ++ int end_col_offset = token->end_col_offset; ++ UNUSED(end_col_offset); // Only used by EXTRA macro ++ res = _Py_Tuple ( CHECK ( _PyPegen_singleton_seq ( p , a ) ) , Load , EXTRA ); ++ if (res == NULL && PyErr_Occurred()) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ goto done; ++ } ++ p->mark = mark; ++ } ++ { // star_expression ++ expr_ty star_expression_var; ++ if ( ++ (star_expression_var = star_expression_rule(p)) ++ ) ++ { ++ res = star_expression_var; ++ goto done; ++ } ++ p->mark = mark; ++ } ++ res = NULL; ++ done: ++ return res; ++} ++ ++// star_expression: '*' bitwise_or | expression ++static expr_ty ++star_expression_rule(Parser *p) ++{ ++ if (p->error_indicator) { ++ return NULL; ++ } ++ expr_ty res = NULL; ++ if (_PyPegen_is_memoized(p, star_expression_type, &res)) ++ return res; ++ int mark = p->mark; ++ if (p->mark == p->fill && _PyPegen_fill_token(p) < 0) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ int start_lineno = p->tokens[mark]->lineno; ++ UNUSED(start_lineno); // Only used by EXTRA macro ++ int start_col_offset = p->tokens[mark]->col_offset; ++ UNUSED(start_col_offset); // Only used by EXTRA macro ++ { // '*' bitwise_or ++ expr_ty a; ++ void *literal; ++ if ( ++ (literal = _PyPegen_expect_token(p, 16)) ++ && ++ (a = bitwise_or_rule(p)) ++ ) ++ { ++ Token *token = _PyPegen_get_last_nonnwhitespace_token(p); ++ if (token == NULL) { ++ return NULL; ++ } ++ int end_lineno = token->end_lineno; ++ UNUSED(end_lineno); // Only used by EXTRA macro ++ int end_col_offset = token->end_col_offset; ++ UNUSED(end_col_offset); // Only used by EXTRA macro ++ res = _Py_Starred ( a , Load , EXTRA ); ++ if (res == NULL && PyErr_Occurred()) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ goto done; ++ } ++ p->mark = mark; ++ } ++ { // expression ++ expr_ty expression_var; ++ if ( ++ (expression_var = expression_rule(p)) ++ ) ++ { ++ res = expression_var; ++ goto done; ++ } ++ p->mark = mark; ++ } ++ res = NULL; ++ done: ++ _PyPegen_insert_memo(p, mark, star_expression_type, res); ++ return res; ++} ++ ++// star_named_expressions: ','.star_named_expression+ ','? ++static asdl_seq* ++star_named_expressions_rule(Parser *p) ++{ ++ if (p->error_indicator) { ++ return NULL; ++ } ++ asdl_seq* res = NULL; ++ int mark = p->mark; ++ { // ','.star_named_expression+ ','? ++ asdl_seq * a; ++ void *opt_var; ++ UNUSED(opt_var); // Silence compiler warnings ++ if ( ++ (a = _gather_62_rule(p)) ++ && ++ (opt_var = _PyPegen_expect_token(p, 12), 1) ++ ) ++ { ++ res = a; ++ if (res == NULL && PyErr_Occurred()) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ goto done; ++ } ++ p->mark = mark; ++ } ++ res = NULL; ++ done: ++ return res; ++} ++ ++// star_named_expression: '*' bitwise_or | named_expression ++static expr_ty ++star_named_expression_rule(Parser *p) ++{ ++ if (p->error_indicator) { ++ return NULL; ++ } ++ expr_ty res = NULL; ++ int mark = p->mark; ++ if (p->mark == p->fill && _PyPegen_fill_token(p) < 0) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ int start_lineno = p->tokens[mark]->lineno; ++ UNUSED(start_lineno); // Only used by EXTRA macro ++ int start_col_offset = p->tokens[mark]->col_offset; ++ UNUSED(start_col_offset); // Only used by EXTRA macro ++ { // '*' bitwise_or ++ expr_ty a; ++ void *literal; ++ if ( ++ (literal = _PyPegen_expect_token(p, 16)) ++ && ++ (a = bitwise_or_rule(p)) ++ ) ++ { ++ Token *token = _PyPegen_get_last_nonnwhitespace_token(p); ++ if (token == NULL) { ++ return NULL; ++ } ++ int end_lineno = token->end_lineno; ++ UNUSED(end_lineno); // Only used by EXTRA macro ++ int end_col_offset = token->end_col_offset; ++ UNUSED(end_col_offset); // Only used by EXTRA macro ++ res = _Py_Starred ( a , Load , EXTRA ); ++ if (res == NULL && PyErr_Occurred()) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ goto done; ++ } ++ p->mark = mark; ++ } ++ { // named_expression ++ expr_ty named_expression_var; ++ if ( ++ (named_expression_var = named_expression_rule(p)) ++ ) ++ { ++ res = named_expression_var; ++ goto done; ++ } ++ p->mark = mark; ++ } ++ res = NULL; ++ done: ++ return res; ++} ++ ++// named_expression: NAME ':=' expression | expression !':=' | invalid_named_expression ++static expr_ty ++named_expression_rule(Parser *p) ++{ ++ if (p->error_indicator) { ++ return NULL; ++ } ++ expr_ty res = NULL; ++ int mark = p->mark; ++ if (p->mark == p->fill && _PyPegen_fill_token(p) < 0) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ int start_lineno = p->tokens[mark]->lineno; ++ UNUSED(start_lineno); // Only used by EXTRA macro ++ int start_col_offset = p->tokens[mark]->col_offset; ++ UNUSED(start_col_offset); // Only used by EXTRA macro ++ { // NAME ':=' expression ++ expr_ty a; ++ expr_ty b; ++ void *literal; ++ if ( ++ (a = _PyPegen_name_token(p)) ++ && ++ (literal = _PyPegen_expect_token(p, 53)) ++ && ++ (b = expression_rule(p)) ++ ) ++ { ++ Token *token = _PyPegen_get_last_nonnwhitespace_token(p); ++ if (token == NULL) { ++ return NULL; ++ } ++ int end_lineno = token->end_lineno; ++ UNUSED(end_lineno); // Only used by EXTRA macro ++ int end_col_offset = token->end_col_offset; ++ UNUSED(end_col_offset); // Only used by EXTRA macro ++ res = _Py_NamedExpr ( CHECK ( _PyPegen_set_expr_context ( p , a , Store ) ) , b , EXTRA ); ++ if (res == NULL && PyErr_Occurred()) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ goto done; ++ } ++ p->mark = mark; ++ } ++ { // expression !':=' ++ expr_ty expression_var; ++ if ( ++ (expression_var = expression_rule(p)) ++ && ++ _PyPegen_lookahead_with_int(0, _PyPegen_expect_token, p, 53) ++ ) ++ { ++ res = expression_var; ++ goto done; ++ } ++ p->mark = mark; ++ } ++ { // invalid_named_expression ++ void *invalid_named_expression_var; ++ if ( ++ (invalid_named_expression_var = invalid_named_expression_rule(p)) ++ ) ++ { ++ res = invalid_named_expression_var; ++ goto done; ++ } ++ p->mark = mark; ++ } ++ res = NULL; ++ done: ++ return res; ++} ++ ++// annotated_rhs: yield_expr | star_expressions ++static expr_ty ++annotated_rhs_rule(Parser *p) ++{ ++ if (p->error_indicator) { ++ return NULL; ++ } ++ expr_ty res = NULL; ++ int mark = p->mark; ++ { // yield_expr ++ expr_ty yield_expr_var; ++ if ( ++ (yield_expr_var = yield_expr_rule(p)) ++ ) ++ { ++ res = yield_expr_var; ++ goto done; ++ } ++ p->mark = mark; ++ } ++ { // star_expressions ++ expr_ty star_expressions_var; ++ if ( ++ (star_expressions_var = star_expressions_rule(p)) ++ ) ++ { ++ res = star_expressions_var; ++ goto done; ++ } ++ p->mark = mark; ++ } ++ res = NULL; ++ done: ++ return res; ++} ++ ++// expressions: expression ((',' expression))+ ','? | expression ',' | expression ++static expr_ty ++expressions_rule(Parser *p) ++{ ++ if (p->error_indicator) { ++ return NULL; ++ } ++ expr_ty res = NULL; ++ int mark = p->mark; ++ if (p->mark == p->fill && _PyPegen_fill_token(p) < 0) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ int start_lineno = p->tokens[mark]->lineno; ++ UNUSED(start_lineno); // Only used by EXTRA macro ++ int start_col_offset = p->tokens[mark]->col_offset; ++ UNUSED(start_col_offset); // Only used by EXTRA macro ++ { // expression ((',' expression))+ ','? ++ expr_ty a; ++ asdl_seq * b; ++ void *opt_var; ++ UNUSED(opt_var); // Silence compiler warnings ++ if ( ++ (a = expression_rule(p)) ++ && ++ (b = _loop1_64_rule(p)) ++ && ++ (opt_var = _PyPegen_expect_token(p, 12), 1) ++ ) ++ { ++ Token *token = _PyPegen_get_last_nonnwhitespace_token(p); ++ if (token == NULL) { ++ return NULL; ++ } ++ int end_lineno = token->end_lineno; ++ UNUSED(end_lineno); // Only used by EXTRA macro ++ int end_col_offset = token->end_col_offset; ++ UNUSED(end_col_offset); // Only used by EXTRA macro ++ res = _Py_Tuple ( CHECK ( _PyPegen_seq_insert_in_front ( p , a , b ) ) , Load , EXTRA ); ++ if (res == NULL && PyErr_Occurred()) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ goto done; ++ } ++ p->mark = mark; ++ } ++ { // expression ',' ++ expr_ty a; ++ void *literal; ++ if ( ++ (a = expression_rule(p)) ++ && ++ (literal = _PyPegen_expect_token(p, 12)) ++ ) ++ { ++ Token *token = _PyPegen_get_last_nonnwhitespace_token(p); ++ if (token == NULL) { ++ return NULL; ++ } ++ int end_lineno = token->end_lineno; ++ UNUSED(end_lineno); // Only used by EXTRA macro ++ int end_col_offset = token->end_col_offset; ++ UNUSED(end_col_offset); // Only used by EXTRA macro ++ res = _Py_Tuple ( CHECK ( _PyPegen_singleton_seq ( p , a ) ) , Load , EXTRA ); ++ if (res == NULL && PyErr_Occurred()) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ goto done; ++ } ++ p->mark = mark; ++ } ++ { // expression ++ expr_ty expression_var; ++ if ( ++ (expression_var = expression_rule(p)) ++ ) ++ { ++ res = expression_var; ++ goto done; ++ } ++ p->mark = mark; ++ } ++ res = NULL; ++ done: ++ return res; ++} ++ ++// expression: disjunction 'if' disjunction 'else' expression | disjunction | lambdef ++static expr_ty ++expression_rule(Parser *p) ++{ ++ if (p->error_indicator) { ++ return NULL; ++ } ++ expr_ty res = NULL; ++ if (_PyPegen_is_memoized(p, expression_type, &res)) ++ return res; ++ int mark = p->mark; ++ if (p->mark == p->fill && _PyPegen_fill_token(p) < 0) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ int start_lineno = p->tokens[mark]->lineno; ++ UNUSED(start_lineno); // Only used by EXTRA macro ++ int start_col_offset = p->tokens[mark]->col_offset; ++ UNUSED(start_col_offset); // Only used by EXTRA macro ++ { // disjunction 'if' disjunction 'else' expression ++ expr_ty a; ++ expr_ty b; ++ expr_ty c; ++ void *keyword; ++ void *keyword_1; ++ if ( ++ (a = disjunction_rule(p)) ++ && ++ (keyword = _PyPegen_expect_token(p, 510)) ++ && ++ (b = disjunction_rule(p)) ++ && ++ (keyword_1 = _PyPegen_expect_token(p, 516)) ++ && ++ (c = expression_rule(p)) ++ ) ++ { ++ Token *token = _PyPegen_get_last_nonnwhitespace_token(p); ++ if (token == NULL) { ++ return NULL; ++ } ++ int end_lineno = token->end_lineno; ++ UNUSED(end_lineno); // Only used by EXTRA macro ++ int end_col_offset = token->end_col_offset; ++ UNUSED(end_col_offset); // Only used by EXTRA macro ++ res = _Py_IfExp ( b , a , c , EXTRA ); ++ if (res == NULL && PyErr_Occurred()) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ goto done; ++ } ++ p->mark = mark; ++ } ++ { // disjunction ++ expr_ty disjunction_var; ++ if ( ++ (disjunction_var = disjunction_rule(p)) ++ ) ++ { ++ res = disjunction_var; ++ goto done; ++ } ++ p->mark = mark; ++ } ++ { // lambdef ++ expr_ty lambdef_var; ++ if ( ++ (lambdef_var = lambdef_rule(p)) ++ ) ++ { ++ res = lambdef_var; ++ goto done; ++ } ++ p->mark = mark; ++ } ++ res = NULL; ++ done: ++ _PyPegen_insert_memo(p, mark, expression_type, res); ++ return res; ++} ++ ++// lambdef: 'lambda' lambda_parameters? ':' expression ++static expr_ty ++lambdef_rule(Parser *p) ++{ ++ if (p->error_indicator) { ++ return NULL; ++ } ++ expr_ty res = NULL; ++ int mark = p->mark; ++ if (p->mark == p->fill && _PyPegen_fill_token(p) < 0) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ int start_lineno = p->tokens[mark]->lineno; ++ UNUSED(start_lineno); // Only used by EXTRA macro ++ int start_col_offset = p->tokens[mark]->col_offset; ++ UNUSED(start_col_offset); // Only used by EXTRA macro ++ { // 'lambda' lambda_parameters? ':' expression ++ void *a; ++ expr_ty b; ++ void *keyword; ++ void *literal; ++ if ( ++ (keyword = _PyPegen_expect_token(p, 524)) ++ && ++ (a = lambda_parameters_rule(p), 1) ++ && ++ (literal = _PyPegen_expect_token(p, 11)) ++ && ++ (b = expression_rule(p)) ++ ) ++ { ++ Token *token = _PyPegen_get_last_nonnwhitespace_token(p); ++ if (token == NULL) { ++ return NULL; ++ } ++ int end_lineno = token->end_lineno; ++ UNUSED(end_lineno); // Only used by EXTRA macro ++ int end_col_offset = token->end_col_offset; ++ UNUSED(end_col_offset); // Only used by EXTRA macro ++ res = _Py_Lambda ( ( a ) ? a : CHECK ( _PyPegen_empty_arguments ( p ) ) , b , EXTRA ); ++ if (res == NULL && PyErr_Occurred()) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ goto done; ++ } ++ p->mark = mark; ++ } ++ res = NULL; ++ done: ++ return res; ++} ++ ++// lambda_parameters: ++// | lambda_slash_without_default [',' lambda_plain_names] [',' lambda_names_with_default] [',' lambda_star_etc?] ++// | lambda_slash_with_default [',' lambda_names_with_default] [',' lambda_star_etc?] ++// | lambda_plain_names [',' lambda_names_with_default] [',' lambda_star_etc?] ++// | lambda_names_with_default [',' lambda_star_etc?] ++// | lambda_star_etc ++static arguments_ty ++lambda_parameters_rule(Parser *p) ++{ ++ if (p->error_indicator) { ++ return NULL; ++ } ++ arguments_ty res = NULL; ++ int mark = p->mark; ++ { // lambda_slash_without_default [',' lambda_plain_names] [',' lambda_names_with_default] [',' lambda_star_etc?] ++ asdl_seq* a; ++ void *b; ++ void *c; ++ void *d; ++ if ( ++ (a = lambda_slash_without_default_rule(p)) ++ && ++ (b = _tmp_65_rule(p), 1) ++ && ++ (c = _tmp_66_rule(p), 1) ++ && ++ (d = _tmp_67_rule(p), 1) ++ ) ++ { ++ res = _PyPegen_make_arguments ( p , a , NULL , b , c , d ); ++ if (res == NULL && PyErr_Occurred()) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ goto done; ++ } ++ p->mark = mark; ++ } ++ { // lambda_slash_with_default [',' lambda_names_with_default] [',' lambda_star_etc?] ++ SlashWithDefault* a; ++ void *b; ++ void *c; ++ if ( ++ (a = lambda_slash_with_default_rule(p)) ++ && ++ (b = _tmp_68_rule(p), 1) ++ && ++ (c = _tmp_69_rule(p), 1) ++ ) ++ { ++ res = _PyPegen_make_arguments ( p , NULL , a , NULL , b , c ); ++ if (res == NULL && PyErr_Occurred()) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ goto done; ++ } ++ p->mark = mark; ++ } ++ { // lambda_plain_names [',' lambda_names_with_default] [',' lambda_star_etc?] ++ asdl_seq* a; ++ void *b; ++ void *c; ++ if ( ++ (a = lambda_plain_names_rule(p)) ++ && ++ (b = _tmp_70_rule(p), 1) ++ && ++ (c = _tmp_71_rule(p), 1) ++ ) ++ { ++ res = _PyPegen_make_arguments ( p , NULL , NULL , a , b , c ); ++ if (res == NULL && PyErr_Occurred()) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ goto done; ++ } ++ p->mark = mark; ++ } ++ { // lambda_names_with_default [',' lambda_star_etc?] ++ asdl_seq* a; ++ void *b; ++ if ( ++ (a = lambda_names_with_default_rule(p)) ++ && ++ (b = _tmp_72_rule(p), 1) ++ ) ++ { ++ res = _PyPegen_make_arguments ( p , NULL , NULL , NULL , a , b ); ++ if (res == NULL && PyErr_Occurred()) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ goto done; ++ } ++ p->mark = mark; ++ } ++ { // lambda_star_etc ++ StarEtc* a; ++ if ( ++ (a = lambda_star_etc_rule(p)) ++ ) ++ { ++ res = _PyPegen_make_arguments ( p , NULL , NULL , NULL , NULL , a ); ++ if (res == NULL && PyErr_Occurred()) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ goto done; ++ } ++ p->mark = mark; ++ } ++ res = NULL; ++ done: ++ return res; ++} ++ ++// lambda_slash_without_default: lambda_plain_names ',' '/' ++static asdl_seq* ++lambda_slash_without_default_rule(Parser *p) ++{ ++ if (p->error_indicator) { ++ return NULL; ++ } ++ asdl_seq* res = NULL; ++ int mark = p->mark; ++ { // lambda_plain_names ',' '/' ++ asdl_seq* a; ++ void *literal; ++ void *literal_1; ++ if ( ++ (a = lambda_plain_names_rule(p)) ++ && ++ (literal = _PyPegen_expect_token(p, 12)) ++ && ++ (literal_1 = _PyPegen_expect_token(p, 17)) ++ ) ++ { ++ res = a; ++ if (res == NULL && PyErr_Occurred()) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ goto done; ++ } ++ p->mark = mark; ++ } ++ res = NULL; ++ done: ++ return res; ++} ++ ++// lambda_slash_with_default: [lambda_plain_names ','] lambda_names_with_default ',' '/' ++static SlashWithDefault* ++lambda_slash_with_default_rule(Parser *p) ++{ ++ if (p->error_indicator) { ++ return NULL; ++ } ++ SlashWithDefault* res = NULL; ++ int mark = p->mark; ++ { // [lambda_plain_names ','] lambda_names_with_default ',' '/' ++ void *a; ++ asdl_seq* b; ++ void *literal; ++ void *literal_1; ++ if ( ++ (a = _tmp_73_rule(p), 1) ++ && ++ (b = lambda_names_with_default_rule(p)) ++ && ++ (literal = _PyPegen_expect_token(p, 12)) ++ && ++ (literal_1 = _PyPegen_expect_token(p, 17)) ++ ) ++ { ++ res = _PyPegen_slash_with_default ( p , a , b ); ++ if (res == NULL && PyErr_Occurred()) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ goto done; ++ } ++ p->mark = mark; ++ } ++ res = NULL; ++ done: ++ return res; ++} ++ ++// lambda_star_etc: ++// | '*' lambda_plain_name lambda_name_with_optional_default* [',' lambda_kwds] ','? ++// | '*' lambda_name_with_optional_default+ [',' lambda_kwds] ','? ++// | lambda_kwds ','? ++static StarEtc* ++lambda_star_etc_rule(Parser *p) ++{ ++ if (p->error_indicator) { ++ return NULL; ++ } ++ StarEtc* res = NULL; ++ int mark = p->mark; ++ { // '*' lambda_plain_name lambda_name_with_optional_default* [',' lambda_kwds] ','? ++ arg_ty a; ++ asdl_seq * b; ++ void *c; ++ void *literal; ++ void *opt_var; ++ UNUSED(opt_var); // Silence compiler warnings ++ if ( ++ (literal = _PyPegen_expect_token(p, 16)) ++ && ++ (a = lambda_plain_name_rule(p)) ++ && ++ (b = _loop0_74_rule(p)) ++ && ++ (c = _tmp_75_rule(p), 1) ++ && ++ (opt_var = _PyPegen_expect_token(p, 12), 1) ++ ) ++ { ++ res = _PyPegen_star_etc ( p , a , b , c ); ++ if (res == NULL && PyErr_Occurred()) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ goto done; ++ } ++ p->mark = mark; ++ } ++ { // '*' lambda_name_with_optional_default+ [',' lambda_kwds] ','? ++ asdl_seq * b; ++ void *c; ++ void *literal; ++ void *opt_var; ++ UNUSED(opt_var); // Silence compiler warnings ++ if ( ++ (literal = _PyPegen_expect_token(p, 16)) ++ && ++ (b = _loop1_76_rule(p)) ++ && ++ (c = _tmp_77_rule(p), 1) ++ && ++ (opt_var = _PyPegen_expect_token(p, 12), 1) ++ ) ++ { ++ res = _PyPegen_star_etc ( p , NULL , b , c ); ++ if (res == NULL && PyErr_Occurred()) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ goto done; ++ } ++ p->mark = mark; ++ } ++ { // lambda_kwds ','? ++ arg_ty a; ++ void *opt_var; ++ UNUSED(opt_var); // Silence compiler warnings ++ if ( ++ (a = lambda_kwds_rule(p)) ++ && ++ (opt_var = _PyPegen_expect_token(p, 12), 1) ++ ) ++ { ++ res = _PyPegen_star_etc ( p , NULL , NULL , a ); ++ if (res == NULL && PyErr_Occurred()) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ goto done; ++ } ++ p->mark = mark; ++ } ++ res = NULL; ++ done: ++ return res; ++} ++ ++// lambda_name_with_optional_default: ',' lambda_plain_name ['=' expression] ++static NameDefaultPair* ++lambda_name_with_optional_default_rule(Parser *p) ++{ ++ if (p->error_indicator) { ++ return NULL; ++ } ++ NameDefaultPair* res = NULL; ++ int mark = p->mark; ++ { // ',' lambda_plain_name ['=' expression] ++ arg_ty a; ++ void *b; ++ void *literal; ++ if ( ++ (literal = _PyPegen_expect_token(p, 12)) ++ && ++ (a = lambda_plain_name_rule(p)) ++ && ++ (b = _tmp_78_rule(p), 1) ++ ) ++ { ++ res = _PyPegen_name_default_pair ( p , a , b ); ++ if (res == NULL && PyErr_Occurred()) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ goto done; ++ } ++ p->mark = mark; ++ } ++ res = NULL; ++ done: ++ return res; ++} ++ ++// lambda_names_with_default: ','.lambda_name_with_default+ ++static asdl_seq* ++lambda_names_with_default_rule(Parser *p) ++{ ++ if (p->error_indicator) { ++ return NULL; ++ } ++ asdl_seq* res = NULL; ++ int mark = p->mark; ++ { // ','.lambda_name_with_default+ ++ asdl_seq * a; ++ if ( ++ (a = _gather_79_rule(p)) ++ ) ++ { ++ res = a; ++ if (res == NULL && PyErr_Occurred()) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ goto done; ++ } ++ p->mark = mark; ++ } ++ res = NULL; ++ done: ++ return res; ++} ++ ++// lambda_name_with_default: lambda_plain_name '=' expression ++static NameDefaultPair* ++lambda_name_with_default_rule(Parser *p) ++{ ++ if (p->error_indicator) { ++ return NULL; ++ } ++ NameDefaultPair* res = NULL; ++ int mark = p->mark; ++ { // lambda_plain_name '=' expression ++ expr_ty e; ++ void *literal; ++ arg_ty n; ++ if ( ++ (n = lambda_plain_name_rule(p)) ++ && ++ (literal = _PyPegen_expect_token(p, 22)) ++ && ++ (e = expression_rule(p)) ++ ) ++ { ++ res = _PyPegen_name_default_pair ( p , n , e ); ++ if (res == NULL && PyErr_Occurred()) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ goto done; ++ } ++ p->mark = mark; ++ } ++ res = NULL; ++ done: ++ return res; ++} ++ ++// lambda_plain_names: ','.(lambda_plain_name !'=')+ ++static asdl_seq* ++lambda_plain_names_rule(Parser *p) ++{ ++ if (p->error_indicator) { ++ return NULL; ++ } ++ asdl_seq* res = NULL; ++ int mark = p->mark; ++ { // ','.(lambda_plain_name !'=')+ ++ asdl_seq * a; ++ if ( ++ (a = _gather_81_rule(p)) ++ ) ++ { ++ res = a; ++ if (res == NULL && PyErr_Occurred()) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ goto done; ++ } ++ p->mark = mark; ++ } ++ res = NULL; ++ done: ++ return res; ++} ++ ++// lambda_plain_name: NAME ++static arg_ty ++lambda_plain_name_rule(Parser *p) ++{ ++ if (p->error_indicator) { ++ return NULL; ++ } ++ arg_ty res = NULL; ++ int mark = p->mark; ++ if (p->mark == p->fill && _PyPegen_fill_token(p) < 0) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ int start_lineno = p->tokens[mark]->lineno; ++ UNUSED(start_lineno); // Only used by EXTRA macro ++ int start_col_offset = p->tokens[mark]->col_offset; ++ UNUSED(start_col_offset); // Only used by EXTRA macro ++ { // NAME ++ expr_ty a; ++ if ( ++ (a = _PyPegen_name_token(p)) ++ ) ++ { ++ Token *token = _PyPegen_get_last_nonnwhitespace_token(p); ++ if (token == NULL) { ++ return NULL; ++ } ++ int end_lineno = token->end_lineno; ++ UNUSED(end_lineno); // Only used by EXTRA macro ++ int end_col_offset = token->end_col_offset; ++ UNUSED(end_col_offset); // Only used by EXTRA macro ++ res = _Py_arg ( a -> v . Name . id , NULL , NULL , EXTRA ); ++ if (res == NULL && PyErr_Occurred()) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ goto done; ++ } ++ p->mark = mark; ++ } ++ res = NULL; ++ done: ++ return res; ++} ++ ++// lambda_kwds: '**' lambda_plain_name ++static arg_ty ++lambda_kwds_rule(Parser *p) ++{ ++ if (p->error_indicator) { ++ return NULL; ++ } ++ arg_ty res = NULL; ++ int mark = p->mark; ++ { // '**' lambda_plain_name ++ arg_ty a; ++ void *literal; ++ if ( ++ (literal = _PyPegen_expect_token(p, 35)) ++ && ++ (a = lambda_plain_name_rule(p)) ++ ) ++ { ++ res = a; ++ if (res == NULL && PyErr_Occurred()) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ goto done; ++ } ++ p->mark = mark; ++ } ++ res = NULL; ++ done: ++ return res; ++} ++ ++// disjunction: conjunction (('or' conjunction))+ | conjunction ++static expr_ty ++disjunction_rule(Parser *p) ++{ ++ if (p->error_indicator) { ++ return NULL; ++ } ++ expr_ty res = NULL; ++ if (_PyPegen_is_memoized(p, disjunction_type, &res)) ++ return res; ++ int mark = p->mark; ++ if (p->mark == p->fill && _PyPegen_fill_token(p) < 0) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ int start_lineno = p->tokens[mark]->lineno; ++ UNUSED(start_lineno); // Only used by EXTRA macro ++ int start_col_offset = p->tokens[mark]->col_offset; ++ UNUSED(start_col_offset); // Only used by EXTRA macro ++ { // conjunction (('or' conjunction))+ ++ expr_ty a; ++ asdl_seq * b; ++ if ( ++ (a = conjunction_rule(p)) ++ && ++ (b = _loop1_83_rule(p)) ++ ) ++ { ++ Token *token = _PyPegen_get_last_nonnwhitespace_token(p); ++ if (token == NULL) { ++ return NULL; ++ } ++ int end_lineno = token->end_lineno; ++ UNUSED(end_lineno); // Only used by EXTRA macro ++ int end_col_offset = token->end_col_offset; ++ UNUSED(end_col_offset); // Only used by EXTRA macro ++ res = _Py_BoolOp ( Or , CHECK ( _PyPegen_seq_insert_in_front ( p , a , b ) ) , EXTRA ); ++ if (res == NULL && PyErr_Occurred()) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ goto done; ++ } ++ p->mark = mark; ++ } ++ { // conjunction ++ expr_ty conjunction_var; ++ if ( ++ (conjunction_var = conjunction_rule(p)) ++ ) ++ { ++ res = conjunction_var; ++ goto done; ++ } ++ p->mark = mark; ++ } ++ res = NULL; ++ done: ++ _PyPegen_insert_memo(p, mark, disjunction_type, res); ++ return res; ++} ++ ++// conjunction: inversion (('and' inversion))+ | inversion ++static expr_ty ++conjunction_rule(Parser *p) ++{ ++ if (p->error_indicator) { ++ return NULL; ++ } ++ expr_ty res = NULL; ++ if (_PyPegen_is_memoized(p, conjunction_type, &res)) ++ return res; ++ int mark = p->mark; ++ if (p->mark == p->fill && _PyPegen_fill_token(p) < 0) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ int start_lineno = p->tokens[mark]->lineno; ++ UNUSED(start_lineno); // Only used by EXTRA macro ++ int start_col_offset = p->tokens[mark]->col_offset; ++ UNUSED(start_col_offset); // Only used by EXTRA macro ++ { // inversion (('and' inversion))+ ++ expr_ty a; ++ asdl_seq * b; ++ if ( ++ (a = inversion_rule(p)) ++ && ++ (b = _loop1_84_rule(p)) ++ ) ++ { ++ Token *token = _PyPegen_get_last_nonnwhitespace_token(p); ++ if (token == NULL) { ++ return NULL; ++ } ++ int end_lineno = token->end_lineno; ++ UNUSED(end_lineno); // Only used by EXTRA macro ++ int end_col_offset = token->end_col_offset; ++ UNUSED(end_col_offset); // Only used by EXTRA macro ++ res = _Py_BoolOp ( And , CHECK ( _PyPegen_seq_insert_in_front ( p , a , b ) ) , EXTRA ); ++ if (res == NULL && PyErr_Occurred()) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ goto done; ++ } ++ p->mark = mark; ++ } ++ { // inversion ++ expr_ty inversion_var; ++ if ( ++ (inversion_var = inversion_rule(p)) ++ ) ++ { ++ res = inversion_var; ++ goto done; ++ } ++ p->mark = mark; ++ } ++ res = NULL; ++ done: ++ _PyPegen_insert_memo(p, mark, conjunction_type, res); ++ return res; ++} ++ ++// inversion: 'not' inversion | comparison ++static expr_ty ++inversion_rule(Parser *p) ++{ ++ if (p->error_indicator) { ++ return NULL; ++ } ++ expr_ty res = NULL; ++ if (_PyPegen_is_memoized(p, inversion_type, &res)) ++ return res; ++ int mark = p->mark; ++ if (p->mark == p->fill && _PyPegen_fill_token(p) < 0) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ int start_lineno = p->tokens[mark]->lineno; ++ UNUSED(start_lineno); // Only used by EXTRA macro ++ int start_col_offset = p->tokens[mark]->col_offset; ++ UNUSED(start_col_offset); // Only used by EXTRA macro ++ { // 'not' inversion ++ expr_ty a; ++ void *keyword; ++ if ( ++ (keyword = _PyPegen_expect_token(p, 525)) ++ && ++ (a = inversion_rule(p)) ++ ) ++ { ++ Token *token = _PyPegen_get_last_nonnwhitespace_token(p); ++ if (token == NULL) { ++ return NULL; ++ } ++ int end_lineno = token->end_lineno; ++ UNUSED(end_lineno); // Only used by EXTRA macro ++ int end_col_offset = token->end_col_offset; ++ UNUSED(end_col_offset); // Only used by EXTRA macro ++ res = _Py_UnaryOp ( Not , a , EXTRA ); ++ if (res == NULL && PyErr_Occurred()) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ goto done; ++ } ++ p->mark = mark; ++ } ++ { // comparison ++ expr_ty comparison_var; ++ if ( ++ (comparison_var = comparison_rule(p)) ++ ) ++ { ++ res = comparison_var; ++ goto done; ++ } ++ p->mark = mark; ++ } ++ res = NULL; ++ done: ++ _PyPegen_insert_memo(p, mark, inversion_type, res); ++ return res; ++} ++ ++// comparison: bitwise_or compare_op_bitwise_or_pair+ | bitwise_or ++static expr_ty ++comparison_rule(Parser *p) ++{ ++ if (p->error_indicator) { ++ return NULL; ++ } ++ expr_ty res = NULL; ++ int mark = p->mark; ++ if (p->mark == p->fill && _PyPegen_fill_token(p) < 0) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ int start_lineno = p->tokens[mark]->lineno; ++ UNUSED(start_lineno); // Only used by EXTRA macro ++ int start_col_offset = p->tokens[mark]->col_offset; ++ UNUSED(start_col_offset); // Only used by EXTRA macro ++ { // bitwise_or compare_op_bitwise_or_pair+ ++ expr_ty a; ++ asdl_seq * b; ++ if ( ++ (a = bitwise_or_rule(p)) ++ && ++ (b = _loop1_85_rule(p)) ++ ) ++ { ++ Token *token = _PyPegen_get_last_nonnwhitespace_token(p); ++ if (token == NULL) { ++ return NULL; ++ } ++ int end_lineno = token->end_lineno; ++ UNUSED(end_lineno); // Only used by EXTRA macro ++ int end_col_offset = token->end_col_offset; ++ UNUSED(end_col_offset); // Only used by EXTRA macro ++ res = _Py_Compare ( a , CHECK ( _PyPegen_get_cmpops ( p , b ) ) , CHECK ( _PyPegen_get_exprs ( p , b ) ) , EXTRA ); ++ if (res == NULL && PyErr_Occurred()) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ goto done; ++ } ++ p->mark = mark; ++ } ++ { // bitwise_or ++ expr_ty bitwise_or_var; ++ if ( ++ (bitwise_or_var = bitwise_or_rule(p)) ++ ) ++ { ++ res = bitwise_or_var; ++ goto done; ++ } ++ p->mark = mark; ++ } ++ res = NULL; ++ done: ++ return res; ++} ++ ++// compare_op_bitwise_or_pair: ++// | eq_bitwise_or ++// | noteq_bitwise_or ++// | lte_bitwise_or ++// | lt_bitwise_or ++// | gte_bitwise_or ++// | gt_bitwise_or ++// | notin_bitwise_or ++// | in_bitwise_or ++// | isnot_bitwise_or ++// | is_bitwise_or ++static CmpopExprPair* ++compare_op_bitwise_or_pair_rule(Parser *p) ++{ ++ if (p->error_indicator) { ++ return NULL; ++ } ++ CmpopExprPair* res = NULL; ++ int mark = p->mark; ++ { // eq_bitwise_or ++ CmpopExprPair* eq_bitwise_or_var; ++ if ( ++ (eq_bitwise_or_var = eq_bitwise_or_rule(p)) ++ ) ++ { ++ res = eq_bitwise_or_var; ++ goto done; ++ } ++ p->mark = mark; ++ } ++ { // noteq_bitwise_or ++ CmpopExprPair* noteq_bitwise_or_var; ++ if ( ++ (noteq_bitwise_or_var = noteq_bitwise_or_rule(p)) ++ ) ++ { ++ res = noteq_bitwise_or_var; ++ goto done; ++ } ++ p->mark = mark; ++ } ++ { // lte_bitwise_or ++ CmpopExprPair* lte_bitwise_or_var; ++ if ( ++ (lte_bitwise_or_var = lte_bitwise_or_rule(p)) ++ ) ++ { ++ res = lte_bitwise_or_var; ++ goto done; ++ } ++ p->mark = mark; ++ } ++ { // lt_bitwise_or ++ CmpopExprPair* lt_bitwise_or_var; ++ if ( ++ (lt_bitwise_or_var = lt_bitwise_or_rule(p)) ++ ) ++ { ++ res = lt_bitwise_or_var; ++ goto done; ++ } ++ p->mark = mark; ++ } ++ { // gte_bitwise_or ++ CmpopExprPair* gte_bitwise_or_var; ++ if ( ++ (gte_bitwise_or_var = gte_bitwise_or_rule(p)) ++ ) ++ { ++ res = gte_bitwise_or_var; ++ goto done; ++ } ++ p->mark = mark; ++ } ++ { // gt_bitwise_or ++ CmpopExprPair* gt_bitwise_or_var; ++ if ( ++ (gt_bitwise_or_var = gt_bitwise_or_rule(p)) ++ ) ++ { ++ res = gt_bitwise_or_var; ++ goto done; ++ } ++ p->mark = mark; ++ } ++ { // notin_bitwise_or ++ CmpopExprPair* notin_bitwise_or_var; ++ if ( ++ (notin_bitwise_or_var = notin_bitwise_or_rule(p)) ++ ) ++ { ++ res = notin_bitwise_or_var; ++ goto done; ++ } ++ p->mark = mark; ++ } ++ { // in_bitwise_or ++ CmpopExprPair* in_bitwise_or_var; ++ if ( ++ (in_bitwise_or_var = in_bitwise_or_rule(p)) ++ ) ++ { ++ res = in_bitwise_or_var; ++ goto done; ++ } ++ p->mark = mark; ++ } ++ { // isnot_bitwise_or ++ CmpopExprPair* isnot_bitwise_or_var; ++ if ( ++ (isnot_bitwise_or_var = isnot_bitwise_or_rule(p)) ++ ) ++ { ++ res = isnot_bitwise_or_var; ++ goto done; ++ } ++ p->mark = mark; ++ } ++ { // is_bitwise_or ++ CmpopExprPair* is_bitwise_or_var; ++ if ( ++ (is_bitwise_or_var = is_bitwise_or_rule(p)) ++ ) ++ { ++ res = is_bitwise_or_var; ++ goto done; ++ } ++ p->mark = mark; ++ } ++ res = NULL; ++ done: ++ return res; ++} ++ ++// eq_bitwise_or: '==' bitwise_or ++static CmpopExprPair* ++eq_bitwise_or_rule(Parser *p) ++{ ++ if (p->error_indicator) { ++ return NULL; ++ } ++ CmpopExprPair* res = NULL; ++ int mark = p->mark; ++ { // '==' bitwise_or ++ expr_ty a; ++ void *literal; ++ if ( ++ (literal = _PyPegen_expect_token(p, 27)) ++ && ++ (a = bitwise_or_rule(p)) ++ ) ++ { ++ res = _PyPegen_cmpop_expr_pair ( p , Eq , a ); ++ if (res == NULL && PyErr_Occurred()) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ goto done; ++ } ++ p->mark = mark; ++ } ++ res = NULL; ++ done: ++ return res; ++} ++ ++// noteq_bitwise_or: '!=' bitwise_or ++static CmpopExprPair* ++noteq_bitwise_or_rule(Parser *p) ++{ ++ if (p->error_indicator) { ++ return NULL; ++ } ++ CmpopExprPair* res = NULL; ++ int mark = p->mark; ++ { // '!=' bitwise_or ++ expr_ty a; ++ void *literal; ++ if ( ++ (literal = _PyPegen_expect_token(p, 28)) ++ && ++ (a = bitwise_or_rule(p)) ++ ) ++ { ++ res = _PyPegen_cmpop_expr_pair ( p , NotEq , a ); ++ if (res == NULL && PyErr_Occurred()) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ goto done; ++ } ++ p->mark = mark; ++ } ++ res = NULL; ++ done: ++ return res; ++} ++ ++// lte_bitwise_or: '<=' bitwise_or ++static CmpopExprPair* ++lte_bitwise_or_rule(Parser *p) ++{ ++ if (p->error_indicator) { ++ return NULL; ++ } ++ CmpopExprPair* res = NULL; ++ int mark = p->mark; ++ { // '<=' bitwise_or ++ expr_ty a; ++ void *literal; ++ if ( ++ (literal = _PyPegen_expect_token(p, 29)) ++ && ++ (a = bitwise_or_rule(p)) ++ ) ++ { ++ res = _PyPegen_cmpop_expr_pair ( p , LtE , a ); ++ if (res == NULL && PyErr_Occurred()) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ goto done; ++ } ++ p->mark = mark; ++ } ++ res = NULL; ++ done: ++ return res; ++} ++ ++// lt_bitwise_or: '<' bitwise_or ++static CmpopExprPair* ++lt_bitwise_or_rule(Parser *p) ++{ ++ if (p->error_indicator) { ++ return NULL; ++ } ++ CmpopExprPair* res = NULL; ++ int mark = p->mark; ++ { // '<' bitwise_or ++ expr_ty a; ++ void *literal; ++ if ( ++ (literal = _PyPegen_expect_token(p, 20)) ++ && ++ (a = bitwise_or_rule(p)) ++ ) ++ { ++ res = _PyPegen_cmpop_expr_pair ( p , Lt , a ); ++ if (res == NULL && PyErr_Occurred()) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ goto done; ++ } ++ p->mark = mark; ++ } ++ res = NULL; ++ done: ++ return res; ++} ++ ++// gte_bitwise_or: '>=' bitwise_or ++static CmpopExprPair* ++gte_bitwise_or_rule(Parser *p) ++{ ++ if (p->error_indicator) { ++ return NULL; ++ } ++ CmpopExprPair* res = NULL; ++ int mark = p->mark; ++ { // '>=' bitwise_or ++ expr_ty a; ++ void *literal; ++ if ( ++ (literal = _PyPegen_expect_token(p, 30)) ++ && ++ (a = bitwise_or_rule(p)) ++ ) ++ { ++ res = _PyPegen_cmpop_expr_pair ( p , GtE , a ); ++ if (res == NULL && PyErr_Occurred()) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ goto done; ++ } ++ p->mark = mark; ++ } ++ res = NULL; ++ done: ++ return res; ++} ++ ++// gt_bitwise_or: '>' bitwise_or ++static CmpopExprPair* ++gt_bitwise_or_rule(Parser *p) ++{ ++ if (p->error_indicator) { ++ return NULL; ++ } ++ CmpopExprPair* res = NULL; ++ int mark = p->mark; ++ { // '>' bitwise_or ++ expr_ty a; ++ void *literal; ++ if ( ++ (literal = _PyPegen_expect_token(p, 21)) ++ && ++ (a = bitwise_or_rule(p)) ++ ) ++ { ++ res = _PyPegen_cmpop_expr_pair ( p , Gt , a ); ++ if (res == NULL && PyErr_Occurred()) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ goto done; ++ } ++ p->mark = mark; ++ } ++ res = NULL; ++ done: ++ return res; ++} ++ ++// notin_bitwise_or: 'not' 'in' bitwise_or ++static CmpopExprPair* ++notin_bitwise_or_rule(Parser *p) ++{ ++ if (p->error_indicator) { ++ return NULL; ++ } ++ CmpopExprPair* res = NULL; ++ int mark = p->mark; ++ { // 'not' 'in' bitwise_or ++ expr_ty a; ++ void *keyword; ++ void *keyword_1; ++ if ( ++ (keyword = _PyPegen_expect_token(p, 525)) ++ && ++ (keyword_1 = _PyPegen_expect_token(p, 518)) ++ && ++ (a = bitwise_or_rule(p)) ++ ) ++ { ++ res = _PyPegen_cmpop_expr_pair ( p , NotIn , a ); ++ if (res == NULL && PyErr_Occurred()) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ goto done; ++ } ++ p->mark = mark; ++ } ++ res = NULL; ++ done: ++ return res; ++} ++ ++// in_bitwise_or: 'in' bitwise_or ++static CmpopExprPair* ++in_bitwise_or_rule(Parser *p) ++{ ++ if (p->error_indicator) { ++ return NULL; ++ } ++ CmpopExprPair* res = NULL; ++ int mark = p->mark; ++ { // 'in' bitwise_or ++ expr_ty a; ++ void *keyword; ++ if ( ++ (keyword = _PyPegen_expect_token(p, 518)) ++ && ++ (a = bitwise_or_rule(p)) ++ ) ++ { ++ res = _PyPegen_cmpop_expr_pair ( p , In , a ); ++ if (res == NULL && PyErr_Occurred()) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ goto done; ++ } ++ p->mark = mark; ++ } ++ res = NULL; ++ done: ++ return res; ++} ++ ++// isnot_bitwise_or: 'is' 'not' bitwise_or ++static CmpopExprPair* ++isnot_bitwise_or_rule(Parser *p) ++{ ++ if (p->error_indicator) { ++ return NULL; ++ } ++ CmpopExprPair* res = NULL; ++ int mark = p->mark; ++ { // 'is' 'not' bitwise_or ++ expr_ty a; ++ void *keyword; ++ void *keyword_1; ++ if ( ++ (keyword = _PyPegen_expect_token(p, 526)) ++ && ++ (keyword_1 = _PyPegen_expect_token(p, 525)) ++ && ++ (a = bitwise_or_rule(p)) ++ ) ++ { ++ res = _PyPegen_cmpop_expr_pair ( p , IsNot , a ); ++ if (res == NULL && PyErr_Occurred()) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ goto done; ++ } ++ p->mark = mark; ++ } ++ res = NULL; ++ done: ++ return res; ++} ++ ++// is_bitwise_or: 'is' bitwise_or ++static CmpopExprPair* ++is_bitwise_or_rule(Parser *p) ++{ ++ if (p->error_indicator) { ++ return NULL; ++ } ++ CmpopExprPair* res = NULL; ++ int mark = p->mark; ++ { // 'is' bitwise_or ++ expr_ty a; ++ void *keyword; ++ if ( ++ (keyword = _PyPegen_expect_token(p, 526)) ++ && ++ (a = bitwise_or_rule(p)) ++ ) ++ { ++ res = _PyPegen_cmpop_expr_pair ( p , Is , a ); ++ if (res == NULL && PyErr_Occurred()) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ goto done; ++ } ++ p->mark = mark; ++ } ++ res = NULL; ++ done: ++ return res; ++} ++ ++// Left-recursive ++// bitwise_or: bitwise_or '|' bitwise_xor | bitwise_xor ++static expr_ty bitwise_or_raw(Parser *); ++static expr_ty ++bitwise_or_rule(Parser *p) ++{ ++ expr_ty res = NULL; ++ if (_PyPegen_is_memoized(p, bitwise_or_type, &res)) ++ return res; ++ int mark = p->mark; ++ int resmark = p->mark; ++ while (1) { ++ int tmpvar_1 = _PyPegen_update_memo(p, mark, bitwise_or_type, res); ++ if (tmpvar_1) { ++ return res; ++ } ++ p->mark = mark; ++ void *raw = bitwise_or_raw(p); ++ if (raw == NULL || p->mark <= resmark) ++ break; ++ resmark = p->mark; ++ res = raw; ++ } ++ p->mark = resmark; ++ return res; ++} ++static expr_ty ++bitwise_or_raw(Parser *p) ++{ ++ if (p->error_indicator) { ++ return NULL; ++ } ++ expr_ty res = NULL; ++ int mark = p->mark; ++ if (p->mark == p->fill && _PyPegen_fill_token(p) < 0) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ int start_lineno = p->tokens[mark]->lineno; ++ UNUSED(start_lineno); // Only used by EXTRA macro ++ int start_col_offset = p->tokens[mark]->col_offset; ++ UNUSED(start_col_offset); // Only used by EXTRA macro ++ { // bitwise_or '|' bitwise_xor ++ expr_ty a; ++ expr_ty b; ++ void *literal; ++ if ( ++ (a = bitwise_or_rule(p)) ++ && ++ (literal = _PyPegen_expect_token(p, 18)) ++ && ++ (b = bitwise_xor_rule(p)) ++ ) ++ { ++ Token *token = _PyPegen_get_last_nonnwhitespace_token(p); ++ if (token == NULL) { ++ return NULL; ++ } ++ int end_lineno = token->end_lineno; ++ UNUSED(end_lineno); // Only used by EXTRA macro ++ int end_col_offset = token->end_col_offset; ++ UNUSED(end_col_offset); // Only used by EXTRA macro ++ res = _Py_BinOp ( a , BitOr , b , EXTRA ); ++ if (res == NULL && PyErr_Occurred()) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ goto done; ++ } ++ p->mark = mark; ++ } ++ { // bitwise_xor ++ expr_ty bitwise_xor_var; ++ if ( ++ (bitwise_xor_var = bitwise_xor_rule(p)) ++ ) ++ { ++ res = bitwise_xor_var; ++ goto done; ++ } ++ p->mark = mark; ++ } ++ res = NULL; ++ done: ++ return res; ++} ++ ++// Left-recursive ++// bitwise_xor: bitwise_xor '^' bitwise_and | bitwise_and ++static expr_ty bitwise_xor_raw(Parser *); ++static expr_ty ++bitwise_xor_rule(Parser *p) ++{ ++ expr_ty res = NULL; ++ if (_PyPegen_is_memoized(p, bitwise_xor_type, &res)) ++ return res; ++ int mark = p->mark; ++ int resmark = p->mark; ++ while (1) { ++ int tmpvar_2 = _PyPegen_update_memo(p, mark, bitwise_xor_type, res); ++ if (tmpvar_2) { ++ return res; ++ } ++ p->mark = mark; ++ void *raw = bitwise_xor_raw(p); ++ if (raw == NULL || p->mark <= resmark) ++ break; ++ resmark = p->mark; ++ res = raw; ++ } ++ p->mark = resmark; ++ return res; ++} ++static expr_ty ++bitwise_xor_raw(Parser *p) ++{ ++ if (p->error_indicator) { ++ return NULL; ++ } ++ expr_ty res = NULL; ++ int mark = p->mark; ++ if (p->mark == p->fill && _PyPegen_fill_token(p) < 0) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ int start_lineno = p->tokens[mark]->lineno; ++ UNUSED(start_lineno); // Only used by EXTRA macro ++ int start_col_offset = p->tokens[mark]->col_offset; ++ UNUSED(start_col_offset); // Only used by EXTRA macro ++ { // bitwise_xor '^' bitwise_and ++ expr_ty a; ++ expr_ty b; ++ void *literal; ++ if ( ++ (a = bitwise_xor_rule(p)) ++ && ++ (literal = _PyPegen_expect_token(p, 32)) ++ && ++ (b = bitwise_and_rule(p)) ++ ) ++ { ++ Token *token = _PyPegen_get_last_nonnwhitespace_token(p); ++ if (token == NULL) { ++ return NULL; ++ } ++ int end_lineno = token->end_lineno; ++ UNUSED(end_lineno); // Only used by EXTRA macro ++ int end_col_offset = token->end_col_offset; ++ UNUSED(end_col_offset); // Only used by EXTRA macro ++ res = _Py_BinOp ( a , BitXor , b , EXTRA ); ++ if (res == NULL && PyErr_Occurred()) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ goto done; ++ } ++ p->mark = mark; ++ } ++ { // bitwise_and ++ expr_ty bitwise_and_var; ++ if ( ++ (bitwise_and_var = bitwise_and_rule(p)) ++ ) ++ { ++ res = bitwise_and_var; ++ goto done; ++ } ++ p->mark = mark; ++ } ++ res = NULL; ++ done: ++ return res; ++} ++ ++// Left-recursive ++// bitwise_and: bitwise_and '&' shift_expr | shift_expr ++static expr_ty bitwise_and_raw(Parser *); ++static expr_ty ++bitwise_and_rule(Parser *p) ++{ ++ expr_ty res = NULL; ++ if (_PyPegen_is_memoized(p, bitwise_and_type, &res)) ++ return res; ++ int mark = p->mark; ++ int resmark = p->mark; ++ while (1) { ++ int tmpvar_3 = _PyPegen_update_memo(p, mark, bitwise_and_type, res); ++ if (tmpvar_3) { ++ return res; ++ } ++ p->mark = mark; ++ void *raw = bitwise_and_raw(p); ++ if (raw == NULL || p->mark <= resmark) ++ break; ++ resmark = p->mark; ++ res = raw; ++ } ++ p->mark = resmark; ++ return res; ++} ++static expr_ty ++bitwise_and_raw(Parser *p) ++{ ++ if (p->error_indicator) { ++ return NULL; ++ } ++ expr_ty res = NULL; ++ int mark = p->mark; ++ if (p->mark == p->fill && _PyPegen_fill_token(p) < 0) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ int start_lineno = p->tokens[mark]->lineno; ++ UNUSED(start_lineno); // Only used by EXTRA macro ++ int start_col_offset = p->tokens[mark]->col_offset; ++ UNUSED(start_col_offset); // Only used by EXTRA macro ++ { // bitwise_and '&' shift_expr ++ expr_ty a; ++ expr_ty b; ++ void *literal; ++ if ( ++ (a = bitwise_and_rule(p)) ++ && ++ (literal = _PyPegen_expect_token(p, 19)) ++ && ++ (b = shift_expr_rule(p)) ++ ) ++ { ++ Token *token = _PyPegen_get_last_nonnwhitespace_token(p); ++ if (token == NULL) { ++ return NULL; ++ } ++ int end_lineno = token->end_lineno; ++ UNUSED(end_lineno); // Only used by EXTRA macro ++ int end_col_offset = token->end_col_offset; ++ UNUSED(end_col_offset); // Only used by EXTRA macro ++ res = _Py_BinOp ( a , BitAnd , b , EXTRA ); ++ if (res == NULL && PyErr_Occurred()) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ goto done; ++ } ++ p->mark = mark; ++ } ++ { // shift_expr ++ expr_ty shift_expr_var; ++ if ( ++ (shift_expr_var = shift_expr_rule(p)) ++ ) ++ { ++ res = shift_expr_var; ++ goto done; ++ } ++ p->mark = mark; ++ } ++ res = NULL; ++ done: ++ return res; ++} ++ ++// Left-recursive ++// shift_expr: shift_expr '<<' sum | shift_expr '>>' sum | sum ++static expr_ty shift_expr_raw(Parser *); ++static expr_ty ++shift_expr_rule(Parser *p) ++{ ++ expr_ty res = NULL; ++ if (_PyPegen_is_memoized(p, shift_expr_type, &res)) ++ return res; ++ int mark = p->mark; ++ int resmark = p->mark; ++ while (1) { ++ int tmpvar_4 = _PyPegen_update_memo(p, mark, shift_expr_type, res); ++ if (tmpvar_4) { ++ return res; ++ } ++ p->mark = mark; ++ void *raw = shift_expr_raw(p); ++ if (raw == NULL || p->mark <= resmark) ++ break; ++ resmark = p->mark; ++ res = raw; ++ } ++ p->mark = resmark; ++ return res; ++} ++static expr_ty ++shift_expr_raw(Parser *p) ++{ ++ if (p->error_indicator) { ++ return NULL; ++ } ++ expr_ty res = NULL; ++ int mark = p->mark; ++ if (p->mark == p->fill && _PyPegen_fill_token(p) < 0) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ int start_lineno = p->tokens[mark]->lineno; ++ UNUSED(start_lineno); // Only used by EXTRA macro ++ int start_col_offset = p->tokens[mark]->col_offset; ++ UNUSED(start_col_offset); // Only used by EXTRA macro ++ { // shift_expr '<<' sum ++ expr_ty a; ++ expr_ty b; ++ void *literal; ++ if ( ++ (a = shift_expr_rule(p)) ++ && ++ (literal = _PyPegen_expect_token(p, 33)) ++ && ++ (b = sum_rule(p)) ++ ) ++ { ++ Token *token = _PyPegen_get_last_nonnwhitespace_token(p); ++ if (token == NULL) { ++ return NULL; ++ } ++ int end_lineno = token->end_lineno; ++ UNUSED(end_lineno); // Only used by EXTRA macro ++ int end_col_offset = token->end_col_offset; ++ UNUSED(end_col_offset); // Only used by EXTRA macro ++ res = _Py_BinOp ( a , LShift , b , EXTRA ); ++ if (res == NULL && PyErr_Occurred()) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ goto done; ++ } ++ p->mark = mark; ++ } ++ { // shift_expr '>>' sum ++ expr_ty a; ++ expr_ty b; ++ void *literal; ++ if ( ++ (a = shift_expr_rule(p)) ++ && ++ (literal = _PyPegen_expect_token(p, 34)) ++ && ++ (b = sum_rule(p)) ++ ) ++ { ++ Token *token = _PyPegen_get_last_nonnwhitespace_token(p); ++ if (token == NULL) { ++ return NULL; ++ } ++ int end_lineno = token->end_lineno; ++ UNUSED(end_lineno); // Only used by EXTRA macro ++ int end_col_offset = token->end_col_offset; ++ UNUSED(end_col_offset); // Only used by EXTRA macro ++ res = _Py_BinOp ( a , RShift , b , EXTRA ); ++ if (res == NULL && PyErr_Occurred()) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ goto done; ++ } ++ p->mark = mark; ++ } ++ { // sum ++ expr_ty sum_var; ++ if ( ++ (sum_var = sum_rule(p)) ++ ) ++ { ++ res = sum_var; ++ goto done; ++ } ++ p->mark = mark; ++ } ++ res = NULL; ++ done: ++ return res; ++} ++ ++// Left-recursive ++// sum: sum '+' term | sum '-' term | term ++static expr_ty sum_raw(Parser *); ++static expr_ty ++sum_rule(Parser *p) ++{ ++ expr_ty res = NULL; ++ if (_PyPegen_is_memoized(p, sum_type, &res)) ++ return res; ++ int mark = p->mark; ++ int resmark = p->mark; ++ while (1) { ++ int tmpvar_5 = _PyPegen_update_memo(p, mark, sum_type, res); ++ if (tmpvar_5) { ++ return res; ++ } ++ p->mark = mark; ++ void *raw = sum_raw(p); ++ if (raw == NULL || p->mark <= resmark) ++ break; ++ resmark = p->mark; ++ res = raw; ++ } ++ p->mark = resmark; ++ return res; ++} ++static expr_ty ++sum_raw(Parser *p) ++{ ++ if (p->error_indicator) { ++ return NULL; ++ } ++ expr_ty res = NULL; ++ int mark = p->mark; ++ if (p->mark == p->fill && _PyPegen_fill_token(p) < 0) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ int start_lineno = p->tokens[mark]->lineno; ++ UNUSED(start_lineno); // Only used by EXTRA macro ++ int start_col_offset = p->tokens[mark]->col_offset; ++ UNUSED(start_col_offset); // Only used by EXTRA macro ++ { // sum '+' term ++ expr_ty a; ++ expr_ty b; ++ void *literal; ++ if ( ++ (a = sum_rule(p)) ++ && ++ (literal = _PyPegen_expect_token(p, 14)) ++ && ++ (b = term_rule(p)) ++ ) ++ { ++ Token *token = _PyPegen_get_last_nonnwhitespace_token(p); ++ if (token == NULL) { ++ return NULL; ++ } ++ int end_lineno = token->end_lineno; ++ UNUSED(end_lineno); // Only used by EXTRA macro ++ int end_col_offset = token->end_col_offset; ++ UNUSED(end_col_offset); // Only used by EXTRA macro ++ res = _Py_BinOp ( a , Add , b , EXTRA ); ++ if (res == NULL && PyErr_Occurred()) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ goto done; ++ } ++ p->mark = mark; ++ } ++ { // sum '-' term ++ expr_ty a; ++ expr_ty b; ++ void *literal; ++ if ( ++ (a = sum_rule(p)) ++ && ++ (literal = _PyPegen_expect_token(p, 15)) ++ && ++ (b = term_rule(p)) ++ ) ++ { ++ Token *token = _PyPegen_get_last_nonnwhitespace_token(p); ++ if (token == NULL) { ++ return NULL; ++ } ++ int end_lineno = token->end_lineno; ++ UNUSED(end_lineno); // Only used by EXTRA macro ++ int end_col_offset = token->end_col_offset; ++ UNUSED(end_col_offset); // Only used by EXTRA macro ++ res = _Py_BinOp ( a , Sub , b , EXTRA ); ++ if (res == NULL && PyErr_Occurred()) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ goto done; ++ } ++ p->mark = mark; ++ } ++ { // term ++ expr_ty term_var; ++ if ( ++ (term_var = term_rule(p)) ++ ) ++ { ++ res = term_var; ++ goto done; ++ } ++ p->mark = mark; ++ } ++ res = NULL; ++ done: ++ return res; ++} ++ ++// Left-recursive ++// term: ++// | term '*' factor ++// | term '/' factor ++// | term '//' factor ++// | term '%' factor ++// | term '@' factor ++// | factor ++static expr_ty term_raw(Parser *); ++static expr_ty ++term_rule(Parser *p) ++{ ++ expr_ty res = NULL; ++ if (_PyPegen_is_memoized(p, term_type, &res)) ++ return res; ++ int mark = p->mark; ++ int resmark = p->mark; ++ while (1) { ++ int tmpvar_6 = _PyPegen_update_memo(p, mark, term_type, res); ++ if (tmpvar_6) { ++ return res; ++ } ++ p->mark = mark; ++ void *raw = term_raw(p); ++ if (raw == NULL || p->mark <= resmark) ++ break; ++ resmark = p->mark; ++ res = raw; ++ } ++ p->mark = resmark; ++ return res; ++} ++static expr_ty ++term_raw(Parser *p) ++{ ++ if (p->error_indicator) { ++ return NULL; ++ } ++ expr_ty res = NULL; ++ int mark = p->mark; ++ if (p->mark == p->fill && _PyPegen_fill_token(p) < 0) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ int start_lineno = p->tokens[mark]->lineno; ++ UNUSED(start_lineno); // Only used by EXTRA macro ++ int start_col_offset = p->tokens[mark]->col_offset; ++ UNUSED(start_col_offset); // Only used by EXTRA macro ++ { // term '*' factor ++ expr_ty a; ++ expr_ty b; ++ void *literal; ++ if ( ++ (a = term_rule(p)) ++ && ++ (literal = _PyPegen_expect_token(p, 16)) ++ && ++ (b = factor_rule(p)) ++ ) ++ { ++ Token *token = _PyPegen_get_last_nonnwhitespace_token(p); ++ if (token == NULL) { ++ return NULL; ++ } ++ int end_lineno = token->end_lineno; ++ UNUSED(end_lineno); // Only used by EXTRA macro ++ int end_col_offset = token->end_col_offset; ++ UNUSED(end_col_offset); // Only used by EXTRA macro ++ res = _Py_BinOp ( a , Mult , b , EXTRA ); ++ if (res == NULL && PyErr_Occurred()) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ goto done; ++ } ++ p->mark = mark; ++ } ++ { // term '/' factor ++ expr_ty a; ++ expr_ty b; ++ void *literal; ++ if ( ++ (a = term_rule(p)) ++ && ++ (literal = _PyPegen_expect_token(p, 17)) ++ && ++ (b = factor_rule(p)) ++ ) ++ { ++ Token *token = _PyPegen_get_last_nonnwhitespace_token(p); ++ if (token == NULL) { ++ return NULL; ++ } ++ int end_lineno = token->end_lineno; ++ UNUSED(end_lineno); // Only used by EXTRA macro ++ int end_col_offset = token->end_col_offset; ++ UNUSED(end_col_offset); // Only used by EXTRA macro ++ res = _Py_BinOp ( a , Div , b , EXTRA ); ++ if (res == NULL && PyErr_Occurred()) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ goto done; ++ } ++ p->mark = mark; ++ } ++ { // term '//' factor ++ expr_ty a; ++ expr_ty b; ++ void *literal; ++ if ( ++ (a = term_rule(p)) ++ && ++ (literal = _PyPegen_expect_token(p, 47)) ++ && ++ (b = factor_rule(p)) ++ ) ++ { ++ Token *token = _PyPegen_get_last_nonnwhitespace_token(p); ++ if (token == NULL) { ++ return NULL; ++ } ++ int end_lineno = token->end_lineno; ++ UNUSED(end_lineno); // Only used by EXTRA macro ++ int end_col_offset = token->end_col_offset; ++ UNUSED(end_col_offset); // Only used by EXTRA macro ++ res = _Py_BinOp ( a , FloorDiv , b , EXTRA ); ++ if (res == NULL && PyErr_Occurred()) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ goto done; ++ } ++ p->mark = mark; ++ } ++ { // term '%' factor ++ expr_ty a; ++ expr_ty b; ++ void *literal; ++ if ( ++ (a = term_rule(p)) ++ && ++ (literal = _PyPegen_expect_token(p, 24)) ++ && ++ (b = factor_rule(p)) ++ ) ++ { ++ Token *token = _PyPegen_get_last_nonnwhitespace_token(p); ++ if (token == NULL) { ++ return NULL; ++ } ++ int end_lineno = token->end_lineno; ++ UNUSED(end_lineno); // Only used by EXTRA macro ++ int end_col_offset = token->end_col_offset; ++ UNUSED(end_col_offset); // Only used by EXTRA macro ++ res = _Py_BinOp ( a , Mod , b , EXTRA ); ++ if (res == NULL && PyErr_Occurred()) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ goto done; ++ } ++ p->mark = mark; ++ } ++ { // term '@' factor ++ expr_ty a; ++ expr_ty b; ++ void *literal; ++ if ( ++ (a = term_rule(p)) ++ && ++ (literal = _PyPegen_expect_token(p, 49)) ++ && ++ (b = factor_rule(p)) ++ ) ++ { ++ Token *token = _PyPegen_get_last_nonnwhitespace_token(p); ++ if (token == NULL) { ++ return NULL; ++ } ++ int end_lineno = token->end_lineno; ++ UNUSED(end_lineno); // Only used by EXTRA macro ++ int end_col_offset = token->end_col_offset; ++ UNUSED(end_col_offset); // Only used by EXTRA macro ++ res = _Py_BinOp ( a , MatMult , b , EXTRA ); ++ if (res == NULL && PyErr_Occurred()) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ goto done; ++ } ++ p->mark = mark; ++ } ++ { // factor ++ expr_ty factor_var; ++ if ( ++ (factor_var = factor_rule(p)) ++ ) ++ { ++ res = factor_var; ++ goto done; ++ } ++ p->mark = mark; ++ } ++ res = NULL; ++ done: ++ return res; ++} ++ ++// factor: '+' factor | '-' factor | '~' factor | power ++static expr_ty ++factor_rule(Parser *p) ++{ ++ if (p->error_indicator) { ++ return NULL; ++ } ++ expr_ty res = NULL; ++ if (_PyPegen_is_memoized(p, factor_type, &res)) ++ return res; ++ int mark = p->mark; ++ if (p->mark == p->fill && _PyPegen_fill_token(p) < 0) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ int start_lineno = p->tokens[mark]->lineno; ++ UNUSED(start_lineno); // Only used by EXTRA macro ++ int start_col_offset = p->tokens[mark]->col_offset; ++ UNUSED(start_col_offset); // Only used by EXTRA macro ++ { // '+' factor ++ expr_ty a; ++ void *literal; ++ if ( ++ (literal = _PyPegen_expect_token(p, 14)) ++ && ++ (a = factor_rule(p)) ++ ) ++ { ++ Token *token = _PyPegen_get_last_nonnwhitespace_token(p); ++ if (token == NULL) { ++ return NULL; ++ } ++ int end_lineno = token->end_lineno; ++ UNUSED(end_lineno); // Only used by EXTRA macro ++ int end_col_offset = token->end_col_offset; ++ UNUSED(end_col_offset); // Only used by EXTRA macro ++ res = _Py_UnaryOp ( UAdd , a , EXTRA ); ++ if (res == NULL && PyErr_Occurred()) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ goto done; ++ } ++ p->mark = mark; ++ } ++ { // '-' factor ++ expr_ty a; ++ void *literal; ++ if ( ++ (literal = _PyPegen_expect_token(p, 15)) ++ && ++ (a = factor_rule(p)) ++ ) ++ { ++ Token *token = _PyPegen_get_last_nonnwhitespace_token(p); ++ if (token == NULL) { ++ return NULL; ++ } ++ int end_lineno = token->end_lineno; ++ UNUSED(end_lineno); // Only used by EXTRA macro ++ int end_col_offset = token->end_col_offset; ++ UNUSED(end_col_offset); // Only used by EXTRA macro ++ res = _Py_UnaryOp ( USub , a , EXTRA ); ++ if (res == NULL && PyErr_Occurred()) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ goto done; ++ } ++ p->mark = mark; ++ } ++ { // '~' factor ++ expr_ty a; ++ void *literal; ++ if ( ++ (literal = _PyPegen_expect_token(p, 31)) ++ && ++ (a = factor_rule(p)) ++ ) ++ { ++ Token *token = _PyPegen_get_last_nonnwhitespace_token(p); ++ if (token == NULL) { ++ return NULL; ++ } ++ int end_lineno = token->end_lineno; ++ UNUSED(end_lineno); // Only used by EXTRA macro ++ int end_col_offset = token->end_col_offset; ++ UNUSED(end_col_offset); // Only used by EXTRA macro ++ res = _Py_UnaryOp ( Invert , a , EXTRA ); ++ if (res == NULL && PyErr_Occurred()) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ goto done; ++ } ++ p->mark = mark; ++ } ++ { // power ++ expr_ty power_var; ++ if ( ++ (power_var = power_rule(p)) ++ ) ++ { ++ res = power_var; ++ goto done; ++ } ++ p->mark = mark; ++ } ++ res = NULL; ++ done: ++ _PyPegen_insert_memo(p, mark, factor_type, res); ++ return res; ++} ++ ++// power: await_primary '**' factor | await_primary ++static expr_ty ++power_rule(Parser *p) ++{ ++ if (p->error_indicator) { ++ return NULL; ++ } ++ expr_ty res = NULL; ++ int mark = p->mark; ++ if (p->mark == p->fill && _PyPegen_fill_token(p) < 0) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ int start_lineno = p->tokens[mark]->lineno; ++ UNUSED(start_lineno); // Only used by EXTRA macro ++ int start_col_offset = p->tokens[mark]->col_offset; ++ UNUSED(start_col_offset); // Only used by EXTRA macro ++ { // await_primary '**' factor ++ expr_ty a; ++ expr_ty b; ++ void *literal; ++ if ( ++ (a = await_primary_rule(p)) ++ && ++ (literal = _PyPegen_expect_token(p, 35)) ++ && ++ (b = factor_rule(p)) ++ ) ++ { ++ Token *token = _PyPegen_get_last_nonnwhitespace_token(p); ++ if (token == NULL) { ++ return NULL; ++ } ++ int end_lineno = token->end_lineno; ++ UNUSED(end_lineno); // Only used by EXTRA macro ++ int end_col_offset = token->end_col_offset; ++ UNUSED(end_col_offset); // Only used by EXTRA macro ++ res = _Py_BinOp ( a , Pow , b , EXTRA ); ++ if (res == NULL && PyErr_Occurred()) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ goto done; ++ } ++ p->mark = mark; ++ } ++ { // await_primary ++ expr_ty await_primary_var; ++ if ( ++ (await_primary_var = await_primary_rule(p)) ++ ) ++ { ++ res = await_primary_var; ++ goto done; ++ } ++ p->mark = mark; ++ } ++ res = NULL; ++ done: ++ return res; ++} ++ ++// await_primary: AWAIT primary | primary ++static expr_ty ++await_primary_rule(Parser *p) ++{ ++ if (p->error_indicator) { ++ return NULL; ++ } ++ expr_ty res = NULL; ++ if (_PyPegen_is_memoized(p, await_primary_type, &res)) ++ return res; ++ int mark = p->mark; ++ if (p->mark == p->fill && _PyPegen_fill_token(p) < 0) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ int start_lineno = p->tokens[mark]->lineno; ++ UNUSED(start_lineno); // Only used by EXTRA macro ++ int start_col_offset = p->tokens[mark]->col_offset; ++ UNUSED(start_col_offset); // Only used by EXTRA macro ++ { // AWAIT primary ++ expr_ty a; ++ void *await_var; ++ if ( ++ (await_var = _PyPegen_await_token(p)) ++ && ++ (a = primary_rule(p)) ++ ) ++ { ++ Token *token = _PyPegen_get_last_nonnwhitespace_token(p); ++ if (token == NULL) { ++ return NULL; ++ } ++ int end_lineno = token->end_lineno; ++ UNUSED(end_lineno); // Only used by EXTRA macro ++ int end_col_offset = token->end_col_offset; ++ UNUSED(end_col_offset); // Only used by EXTRA macro ++ res = _Py_Await ( a , EXTRA ); ++ if (res == NULL && PyErr_Occurred()) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ goto done; ++ } ++ p->mark = mark; ++ } ++ { // primary ++ expr_ty primary_var; ++ if ( ++ (primary_var = primary_rule(p)) ++ ) ++ { ++ res = primary_var; ++ goto done; ++ } ++ p->mark = mark; ++ } ++ res = NULL; ++ done: ++ _PyPegen_insert_memo(p, mark, await_primary_type, res); ++ return res; ++} ++ ++// Left-recursive ++// primary: ++// | primary '.' NAME ++// | primary genexp ++// | primary '(' arguments? ')' ++// | primary '[' slices ']' ++// | atom ++static expr_ty primary_raw(Parser *); ++static expr_ty ++primary_rule(Parser *p) ++{ ++ expr_ty res = NULL; ++ if (_PyPegen_is_memoized(p, primary_type, &res)) ++ return res; ++ int mark = p->mark; ++ int resmark = p->mark; ++ while (1) { ++ int tmpvar_7 = _PyPegen_update_memo(p, mark, primary_type, res); ++ if (tmpvar_7) { ++ return res; ++ } ++ p->mark = mark; ++ void *raw = primary_raw(p); ++ if (raw == NULL || p->mark <= resmark) ++ break; ++ resmark = p->mark; ++ res = raw; ++ } ++ p->mark = resmark; ++ return res; ++} ++static expr_ty ++primary_raw(Parser *p) ++{ ++ if (p->error_indicator) { ++ return NULL; ++ } ++ expr_ty res = NULL; ++ int mark = p->mark; ++ if (p->mark == p->fill && _PyPegen_fill_token(p) < 0) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ int start_lineno = p->tokens[mark]->lineno; ++ UNUSED(start_lineno); // Only used by EXTRA macro ++ int start_col_offset = p->tokens[mark]->col_offset; ++ UNUSED(start_col_offset); // Only used by EXTRA macro ++ { // primary '.' NAME ++ expr_ty a; ++ expr_ty b; ++ void *literal; ++ if ( ++ (a = primary_rule(p)) ++ && ++ (literal = _PyPegen_expect_token(p, 23)) ++ && ++ (b = _PyPegen_name_token(p)) ++ ) ++ { ++ Token *token = _PyPegen_get_last_nonnwhitespace_token(p); ++ if (token == NULL) { ++ return NULL; ++ } ++ int end_lineno = token->end_lineno; ++ UNUSED(end_lineno); // Only used by EXTRA macro ++ int end_col_offset = token->end_col_offset; ++ UNUSED(end_col_offset); // Only used by EXTRA macro ++ res = _Py_Attribute ( a , b -> v . Name . id , Load , EXTRA ); ++ if (res == NULL && PyErr_Occurred()) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ goto done; ++ } ++ p->mark = mark; ++ } ++ { // primary genexp ++ expr_ty a; ++ expr_ty b; ++ if ( ++ (a = primary_rule(p)) ++ && ++ (b = genexp_rule(p)) ++ ) ++ { ++ Token *token = _PyPegen_get_last_nonnwhitespace_token(p); ++ if (token == NULL) { ++ return NULL; ++ } ++ int end_lineno = token->end_lineno; ++ UNUSED(end_lineno); // Only used by EXTRA macro ++ int end_col_offset = token->end_col_offset; ++ UNUSED(end_col_offset); // Only used by EXTRA macro ++ res = _Py_Call ( a , CHECK ( _PyPegen_singleton_seq ( p , b ) ) , NULL , EXTRA ); ++ if (res == NULL && PyErr_Occurred()) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ goto done; ++ } ++ p->mark = mark; ++ } ++ { // primary '(' arguments? ')' ++ expr_ty a; ++ void *b; ++ void *literal; ++ void *literal_1; ++ if ( ++ (a = primary_rule(p)) ++ && ++ (literal = _PyPegen_expect_token(p, 7)) ++ && ++ (b = arguments_rule(p), 1) ++ && ++ (literal_1 = _PyPegen_expect_token(p, 8)) ++ ) ++ { ++ Token *token = _PyPegen_get_last_nonnwhitespace_token(p); ++ if (token == NULL) { ++ return NULL; ++ } ++ int end_lineno = token->end_lineno; ++ UNUSED(end_lineno); // Only used by EXTRA macro ++ int end_col_offset = token->end_col_offset; ++ UNUSED(end_col_offset); // Only used by EXTRA macro ++ res = _Py_Call ( a , ( b ) ? ( ( expr_ty ) b ) -> v . Call . args : NULL , ( b ) ? ( ( expr_ty ) b ) -> v . Call . keywords : NULL , EXTRA ); ++ if (res == NULL && PyErr_Occurred()) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ goto done; ++ } ++ p->mark = mark; ++ } ++ { // primary '[' slices ']' ++ expr_ty a; ++ expr_ty b; ++ void *literal; ++ void *literal_1; ++ if ( ++ (a = primary_rule(p)) ++ && ++ (literal = _PyPegen_expect_token(p, 9)) ++ && ++ (b = slices_rule(p)) ++ && ++ (literal_1 = _PyPegen_expect_token(p, 10)) ++ ) ++ { ++ Token *token = _PyPegen_get_last_nonnwhitespace_token(p); ++ if (token == NULL) { ++ return NULL; ++ } ++ int end_lineno = token->end_lineno; ++ UNUSED(end_lineno); // Only used by EXTRA macro ++ int end_col_offset = token->end_col_offset; ++ UNUSED(end_col_offset); // Only used by EXTRA macro ++ res = _Py_Subscript ( a , b , Load , EXTRA ); ++ if (res == NULL && PyErr_Occurred()) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ goto done; ++ } ++ p->mark = mark; ++ } ++ { // atom ++ expr_ty atom_var; ++ if ( ++ (atom_var = atom_rule(p)) ++ ) ++ { ++ res = atom_var; ++ goto done; ++ } ++ p->mark = mark; ++ } ++ res = NULL; ++ done: ++ return res; ++} ++ ++// slices: slice !',' | ','.slice+ ','? ++static expr_ty ++slices_rule(Parser *p) ++{ ++ if (p->error_indicator) { ++ return NULL; ++ } ++ expr_ty res = NULL; ++ int mark = p->mark; ++ if (p->mark == p->fill && _PyPegen_fill_token(p) < 0) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ int start_lineno = p->tokens[mark]->lineno; ++ UNUSED(start_lineno); // Only used by EXTRA macro ++ int start_col_offset = p->tokens[mark]->col_offset; ++ UNUSED(start_col_offset); // Only used by EXTRA macro ++ { // slice !',' ++ expr_ty a; ++ if ( ++ (a = slice_rule(p)) ++ && ++ _PyPegen_lookahead_with_int(0, _PyPegen_expect_token, p, 12) ++ ) ++ { ++ res = a; ++ if (res == NULL && PyErr_Occurred()) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ goto done; ++ } ++ p->mark = mark; ++ } ++ { // ','.slice+ ','? ++ asdl_seq * a; ++ void *opt_var; ++ UNUSED(opt_var); // Silence compiler warnings ++ if ( ++ (a = _gather_86_rule(p)) ++ && ++ (opt_var = _PyPegen_expect_token(p, 12), 1) ++ ) ++ { ++ Token *token = _PyPegen_get_last_nonnwhitespace_token(p); ++ if (token == NULL) { ++ return NULL; ++ } ++ int end_lineno = token->end_lineno; ++ UNUSED(end_lineno); // Only used by EXTRA macro ++ int end_col_offset = token->end_col_offset; ++ UNUSED(end_col_offset); // Only used by EXTRA macro ++ res = _Py_Tuple ( a , Load , EXTRA ); ++ if (res == NULL && PyErr_Occurred()) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ goto done; ++ } ++ p->mark = mark; ++ } ++ res = NULL; ++ done: ++ return res; ++} ++ ++// slice: expression? ':' expression? [':' expression?] | expression ++static expr_ty ++slice_rule(Parser *p) ++{ ++ if (p->error_indicator) { ++ return NULL; ++ } ++ expr_ty res = NULL; ++ int mark = p->mark; ++ if (p->mark == p->fill && _PyPegen_fill_token(p) < 0) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ int start_lineno = p->tokens[mark]->lineno; ++ UNUSED(start_lineno); // Only used by EXTRA macro ++ int start_col_offset = p->tokens[mark]->col_offset; ++ UNUSED(start_col_offset); // Only used by EXTRA macro ++ { // expression? ':' expression? [':' expression?] ++ void *a; ++ void *b; ++ void *c; ++ void *literal; ++ if ( ++ (a = expression_rule(p), 1) ++ && ++ (literal = _PyPegen_expect_token(p, 11)) ++ && ++ (b = expression_rule(p), 1) ++ && ++ (c = _tmp_88_rule(p), 1) ++ ) ++ { ++ Token *token = _PyPegen_get_last_nonnwhitespace_token(p); ++ if (token == NULL) { ++ return NULL; ++ } ++ int end_lineno = token->end_lineno; ++ UNUSED(end_lineno); // Only used by EXTRA macro ++ int end_col_offset = token->end_col_offset; ++ UNUSED(end_col_offset); // Only used by EXTRA macro ++ res = _Py_Slice ( a , b , c , EXTRA ); ++ if (res == NULL && PyErr_Occurred()) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ goto done; ++ } ++ p->mark = mark; ++ } ++ { // expression ++ expr_ty a; ++ if ( ++ (a = expression_rule(p)) ++ ) ++ { ++ res = a; ++ if (res == NULL && PyErr_Occurred()) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ goto done; ++ } ++ p->mark = mark; ++ } ++ res = NULL; ++ done: ++ return res; ++} ++ ++// atom: ++// | NAME ++// | 'True' ++// | 'False' ++// | 'None' ++// | '__new_parser__' ++// | &STRING strings ++// | NUMBER ++// | &'(' (tuple | group | genexp) ++// | &'[' (list | listcomp) ++// | &'{' (dict | set | dictcomp | setcomp) ++// | '...' ++static expr_ty ++atom_rule(Parser *p) ++{ ++ if (p->error_indicator) { ++ return NULL; ++ } ++ expr_ty res = NULL; ++ int mark = p->mark; ++ if (p->mark == p->fill && _PyPegen_fill_token(p) < 0) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ int start_lineno = p->tokens[mark]->lineno; ++ UNUSED(start_lineno); // Only used by EXTRA macro ++ int start_col_offset = p->tokens[mark]->col_offset; ++ UNUSED(start_col_offset); // Only used by EXTRA macro ++ { // NAME ++ expr_ty name_var; ++ if ( ++ (name_var = _PyPegen_name_token(p)) ++ ) ++ { ++ res = name_var; ++ goto done; ++ } ++ p->mark = mark; ++ } ++ { // 'True' ++ void *keyword; ++ if ( ++ (keyword = _PyPegen_expect_token(p, 527)) ++ ) ++ { ++ Token *token = _PyPegen_get_last_nonnwhitespace_token(p); ++ if (token == NULL) { ++ return NULL; ++ } ++ int end_lineno = token->end_lineno; ++ UNUSED(end_lineno); // Only used by EXTRA macro ++ int end_col_offset = token->end_col_offset; ++ UNUSED(end_col_offset); // Only used by EXTRA macro ++ res = _Py_Constant ( Py_True , NULL , EXTRA ); ++ if (res == NULL && PyErr_Occurred()) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ goto done; ++ } ++ p->mark = mark; ++ } ++ { // 'False' ++ void *keyword; ++ if ( ++ (keyword = _PyPegen_expect_token(p, 528)) ++ ) ++ { ++ Token *token = _PyPegen_get_last_nonnwhitespace_token(p); ++ if (token == NULL) { ++ return NULL; ++ } ++ int end_lineno = token->end_lineno; ++ UNUSED(end_lineno); // Only used by EXTRA macro ++ int end_col_offset = token->end_col_offset; ++ UNUSED(end_col_offset); // Only used by EXTRA macro ++ res = _Py_Constant ( Py_False , NULL , EXTRA ); ++ if (res == NULL && PyErr_Occurred()) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ goto done; ++ } ++ p->mark = mark; ++ } ++ { // 'None' ++ void *keyword; ++ if ( ++ (keyword = _PyPegen_expect_token(p, 529)) ++ ) ++ { ++ Token *token = _PyPegen_get_last_nonnwhitespace_token(p); ++ if (token == NULL) { ++ return NULL; ++ } ++ int end_lineno = token->end_lineno; ++ UNUSED(end_lineno); // Only used by EXTRA macro ++ int end_col_offset = token->end_col_offset; ++ UNUSED(end_col_offset); // Only used by EXTRA macro ++ res = _Py_Constant ( Py_None , NULL , EXTRA ); ++ if (res == NULL && PyErr_Occurred()) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ goto done; ++ } ++ p->mark = mark; ++ } ++ { // '__new_parser__' ++ void *keyword; ++ if ( ++ (keyword = _PyPegen_expect_token(p, 530)) ++ ) ++ { ++ res = RAISE_SYNTAX_ERROR ( "You found it!" ); ++ if (res == NULL && PyErr_Occurred()) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ goto done; ++ } ++ p->mark = mark; ++ } ++ { // &STRING strings ++ expr_ty strings_var; ++ if ( ++ _PyPegen_lookahead(1, _PyPegen_string_token, p) ++ && ++ (strings_var = strings_rule(p)) ++ ) ++ { ++ res = strings_var; ++ goto done; ++ } ++ p->mark = mark; ++ } ++ { // NUMBER ++ expr_ty number_var; ++ if ( ++ (number_var = _PyPegen_number_token(p)) ++ ) ++ { ++ res = number_var; ++ goto done; ++ } ++ p->mark = mark; ++ } ++ { // &'(' (tuple | group | genexp) ++ void *_tmp_89_var; ++ if ( ++ _PyPegen_lookahead_with_int(1, _PyPegen_expect_token, p, 7) ++ && ++ (_tmp_89_var = _tmp_89_rule(p)) ++ ) ++ { ++ res = _tmp_89_var; ++ goto done; ++ } ++ p->mark = mark; ++ } ++ { // &'[' (list | listcomp) ++ void *_tmp_90_var; ++ if ( ++ _PyPegen_lookahead_with_int(1, _PyPegen_expect_token, p, 9) ++ && ++ (_tmp_90_var = _tmp_90_rule(p)) ++ ) ++ { ++ res = _tmp_90_var; ++ goto done; ++ } ++ p->mark = mark; ++ } ++ { // &'{' (dict | set | dictcomp | setcomp) ++ void *_tmp_91_var; ++ if ( ++ _PyPegen_lookahead_with_int(1, _PyPegen_expect_token, p, 25) ++ && ++ (_tmp_91_var = _tmp_91_rule(p)) ++ ) ++ { ++ res = _tmp_91_var; ++ goto done; ++ } ++ p->mark = mark; ++ } ++ { // '...' ++ void *literal; ++ if ( ++ (literal = _PyPegen_expect_token(p, 52)) ++ ) ++ { ++ Token *token = _PyPegen_get_last_nonnwhitespace_token(p); ++ if (token == NULL) { ++ return NULL; ++ } ++ int end_lineno = token->end_lineno; ++ UNUSED(end_lineno); // Only used by EXTRA macro ++ int end_col_offset = token->end_col_offset; ++ UNUSED(end_col_offset); // Only used by EXTRA macro ++ res = _Py_Constant ( Py_Ellipsis , NULL , EXTRA ); ++ if (res == NULL && PyErr_Occurred()) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ goto done; ++ } ++ p->mark = mark; ++ } ++ res = NULL; ++ done: ++ return res; ++} ++ ++// strings: STRING+ ++static expr_ty ++strings_rule(Parser *p) ++{ ++ if (p->error_indicator) { ++ return NULL; ++ } ++ expr_ty res = NULL; ++ if (_PyPegen_is_memoized(p, strings_type, &res)) ++ return res; ++ int mark = p->mark; ++ { // STRING+ ++ asdl_seq * a; ++ if ( ++ (a = _loop1_92_rule(p)) ++ ) ++ { ++ res = _PyPegen_concatenate_strings ( p , a ); ++ if (res == NULL && PyErr_Occurred()) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ goto done; ++ } ++ p->mark = mark; ++ } ++ res = NULL; ++ done: ++ _PyPegen_insert_memo(p, mark, strings_type, res); ++ return res; ++} ++ ++// list: '[' star_named_expressions? ']' ++static expr_ty ++list_rule(Parser *p) ++{ ++ if (p->error_indicator) { ++ return NULL; ++ } ++ expr_ty res = NULL; ++ int mark = p->mark; ++ if (p->mark == p->fill && _PyPegen_fill_token(p) < 0) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ int start_lineno = p->tokens[mark]->lineno; ++ UNUSED(start_lineno); // Only used by EXTRA macro ++ int start_col_offset = p->tokens[mark]->col_offset; ++ UNUSED(start_col_offset); // Only used by EXTRA macro ++ { // '[' star_named_expressions? ']' ++ void *a; ++ void *literal; ++ void *literal_1; ++ if ( ++ (literal = _PyPegen_expect_token(p, 9)) ++ && ++ (a = star_named_expressions_rule(p), 1) ++ && ++ (literal_1 = _PyPegen_expect_token(p, 10)) ++ ) ++ { ++ Token *token = _PyPegen_get_last_nonnwhitespace_token(p); ++ if (token == NULL) { ++ return NULL; ++ } ++ int end_lineno = token->end_lineno; ++ UNUSED(end_lineno); // Only used by EXTRA macro ++ int end_col_offset = token->end_col_offset; ++ UNUSED(end_col_offset); // Only used by EXTRA macro ++ res = _Py_List ( a , Load , EXTRA ); ++ if (res == NULL && PyErr_Occurred()) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ goto done; ++ } ++ p->mark = mark; ++ } ++ res = NULL; ++ done: ++ return res; ++} ++ ++// listcomp: '[' named_expression for_if_clauses ']' | invalid_comprehension ++static expr_ty ++listcomp_rule(Parser *p) ++{ ++ if (p->error_indicator) { ++ return NULL; ++ } ++ expr_ty res = NULL; ++ int mark = p->mark; ++ if (p->mark == p->fill && _PyPegen_fill_token(p) < 0) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ int start_lineno = p->tokens[mark]->lineno; ++ UNUSED(start_lineno); // Only used by EXTRA macro ++ int start_col_offset = p->tokens[mark]->col_offset; ++ UNUSED(start_col_offset); // Only used by EXTRA macro ++ { // '[' named_expression for_if_clauses ']' ++ expr_ty a; ++ asdl_seq* b; ++ void *literal; ++ void *literal_1; ++ if ( ++ (literal = _PyPegen_expect_token(p, 9)) ++ && ++ (a = named_expression_rule(p)) ++ && ++ (b = for_if_clauses_rule(p)) ++ && ++ (literal_1 = _PyPegen_expect_token(p, 10)) ++ ) ++ { ++ Token *token = _PyPegen_get_last_nonnwhitespace_token(p); ++ if (token == NULL) { ++ return NULL; ++ } ++ int end_lineno = token->end_lineno; ++ UNUSED(end_lineno); // Only used by EXTRA macro ++ int end_col_offset = token->end_col_offset; ++ UNUSED(end_col_offset); // Only used by EXTRA macro ++ res = _Py_ListComp ( a , b , EXTRA ); ++ if (res == NULL && PyErr_Occurred()) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ goto done; ++ } ++ p->mark = mark; ++ } ++ { // invalid_comprehension ++ void *invalid_comprehension_var; ++ if ( ++ (invalid_comprehension_var = invalid_comprehension_rule(p)) ++ ) ++ { ++ res = invalid_comprehension_var; ++ goto done; ++ } ++ p->mark = mark; ++ } ++ res = NULL; ++ done: ++ return res; ++} ++ ++// tuple: '(' [star_named_expression ',' star_named_expressions?] ')' ++static expr_ty ++tuple_rule(Parser *p) ++{ ++ if (p->error_indicator) { ++ return NULL; ++ } ++ expr_ty res = NULL; ++ int mark = p->mark; ++ if (p->mark == p->fill && _PyPegen_fill_token(p) < 0) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ int start_lineno = p->tokens[mark]->lineno; ++ UNUSED(start_lineno); // Only used by EXTRA macro ++ int start_col_offset = p->tokens[mark]->col_offset; ++ UNUSED(start_col_offset); // Only used by EXTRA macro ++ { // '(' [star_named_expression ',' star_named_expressions?] ')' ++ void *a; ++ void *literal; ++ void *literal_1; ++ if ( ++ (literal = _PyPegen_expect_token(p, 7)) ++ && ++ (a = _tmp_93_rule(p), 1) ++ && ++ (literal_1 = _PyPegen_expect_token(p, 8)) ++ ) ++ { ++ Token *token = _PyPegen_get_last_nonnwhitespace_token(p); ++ if (token == NULL) { ++ return NULL; ++ } ++ int end_lineno = token->end_lineno; ++ UNUSED(end_lineno); // Only used by EXTRA macro ++ int end_col_offset = token->end_col_offset; ++ UNUSED(end_col_offset); // Only used by EXTRA macro ++ res = _Py_Tuple ( a , Load , EXTRA ); ++ if (res == NULL && PyErr_Occurred()) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ goto done; ++ } ++ p->mark = mark; ++ } ++ res = NULL; ++ done: ++ return res; ++} ++ ++// group: '(' (yield_expr | named_expression) ')' ++static expr_ty ++group_rule(Parser *p) ++{ ++ if (p->error_indicator) { ++ return NULL; ++ } ++ expr_ty res = NULL; ++ int mark = p->mark; ++ { // '(' (yield_expr | named_expression) ')' ++ void *a; ++ void *literal; ++ void *literal_1; ++ if ( ++ (literal = _PyPegen_expect_token(p, 7)) ++ && ++ (a = _tmp_94_rule(p)) ++ && ++ (literal_1 = _PyPegen_expect_token(p, 8)) ++ ) ++ { ++ res = a; ++ if (res == NULL && PyErr_Occurred()) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ goto done; ++ } ++ p->mark = mark; ++ } ++ res = NULL; ++ done: ++ return res; ++} ++ ++// genexp: '(' expression for_if_clauses ')' | invalid_comprehension ++static expr_ty ++genexp_rule(Parser *p) ++{ ++ if (p->error_indicator) { ++ return NULL; ++ } ++ expr_ty res = NULL; ++ int mark = p->mark; ++ if (p->mark == p->fill && _PyPegen_fill_token(p) < 0) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ int start_lineno = p->tokens[mark]->lineno; ++ UNUSED(start_lineno); // Only used by EXTRA macro ++ int start_col_offset = p->tokens[mark]->col_offset; ++ UNUSED(start_col_offset); // Only used by EXTRA macro ++ { // '(' expression for_if_clauses ')' ++ expr_ty a; ++ asdl_seq* b; ++ void *literal; ++ void *literal_1; ++ if ( ++ (literal = _PyPegen_expect_token(p, 7)) ++ && ++ (a = expression_rule(p)) ++ && ++ (b = for_if_clauses_rule(p)) ++ && ++ (literal_1 = _PyPegen_expect_token(p, 8)) ++ ) ++ { ++ Token *token = _PyPegen_get_last_nonnwhitespace_token(p); ++ if (token == NULL) { ++ return NULL; ++ } ++ int end_lineno = token->end_lineno; ++ UNUSED(end_lineno); // Only used by EXTRA macro ++ int end_col_offset = token->end_col_offset; ++ UNUSED(end_col_offset); // Only used by EXTRA macro ++ res = _Py_GeneratorExp ( a , b , EXTRA ); ++ if (res == NULL && PyErr_Occurred()) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ goto done; ++ } ++ p->mark = mark; ++ } ++ { // invalid_comprehension ++ void *invalid_comprehension_var; ++ if ( ++ (invalid_comprehension_var = invalid_comprehension_rule(p)) ++ ) ++ { ++ res = invalid_comprehension_var; ++ goto done; ++ } ++ p->mark = mark; ++ } ++ res = NULL; ++ done: ++ return res; ++} ++ ++// set: '{' expressions_list '}' ++static expr_ty ++set_rule(Parser *p) ++{ ++ if (p->error_indicator) { ++ return NULL; ++ } ++ expr_ty res = NULL; ++ int mark = p->mark; ++ if (p->mark == p->fill && _PyPegen_fill_token(p) < 0) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ int start_lineno = p->tokens[mark]->lineno; ++ UNUSED(start_lineno); // Only used by EXTRA macro ++ int start_col_offset = p->tokens[mark]->col_offset; ++ UNUSED(start_col_offset); // Only used by EXTRA macro ++ { // '{' expressions_list '}' ++ asdl_seq* a; ++ void *literal; ++ void *literal_1; ++ if ( ++ (literal = _PyPegen_expect_token(p, 25)) ++ && ++ (a = expressions_list_rule(p)) ++ && ++ (literal_1 = _PyPegen_expect_token(p, 26)) ++ ) ++ { ++ Token *token = _PyPegen_get_last_nonnwhitespace_token(p); ++ if (token == NULL) { ++ return NULL; ++ } ++ int end_lineno = token->end_lineno; ++ UNUSED(end_lineno); // Only used by EXTRA macro ++ int end_col_offset = token->end_col_offset; ++ UNUSED(end_col_offset); // Only used by EXTRA macro ++ res = _Py_Set ( a , EXTRA ); ++ if (res == NULL && PyErr_Occurred()) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ goto done; ++ } ++ p->mark = mark; ++ } ++ res = NULL; ++ done: ++ return res; ++} ++ ++// setcomp: '{' expression for_if_clauses '}' | invalid_comprehension ++static expr_ty ++setcomp_rule(Parser *p) ++{ ++ if (p->error_indicator) { ++ return NULL; ++ } ++ expr_ty res = NULL; ++ int mark = p->mark; ++ if (p->mark == p->fill && _PyPegen_fill_token(p) < 0) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ int start_lineno = p->tokens[mark]->lineno; ++ UNUSED(start_lineno); // Only used by EXTRA macro ++ int start_col_offset = p->tokens[mark]->col_offset; ++ UNUSED(start_col_offset); // Only used by EXTRA macro ++ { // '{' expression for_if_clauses '}' ++ expr_ty a; ++ asdl_seq* b; ++ void *literal; ++ void *literal_1; ++ if ( ++ (literal = _PyPegen_expect_token(p, 25)) ++ && ++ (a = expression_rule(p)) ++ && ++ (b = for_if_clauses_rule(p)) ++ && ++ (literal_1 = _PyPegen_expect_token(p, 26)) ++ ) ++ { ++ Token *token = _PyPegen_get_last_nonnwhitespace_token(p); ++ if (token == NULL) { ++ return NULL; ++ } ++ int end_lineno = token->end_lineno; ++ UNUSED(end_lineno); // Only used by EXTRA macro ++ int end_col_offset = token->end_col_offset; ++ UNUSED(end_col_offset); // Only used by EXTRA macro ++ res = _Py_SetComp ( a , b , EXTRA ); ++ if (res == NULL && PyErr_Occurred()) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ goto done; ++ } ++ p->mark = mark; ++ } ++ { // invalid_comprehension ++ void *invalid_comprehension_var; ++ if ( ++ (invalid_comprehension_var = invalid_comprehension_rule(p)) ++ ) ++ { ++ res = invalid_comprehension_var; ++ goto done; ++ } ++ p->mark = mark; ++ } ++ res = NULL; ++ done: ++ return res; ++} ++ ++// dict: '{' kvpairs? '}' ++static expr_ty ++dict_rule(Parser *p) ++{ ++ if (p->error_indicator) { ++ return NULL; ++ } ++ expr_ty res = NULL; ++ int mark = p->mark; ++ if (p->mark == p->fill && _PyPegen_fill_token(p) < 0) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ int start_lineno = p->tokens[mark]->lineno; ++ UNUSED(start_lineno); // Only used by EXTRA macro ++ int start_col_offset = p->tokens[mark]->col_offset; ++ UNUSED(start_col_offset); // Only used by EXTRA macro ++ { // '{' kvpairs? '}' ++ void *a; ++ void *literal; ++ void *literal_1; ++ if ( ++ (literal = _PyPegen_expect_token(p, 25)) ++ && ++ (a = kvpairs_rule(p), 1) ++ && ++ (literal_1 = _PyPegen_expect_token(p, 26)) ++ ) ++ { ++ Token *token = _PyPegen_get_last_nonnwhitespace_token(p); ++ if (token == NULL) { ++ return NULL; ++ } ++ int end_lineno = token->end_lineno; ++ UNUSED(end_lineno); // Only used by EXTRA macro ++ int end_col_offset = token->end_col_offset; ++ UNUSED(end_col_offset); // Only used by EXTRA macro ++ res = _Py_Dict ( CHECK ( _PyPegen_get_keys ( p , a ) ) , CHECK ( _PyPegen_get_values ( p , a ) ) , EXTRA ); ++ if (res == NULL && PyErr_Occurred()) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ goto done; ++ } ++ p->mark = mark; ++ } ++ res = NULL; ++ done: ++ return res; ++} ++ ++// dictcomp: '{' kvpair for_if_clauses '}' ++static expr_ty ++dictcomp_rule(Parser *p) ++{ ++ if (p->error_indicator) { ++ return NULL; ++ } ++ expr_ty res = NULL; ++ int mark = p->mark; ++ if (p->mark == p->fill && _PyPegen_fill_token(p) < 0) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ int start_lineno = p->tokens[mark]->lineno; ++ UNUSED(start_lineno); // Only used by EXTRA macro ++ int start_col_offset = p->tokens[mark]->col_offset; ++ UNUSED(start_col_offset); // Only used by EXTRA macro ++ { // '{' kvpair for_if_clauses '}' ++ KeyValuePair* a; ++ asdl_seq* b; ++ void *literal; ++ void *literal_1; ++ if ( ++ (literal = _PyPegen_expect_token(p, 25)) ++ && ++ (a = kvpair_rule(p)) ++ && ++ (b = for_if_clauses_rule(p)) ++ && ++ (literal_1 = _PyPegen_expect_token(p, 26)) ++ ) ++ { ++ Token *token = _PyPegen_get_last_nonnwhitespace_token(p); ++ if (token == NULL) { ++ return NULL; ++ } ++ int end_lineno = token->end_lineno; ++ UNUSED(end_lineno); // Only used by EXTRA macro ++ int end_col_offset = token->end_col_offset; ++ UNUSED(end_col_offset); // Only used by EXTRA macro ++ res = _Py_DictComp ( a -> key , a -> value , b , EXTRA ); ++ if (res == NULL && PyErr_Occurred()) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ goto done; ++ } ++ p->mark = mark; ++ } ++ res = NULL; ++ done: ++ return res; ++} ++ ++// kvpairs: ','.kvpair+ ','? ++static asdl_seq* ++kvpairs_rule(Parser *p) ++{ ++ if (p->error_indicator) { ++ return NULL; ++ } ++ asdl_seq* res = NULL; ++ int mark = p->mark; ++ { // ','.kvpair+ ','? ++ asdl_seq * a; ++ void *opt_var; ++ UNUSED(opt_var); // Silence compiler warnings ++ if ( ++ (a = _gather_95_rule(p)) ++ && ++ (opt_var = _PyPegen_expect_token(p, 12), 1) ++ ) ++ { ++ res = a; ++ if (res == NULL && PyErr_Occurred()) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ goto done; ++ } ++ p->mark = mark; ++ } ++ res = NULL; ++ done: ++ return res; ++} ++ ++// kvpair: '**' bitwise_or | expression ':' expression ++static KeyValuePair* ++kvpair_rule(Parser *p) ++{ ++ if (p->error_indicator) { ++ return NULL; ++ } ++ KeyValuePair* res = NULL; ++ int mark = p->mark; ++ { // '**' bitwise_or ++ expr_ty a; ++ void *literal; ++ if ( ++ (literal = _PyPegen_expect_token(p, 35)) ++ && ++ (a = bitwise_or_rule(p)) ++ ) ++ { ++ res = _PyPegen_key_value_pair ( p , NULL , a ); ++ if (res == NULL && PyErr_Occurred()) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ goto done; ++ } ++ p->mark = mark; ++ } ++ { // expression ':' expression ++ expr_ty a; ++ expr_ty b; ++ void *literal; ++ if ( ++ (a = expression_rule(p)) ++ && ++ (literal = _PyPegen_expect_token(p, 11)) ++ && ++ (b = expression_rule(p)) ++ ) ++ { ++ res = _PyPegen_key_value_pair ( p , a , b ); ++ if (res == NULL && PyErr_Occurred()) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ goto done; ++ } ++ p->mark = mark; ++ } ++ res = NULL; ++ done: ++ return res; ++} ++ ++// for_if_clauses: ((ASYNC? 'for' star_targets 'in' disjunction (('if' disjunction))*))+ ++static asdl_seq* ++for_if_clauses_rule(Parser *p) ++{ ++ if (p->error_indicator) { ++ return NULL; ++ } ++ asdl_seq* res = NULL; ++ int mark = p->mark; ++ { // ((ASYNC? 'for' star_targets 'in' disjunction (('if' disjunction))*))+ ++ asdl_seq * a; ++ if ( ++ (a = _loop1_97_rule(p)) ++ ) ++ { ++ res = a; ++ if (res == NULL && PyErr_Occurred()) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ goto done; ++ } ++ p->mark = mark; ++ } ++ res = NULL; ++ done: ++ return res; ++} ++ ++// yield_expr: 'yield' 'from' expression | 'yield' star_expressions? ++static expr_ty ++yield_expr_rule(Parser *p) ++{ ++ if (p->error_indicator) { ++ return NULL; ++ } ++ expr_ty res = NULL; ++ int mark = p->mark; ++ if (p->mark == p->fill && _PyPegen_fill_token(p) < 0) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ int start_lineno = p->tokens[mark]->lineno; ++ UNUSED(start_lineno); // Only used by EXTRA macro ++ int start_col_offset = p->tokens[mark]->col_offset; ++ UNUSED(start_col_offset); // Only used by EXTRA macro ++ { // 'yield' 'from' expression ++ expr_ty a; ++ void *keyword; ++ void *keyword_1; ++ if ( ++ (keyword = _PyPegen_expect_token(p, 504)) ++ && ++ (keyword_1 = _PyPegen_expect_token(p, 514)) ++ && ++ (a = expression_rule(p)) ++ ) ++ { ++ Token *token = _PyPegen_get_last_nonnwhitespace_token(p); ++ if (token == NULL) { ++ return NULL; ++ } ++ int end_lineno = token->end_lineno; ++ UNUSED(end_lineno); // Only used by EXTRA macro ++ int end_col_offset = token->end_col_offset; ++ UNUSED(end_col_offset); // Only used by EXTRA macro ++ res = _Py_YieldFrom ( a , EXTRA ); ++ if (res == NULL && PyErr_Occurred()) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ goto done; ++ } ++ p->mark = mark; ++ } ++ { // 'yield' star_expressions? ++ void *a; ++ void *keyword; ++ if ( ++ (keyword = _PyPegen_expect_token(p, 504)) ++ && ++ (a = star_expressions_rule(p), 1) ++ ) ++ { ++ Token *token = _PyPegen_get_last_nonnwhitespace_token(p); ++ if (token == NULL) { ++ return NULL; ++ } ++ int end_lineno = token->end_lineno; ++ UNUSED(end_lineno); // Only used by EXTRA macro ++ int end_col_offset = token->end_col_offset; ++ UNUSED(end_col_offset); // Only used by EXTRA macro ++ res = _Py_Yield ( a , EXTRA ); ++ if (res == NULL && PyErr_Occurred()) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ goto done; ++ } ++ p->mark = mark; ++ } ++ res = NULL; ++ done: ++ return res; ++} ++ ++// arguments: args ','? &')' | incorrect_arguments ++static expr_ty ++arguments_rule(Parser *p) ++{ ++ if (p->error_indicator) { ++ return NULL; ++ } ++ expr_ty res = NULL; ++ if (_PyPegen_is_memoized(p, arguments_type, &res)) ++ return res; ++ int mark = p->mark; ++ { // args ','? &')' ++ expr_ty a; ++ void *opt_var; ++ UNUSED(opt_var); // Silence compiler warnings ++ if ( ++ (a = args_rule(p)) ++ && ++ (opt_var = _PyPegen_expect_token(p, 12), 1) ++ && ++ _PyPegen_lookahead_with_int(1, _PyPegen_expect_token, p, 8) ++ ) ++ { ++ res = a; ++ if (res == NULL && PyErr_Occurred()) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ goto done; ++ } ++ p->mark = mark; ++ } ++ { // incorrect_arguments ++ void *incorrect_arguments_var; ++ if ( ++ (incorrect_arguments_var = incorrect_arguments_rule(p)) ++ ) ++ { ++ res = incorrect_arguments_var; ++ goto done; ++ } ++ p->mark = mark; ++ } ++ res = NULL; ++ done: ++ _PyPegen_insert_memo(p, mark, arguments_type, res); ++ return res; ++} ++ ++// args: starred_expression [',' args] | kwargs | named_expression [',' args] ++static expr_ty ++args_rule(Parser *p) ++{ ++ if (p->error_indicator) { ++ return NULL; ++ } ++ expr_ty res = NULL; ++ int mark = p->mark; ++ if (p->mark == p->fill && _PyPegen_fill_token(p) < 0) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ int start_lineno = p->tokens[mark]->lineno; ++ UNUSED(start_lineno); // Only used by EXTRA macro ++ int start_col_offset = p->tokens[mark]->col_offset; ++ UNUSED(start_col_offset); // Only used by EXTRA macro ++ { // starred_expression [',' args] ++ expr_ty a; ++ void *b; ++ if ( ++ (a = starred_expression_rule(p)) ++ && ++ (b = _tmp_98_rule(p), 1) ++ ) ++ { ++ Token *token = _PyPegen_get_last_nonnwhitespace_token(p); ++ if (token == NULL) { ++ return NULL; ++ } ++ int end_lineno = token->end_lineno; ++ UNUSED(end_lineno); // Only used by EXTRA macro ++ int end_col_offset = token->end_col_offset; ++ UNUSED(end_col_offset); // Only used by EXTRA macro ++ res = _Py_Call ( _PyPegen_dummy_name ( p ) , ( b ) ? CHECK ( _PyPegen_seq_insert_in_front ( p , a , ( ( expr_ty ) b ) -> v . Call . args ) ) : CHECK ( _PyPegen_singleton_seq ( p , a ) ) , ( b ) ? ( ( expr_ty ) b ) -> v . Call . keywords : NULL , EXTRA ); ++ if (res == NULL && PyErr_Occurred()) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ goto done; ++ } ++ p->mark = mark; ++ } ++ { // kwargs ++ asdl_seq* a; ++ if ( ++ (a = kwargs_rule(p)) ++ ) ++ { ++ Token *token = _PyPegen_get_last_nonnwhitespace_token(p); ++ if (token == NULL) { ++ return NULL; ++ } ++ int end_lineno = token->end_lineno; ++ UNUSED(end_lineno); // Only used by EXTRA macro ++ int end_col_offset = token->end_col_offset; ++ UNUSED(end_col_offset); // Only used by EXTRA macro ++ res = _Py_Call ( _PyPegen_dummy_name ( p ) , CHECK_NULL_ALLOWED ( _PyPegen_seq_extract_starred_exprs ( p , a ) ) , CHECK_NULL_ALLOWED ( _PyPegen_seq_delete_starred_exprs ( p , a ) ) , EXTRA ); ++ if (res == NULL && PyErr_Occurred()) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ goto done; ++ } ++ p->mark = mark; ++ } ++ { // named_expression [',' args] ++ expr_ty a; ++ void *b; ++ if ( ++ (a = named_expression_rule(p)) ++ && ++ (b = _tmp_99_rule(p), 1) ++ ) ++ { ++ Token *token = _PyPegen_get_last_nonnwhitespace_token(p); ++ if (token == NULL) { ++ return NULL; ++ } ++ int end_lineno = token->end_lineno; ++ UNUSED(end_lineno); // Only used by EXTRA macro ++ int end_col_offset = token->end_col_offset; ++ UNUSED(end_col_offset); // Only used by EXTRA macro ++ res = _Py_Call ( _PyPegen_dummy_name ( p ) , ( b ) ? CHECK ( _PyPegen_seq_insert_in_front ( p , a , ( ( expr_ty ) b ) -> v . Call . args ) ) : CHECK ( _PyPegen_singleton_seq ( p , a ) ) , ( b ) ? ( ( expr_ty ) b ) -> v . Call . keywords : NULL , EXTRA ); ++ if (res == NULL && PyErr_Occurred()) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ goto done; ++ } ++ p->mark = mark; ++ } ++ res = NULL; ++ done: ++ return res; ++} ++ ++// kwargs: ++// | ','.kwarg_or_starred+ ',' ','.kwarg_or_double_starred+ ++// | ','.kwarg_or_starred+ ++// | ','.kwarg_or_double_starred+ ++static asdl_seq* ++kwargs_rule(Parser *p) ++{ ++ if (p->error_indicator) { ++ return NULL; ++ } ++ asdl_seq* res = NULL; ++ int mark = p->mark; ++ { // ','.kwarg_or_starred+ ',' ','.kwarg_or_double_starred+ ++ asdl_seq * a; ++ asdl_seq * b; ++ void *literal; ++ if ( ++ (a = _gather_100_rule(p)) ++ && ++ (literal = _PyPegen_expect_token(p, 12)) ++ && ++ (b = _gather_102_rule(p)) ++ ) ++ { ++ res = _PyPegen_join_sequences ( p , a , b ); ++ if (res == NULL && PyErr_Occurred()) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ goto done; ++ } ++ p->mark = mark; ++ } ++ { // ','.kwarg_or_starred+ ++ asdl_seq * _gather_104_var; ++ if ( ++ (_gather_104_var = _gather_104_rule(p)) ++ ) ++ { ++ res = _gather_104_var; ++ goto done; ++ } ++ p->mark = mark; ++ } ++ { // ','.kwarg_or_double_starred+ ++ asdl_seq * _gather_106_var; ++ if ( ++ (_gather_106_var = _gather_106_rule(p)) ++ ) ++ { ++ res = _gather_106_var; ++ goto done; ++ } ++ p->mark = mark; ++ } ++ res = NULL; ++ done: ++ return res; ++} ++ ++// starred_expression: '*' expression ++static expr_ty ++starred_expression_rule(Parser *p) ++{ ++ if (p->error_indicator) { ++ return NULL; ++ } ++ expr_ty res = NULL; ++ int mark = p->mark; ++ if (p->mark == p->fill && _PyPegen_fill_token(p) < 0) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ int start_lineno = p->tokens[mark]->lineno; ++ UNUSED(start_lineno); // Only used by EXTRA macro ++ int start_col_offset = p->tokens[mark]->col_offset; ++ UNUSED(start_col_offset); // Only used by EXTRA macro ++ { // '*' expression ++ expr_ty a; ++ void *literal; ++ if ( ++ (literal = _PyPegen_expect_token(p, 16)) ++ && ++ (a = expression_rule(p)) ++ ) ++ { ++ Token *token = _PyPegen_get_last_nonnwhitespace_token(p); ++ if (token == NULL) { ++ return NULL; ++ } ++ int end_lineno = token->end_lineno; ++ UNUSED(end_lineno); // Only used by EXTRA macro ++ int end_col_offset = token->end_col_offset; ++ UNUSED(end_col_offset); // Only used by EXTRA macro ++ res = _Py_Starred ( a , Load , EXTRA ); ++ if (res == NULL && PyErr_Occurred()) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ goto done; ++ } ++ p->mark = mark; ++ } ++ res = NULL; ++ done: ++ return res; ++} ++ ++// kwarg_or_starred: NAME '=' expression | starred_expression ++static KeywordOrStarred* ++kwarg_or_starred_rule(Parser *p) ++{ ++ if (p->error_indicator) { ++ return NULL; ++ } ++ KeywordOrStarred* res = NULL; ++ int mark = p->mark; ++ if (p->mark == p->fill && _PyPegen_fill_token(p) < 0) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ int start_lineno = p->tokens[mark]->lineno; ++ UNUSED(start_lineno); // Only used by EXTRA macro ++ int start_col_offset = p->tokens[mark]->col_offset; ++ UNUSED(start_col_offset); // Only used by EXTRA macro ++ { // NAME '=' expression ++ expr_ty a; ++ expr_ty b; ++ void *literal; ++ if ( ++ (a = _PyPegen_name_token(p)) ++ && ++ (literal = _PyPegen_expect_token(p, 22)) ++ && ++ (b = expression_rule(p)) ++ ) ++ { ++ Token *token = _PyPegen_get_last_nonnwhitespace_token(p); ++ if (token == NULL) { ++ return NULL; ++ } ++ int end_lineno = token->end_lineno; ++ UNUSED(end_lineno); // Only used by EXTRA macro ++ int end_col_offset = token->end_col_offset; ++ UNUSED(end_col_offset); // Only used by EXTRA macro ++ res = _PyPegen_keyword_or_starred ( p , CHECK ( _Py_keyword ( a -> v . Name . id , b , EXTRA ) ) , 1 ); ++ if (res == NULL && PyErr_Occurred()) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ goto done; ++ } ++ p->mark = mark; ++ } ++ { // starred_expression ++ expr_ty a; ++ if ( ++ (a = starred_expression_rule(p)) ++ ) ++ { ++ res = _PyPegen_keyword_or_starred ( p , a , 0 ); ++ if (res == NULL && PyErr_Occurred()) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ goto done; ++ } ++ p->mark = mark; ++ } ++ res = NULL; ++ done: ++ return res; ++} ++ ++// kwarg_or_double_starred: NAME '=' expression | '**' expression ++static KeywordOrStarred* ++kwarg_or_double_starred_rule(Parser *p) ++{ ++ if (p->error_indicator) { ++ return NULL; ++ } ++ KeywordOrStarred* res = NULL; ++ int mark = p->mark; ++ if (p->mark == p->fill && _PyPegen_fill_token(p) < 0) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ int start_lineno = p->tokens[mark]->lineno; ++ UNUSED(start_lineno); // Only used by EXTRA macro ++ int start_col_offset = p->tokens[mark]->col_offset; ++ UNUSED(start_col_offset); // Only used by EXTRA macro ++ { // NAME '=' expression ++ expr_ty a; ++ expr_ty b; ++ void *literal; ++ if ( ++ (a = _PyPegen_name_token(p)) ++ && ++ (literal = _PyPegen_expect_token(p, 22)) ++ && ++ (b = expression_rule(p)) ++ ) ++ { ++ Token *token = _PyPegen_get_last_nonnwhitespace_token(p); ++ if (token == NULL) { ++ return NULL; ++ } ++ int end_lineno = token->end_lineno; ++ UNUSED(end_lineno); // Only used by EXTRA macro ++ int end_col_offset = token->end_col_offset; ++ UNUSED(end_col_offset); // Only used by EXTRA macro ++ res = _PyPegen_keyword_or_starred ( p , CHECK ( _Py_keyword ( a -> v . Name . id , b , EXTRA ) ) , 1 ); ++ if (res == NULL && PyErr_Occurred()) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ goto done; ++ } ++ p->mark = mark; ++ } ++ { // '**' expression ++ expr_ty a; ++ void *literal; ++ if ( ++ (literal = _PyPegen_expect_token(p, 35)) ++ && ++ (a = expression_rule(p)) ++ ) ++ { ++ Token *token = _PyPegen_get_last_nonnwhitespace_token(p); ++ if (token == NULL) { ++ return NULL; ++ } ++ int end_lineno = token->end_lineno; ++ UNUSED(end_lineno); // Only used by EXTRA macro ++ int end_col_offset = token->end_col_offset; ++ UNUSED(end_col_offset); // Only used by EXTRA macro ++ res = _PyPegen_keyword_or_starred ( p , CHECK ( _Py_keyword ( NULL , a , EXTRA ) ) , 1 ); ++ if (res == NULL && PyErr_Occurred()) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ goto done; ++ } ++ p->mark = mark; ++ } ++ res = NULL; ++ done: ++ return res; ++} ++ ++// star_targets: star_target !',' | star_target ((',' star_target))* ','? ++static expr_ty ++star_targets_rule(Parser *p) ++{ ++ if (p->error_indicator) { ++ return NULL; ++ } ++ expr_ty res = NULL; ++ int mark = p->mark; ++ if (p->mark == p->fill && _PyPegen_fill_token(p) < 0) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ int start_lineno = p->tokens[mark]->lineno; ++ UNUSED(start_lineno); // Only used by EXTRA macro ++ int start_col_offset = p->tokens[mark]->col_offset; ++ UNUSED(start_col_offset); // Only used by EXTRA macro ++ { // star_target !',' ++ expr_ty a; ++ if ( ++ (a = star_target_rule(p)) ++ && ++ _PyPegen_lookahead_with_int(0, _PyPegen_expect_token, p, 12) ++ ) ++ { ++ res = a; ++ if (res == NULL && PyErr_Occurred()) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ goto done; ++ } ++ p->mark = mark; ++ } ++ { // star_target ((',' star_target))* ','? ++ expr_ty a; ++ asdl_seq * b; ++ void *opt_var; ++ UNUSED(opt_var); // Silence compiler warnings ++ if ( ++ (a = star_target_rule(p)) ++ && ++ (b = _loop0_108_rule(p)) ++ && ++ (opt_var = _PyPegen_expect_token(p, 12), 1) ++ ) ++ { ++ Token *token = _PyPegen_get_last_nonnwhitespace_token(p); ++ if (token == NULL) { ++ return NULL; ++ } ++ int end_lineno = token->end_lineno; ++ UNUSED(end_lineno); // Only used by EXTRA macro ++ int end_col_offset = token->end_col_offset; ++ UNUSED(end_col_offset); // Only used by EXTRA macro ++ res = _Py_Tuple ( CHECK ( _PyPegen_seq_insert_in_front ( p , a , b ) ) , Store , EXTRA ); ++ if (res == NULL && PyErr_Occurred()) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ goto done; ++ } ++ p->mark = mark; ++ } ++ res = NULL; ++ done: ++ return res; ++} ++ ++// star_targets_seq: ','.star_target+ ','? ++static asdl_seq* ++star_targets_seq_rule(Parser *p) ++{ ++ if (p->error_indicator) { ++ return NULL; ++ } ++ asdl_seq* res = NULL; ++ int mark = p->mark; ++ { // ','.star_target+ ','? ++ asdl_seq * a; ++ void *opt_var; ++ UNUSED(opt_var); // Silence compiler warnings ++ if ( ++ (a = _gather_109_rule(p)) ++ && ++ (opt_var = _PyPegen_expect_token(p, 12), 1) ++ ) ++ { ++ res = a; ++ if (res == NULL && PyErr_Occurred()) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ goto done; ++ } ++ p->mark = mark; ++ } ++ res = NULL; ++ done: ++ return res; ++} ++ ++// star_target: ++// | '*' (!'*' star_target) ++// | t_primary '.' NAME !t_lookahead ++// | t_primary '[' slices ']' !t_lookahead ++// | star_atom ++static expr_ty ++star_target_rule(Parser *p) ++{ ++ if (p->error_indicator) { ++ return NULL; ++ } ++ expr_ty res = NULL; ++ if (_PyPegen_is_memoized(p, star_target_type, &res)) ++ return res; ++ int mark = p->mark; ++ if (p->mark == p->fill && _PyPegen_fill_token(p) < 0) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ int start_lineno = p->tokens[mark]->lineno; ++ UNUSED(start_lineno); // Only used by EXTRA macro ++ int start_col_offset = p->tokens[mark]->col_offset; ++ UNUSED(start_col_offset); // Only used by EXTRA macro ++ { // '*' (!'*' star_target) ++ void *a; ++ void *literal; ++ if ( ++ (literal = _PyPegen_expect_token(p, 16)) ++ && ++ (a = _tmp_111_rule(p)) ++ ) ++ { ++ Token *token = _PyPegen_get_last_nonnwhitespace_token(p); ++ if (token == NULL) { ++ return NULL; ++ } ++ int end_lineno = token->end_lineno; ++ UNUSED(end_lineno); // Only used by EXTRA macro ++ int end_col_offset = token->end_col_offset; ++ UNUSED(end_col_offset); // Only used by EXTRA macro ++ res = _Py_Starred ( CHECK ( _PyPegen_set_expr_context ( p , a , Store ) ) , Store , EXTRA ); ++ if (res == NULL && PyErr_Occurred()) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ goto done; ++ } ++ p->mark = mark; ++ } ++ { // t_primary '.' NAME !t_lookahead ++ expr_ty a; ++ expr_ty b; ++ void *literal; ++ if ( ++ (a = t_primary_rule(p)) ++ && ++ (literal = _PyPegen_expect_token(p, 23)) ++ && ++ (b = _PyPegen_name_token(p)) ++ && ++ _PyPegen_lookahead(0, t_lookahead_rule, p) ++ ) ++ { ++ Token *token = _PyPegen_get_last_nonnwhitespace_token(p); ++ if (token == NULL) { ++ return NULL; ++ } ++ int end_lineno = token->end_lineno; ++ UNUSED(end_lineno); // Only used by EXTRA macro ++ int end_col_offset = token->end_col_offset; ++ UNUSED(end_col_offset); // Only used by EXTRA macro ++ res = _Py_Attribute ( a , b -> v . Name . id , Store , EXTRA ); ++ if (res == NULL && PyErr_Occurred()) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ goto done; ++ } ++ p->mark = mark; ++ } ++ { // t_primary '[' slices ']' !t_lookahead ++ expr_ty a; ++ expr_ty b; ++ void *literal; ++ void *literal_1; ++ if ( ++ (a = t_primary_rule(p)) ++ && ++ (literal = _PyPegen_expect_token(p, 9)) ++ && ++ (b = slices_rule(p)) ++ && ++ (literal_1 = _PyPegen_expect_token(p, 10)) ++ && ++ _PyPegen_lookahead(0, t_lookahead_rule, p) ++ ) ++ { ++ Token *token = _PyPegen_get_last_nonnwhitespace_token(p); ++ if (token == NULL) { ++ return NULL; ++ } ++ int end_lineno = token->end_lineno; ++ UNUSED(end_lineno); // Only used by EXTRA macro ++ int end_col_offset = token->end_col_offset; ++ UNUSED(end_col_offset); // Only used by EXTRA macro ++ res = _Py_Subscript ( a , b , Store , EXTRA ); ++ if (res == NULL && PyErr_Occurred()) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ goto done; ++ } ++ p->mark = mark; ++ } ++ { // star_atom ++ expr_ty star_atom_var; ++ if ( ++ (star_atom_var = star_atom_rule(p)) ++ ) ++ { ++ res = star_atom_var; ++ goto done; ++ } ++ p->mark = mark; ++ } ++ res = NULL; ++ done: ++ _PyPegen_insert_memo(p, mark, star_target_type, res); ++ return res; ++} ++ ++// star_atom: ++// | NAME ++// | '(' star_target ')' ++// | '(' star_targets_seq? ')' ++// | '[' star_targets_seq? ']' ++static expr_ty ++star_atom_rule(Parser *p) ++{ ++ if (p->error_indicator) { ++ return NULL; ++ } ++ expr_ty res = NULL; ++ int mark = p->mark; ++ if (p->mark == p->fill && _PyPegen_fill_token(p) < 0) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ int start_lineno = p->tokens[mark]->lineno; ++ UNUSED(start_lineno); // Only used by EXTRA macro ++ int start_col_offset = p->tokens[mark]->col_offset; ++ UNUSED(start_col_offset); // Only used by EXTRA macro ++ { // NAME ++ expr_ty a; ++ if ( ++ (a = _PyPegen_name_token(p)) ++ ) ++ { ++ res = _PyPegen_set_expr_context ( p , a , Store ); ++ if (res == NULL && PyErr_Occurred()) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ goto done; ++ } ++ p->mark = mark; ++ } ++ { // '(' star_target ')' ++ expr_ty a; ++ void *literal; ++ void *literal_1; ++ if ( ++ (literal = _PyPegen_expect_token(p, 7)) ++ && ++ (a = star_target_rule(p)) ++ && ++ (literal_1 = _PyPegen_expect_token(p, 8)) ++ ) ++ { ++ res = _PyPegen_set_expr_context ( p , a , Store ); ++ if (res == NULL && PyErr_Occurred()) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ goto done; ++ } ++ p->mark = mark; ++ } ++ { // '(' star_targets_seq? ')' ++ void *a; ++ void *literal; ++ void *literal_1; ++ if ( ++ (literal = _PyPegen_expect_token(p, 7)) ++ && ++ (a = star_targets_seq_rule(p), 1) ++ && ++ (literal_1 = _PyPegen_expect_token(p, 8)) ++ ) ++ { ++ Token *token = _PyPegen_get_last_nonnwhitespace_token(p); ++ if (token == NULL) { ++ return NULL; ++ } ++ int end_lineno = token->end_lineno; ++ UNUSED(end_lineno); // Only used by EXTRA macro ++ int end_col_offset = token->end_col_offset; ++ UNUSED(end_col_offset); // Only used by EXTRA macro ++ res = _Py_Tuple ( a , Store , EXTRA ); ++ if (res == NULL && PyErr_Occurred()) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ goto done; ++ } ++ p->mark = mark; ++ } ++ { // '[' star_targets_seq? ']' ++ void *a; ++ void *literal; ++ void *literal_1; ++ if ( ++ (literal = _PyPegen_expect_token(p, 9)) ++ && ++ (a = star_targets_seq_rule(p), 1) ++ && ++ (literal_1 = _PyPegen_expect_token(p, 10)) ++ ) ++ { ++ Token *token = _PyPegen_get_last_nonnwhitespace_token(p); ++ if (token == NULL) { ++ return NULL; ++ } ++ int end_lineno = token->end_lineno; ++ UNUSED(end_lineno); // Only used by EXTRA macro ++ int end_col_offset = token->end_col_offset; ++ UNUSED(end_col_offset); // Only used by EXTRA macro ++ res = _Py_List ( a , Store , EXTRA ); ++ if (res == NULL && PyErr_Occurred()) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ goto done; ++ } ++ p->mark = mark; ++ } ++ res = NULL; ++ done: ++ return res; ++} ++ ++// inside_paren_ann_assign_target: ++// | ann_assign_subscript_attribute_target ++// | NAME ++// | '(' inside_paren_ann_assign_target ')' ++static expr_ty ++inside_paren_ann_assign_target_rule(Parser *p) ++{ ++ if (p->error_indicator) { ++ return NULL; ++ } ++ expr_ty res = NULL; ++ int mark = p->mark; ++ { // ann_assign_subscript_attribute_target ++ expr_ty ann_assign_subscript_attribute_target_var; ++ if ( ++ (ann_assign_subscript_attribute_target_var = ann_assign_subscript_attribute_target_rule(p)) ++ ) ++ { ++ res = ann_assign_subscript_attribute_target_var; ++ goto done; ++ } ++ p->mark = mark; ++ } ++ { // NAME ++ expr_ty a; ++ if ( ++ (a = _PyPegen_name_token(p)) ++ ) ++ { ++ res = _PyPegen_set_expr_context ( p , a , Store ); ++ if (res == NULL && PyErr_Occurred()) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ goto done; ++ } ++ p->mark = mark; ++ } ++ { // '(' inside_paren_ann_assign_target ')' ++ expr_ty a; ++ void *literal; ++ void *literal_1; ++ if ( ++ (literal = _PyPegen_expect_token(p, 7)) ++ && ++ (a = inside_paren_ann_assign_target_rule(p)) ++ && ++ (literal_1 = _PyPegen_expect_token(p, 8)) ++ ) ++ { ++ res = a; ++ if (res == NULL && PyErr_Occurred()) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ goto done; ++ } ++ p->mark = mark; ++ } ++ res = NULL; ++ done: ++ return res; ++} ++ ++// ann_assign_subscript_attribute_target: ++// | t_primary '.' NAME !t_lookahead ++// | t_primary '[' slices ']' !t_lookahead ++static expr_ty ++ann_assign_subscript_attribute_target_rule(Parser *p) ++{ ++ if (p->error_indicator) { ++ return NULL; ++ } ++ expr_ty res = NULL; ++ int mark = p->mark; ++ if (p->mark == p->fill && _PyPegen_fill_token(p) < 0) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ int start_lineno = p->tokens[mark]->lineno; ++ UNUSED(start_lineno); // Only used by EXTRA macro ++ int start_col_offset = p->tokens[mark]->col_offset; ++ UNUSED(start_col_offset); // Only used by EXTRA macro ++ { // t_primary '.' NAME !t_lookahead ++ expr_ty a; ++ expr_ty b; ++ void *literal; ++ if ( ++ (a = t_primary_rule(p)) ++ && ++ (literal = _PyPegen_expect_token(p, 23)) ++ && ++ (b = _PyPegen_name_token(p)) ++ && ++ _PyPegen_lookahead(0, t_lookahead_rule, p) ++ ) ++ { ++ Token *token = _PyPegen_get_last_nonnwhitespace_token(p); ++ if (token == NULL) { ++ return NULL; ++ } ++ int end_lineno = token->end_lineno; ++ UNUSED(end_lineno); // Only used by EXTRA macro ++ int end_col_offset = token->end_col_offset; ++ UNUSED(end_col_offset); // Only used by EXTRA macro ++ res = _Py_Attribute ( a , b -> v . Name . id , Store , EXTRA ); ++ if (res == NULL && PyErr_Occurred()) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ goto done; ++ } ++ p->mark = mark; ++ } ++ { // t_primary '[' slices ']' !t_lookahead ++ expr_ty a; ++ expr_ty b; ++ void *literal; ++ void *literal_1; ++ if ( ++ (a = t_primary_rule(p)) ++ && ++ (literal = _PyPegen_expect_token(p, 9)) ++ && ++ (b = slices_rule(p)) ++ && ++ (literal_1 = _PyPegen_expect_token(p, 10)) ++ && ++ _PyPegen_lookahead(0, t_lookahead_rule, p) ++ ) ++ { ++ Token *token = _PyPegen_get_last_nonnwhitespace_token(p); ++ if (token == NULL) { ++ return NULL; ++ } ++ int end_lineno = token->end_lineno; ++ UNUSED(end_lineno); // Only used by EXTRA macro ++ int end_col_offset = token->end_col_offset; ++ UNUSED(end_col_offset); // Only used by EXTRA macro ++ res = _Py_Subscript ( a , b , Store , EXTRA ); ++ if (res == NULL && PyErr_Occurred()) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ goto done; ++ } ++ p->mark = mark; ++ } ++ res = NULL; ++ done: ++ return res; ++} ++ ++// del_targets: ','.del_target+ ','? ++static asdl_seq* ++del_targets_rule(Parser *p) ++{ ++ if (p->error_indicator) { ++ return NULL; ++ } ++ asdl_seq* res = NULL; ++ int mark = p->mark; ++ { // ','.del_target+ ','? ++ asdl_seq * a; ++ void *opt_var; ++ UNUSED(opt_var); // Silence compiler warnings ++ if ( ++ (a = _gather_112_rule(p)) ++ && ++ (opt_var = _PyPegen_expect_token(p, 12), 1) ++ ) ++ { ++ res = a; ++ if (res == NULL && PyErr_Occurred()) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ goto done; ++ } ++ p->mark = mark; ++ } ++ res = NULL; ++ done: ++ return res; ++} ++ ++// del_target: ++// | t_primary '.' NAME !t_lookahead ++// | t_primary '[' slices ']' !t_lookahead ++// | del_t_atom ++static expr_ty ++del_target_rule(Parser *p) ++{ ++ if (p->error_indicator) { ++ return NULL; ++ } ++ expr_ty res = NULL; ++ if (_PyPegen_is_memoized(p, del_target_type, &res)) ++ return res; ++ int mark = p->mark; ++ if (p->mark == p->fill && _PyPegen_fill_token(p) < 0) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ int start_lineno = p->tokens[mark]->lineno; ++ UNUSED(start_lineno); // Only used by EXTRA macro ++ int start_col_offset = p->tokens[mark]->col_offset; ++ UNUSED(start_col_offset); // Only used by EXTRA macro ++ { // t_primary '.' NAME !t_lookahead ++ expr_ty a; ++ expr_ty b; ++ void *literal; ++ if ( ++ (a = t_primary_rule(p)) ++ && ++ (literal = _PyPegen_expect_token(p, 23)) ++ && ++ (b = _PyPegen_name_token(p)) ++ && ++ _PyPegen_lookahead(0, t_lookahead_rule, p) ++ ) ++ { ++ Token *token = _PyPegen_get_last_nonnwhitespace_token(p); ++ if (token == NULL) { ++ return NULL; ++ } ++ int end_lineno = token->end_lineno; ++ UNUSED(end_lineno); // Only used by EXTRA macro ++ int end_col_offset = token->end_col_offset; ++ UNUSED(end_col_offset); // Only used by EXTRA macro ++ res = _Py_Attribute ( a , b -> v . Name . id , Del , EXTRA ); ++ if (res == NULL && PyErr_Occurred()) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ goto done; ++ } ++ p->mark = mark; ++ } ++ { // t_primary '[' slices ']' !t_lookahead ++ expr_ty a; ++ expr_ty b; ++ void *literal; ++ void *literal_1; ++ if ( ++ (a = t_primary_rule(p)) ++ && ++ (literal = _PyPegen_expect_token(p, 9)) ++ && ++ (b = slices_rule(p)) ++ && ++ (literal_1 = _PyPegen_expect_token(p, 10)) ++ && ++ _PyPegen_lookahead(0, t_lookahead_rule, p) ++ ) ++ { ++ Token *token = _PyPegen_get_last_nonnwhitespace_token(p); ++ if (token == NULL) { ++ return NULL; ++ } ++ int end_lineno = token->end_lineno; ++ UNUSED(end_lineno); // Only used by EXTRA macro ++ int end_col_offset = token->end_col_offset; ++ UNUSED(end_col_offset); // Only used by EXTRA macro ++ res = _Py_Subscript ( a , b , Del , EXTRA ); ++ if (res == NULL && PyErr_Occurred()) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ goto done; ++ } ++ p->mark = mark; ++ } ++ { // del_t_atom ++ expr_ty del_t_atom_var; ++ if ( ++ (del_t_atom_var = del_t_atom_rule(p)) ++ ) ++ { ++ res = del_t_atom_var; ++ goto done; ++ } ++ p->mark = mark; ++ } ++ res = NULL; ++ done: ++ _PyPegen_insert_memo(p, mark, del_target_type, res); ++ return res; ++} ++ ++// del_t_atom: NAME | '(' del_target ')' | '(' del_targets? ')' | '[' del_targets? ']' ++static expr_ty ++del_t_atom_rule(Parser *p) ++{ ++ if (p->error_indicator) { ++ return NULL; ++ } ++ expr_ty res = NULL; ++ int mark = p->mark; ++ if (p->mark == p->fill && _PyPegen_fill_token(p) < 0) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ int start_lineno = p->tokens[mark]->lineno; ++ UNUSED(start_lineno); // Only used by EXTRA macro ++ int start_col_offset = p->tokens[mark]->col_offset; ++ UNUSED(start_col_offset); // Only used by EXTRA macro ++ { // NAME ++ expr_ty a; ++ if ( ++ (a = _PyPegen_name_token(p)) ++ ) ++ { ++ res = _PyPegen_set_expr_context ( p , a , Del ); ++ if (res == NULL && PyErr_Occurred()) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ goto done; ++ } ++ p->mark = mark; ++ } ++ { // '(' del_target ')' ++ expr_ty a; ++ void *literal; ++ void *literal_1; ++ if ( ++ (literal = _PyPegen_expect_token(p, 7)) ++ && ++ (a = del_target_rule(p)) ++ && ++ (literal_1 = _PyPegen_expect_token(p, 8)) ++ ) ++ { ++ res = _PyPegen_set_expr_context ( p , a , Del ); ++ if (res == NULL && PyErr_Occurred()) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ goto done; ++ } ++ p->mark = mark; ++ } ++ { // '(' del_targets? ')' ++ void *a; ++ void *literal; ++ void *literal_1; ++ if ( ++ (literal = _PyPegen_expect_token(p, 7)) ++ && ++ (a = del_targets_rule(p), 1) ++ && ++ (literal_1 = _PyPegen_expect_token(p, 8)) ++ ) ++ { ++ Token *token = _PyPegen_get_last_nonnwhitespace_token(p); ++ if (token == NULL) { ++ return NULL; ++ } ++ int end_lineno = token->end_lineno; ++ UNUSED(end_lineno); // Only used by EXTRA macro ++ int end_col_offset = token->end_col_offset; ++ UNUSED(end_col_offset); // Only used by EXTRA macro ++ res = _Py_Tuple ( a , Del , EXTRA ); ++ if (res == NULL && PyErr_Occurred()) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ goto done; ++ } ++ p->mark = mark; ++ } ++ { // '[' del_targets? ']' ++ void *a; ++ void *literal; ++ void *literal_1; ++ if ( ++ (literal = _PyPegen_expect_token(p, 9)) ++ && ++ (a = del_targets_rule(p), 1) ++ && ++ (literal_1 = _PyPegen_expect_token(p, 10)) ++ ) ++ { ++ Token *token = _PyPegen_get_last_nonnwhitespace_token(p); ++ if (token == NULL) { ++ return NULL; ++ } ++ int end_lineno = token->end_lineno; ++ UNUSED(end_lineno); // Only used by EXTRA macro ++ int end_col_offset = token->end_col_offset; ++ UNUSED(end_col_offset); // Only used by EXTRA macro ++ res = _Py_List ( a , Del , EXTRA ); ++ if (res == NULL && PyErr_Occurred()) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ goto done; ++ } ++ p->mark = mark; ++ } ++ res = NULL; ++ done: ++ return res; ++} ++ ++// targets: ','.target+ ','? ++static asdl_seq* ++targets_rule(Parser *p) ++{ ++ if (p->error_indicator) { ++ return NULL; ++ } ++ asdl_seq* res = NULL; ++ int mark = p->mark; ++ { // ','.target+ ','? ++ asdl_seq * a; ++ void *opt_var; ++ UNUSED(opt_var); // Silence compiler warnings ++ if ( ++ (a = _gather_114_rule(p)) ++ && ++ (opt_var = _PyPegen_expect_token(p, 12), 1) ++ ) ++ { ++ res = a; ++ if (res == NULL && PyErr_Occurred()) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ goto done; ++ } ++ p->mark = mark; ++ } ++ res = NULL; ++ done: ++ return res; ++} ++ ++// target: ++// | t_primary '.' NAME !t_lookahead ++// | t_primary '[' slices ']' !t_lookahead ++// | t_atom ++static expr_ty ++target_rule(Parser *p) ++{ ++ if (p->error_indicator) { ++ return NULL; ++ } ++ expr_ty res = NULL; ++ if (_PyPegen_is_memoized(p, target_type, &res)) ++ return res; ++ int mark = p->mark; ++ if (p->mark == p->fill && _PyPegen_fill_token(p) < 0) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ int start_lineno = p->tokens[mark]->lineno; ++ UNUSED(start_lineno); // Only used by EXTRA macro ++ int start_col_offset = p->tokens[mark]->col_offset; ++ UNUSED(start_col_offset); // Only used by EXTRA macro ++ { // t_primary '.' NAME !t_lookahead ++ expr_ty a; ++ expr_ty b; ++ void *literal; ++ if ( ++ (a = t_primary_rule(p)) ++ && ++ (literal = _PyPegen_expect_token(p, 23)) ++ && ++ (b = _PyPegen_name_token(p)) ++ && ++ _PyPegen_lookahead(0, t_lookahead_rule, p) ++ ) ++ { ++ Token *token = _PyPegen_get_last_nonnwhitespace_token(p); ++ if (token == NULL) { ++ return NULL; ++ } ++ int end_lineno = token->end_lineno; ++ UNUSED(end_lineno); // Only used by EXTRA macro ++ int end_col_offset = token->end_col_offset; ++ UNUSED(end_col_offset); // Only used by EXTRA macro ++ res = _Py_Attribute ( a , b -> v . Name . id , Store , EXTRA ); ++ if (res == NULL && PyErr_Occurred()) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ goto done; ++ } ++ p->mark = mark; ++ } ++ { // t_primary '[' slices ']' !t_lookahead ++ expr_ty a; ++ expr_ty b; ++ void *literal; ++ void *literal_1; ++ if ( ++ (a = t_primary_rule(p)) ++ && ++ (literal = _PyPegen_expect_token(p, 9)) ++ && ++ (b = slices_rule(p)) ++ && ++ (literal_1 = _PyPegen_expect_token(p, 10)) ++ && ++ _PyPegen_lookahead(0, t_lookahead_rule, p) ++ ) ++ { ++ Token *token = _PyPegen_get_last_nonnwhitespace_token(p); ++ if (token == NULL) { ++ return NULL; ++ } ++ int end_lineno = token->end_lineno; ++ UNUSED(end_lineno); // Only used by EXTRA macro ++ int end_col_offset = token->end_col_offset; ++ UNUSED(end_col_offset); // Only used by EXTRA macro ++ res = _Py_Subscript ( a , b , Store , EXTRA ); ++ if (res == NULL && PyErr_Occurred()) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ goto done; ++ } ++ p->mark = mark; ++ } ++ { // t_atom ++ expr_ty t_atom_var; ++ if ( ++ (t_atom_var = t_atom_rule(p)) ++ ) ++ { ++ res = t_atom_var; ++ goto done; ++ } ++ p->mark = mark; ++ } ++ res = NULL; ++ done: ++ _PyPegen_insert_memo(p, mark, target_type, res); ++ return res; ++} ++ ++// Left-recursive ++// t_primary: ++// | t_primary '.' NAME &t_lookahead ++// | t_primary '[' slices ']' &t_lookahead ++// | t_primary genexp &t_lookahead ++// | t_primary '(' arguments? ')' &t_lookahead ++// | atom &t_lookahead ++static expr_ty t_primary_raw(Parser *); ++static expr_ty ++t_primary_rule(Parser *p) ++{ ++ expr_ty res = NULL; ++ if (_PyPegen_is_memoized(p, t_primary_type, &res)) ++ return res; ++ int mark = p->mark; ++ int resmark = p->mark; ++ while (1) { ++ int tmpvar_8 = _PyPegen_update_memo(p, mark, t_primary_type, res); ++ if (tmpvar_8) { ++ return res; ++ } ++ p->mark = mark; ++ void *raw = t_primary_raw(p); ++ if (raw == NULL || p->mark <= resmark) ++ break; ++ resmark = p->mark; ++ res = raw; ++ } ++ p->mark = resmark; ++ return res; ++} ++static expr_ty ++t_primary_raw(Parser *p) ++{ ++ if (p->error_indicator) { ++ return NULL; ++ } ++ expr_ty res = NULL; ++ int mark = p->mark; ++ if (p->mark == p->fill && _PyPegen_fill_token(p) < 0) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ int start_lineno = p->tokens[mark]->lineno; ++ UNUSED(start_lineno); // Only used by EXTRA macro ++ int start_col_offset = p->tokens[mark]->col_offset; ++ UNUSED(start_col_offset); // Only used by EXTRA macro ++ { // t_primary '.' NAME &t_lookahead ++ expr_ty a; ++ expr_ty b; ++ void *literal; ++ if ( ++ (a = t_primary_rule(p)) ++ && ++ (literal = _PyPegen_expect_token(p, 23)) ++ && ++ (b = _PyPegen_name_token(p)) ++ && ++ _PyPegen_lookahead(1, t_lookahead_rule, p) ++ ) ++ { ++ Token *token = _PyPegen_get_last_nonnwhitespace_token(p); ++ if (token == NULL) { ++ return NULL; ++ } ++ int end_lineno = token->end_lineno; ++ UNUSED(end_lineno); // Only used by EXTRA macro ++ int end_col_offset = token->end_col_offset; ++ UNUSED(end_col_offset); // Only used by EXTRA macro ++ res = _Py_Attribute ( a , b -> v . Name . id , Load , EXTRA ); ++ if (res == NULL && PyErr_Occurred()) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ goto done; ++ } ++ p->mark = mark; ++ } ++ { // t_primary '[' slices ']' &t_lookahead ++ expr_ty a; ++ expr_ty b; ++ void *literal; ++ void *literal_1; ++ if ( ++ (a = t_primary_rule(p)) ++ && ++ (literal = _PyPegen_expect_token(p, 9)) ++ && ++ (b = slices_rule(p)) ++ && ++ (literal_1 = _PyPegen_expect_token(p, 10)) ++ && ++ _PyPegen_lookahead(1, t_lookahead_rule, p) ++ ) ++ { ++ Token *token = _PyPegen_get_last_nonnwhitespace_token(p); ++ if (token == NULL) { ++ return NULL; ++ } ++ int end_lineno = token->end_lineno; ++ UNUSED(end_lineno); // Only used by EXTRA macro ++ int end_col_offset = token->end_col_offset; ++ UNUSED(end_col_offset); // Only used by EXTRA macro ++ res = _Py_Subscript ( a , b , Load , EXTRA ); ++ if (res == NULL && PyErr_Occurred()) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ goto done; ++ } ++ p->mark = mark; ++ } ++ { // t_primary genexp &t_lookahead ++ expr_ty a; ++ expr_ty b; ++ if ( ++ (a = t_primary_rule(p)) ++ && ++ (b = genexp_rule(p)) ++ && ++ _PyPegen_lookahead(1, t_lookahead_rule, p) ++ ) ++ { ++ Token *token = _PyPegen_get_last_nonnwhitespace_token(p); ++ if (token == NULL) { ++ return NULL; ++ } ++ int end_lineno = token->end_lineno; ++ UNUSED(end_lineno); // Only used by EXTRA macro ++ int end_col_offset = token->end_col_offset; ++ UNUSED(end_col_offset); // Only used by EXTRA macro ++ res = _Py_Call ( a , CHECK ( _PyPegen_singleton_seq ( p , b ) ) , NULL , EXTRA ); ++ if (res == NULL && PyErr_Occurred()) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ goto done; ++ } ++ p->mark = mark; ++ } ++ { // t_primary '(' arguments? ')' &t_lookahead ++ expr_ty a; ++ void *b; ++ void *literal; ++ void *literal_1; ++ if ( ++ (a = t_primary_rule(p)) ++ && ++ (literal = _PyPegen_expect_token(p, 7)) ++ && ++ (b = arguments_rule(p), 1) ++ && ++ (literal_1 = _PyPegen_expect_token(p, 8)) ++ && ++ _PyPegen_lookahead(1, t_lookahead_rule, p) ++ ) ++ { ++ Token *token = _PyPegen_get_last_nonnwhitespace_token(p); ++ if (token == NULL) { ++ return NULL; ++ } ++ int end_lineno = token->end_lineno; ++ UNUSED(end_lineno); // Only used by EXTRA macro ++ int end_col_offset = token->end_col_offset; ++ UNUSED(end_col_offset); // Only used by EXTRA macro ++ res = _Py_Call ( a , ( b ) ? ( ( expr_ty ) b ) -> v . Call . args : NULL , ( b ) ? ( ( expr_ty ) b ) -> v . Call . keywords : NULL , EXTRA ); ++ if (res == NULL && PyErr_Occurred()) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ goto done; ++ } ++ p->mark = mark; ++ } ++ { // atom &t_lookahead ++ expr_ty a; ++ if ( ++ (a = atom_rule(p)) ++ && ++ _PyPegen_lookahead(1, t_lookahead_rule, p) ++ ) ++ { ++ res = a; ++ if (res == NULL && PyErr_Occurred()) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ goto done; ++ } ++ p->mark = mark; ++ } ++ res = NULL; ++ done: ++ return res; ++} ++ ++// t_lookahead: '(' | '[' | '.' ++static void * ++t_lookahead_rule(Parser *p) ++{ ++ if (p->error_indicator) { ++ return NULL; ++ } ++ void * res = NULL; ++ int mark = p->mark; ++ { // '(' ++ void *literal; ++ if ( ++ (literal = _PyPegen_expect_token(p, 7)) ++ ) ++ { ++ res = literal; ++ goto done; ++ } ++ p->mark = mark; ++ } ++ { // '[' ++ void *literal; ++ if ( ++ (literal = _PyPegen_expect_token(p, 9)) ++ ) ++ { ++ res = literal; ++ goto done; ++ } ++ p->mark = mark; ++ } ++ { // '.' ++ void *literal; ++ if ( ++ (literal = _PyPegen_expect_token(p, 23)) ++ ) ++ { ++ res = literal; ++ goto done; ++ } ++ p->mark = mark; ++ } ++ res = NULL; ++ done: ++ return res; ++} ++ ++// t_atom: NAME | '(' target ')' | '(' targets? ')' | '[' targets? ']' ++static expr_ty ++t_atom_rule(Parser *p) ++{ ++ if (p->error_indicator) { ++ return NULL; ++ } ++ expr_ty res = NULL; ++ int mark = p->mark; ++ if (p->mark == p->fill && _PyPegen_fill_token(p) < 0) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ int start_lineno = p->tokens[mark]->lineno; ++ UNUSED(start_lineno); // Only used by EXTRA macro ++ int start_col_offset = p->tokens[mark]->col_offset; ++ UNUSED(start_col_offset); // Only used by EXTRA macro ++ { // NAME ++ expr_ty a; ++ if ( ++ (a = _PyPegen_name_token(p)) ++ ) ++ { ++ res = _PyPegen_set_expr_context ( p , a , Store ); ++ if (res == NULL && PyErr_Occurred()) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ goto done; ++ } ++ p->mark = mark; ++ } ++ { // '(' target ')' ++ expr_ty a; ++ void *literal; ++ void *literal_1; ++ if ( ++ (literal = _PyPegen_expect_token(p, 7)) ++ && ++ (a = target_rule(p)) ++ && ++ (literal_1 = _PyPegen_expect_token(p, 8)) ++ ) ++ { ++ res = _PyPegen_set_expr_context ( p , a , Store ); ++ if (res == NULL && PyErr_Occurred()) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ goto done; ++ } ++ p->mark = mark; ++ } ++ { // '(' targets? ')' ++ void *b; ++ void *literal; ++ void *literal_1; ++ if ( ++ (literal = _PyPegen_expect_token(p, 7)) ++ && ++ (b = targets_rule(p), 1) ++ && ++ (literal_1 = _PyPegen_expect_token(p, 8)) ++ ) ++ { ++ Token *token = _PyPegen_get_last_nonnwhitespace_token(p); ++ if (token == NULL) { ++ return NULL; ++ } ++ int end_lineno = token->end_lineno; ++ UNUSED(end_lineno); // Only used by EXTRA macro ++ int end_col_offset = token->end_col_offset; ++ UNUSED(end_col_offset); // Only used by EXTRA macro ++ res = _Py_Tuple ( b , Store , EXTRA ); ++ if (res == NULL && PyErr_Occurred()) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ goto done; ++ } ++ p->mark = mark; ++ } ++ { // '[' targets? ']' ++ void *b; ++ void *literal; ++ void *literal_1; ++ if ( ++ (literal = _PyPegen_expect_token(p, 9)) ++ && ++ (b = targets_rule(p), 1) ++ && ++ (literal_1 = _PyPegen_expect_token(p, 10)) ++ ) ++ { ++ Token *token = _PyPegen_get_last_nonnwhitespace_token(p); ++ if (token == NULL) { ++ return NULL; ++ } ++ int end_lineno = token->end_lineno; ++ UNUSED(end_lineno); // Only used by EXTRA macro ++ int end_col_offset = token->end_col_offset; ++ UNUSED(end_col_offset); // Only used by EXTRA macro ++ res = _Py_List ( b , Store , EXTRA ); ++ if (res == NULL && PyErr_Occurred()) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ goto done; ++ } ++ p->mark = mark; ++ } ++ res = NULL; ++ done: ++ return res; ++} ++ ++// incorrect_arguments: ++// | args ',' '*' ++// | expression for_if_clauses ',' [args | expression for_if_clauses] ++// | args ',' args ++static void * ++incorrect_arguments_rule(Parser *p) ++{ ++ if (p->error_indicator) { ++ return NULL; ++ } ++ void * res = NULL; ++ int mark = p->mark; ++ { // args ',' '*' ++ expr_ty args_var; ++ void *literal; ++ void *literal_1; ++ if ( ++ (args_var = args_rule(p)) ++ && ++ (literal = _PyPegen_expect_token(p, 12)) ++ && ++ (literal_1 = _PyPegen_expect_token(p, 16)) ++ ) ++ { ++ res = RAISE_SYNTAX_ERROR ( "iterable argument unpacking follows keyword argument unpacking" ); ++ if (res == NULL && PyErr_Occurred()) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ goto done; ++ } ++ p->mark = mark; ++ } ++ { // expression for_if_clauses ',' [args | expression for_if_clauses] ++ expr_ty expression_var; ++ asdl_seq* for_if_clauses_var; ++ void *literal; ++ void *opt_var; ++ UNUSED(opt_var); // Silence compiler warnings ++ if ( ++ (expression_var = expression_rule(p)) ++ && ++ (for_if_clauses_var = for_if_clauses_rule(p)) ++ && ++ (literal = _PyPegen_expect_token(p, 12)) ++ && ++ (opt_var = _tmp_116_rule(p), 1) ++ ) ++ { ++ res = RAISE_SYNTAX_ERROR ( "Generator expression must be parenthesized" ); ++ if (res == NULL && PyErr_Occurred()) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ goto done; ++ } ++ p->mark = mark; ++ } ++ { // args ',' args ++ expr_ty a; ++ expr_ty args_var; ++ void *literal; ++ if ( ++ (a = args_rule(p)) ++ && ++ (literal = _PyPegen_expect_token(p, 12)) ++ && ++ (args_var = args_rule(p)) ++ ) ++ { ++ res = _PyPegen_arguments_parsing_error ( p , a ); ++ if (res == NULL && PyErr_Occurred()) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ goto done; ++ } ++ p->mark = mark; ++ } ++ res = NULL; ++ done: ++ return res; ++} ++ ++// invalid_named_expression: expression ':=' expression ++static void * ++invalid_named_expression_rule(Parser *p) ++{ ++ if (p->error_indicator) { ++ return NULL; ++ } ++ void * res = NULL; ++ int mark = p->mark; ++ { // expression ':=' expression ++ expr_ty a; ++ expr_ty expression_var; ++ void *literal; ++ if ( ++ (a = expression_rule(p)) ++ && ++ (literal = _PyPegen_expect_token(p, 53)) ++ && ++ (expression_var = expression_rule(p)) ++ ) ++ { ++ res = RAISE_SYNTAX_ERROR ( "cannot use assignment expressions with %s" , _PyPegen_get_expr_name ( a ) ); ++ if (res == NULL && PyErr_Occurred()) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ goto done; ++ } ++ p->mark = mark; ++ } ++ res = NULL; ++ done: ++ return res; ++} ++ ++// invalid_assignment: ++// | list ':' ++// | tuple ':' ++// | expression ':' expression ['=' annotated_rhs] ++// | expression ('=' | augassign) (yield_expr | star_expressions) ++static void * ++invalid_assignment_rule(Parser *p) ++{ ++ if (p->error_indicator) { ++ return NULL; ++ } ++ void * res = NULL; ++ int mark = p->mark; ++ { // list ':' ++ expr_ty list_var; ++ void *literal; ++ if ( ++ (list_var = list_rule(p)) ++ && ++ (literal = _PyPegen_expect_token(p, 11)) ++ ) ++ { ++ res = RAISE_SYNTAX_ERROR ( "only single target (not list) can be annotated" ); ++ if (res == NULL && PyErr_Occurred()) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ goto done; ++ } ++ p->mark = mark; ++ } ++ { // tuple ':' ++ void *literal; ++ expr_ty tuple_var; ++ if ( ++ (tuple_var = tuple_rule(p)) ++ && ++ (literal = _PyPegen_expect_token(p, 11)) ++ ) ++ { ++ res = RAISE_SYNTAX_ERROR ( "only single target (not tuple) can be annotated" ); ++ if (res == NULL && PyErr_Occurred()) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ goto done; ++ } ++ p->mark = mark; ++ } ++ { // expression ':' expression ['=' annotated_rhs] ++ expr_ty expression_var; ++ expr_ty expression_var_1; ++ void *literal; ++ void *opt_var; ++ UNUSED(opt_var); // Silence compiler warnings ++ if ( ++ (expression_var = expression_rule(p)) ++ && ++ (literal = _PyPegen_expect_token(p, 11)) ++ && ++ (expression_var_1 = expression_rule(p)) ++ && ++ (opt_var = _tmp_117_rule(p), 1) ++ ) ++ { ++ res = RAISE_SYNTAX_ERROR ( "illegal target for annotation" ); ++ if (res == NULL && PyErr_Occurred()) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ goto done; ++ } ++ p->mark = mark; ++ } ++ { // expression ('=' | augassign) (yield_expr | star_expressions) ++ void *_tmp_118_var; ++ void *_tmp_119_var; ++ expr_ty a; ++ if ( ++ (a = expression_rule(p)) ++ && ++ (_tmp_118_var = _tmp_118_rule(p)) ++ && ++ (_tmp_119_var = _tmp_119_rule(p)) ++ ) ++ { ++ res = RAISE_SYNTAX_ERROR ( "cannot assign to %s" , _PyPegen_get_expr_name ( a ) ); ++ if (res == NULL && PyErr_Occurred()) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ goto done; ++ } ++ p->mark = mark; ++ } ++ res = NULL; ++ done: ++ return res; ++} ++ ++// invalid_block: NEWLINE !INDENT ++static void * ++invalid_block_rule(Parser *p) ++{ ++ if (p->error_indicator) { ++ return NULL; ++ } ++ void * res = NULL; ++ int mark = p->mark; ++ { // NEWLINE !INDENT ++ void *newline_var; ++ if ( ++ (newline_var = _PyPegen_newline_token(p)) ++ && ++ _PyPegen_lookahead(0, _PyPegen_indent_token, p) ++ ) ++ { ++ res = RAISE_INDENTATION_ERROR ( "expected an indented block" ); ++ if (res == NULL && PyErr_Occurred()) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ goto done; ++ } ++ p->mark = mark; ++ } ++ res = NULL; ++ done: ++ return res; ++} ++ ++// invalid_comprehension: ('[' | '(' | '{') '*' expression for_if_clauses ++static void * ++invalid_comprehension_rule(Parser *p) ++{ ++ if (p->error_indicator) { ++ return NULL; ++ } ++ void * res = NULL; ++ int mark = p->mark; ++ { // ('[' | '(' | '{') '*' expression for_if_clauses ++ void *_tmp_120_var; ++ expr_ty expression_var; ++ asdl_seq* for_if_clauses_var; ++ void *literal; ++ if ( ++ (_tmp_120_var = _tmp_120_rule(p)) ++ && ++ (literal = _PyPegen_expect_token(p, 16)) ++ && ++ (expression_var = expression_rule(p)) ++ && ++ (for_if_clauses_var = for_if_clauses_rule(p)) ++ ) ++ { ++ res = RAISE_SYNTAX_ERROR ( "iterable unpacking cannot be used in comprehension" ); ++ if (res == NULL && PyErr_Occurred()) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ goto done; ++ } ++ p->mark = mark; ++ } ++ res = NULL; ++ done: ++ return res; ++} ++ ++// invalid_parameters: ++// | [plain_names ','] (slash_with_default | names_with_default) ',' plain_names ++static void * ++invalid_parameters_rule(Parser *p) ++{ ++ if (p->error_indicator) { ++ return NULL; ++ } ++ void * res = NULL; ++ int mark = p->mark; ++ { // [plain_names ','] (slash_with_default | names_with_default) ',' plain_names ++ void *_tmp_122_var; ++ void *literal; ++ void *opt_var; ++ UNUSED(opt_var); // Silence compiler warnings ++ asdl_seq* plain_names_var; ++ if ( ++ (opt_var = _tmp_121_rule(p), 1) ++ && ++ (_tmp_122_var = _tmp_122_rule(p)) ++ && ++ (literal = _PyPegen_expect_token(p, 12)) ++ && ++ (plain_names_var = plain_names_rule(p)) ++ ) ++ { ++ res = RAISE_SYNTAX_ERROR ( "non-default argument follows default argument" ); ++ if (res == NULL && PyErr_Occurred()) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ goto done; ++ } ++ p->mark = mark; ++ } ++ res = NULL; ++ done: ++ return res; ++} ++ ++// _loop0_1: NEWLINE ++static asdl_seq * ++_loop0_1_rule(Parser *p) ++{ ++ if (p->error_indicator) { ++ return NULL; ++ } ++ void *res = NULL; ++ int mark = p->mark; ++ int start_mark = p->mark; ++ void **children = PyMem_Malloc(sizeof(void *)); ++ if (!children) { ++ PyErr_Format(PyExc_MemoryError, "Parser out of memory"); ++ return NULL; ++ } ++ ssize_t children_capacity = 1; ++ ssize_t n = 0; ++ { // NEWLINE ++ void *newline_var; ++ while ( ++ (newline_var = _PyPegen_newline_token(p)) ++ ) ++ { ++ res = newline_var; ++ if (n == children_capacity) { ++ children_capacity *= 2; ++ children = PyMem_Realloc(children, children_capacity*sizeof(void *)); ++ if (!children) { ++ PyErr_Format(PyExc_MemoryError, "realloc None"); ++ return NULL; ++ } ++ } ++ children[n++] = res; ++ mark = p->mark; ++ } ++ p->mark = mark; ++ } ++ asdl_seq *seq = _Py_asdl_seq_new(n, p->arena); ++ if (!seq) { ++ PyErr_Format(PyExc_MemoryError, "asdl_seq_new _loop0_1"); ++ PyMem_Free(children); ++ return NULL; ++ } ++ for (int i = 0; i < n; i++) asdl_seq_SET(seq, i, children[i]); ++ PyMem_Free(children); ++ _PyPegen_insert_memo(p, start_mark, _loop0_1_type, seq); ++ return seq; ++} ++ ++// _loop1_2: statement ++static asdl_seq * ++_loop1_2_rule(Parser *p) ++{ ++ if (p->error_indicator) { ++ return NULL; ++ } ++ void *res = NULL; ++ int mark = p->mark; ++ int start_mark = p->mark; ++ void **children = PyMem_Malloc(sizeof(void *)); ++ if (!children) { ++ PyErr_Format(PyExc_MemoryError, "Parser out of memory"); ++ return NULL; ++ } ++ ssize_t children_capacity = 1; ++ ssize_t n = 0; ++ { // statement ++ asdl_seq* statement_var; ++ while ( ++ (statement_var = statement_rule(p)) ++ ) ++ { ++ res = statement_var; ++ if (n == children_capacity) { ++ children_capacity *= 2; ++ children = PyMem_Realloc(children, children_capacity*sizeof(void *)); ++ if (!children) { ++ PyErr_Format(PyExc_MemoryError, "realloc None"); ++ return NULL; ++ } ++ } ++ children[n++] = res; ++ mark = p->mark; ++ } ++ p->mark = mark; ++ } ++ if (n == 0) { ++ PyMem_Free(children); ++ return NULL; ++ } ++ asdl_seq *seq = _Py_asdl_seq_new(n, p->arena); ++ if (!seq) { ++ PyErr_Format(PyExc_MemoryError, "asdl_seq_new _loop1_2"); ++ PyMem_Free(children); ++ return NULL; ++ } ++ for (int i = 0; i < n; i++) asdl_seq_SET(seq, i, children[i]); ++ PyMem_Free(children); ++ _PyPegen_insert_memo(p, start_mark, _loop1_2_type, seq); ++ return seq; ++} ++ ++// _loop0_4: ';' small_stmt ++static asdl_seq * ++_loop0_4_rule(Parser *p) ++{ ++ if (p->error_indicator) { ++ return NULL; ++ } ++ void *res = NULL; ++ int mark = p->mark; ++ int start_mark = p->mark; ++ void **children = PyMem_Malloc(sizeof(void *)); ++ if (!children) { ++ PyErr_Format(PyExc_MemoryError, "Parser out of memory"); ++ return NULL; ++ } ++ ssize_t children_capacity = 1; ++ ssize_t n = 0; ++ { // ';' small_stmt ++ stmt_ty elem; ++ void *literal; ++ while ( ++ (literal = _PyPegen_expect_token(p, 13)) ++ && ++ (elem = small_stmt_rule(p)) ++ ) ++ { ++ res = elem; ++ if (res == NULL && PyErr_Occurred()) { ++ p->error_indicator = 1; ++ PyMem_Free(children); ++ return NULL; ++ } ++ if (n == children_capacity) { ++ children_capacity *= 2; ++ children = PyMem_Realloc(children, children_capacity*sizeof(void *)); ++ if (!children) { ++ PyErr_Format(PyExc_MemoryError, "realloc None"); ++ return NULL; ++ } ++ } ++ children[n++] = res; ++ mark = p->mark; ++ } ++ p->mark = mark; ++ } ++ asdl_seq *seq = _Py_asdl_seq_new(n, p->arena); ++ if (!seq) { ++ PyErr_Format(PyExc_MemoryError, "asdl_seq_new _loop0_4"); ++ PyMem_Free(children); ++ return NULL; ++ } ++ for (int i = 0; i < n; i++) asdl_seq_SET(seq, i, children[i]); ++ PyMem_Free(children); ++ _PyPegen_insert_memo(p, start_mark, _loop0_4_type, seq); ++ return seq; ++} ++ ++// _gather_3: small_stmt _loop0_4 ++static asdl_seq * ++_gather_3_rule(Parser *p) ++{ ++ if (p->error_indicator) { ++ return NULL; ++ } ++ asdl_seq * res = NULL; ++ int mark = p->mark; ++ { // small_stmt _loop0_4 ++ stmt_ty elem; ++ asdl_seq * seq; ++ if ( ++ (elem = small_stmt_rule(p)) ++ && ++ (seq = _loop0_4_rule(p)) ++ ) ++ { ++ res = _PyPegen_seq_insert_in_front(p, elem, seq); ++ goto done; ++ } ++ p->mark = mark; ++ } ++ res = NULL; ++ done: ++ return res; ++} ++ ++// _tmp_5: 'import' | 'from' ++static void * ++_tmp_5_rule(Parser *p) ++{ ++ if (p->error_indicator) { ++ return NULL; ++ } ++ void * res = NULL; ++ int mark = p->mark; ++ { // 'import' ++ void *keyword; ++ if ( ++ (keyword = _PyPegen_expect_token(p, 513)) ++ ) ++ { ++ res = keyword; ++ goto done; ++ } ++ p->mark = mark; ++ } ++ { // 'from' ++ void *keyword; ++ if ( ++ (keyword = _PyPegen_expect_token(p, 514)) ++ ) ++ { ++ res = keyword; ++ goto done; ++ } ++ p->mark = mark; ++ } ++ res = NULL; ++ done: ++ return res; ++} ++ ++// _tmp_6: 'def' | '@' | ASYNC ++static void * ++_tmp_6_rule(Parser *p) ++{ ++ if (p->error_indicator) { ++ return NULL; ++ } ++ void * res = NULL; ++ int mark = p->mark; ++ { // 'def' ++ void *keyword; ++ if ( ++ (keyword = _PyPegen_expect_token(p, 522)) ++ ) ++ { ++ res = keyword; ++ goto done; ++ } ++ p->mark = mark; ++ } ++ { // '@' ++ void *literal; ++ if ( ++ (literal = _PyPegen_expect_token(p, 49)) ++ ) ++ { ++ res = literal; ++ goto done; ++ } ++ p->mark = mark; ++ } ++ { // ASYNC ++ void *async_var; ++ if ( ++ (async_var = _PyPegen_async_token(p)) ++ ) ++ { ++ res = async_var; ++ goto done; ++ } ++ p->mark = mark; ++ } ++ res = NULL; ++ done: ++ return res; ++} ++ ++// _tmp_7: 'class' | '@' ++static void * ++_tmp_7_rule(Parser *p) ++{ ++ if (p->error_indicator) { ++ return NULL; ++ } ++ void * res = NULL; ++ int mark = p->mark; ++ { // 'class' ++ void *keyword; ++ if ( ++ (keyword = _PyPegen_expect_token(p, 523)) ++ ) ++ { ++ res = keyword; ++ goto done; ++ } ++ p->mark = mark; ++ } ++ { // '@' ++ void *literal; ++ if ( ++ (literal = _PyPegen_expect_token(p, 49)) ++ ) ++ { ++ res = literal; ++ goto done; ++ } ++ p->mark = mark; ++ } ++ res = NULL; ++ done: ++ return res; ++} ++ ++// _tmp_8: 'with' | ASYNC ++static void * ++_tmp_8_rule(Parser *p) ++{ ++ if (p->error_indicator) { ++ return NULL; ++ } ++ void * res = NULL; ++ int mark = p->mark; ++ { // 'with' ++ void *keyword; ++ if ( ++ (keyword = _PyPegen_expect_token(p, 519)) ++ ) ++ { ++ res = keyword; ++ goto done; ++ } ++ p->mark = mark; ++ } ++ { // ASYNC ++ void *async_var; ++ if ( ++ (async_var = _PyPegen_async_token(p)) ++ ) ++ { ++ res = async_var; ++ goto done; ++ } ++ p->mark = mark; ++ } ++ res = NULL; ++ done: ++ return res; ++} ++ ++// _tmp_9: 'for' | ASYNC ++static void * ++_tmp_9_rule(Parser *p) ++{ ++ if (p->error_indicator) { ++ return NULL; ++ } ++ void * res = NULL; ++ int mark = p->mark; ++ { // 'for' ++ void *keyword; ++ if ( ++ (keyword = _PyPegen_expect_token(p, 517)) ++ ) ++ { ++ res = keyword; ++ goto done; ++ } ++ p->mark = mark; ++ } ++ { // ASYNC ++ void *async_var; ++ if ( ++ (async_var = _PyPegen_async_token(p)) ++ ) ++ { ++ res = async_var; ++ goto done; ++ } ++ p->mark = mark; ++ } ++ res = NULL; ++ done: ++ return res; ++} ++ ++// _tmp_10: '=' annotated_rhs ++static void * ++_tmp_10_rule(Parser *p) ++{ ++ if (p->error_indicator) { ++ return NULL; ++ } ++ void * res = NULL; ++ int mark = p->mark; ++ { // '=' annotated_rhs ++ expr_ty d; ++ void *literal; ++ if ( ++ (literal = _PyPegen_expect_token(p, 22)) ++ && ++ (d = annotated_rhs_rule(p)) ++ ) ++ { ++ res = d; ++ if (res == NULL && PyErr_Occurred()) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ goto done; ++ } ++ p->mark = mark; ++ } ++ res = NULL; ++ done: ++ return res; ++} ++ ++// _tmp_11: '(' inside_paren_ann_assign_target ')' | ann_assign_subscript_attribute_target ++static void * ++_tmp_11_rule(Parser *p) ++{ ++ if (p->error_indicator) { ++ return NULL; ++ } ++ void * res = NULL; ++ int mark = p->mark; ++ { // '(' inside_paren_ann_assign_target ')' ++ expr_ty b; ++ void *literal; ++ void *literal_1; ++ if ( ++ (literal = _PyPegen_expect_token(p, 7)) ++ && ++ (b = inside_paren_ann_assign_target_rule(p)) ++ && ++ (literal_1 = _PyPegen_expect_token(p, 8)) ++ ) ++ { ++ res = b; ++ if (res == NULL && PyErr_Occurred()) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ goto done; ++ } ++ p->mark = mark; ++ } ++ { // ann_assign_subscript_attribute_target ++ expr_ty ann_assign_subscript_attribute_target_var; ++ if ( ++ (ann_assign_subscript_attribute_target_var = ann_assign_subscript_attribute_target_rule(p)) ++ ) ++ { ++ res = ann_assign_subscript_attribute_target_var; ++ goto done; ++ } ++ p->mark = mark; ++ } ++ res = NULL; ++ done: ++ return res; ++} ++ ++// _tmp_12: '=' annotated_rhs ++static void * ++_tmp_12_rule(Parser *p) ++{ ++ if (p->error_indicator) { ++ return NULL; ++ } ++ void * res = NULL; ++ int mark = p->mark; ++ { // '=' annotated_rhs ++ expr_ty d; ++ void *literal; ++ if ( ++ (literal = _PyPegen_expect_token(p, 22)) ++ && ++ (d = annotated_rhs_rule(p)) ++ ) ++ { ++ res = d; ++ if (res == NULL && PyErr_Occurred()) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ goto done; ++ } ++ p->mark = mark; ++ } ++ res = NULL; ++ done: ++ return res; ++} ++ ++// _loop1_13: (star_targets '=') ++static asdl_seq * ++_loop1_13_rule(Parser *p) ++{ ++ if (p->error_indicator) { ++ return NULL; ++ } ++ void *res = NULL; ++ int mark = p->mark; ++ int start_mark = p->mark; ++ void **children = PyMem_Malloc(sizeof(void *)); ++ if (!children) { ++ PyErr_Format(PyExc_MemoryError, "Parser out of memory"); ++ return NULL; ++ } ++ ssize_t children_capacity = 1; ++ ssize_t n = 0; ++ { // (star_targets '=') ++ void *_tmp_123_var; ++ while ( ++ (_tmp_123_var = _tmp_123_rule(p)) ++ ) ++ { ++ res = _tmp_123_var; ++ if (n == children_capacity) { ++ children_capacity *= 2; ++ children = PyMem_Realloc(children, children_capacity*sizeof(void *)); ++ if (!children) { ++ PyErr_Format(PyExc_MemoryError, "realloc None"); ++ return NULL; ++ } ++ } ++ children[n++] = res; ++ mark = p->mark; ++ } ++ p->mark = mark; ++ } ++ if (n == 0) { ++ PyMem_Free(children); ++ return NULL; ++ } ++ asdl_seq *seq = _Py_asdl_seq_new(n, p->arena); ++ if (!seq) { ++ PyErr_Format(PyExc_MemoryError, "asdl_seq_new _loop1_13"); ++ PyMem_Free(children); ++ return NULL; ++ } ++ for (int i = 0; i < n; i++) asdl_seq_SET(seq, i, children[i]); ++ PyMem_Free(children); ++ _PyPegen_insert_memo(p, start_mark, _loop1_13_type, seq); ++ return seq; ++} ++ ++// _tmp_14: yield_expr | star_expressions ++static void * ++_tmp_14_rule(Parser *p) ++{ ++ if (p->error_indicator) { ++ return NULL; ++ } ++ void * res = NULL; ++ int mark = p->mark; ++ { // yield_expr ++ expr_ty yield_expr_var; ++ if ( ++ (yield_expr_var = yield_expr_rule(p)) ++ ) ++ { ++ res = yield_expr_var; ++ goto done; ++ } ++ p->mark = mark; ++ } ++ { // star_expressions ++ expr_ty star_expressions_var; ++ if ( ++ (star_expressions_var = star_expressions_rule(p)) ++ ) ++ { ++ res = star_expressions_var; ++ goto done; ++ } ++ p->mark = mark; ++ } ++ res = NULL; ++ done: ++ return res; ++} ++ ++// _tmp_15: yield_expr | star_expressions ++static void * ++_tmp_15_rule(Parser *p) ++{ ++ if (p->error_indicator) { ++ return NULL; ++ } ++ void * res = NULL; ++ int mark = p->mark; ++ { // yield_expr ++ expr_ty yield_expr_var; ++ if ( ++ (yield_expr_var = yield_expr_rule(p)) ++ ) ++ { ++ res = yield_expr_var; ++ goto done; ++ } ++ p->mark = mark; ++ } ++ { // star_expressions ++ expr_ty star_expressions_var; ++ if ( ++ (star_expressions_var = star_expressions_rule(p)) ++ ) ++ { ++ res = star_expressions_var; ++ goto done; ++ } ++ p->mark = mark; ++ } ++ res = NULL; ++ done: ++ return res; ++} ++ ++// _loop0_17: ',' NAME ++static asdl_seq * ++_loop0_17_rule(Parser *p) ++{ ++ if (p->error_indicator) { ++ return NULL; ++ } ++ void *res = NULL; ++ int mark = p->mark; ++ int start_mark = p->mark; ++ void **children = PyMem_Malloc(sizeof(void *)); ++ if (!children) { ++ PyErr_Format(PyExc_MemoryError, "Parser out of memory"); ++ return NULL; ++ } ++ ssize_t children_capacity = 1; ++ ssize_t n = 0; ++ { // ',' NAME ++ expr_ty elem; ++ void *literal; ++ while ( ++ (literal = _PyPegen_expect_token(p, 12)) ++ && ++ (elem = _PyPegen_name_token(p)) ++ ) ++ { ++ res = elem; ++ if (res == NULL && PyErr_Occurred()) { ++ p->error_indicator = 1; ++ PyMem_Free(children); ++ return NULL; ++ } ++ if (n == children_capacity) { ++ children_capacity *= 2; ++ children = PyMem_Realloc(children, children_capacity*sizeof(void *)); ++ if (!children) { ++ PyErr_Format(PyExc_MemoryError, "realloc None"); ++ return NULL; ++ } ++ } ++ children[n++] = res; ++ mark = p->mark; ++ } ++ p->mark = mark; ++ } ++ asdl_seq *seq = _Py_asdl_seq_new(n, p->arena); ++ if (!seq) { ++ PyErr_Format(PyExc_MemoryError, "asdl_seq_new _loop0_17"); ++ PyMem_Free(children); ++ return NULL; ++ } ++ for (int i = 0; i < n; i++) asdl_seq_SET(seq, i, children[i]); ++ PyMem_Free(children); ++ _PyPegen_insert_memo(p, start_mark, _loop0_17_type, seq); ++ return seq; ++} ++ ++// _gather_16: NAME _loop0_17 ++static asdl_seq * ++_gather_16_rule(Parser *p) ++{ ++ if (p->error_indicator) { ++ return NULL; ++ } ++ asdl_seq * res = NULL; ++ int mark = p->mark; ++ { // NAME _loop0_17 ++ expr_ty elem; ++ asdl_seq * seq; ++ if ( ++ (elem = _PyPegen_name_token(p)) ++ && ++ (seq = _loop0_17_rule(p)) ++ ) ++ { ++ res = _PyPegen_seq_insert_in_front(p, elem, seq); ++ goto done; ++ } ++ p->mark = mark; ++ } ++ res = NULL; ++ done: ++ return res; ++} ++ ++// _loop0_19: ',' NAME ++static asdl_seq * ++_loop0_19_rule(Parser *p) ++{ ++ if (p->error_indicator) { ++ return NULL; ++ } ++ void *res = NULL; ++ int mark = p->mark; ++ int start_mark = p->mark; ++ void **children = PyMem_Malloc(sizeof(void *)); ++ if (!children) { ++ PyErr_Format(PyExc_MemoryError, "Parser out of memory"); ++ return NULL; ++ } ++ ssize_t children_capacity = 1; ++ ssize_t n = 0; ++ { // ',' NAME ++ expr_ty elem; ++ void *literal; ++ while ( ++ (literal = _PyPegen_expect_token(p, 12)) ++ && ++ (elem = _PyPegen_name_token(p)) ++ ) ++ { ++ res = elem; ++ if (res == NULL && PyErr_Occurred()) { ++ p->error_indicator = 1; ++ PyMem_Free(children); ++ return NULL; ++ } ++ if (n == children_capacity) { ++ children_capacity *= 2; ++ children = PyMem_Realloc(children, children_capacity*sizeof(void *)); ++ if (!children) { ++ PyErr_Format(PyExc_MemoryError, "realloc None"); ++ return NULL; ++ } ++ } ++ children[n++] = res; ++ mark = p->mark; ++ } ++ p->mark = mark; ++ } ++ asdl_seq *seq = _Py_asdl_seq_new(n, p->arena); ++ if (!seq) { ++ PyErr_Format(PyExc_MemoryError, "asdl_seq_new _loop0_19"); ++ PyMem_Free(children); ++ return NULL; ++ } ++ for (int i = 0; i < n; i++) asdl_seq_SET(seq, i, children[i]); ++ PyMem_Free(children); ++ _PyPegen_insert_memo(p, start_mark, _loop0_19_type, seq); ++ return seq; ++} ++ ++// _gather_18: NAME _loop0_19 ++static asdl_seq * ++_gather_18_rule(Parser *p) ++{ ++ if (p->error_indicator) { ++ return NULL; ++ } ++ asdl_seq * res = NULL; ++ int mark = p->mark; ++ { // NAME _loop0_19 ++ expr_ty elem; ++ asdl_seq * seq; ++ if ( ++ (elem = _PyPegen_name_token(p)) ++ && ++ (seq = _loop0_19_rule(p)) ++ ) ++ { ++ res = _PyPegen_seq_insert_in_front(p, elem, seq); ++ goto done; ++ } ++ p->mark = mark; ++ } ++ res = NULL; ++ done: ++ return res; ++} ++ ++// _tmp_20: ',' expression ++static void * ++_tmp_20_rule(Parser *p) ++{ ++ if (p->error_indicator) { ++ return NULL; ++ } ++ void * res = NULL; ++ int mark = p->mark; ++ { // ',' expression ++ void *literal; ++ expr_ty z; ++ if ( ++ (literal = _PyPegen_expect_token(p, 12)) ++ && ++ (z = expression_rule(p)) ++ ) ++ { ++ res = z; ++ if (res == NULL && PyErr_Occurred()) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ goto done; ++ } ++ p->mark = mark; ++ } ++ res = NULL; ++ done: ++ return res; ++} ++ ++// _loop0_21: ('.' | '...') ++static asdl_seq * ++_loop0_21_rule(Parser *p) ++{ ++ if (p->error_indicator) { ++ return NULL; ++ } ++ void *res = NULL; ++ int mark = p->mark; ++ int start_mark = p->mark; ++ void **children = PyMem_Malloc(sizeof(void *)); ++ if (!children) { ++ PyErr_Format(PyExc_MemoryError, "Parser out of memory"); ++ return NULL; ++ } ++ ssize_t children_capacity = 1; ++ ssize_t n = 0; ++ { // ('.' | '...') ++ void *_tmp_124_var; ++ while ( ++ (_tmp_124_var = _tmp_124_rule(p)) ++ ) ++ { ++ res = _tmp_124_var; ++ if (n == children_capacity) { ++ children_capacity *= 2; ++ children = PyMem_Realloc(children, children_capacity*sizeof(void *)); ++ if (!children) { ++ PyErr_Format(PyExc_MemoryError, "realloc None"); ++ return NULL; ++ } ++ } ++ children[n++] = res; ++ mark = p->mark; ++ } ++ p->mark = mark; ++ } ++ asdl_seq *seq = _Py_asdl_seq_new(n, p->arena); ++ if (!seq) { ++ PyErr_Format(PyExc_MemoryError, "asdl_seq_new _loop0_21"); ++ PyMem_Free(children); ++ return NULL; ++ } ++ for (int i = 0; i < n; i++) asdl_seq_SET(seq, i, children[i]); ++ PyMem_Free(children); ++ _PyPegen_insert_memo(p, start_mark, _loop0_21_type, seq); ++ return seq; ++} ++ ++// _loop1_22: ('.' | '...') ++static asdl_seq * ++_loop1_22_rule(Parser *p) ++{ ++ if (p->error_indicator) { ++ return NULL; ++ } ++ void *res = NULL; ++ int mark = p->mark; ++ int start_mark = p->mark; ++ void **children = PyMem_Malloc(sizeof(void *)); ++ if (!children) { ++ PyErr_Format(PyExc_MemoryError, "Parser out of memory"); ++ return NULL; ++ } ++ ssize_t children_capacity = 1; ++ ssize_t n = 0; ++ { // ('.' | '...') ++ void *_tmp_125_var; ++ while ( ++ (_tmp_125_var = _tmp_125_rule(p)) ++ ) ++ { ++ res = _tmp_125_var; ++ if (n == children_capacity) { ++ children_capacity *= 2; ++ children = PyMem_Realloc(children, children_capacity*sizeof(void *)); ++ if (!children) { ++ PyErr_Format(PyExc_MemoryError, "realloc None"); ++ return NULL; ++ } ++ } ++ children[n++] = res; ++ mark = p->mark; ++ } ++ p->mark = mark; ++ } ++ if (n == 0) { ++ PyMem_Free(children); ++ return NULL; ++ } ++ asdl_seq *seq = _Py_asdl_seq_new(n, p->arena); ++ if (!seq) { ++ PyErr_Format(PyExc_MemoryError, "asdl_seq_new _loop1_22"); ++ PyMem_Free(children); ++ return NULL; ++ } ++ for (int i = 0; i < n; i++) asdl_seq_SET(seq, i, children[i]); ++ PyMem_Free(children); ++ _PyPegen_insert_memo(p, start_mark, _loop1_22_type, seq); ++ return seq; ++} ++ ++// _loop0_24: ',' import_from_as_name ++static asdl_seq * ++_loop0_24_rule(Parser *p) ++{ ++ if (p->error_indicator) { ++ return NULL; ++ } ++ void *res = NULL; ++ int mark = p->mark; ++ int start_mark = p->mark; ++ void **children = PyMem_Malloc(sizeof(void *)); ++ if (!children) { ++ PyErr_Format(PyExc_MemoryError, "Parser out of memory"); ++ return NULL; ++ } ++ ssize_t children_capacity = 1; ++ ssize_t n = 0; ++ { // ',' import_from_as_name ++ alias_ty elem; ++ void *literal; ++ while ( ++ (literal = _PyPegen_expect_token(p, 12)) ++ && ++ (elem = import_from_as_name_rule(p)) ++ ) ++ { ++ res = elem; ++ if (res == NULL && PyErr_Occurred()) { ++ p->error_indicator = 1; ++ PyMem_Free(children); ++ return NULL; ++ } ++ if (n == children_capacity) { ++ children_capacity *= 2; ++ children = PyMem_Realloc(children, children_capacity*sizeof(void *)); ++ if (!children) { ++ PyErr_Format(PyExc_MemoryError, "realloc None"); ++ return NULL; ++ } ++ } ++ children[n++] = res; ++ mark = p->mark; ++ } ++ p->mark = mark; ++ } ++ asdl_seq *seq = _Py_asdl_seq_new(n, p->arena); ++ if (!seq) { ++ PyErr_Format(PyExc_MemoryError, "asdl_seq_new _loop0_24"); ++ PyMem_Free(children); ++ return NULL; ++ } ++ for (int i = 0; i < n; i++) asdl_seq_SET(seq, i, children[i]); ++ PyMem_Free(children); ++ _PyPegen_insert_memo(p, start_mark, _loop0_24_type, seq); ++ return seq; ++} ++ ++// _gather_23: import_from_as_name _loop0_24 ++static asdl_seq * ++_gather_23_rule(Parser *p) ++{ ++ if (p->error_indicator) { ++ return NULL; ++ } ++ asdl_seq * res = NULL; ++ int mark = p->mark; ++ { // import_from_as_name _loop0_24 ++ alias_ty elem; ++ asdl_seq * seq; ++ if ( ++ (elem = import_from_as_name_rule(p)) ++ && ++ (seq = _loop0_24_rule(p)) ++ ) ++ { ++ res = _PyPegen_seq_insert_in_front(p, elem, seq); ++ goto done; ++ } ++ p->mark = mark; ++ } ++ res = NULL; ++ done: ++ return res; ++} ++ ++// _tmp_25: 'as' NAME ++static void * ++_tmp_25_rule(Parser *p) ++{ ++ if (p->error_indicator) { ++ return NULL; ++ } ++ void * res = NULL; ++ int mark = p->mark; ++ { // 'as' NAME ++ void *keyword; ++ expr_ty z; ++ if ( ++ (keyword = _PyPegen_expect_token(p, 531)) ++ && ++ (z = _PyPegen_name_token(p)) ++ ) ++ { ++ res = z; ++ if (res == NULL && PyErr_Occurred()) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ goto done; ++ } ++ p->mark = mark; ++ } ++ res = NULL; ++ done: ++ return res; ++} ++ ++// _loop0_27: ',' dotted_as_name ++static asdl_seq * ++_loop0_27_rule(Parser *p) ++{ ++ if (p->error_indicator) { ++ return NULL; ++ } ++ void *res = NULL; ++ int mark = p->mark; ++ int start_mark = p->mark; ++ void **children = PyMem_Malloc(sizeof(void *)); ++ if (!children) { ++ PyErr_Format(PyExc_MemoryError, "Parser out of memory"); ++ return NULL; ++ } ++ ssize_t children_capacity = 1; ++ ssize_t n = 0; ++ { // ',' dotted_as_name ++ alias_ty elem; ++ void *literal; ++ while ( ++ (literal = _PyPegen_expect_token(p, 12)) ++ && ++ (elem = dotted_as_name_rule(p)) ++ ) ++ { ++ res = elem; ++ if (res == NULL && PyErr_Occurred()) { ++ p->error_indicator = 1; ++ PyMem_Free(children); ++ return NULL; ++ } ++ if (n == children_capacity) { ++ children_capacity *= 2; ++ children = PyMem_Realloc(children, children_capacity*sizeof(void *)); ++ if (!children) { ++ PyErr_Format(PyExc_MemoryError, "realloc None"); ++ return NULL; ++ } ++ } ++ children[n++] = res; ++ mark = p->mark; ++ } ++ p->mark = mark; ++ } ++ asdl_seq *seq = _Py_asdl_seq_new(n, p->arena); ++ if (!seq) { ++ PyErr_Format(PyExc_MemoryError, "asdl_seq_new _loop0_27"); ++ PyMem_Free(children); ++ return NULL; ++ } ++ for (int i = 0; i < n; i++) asdl_seq_SET(seq, i, children[i]); ++ PyMem_Free(children); ++ _PyPegen_insert_memo(p, start_mark, _loop0_27_type, seq); ++ return seq; ++} ++ ++// _gather_26: dotted_as_name _loop0_27 ++static asdl_seq * ++_gather_26_rule(Parser *p) ++{ ++ if (p->error_indicator) { ++ return NULL; ++ } ++ asdl_seq * res = NULL; ++ int mark = p->mark; ++ { // dotted_as_name _loop0_27 ++ alias_ty elem; ++ asdl_seq * seq; ++ if ( ++ (elem = dotted_as_name_rule(p)) ++ && ++ (seq = _loop0_27_rule(p)) ++ ) ++ { ++ res = _PyPegen_seq_insert_in_front(p, elem, seq); ++ goto done; ++ } ++ p->mark = mark; ++ } ++ res = NULL; ++ done: ++ return res; ++} ++ ++// _tmp_28: 'as' NAME ++static void * ++_tmp_28_rule(Parser *p) ++{ ++ if (p->error_indicator) { ++ return NULL; ++ } ++ void * res = NULL; ++ int mark = p->mark; ++ { // 'as' NAME ++ void *keyword; ++ expr_ty z; ++ if ( ++ (keyword = _PyPegen_expect_token(p, 531)) ++ && ++ (z = _PyPegen_name_token(p)) ++ ) ++ { ++ res = z; ++ if (res == NULL && PyErr_Occurred()) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ goto done; ++ } ++ p->mark = mark; ++ } ++ res = NULL; ++ done: ++ return res; ++} ++ ++// _loop0_30: ',' with_item ++static asdl_seq * ++_loop0_30_rule(Parser *p) ++{ ++ if (p->error_indicator) { ++ return NULL; ++ } ++ void *res = NULL; ++ int mark = p->mark; ++ int start_mark = p->mark; ++ void **children = PyMem_Malloc(sizeof(void *)); ++ if (!children) { ++ PyErr_Format(PyExc_MemoryError, "Parser out of memory"); ++ return NULL; ++ } ++ ssize_t children_capacity = 1; ++ ssize_t n = 0; ++ { // ',' with_item ++ withitem_ty elem; ++ void *literal; ++ while ( ++ (literal = _PyPegen_expect_token(p, 12)) ++ && ++ (elem = with_item_rule(p)) ++ ) ++ { ++ res = elem; ++ if (res == NULL && PyErr_Occurred()) { ++ p->error_indicator = 1; ++ PyMem_Free(children); ++ return NULL; ++ } ++ if (n == children_capacity) { ++ children_capacity *= 2; ++ children = PyMem_Realloc(children, children_capacity*sizeof(void *)); ++ if (!children) { ++ PyErr_Format(PyExc_MemoryError, "realloc None"); ++ return NULL; ++ } ++ } ++ children[n++] = res; ++ mark = p->mark; ++ } ++ p->mark = mark; ++ } ++ asdl_seq *seq = _Py_asdl_seq_new(n, p->arena); ++ if (!seq) { ++ PyErr_Format(PyExc_MemoryError, "asdl_seq_new _loop0_30"); ++ PyMem_Free(children); ++ return NULL; ++ } ++ for (int i = 0; i < n; i++) asdl_seq_SET(seq, i, children[i]); ++ PyMem_Free(children); ++ _PyPegen_insert_memo(p, start_mark, _loop0_30_type, seq); ++ return seq; ++} ++ ++// _gather_29: with_item _loop0_30 ++static asdl_seq * ++_gather_29_rule(Parser *p) ++{ ++ if (p->error_indicator) { ++ return NULL; ++ } ++ asdl_seq * res = NULL; ++ int mark = p->mark; ++ { // with_item _loop0_30 ++ withitem_ty elem; ++ asdl_seq * seq; ++ if ( ++ (elem = with_item_rule(p)) ++ && ++ (seq = _loop0_30_rule(p)) ++ ) ++ { ++ res = _PyPegen_seq_insert_in_front(p, elem, seq); ++ goto done; ++ } ++ p->mark = mark; ++ } ++ res = NULL; ++ done: ++ return res; ++} ++ ++// _loop0_32: ',' with_item ++static asdl_seq * ++_loop0_32_rule(Parser *p) ++{ ++ if (p->error_indicator) { ++ return NULL; ++ } ++ void *res = NULL; ++ int mark = p->mark; ++ int start_mark = p->mark; ++ void **children = PyMem_Malloc(sizeof(void *)); ++ if (!children) { ++ PyErr_Format(PyExc_MemoryError, "Parser out of memory"); ++ return NULL; ++ } ++ ssize_t children_capacity = 1; ++ ssize_t n = 0; ++ { // ',' with_item ++ withitem_ty elem; ++ void *literal; ++ while ( ++ (literal = _PyPegen_expect_token(p, 12)) ++ && ++ (elem = with_item_rule(p)) ++ ) ++ { ++ res = elem; ++ if (res == NULL && PyErr_Occurred()) { ++ p->error_indicator = 1; ++ PyMem_Free(children); ++ return NULL; ++ } ++ if (n == children_capacity) { ++ children_capacity *= 2; ++ children = PyMem_Realloc(children, children_capacity*sizeof(void *)); ++ if (!children) { ++ PyErr_Format(PyExc_MemoryError, "realloc None"); ++ return NULL; ++ } ++ } ++ children[n++] = res; ++ mark = p->mark; ++ } ++ p->mark = mark; ++ } ++ asdl_seq *seq = _Py_asdl_seq_new(n, p->arena); ++ if (!seq) { ++ PyErr_Format(PyExc_MemoryError, "asdl_seq_new _loop0_32"); ++ PyMem_Free(children); ++ return NULL; ++ } ++ for (int i = 0; i < n; i++) asdl_seq_SET(seq, i, children[i]); ++ PyMem_Free(children); ++ _PyPegen_insert_memo(p, start_mark, _loop0_32_type, seq); ++ return seq; ++} ++ ++// _gather_31: with_item _loop0_32 ++static asdl_seq * ++_gather_31_rule(Parser *p) ++{ ++ if (p->error_indicator) { ++ return NULL; ++ } ++ asdl_seq * res = NULL; ++ int mark = p->mark; ++ { // with_item _loop0_32 ++ withitem_ty elem; ++ asdl_seq * seq; ++ if ( ++ (elem = with_item_rule(p)) ++ && ++ (seq = _loop0_32_rule(p)) ++ ) ++ { ++ res = _PyPegen_seq_insert_in_front(p, elem, seq); ++ goto done; ++ } ++ p->mark = mark; ++ } ++ res = NULL; ++ done: ++ return res; ++} ++ ++// _tmp_33: 'as' target ++static void * ++_tmp_33_rule(Parser *p) ++{ ++ if (p->error_indicator) { ++ return NULL; ++ } ++ void * res = NULL; ++ int mark = p->mark; ++ { // 'as' target ++ void *keyword; ++ expr_ty t; ++ if ( ++ (keyword = _PyPegen_expect_token(p, 531)) ++ && ++ (t = target_rule(p)) ++ ) ++ { ++ res = t; ++ if (res == NULL && PyErr_Occurred()) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ goto done; ++ } ++ p->mark = mark; ++ } ++ res = NULL; ++ done: ++ return res; ++} ++ ++// _loop1_34: except_block ++static asdl_seq * ++_loop1_34_rule(Parser *p) ++{ ++ if (p->error_indicator) { ++ return NULL; ++ } ++ void *res = NULL; ++ int mark = p->mark; ++ int start_mark = p->mark; ++ void **children = PyMem_Malloc(sizeof(void *)); ++ if (!children) { ++ PyErr_Format(PyExc_MemoryError, "Parser out of memory"); ++ return NULL; ++ } ++ ssize_t children_capacity = 1; ++ ssize_t n = 0; ++ { // except_block ++ excepthandler_ty except_block_var; ++ while ( ++ (except_block_var = except_block_rule(p)) ++ ) ++ { ++ res = except_block_var; ++ if (n == children_capacity) { ++ children_capacity *= 2; ++ children = PyMem_Realloc(children, children_capacity*sizeof(void *)); ++ if (!children) { ++ PyErr_Format(PyExc_MemoryError, "realloc None"); ++ return NULL; ++ } ++ } ++ children[n++] = res; ++ mark = p->mark; ++ } ++ p->mark = mark; ++ } ++ if (n == 0) { ++ PyMem_Free(children); ++ return NULL; ++ } ++ asdl_seq *seq = _Py_asdl_seq_new(n, p->arena); ++ if (!seq) { ++ PyErr_Format(PyExc_MemoryError, "asdl_seq_new _loop1_34"); ++ PyMem_Free(children); ++ return NULL; ++ } ++ for (int i = 0; i < n; i++) asdl_seq_SET(seq, i, children[i]); ++ PyMem_Free(children); ++ _PyPegen_insert_memo(p, start_mark, _loop1_34_type, seq); ++ return seq; ++} ++ ++// _tmp_35: 'as' target ++static void * ++_tmp_35_rule(Parser *p) ++{ ++ if (p->error_indicator) { ++ return NULL; ++ } ++ void * res = NULL; ++ int mark = p->mark; ++ { // 'as' target ++ void *keyword; ++ expr_ty z; ++ if ( ++ (keyword = _PyPegen_expect_token(p, 531)) ++ && ++ (z = target_rule(p)) ++ ) ++ { ++ res = z; ++ if (res == NULL && PyErr_Occurred()) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ goto done; ++ } ++ p->mark = mark; ++ } ++ res = NULL; ++ done: ++ return res; ++} ++ ++// _tmp_36: 'from' expression ++static void * ++_tmp_36_rule(Parser *p) ++{ ++ if (p->error_indicator) { ++ return NULL; ++ } ++ void * res = NULL; ++ int mark = p->mark; ++ { // 'from' expression ++ void *keyword; ++ expr_ty z; ++ if ( ++ (keyword = _PyPegen_expect_token(p, 514)) ++ && ++ (z = expression_rule(p)) ++ ) ++ { ++ res = z; ++ if (res == NULL && PyErr_Occurred()) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ goto done; ++ } ++ p->mark = mark; ++ } ++ res = NULL; ++ done: ++ return res; ++} ++ ++// _tmp_37: '->' annotation ++static void * ++_tmp_37_rule(Parser *p) ++{ ++ if (p->error_indicator) { ++ return NULL; ++ } ++ void * res = NULL; ++ int mark = p->mark; ++ { // '->' annotation ++ void *literal; ++ expr_ty z; ++ if ( ++ (literal = _PyPegen_expect_token(p, 51)) ++ && ++ (z = annotation_rule(p)) ++ ) ++ { ++ res = z; ++ if (res == NULL && PyErr_Occurred()) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ goto done; ++ } ++ p->mark = mark; ++ } ++ res = NULL; ++ done: ++ return res; ++} ++ ++// _tmp_38: ',' plain_names ++static void * ++_tmp_38_rule(Parser *p) ++{ ++ if (p->error_indicator) { ++ return NULL; ++ } ++ void * res = NULL; ++ int mark = p->mark; ++ { // ',' plain_names ++ void *literal; ++ asdl_seq* x; ++ if ( ++ (literal = _PyPegen_expect_token(p, 12)) ++ && ++ (x = plain_names_rule(p)) ++ ) ++ { ++ res = x; ++ if (res == NULL && PyErr_Occurred()) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ goto done; ++ } ++ p->mark = mark; ++ } ++ res = NULL; ++ done: ++ return res; ++} ++ ++// _tmp_39: ',' names_with_default ++static void * ++_tmp_39_rule(Parser *p) ++{ ++ if (p->error_indicator) { ++ return NULL; ++ } ++ void * res = NULL; ++ int mark = p->mark; ++ { // ',' names_with_default ++ void *literal; ++ asdl_seq* y; ++ if ( ++ (literal = _PyPegen_expect_token(p, 12)) ++ && ++ (y = names_with_default_rule(p)) ++ ) ++ { ++ res = y; ++ if (res == NULL && PyErr_Occurred()) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ goto done; ++ } ++ p->mark = mark; ++ } ++ res = NULL; ++ done: ++ return res; ++} ++ ++// _tmp_40: ',' star_etc? ++static void * ++_tmp_40_rule(Parser *p) ++{ ++ if (p->error_indicator) { ++ return NULL; ++ } ++ void * res = NULL; ++ int mark = p->mark; ++ { // ',' star_etc? ++ void *literal; ++ void *z; ++ if ( ++ (literal = _PyPegen_expect_token(p, 12)) ++ && ++ (z = star_etc_rule(p), 1) ++ ) ++ { ++ res = z; ++ if (res == NULL && PyErr_Occurred()) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ goto done; ++ } ++ p->mark = mark; ++ } ++ res = NULL; ++ done: ++ return res; ++} ++ ++// _tmp_41: ',' names_with_default ++static void * ++_tmp_41_rule(Parser *p) ++{ ++ if (p->error_indicator) { ++ return NULL; ++ } ++ void * res = NULL; ++ int mark = p->mark; ++ { // ',' names_with_default ++ void *literal; ++ asdl_seq* y; ++ if ( ++ (literal = _PyPegen_expect_token(p, 12)) ++ && ++ (y = names_with_default_rule(p)) ++ ) ++ { ++ res = y; ++ if (res == NULL && PyErr_Occurred()) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ goto done; ++ } ++ p->mark = mark; ++ } ++ res = NULL; ++ done: ++ return res; ++} ++ ++// _tmp_42: ',' star_etc? ++static void * ++_tmp_42_rule(Parser *p) ++{ ++ if (p->error_indicator) { ++ return NULL; ++ } ++ void * res = NULL; ++ int mark = p->mark; ++ { // ',' star_etc? ++ void *literal; ++ void *z; ++ if ( ++ (literal = _PyPegen_expect_token(p, 12)) ++ && ++ (z = star_etc_rule(p), 1) ++ ) ++ { ++ res = z; ++ if (res == NULL && PyErr_Occurred()) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ goto done; ++ } ++ p->mark = mark; ++ } ++ res = NULL; ++ done: ++ return res; ++} ++ ++// _tmp_43: ',' names_with_default ++static void * ++_tmp_43_rule(Parser *p) ++{ ++ if (p->error_indicator) { ++ return NULL; ++ } ++ void * res = NULL; ++ int mark = p->mark; ++ { // ',' names_with_default ++ void *literal; ++ asdl_seq* y; ++ if ( ++ (literal = _PyPegen_expect_token(p, 12)) ++ && ++ (y = names_with_default_rule(p)) ++ ) ++ { ++ res = y; ++ if (res == NULL && PyErr_Occurred()) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ goto done; ++ } ++ p->mark = mark; ++ } ++ res = NULL; ++ done: ++ return res; ++} ++ ++// _tmp_44: ',' star_etc? ++static void * ++_tmp_44_rule(Parser *p) ++{ ++ if (p->error_indicator) { ++ return NULL; ++ } ++ void * res = NULL; ++ int mark = p->mark; ++ { // ',' star_etc? ++ void *literal; ++ void *z; ++ if ( ++ (literal = _PyPegen_expect_token(p, 12)) ++ && ++ (z = star_etc_rule(p), 1) ++ ) ++ { ++ res = z; ++ if (res == NULL && PyErr_Occurred()) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ goto done; ++ } ++ p->mark = mark; ++ } ++ res = NULL; ++ done: ++ return res; ++} ++ ++// _tmp_45: ',' star_etc? ++static void * ++_tmp_45_rule(Parser *p) ++{ ++ if (p->error_indicator) { ++ return NULL; ++ } ++ void * res = NULL; ++ int mark = p->mark; ++ { // ',' star_etc? ++ void *literal; ++ void *z; ++ if ( ++ (literal = _PyPegen_expect_token(p, 12)) ++ && ++ (z = star_etc_rule(p), 1) ++ ) ++ { ++ res = z; ++ if (res == NULL && PyErr_Occurred()) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ goto done; ++ } ++ p->mark = mark; ++ } ++ res = NULL; ++ done: ++ return res; ++} ++ ++// _tmp_46: plain_names ',' ++static void * ++_tmp_46_rule(Parser *p) ++{ ++ if (p->error_indicator) { ++ return NULL; ++ } ++ void * res = NULL; ++ int mark = p->mark; ++ { // plain_names ',' ++ void *literal; ++ asdl_seq* n; ++ if ( ++ (n = plain_names_rule(p)) ++ && ++ (literal = _PyPegen_expect_token(p, 12)) ++ ) ++ { ++ res = n; ++ if (res == NULL && PyErr_Occurred()) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ goto done; ++ } ++ p->mark = mark; ++ } ++ res = NULL; ++ done: ++ return res; ++} ++ ++// _loop0_47: name_with_optional_default ++static asdl_seq * ++_loop0_47_rule(Parser *p) ++{ ++ if (p->error_indicator) { ++ return NULL; ++ } ++ void *res = NULL; ++ int mark = p->mark; ++ int start_mark = p->mark; ++ void **children = PyMem_Malloc(sizeof(void *)); ++ if (!children) { ++ PyErr_Format(PyExc_MemoryError, "Parser out of memory"); ++ return NULL; ++ } ++ ssize_t children_capacity = 1; ++ ssize_t n = 0; ++ { // name_with_optional_default ++ NameDefaultPair* name_with_optional_default_var; ++ while ( ++ (name_with_optional_default_var = name_with_optional_default_rule(p)) ++ ) ++ { ++ res = name_with_optional_default_var; ++ if (n == children_capacity) { ++ children_capacity *= 2; ++ children = PyMem_Realloc(children, children_capacity*sizeof(void *)); ++ if (!children) { ++ PyErr_Format(PyExc_MemoryError, "realloc None"); ++ return NULL; ++ } ++ } ++ children[n++] = res; ++ mark = p->mark; ++ } ++ p->mark = mark; ++ } ++ asdl_seq *seq = _Py_asdl_seq_new(n, p->arena); ++ if (!seq) { ++ PyErr_Format(PyExc_MemoryError, "asdl_seq_new _loop0_47"); ++ PyMem_Free(children); ++ return NULL; ++ } ++ for (int i = 0; i < n; i++) asdl_seq_SET(seq, i, children[i]); ++ PyMem_Free(children); ++ _PyPegen_insert_memo(p, start_mark, _loop0_47_type, seq); ++ return seq; ++} ++ ++// _tmp_48: ',' kwds ++static void * ++_tmp_48_rule(Parser *p) ++{ ++ if (p->error_indicator) { ++ return NULL; ++ } ++ void * res = NULL; ++ int mark = p->mark; ++ { // ',' kwds ++ arg_ty d; ++ void *literal; ++ if ( ++ (literal = _PyPegen_expect_token(p, 12)) ++ && ++ (d = kwds_rule(p)) ++ ) ++ { ++ res = d; ++ if (res == NULL && PyErr_Occurred()) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ goto done; ++ } ++ p->mark = mark; ++ } ++ res = NULL; ++ done: ++ return res; ++} ++ ++// _loop1_49: name_with_optional_default ++static asdl_seq * ++_loop1_49_rule(Parser *p) ++{ ++ if (p->error_indicator) { ++ return NULL; ++ } ++ void *res = NULL; ++ int mark = p->mark; ++ int start_mark = p->mark; ++ void **children = PyMem_Malloc(sizeof(void *)); ++ if (!children) { ++ PyErr_Format(PyExc_MemoryError, "Parser out of memory"); ++ return NULL; ++ } ++ ssize_t children_capacity = 1; ++ ssize_t n = 0; ++ { // name_with_optional_default ++ NameDefaultPair* name_with_optional_default_var; ++ while ( ++ (name_with_optional_default_var = name_with_optional_default_rule(p)) ++ ) ++ { ++ res = name_with_optional_default_var; ++ if (n == children_capacity) { ++ children_capacity *= 2; ++ children = PyMem_Realloc(children, children_capacity*sizeof(void *)); ++ if (!children) { ++ PyErr_Format(PyExc_MemoryError, "realloc None"); ++ return NULL; ++ } ++ } ++ children[n++] = res; ++ mark = p->mark; ++ } ++ p->mark = mark; ++ } ++ if (n == 0) { ++ PyMem_Free(children); ++ return NULL; ++ } ++ asdl_seq *seq = _Py_asdl_seq_new(n, p->arena); ++ if (!seq) { ++ PyErr_Format(PyExc_MemoryError, "asdl_seq_new _loop1_49"); ++ PyMem_Free(children); ++ return NULL; ++ } ++ for (int i = 0; i < n; i++) asdl_seq_SET(seq, i, children[i]); ++ PyMem_Free(children); ++ _PyPegen_insert_memo(p, start_mark, _loop1_49_type, seq); ++ return seq; ++} ++ ++// _tmp_50: ',' kwds ++static void * ++_tmp_50_rule(Parser *p) ++{ ++ if (p->error_indicator) { ++ return NULL; ++ } ++ void * res = NULL; ++ int mark = p->mark; ++ { // ',' kwds ++ arg_ty d; ++ void *literal; ++ if ( ++ (literal = _PyPegen_expect_token(p, 12)) ++ && ++ (d = kwds_rule(p)) ++ ) ++ { ++ res = d; ++ if (res == NULL && PyErr_Occurred()) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ goto done; ++ } ++ p->mark = mark; ++ } ++ res = NULL; ++ done: ++ return res; ++} ++ ++// _tmp_51: '=' expression ++static void * ++_tmp_51_rule(Parser *p) ++{ ++ if (p->error_indicator) { ++ return NULL; ++ } ++ void * res = NULL; ++ int mark = p->mark; ++ { // '=' expression ++ expr_ty e; ++ void *literal; ++ if ( ++ (literal = _PyPegen_expect_token(p, 22)) ++ && ++ (e = expression_rule(p)) ++ ) ++ { ++ res = e; ++ if (res == NULL && PyErr_Occurred()) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ goto done; ++ } ++ p->mark = mark; ++ } ++ res = NULL; ++ done: ++ return res; ++} ++ ++// _loop0_53: ',' name_with_default ++static asdl_seq * ++_loop0_53_rule(Parser *p) ++{ ++ if (p->error_indicator) { ++ return NULL; ++ } ++ void *res = NULL; ++ int mark = p->mark; ++ int start_mark = p->mark; ++ void **children = PyMem_Malloc(sizeof(void *)); ++ if (!children) { ++ PyErr_Format(PyExc_MemoryError, "Parser out of memory"); ++ return NULL; ++ } ++ ssize_t children_capacity = 1; ++ ssize_t n = 0; ++ { // ',' name_with_default ++ NameDefaultPair* elem; ++ void *literal; ++ while ( ++ (literal = _PyPegen_expect_token(p, 12)) ++ && ++ (elem = name_with_default_rule(p)) ++ ) ++ { ++ res = elem; ++ if (res == NULL && PyErr_Occurred()) { ++ p->error_indicator = 1; ++ PyMem_Free(children); ++ return NULL; ++ } ++ if (n == children_capacity) { ++ children_capacity *= 2; ++ children = PyMem_Realloc(children, children_capacity*sizeof(void *)); ++ if (!children) { ++ PyErr_Format(PyExc_MemoryError, "realloc None"); ++ return NULL; ++ } ++ } ++ children[n++] = res; ++ mark = p->mark; ++ } ++ p->mark = mark; ++ } ++ asdl_seq *seq = _Py_asdl_seq_new(n, p->arena); ++ if (!seq) { ++ PyErr_Format(PyExc_MemoryError, "asdl_seq_new _loop0_53"); ++ PyMem_Free(children); ++ return NULL; ++ } ++ for (int i = 0; i < n; i++) asdl_seq_SET(seq, i, children[i]); ++ PyMem_Free(children); ++ _PyPegen_insert_memo(p, start_mark, _loop0_53_type, seq); ++ return seq; ++} ++ ++// _gather_52: name_with_default _loop0_53 ++static asdl_seq * ++_gather_52_rule(Parser *p) ++{ ++ if (p->error_indicator) { ++ return NULL; ++ } ++ asdl_seq * res = NULL; ++ int mark = p->mark; ++ { // name_with_default _loop0_53 ++ NameDefaultPair* elem; ++ asdl_seq * seq; ++ if ( ++ (elem = name_with_default_rule(p)) ++ && ++ (seq = _loop0_53_rule(p)) ++ ) ++ { ++ res = _PyPegen_seq_insert_in_front(p, elem, seq); ++ goto done; ++ } ++ p->mark = mark; ++ } ++ res = NULL; ++ done: ++ return res; ++} ++ ++// _loop0_55: ',' (plain_name !'=') ++static asdl_seq * ++_loop0_55_rule(Parser *p) ++{ ++ if (p->error_indicator) { ++ return NULL; ++ } ++ void *res = NULL; ++ int mark = p->mark; ++ int start_mark = p->mark; ++ void **children = PyMem_Malloc(sizeof(void *)); ++ if (!children) { ++ PyErr_Format(PyExc_MemoryError, "Parser out of memory"); ++ return NULL; ++ } ++ ssize_t children_capacity = 1; ++ ssize_t n = 0; ++ { // ',' (plain_name !'=') ++ void *elem; ++ void *literal; ++ while ( ++ (literal = _PyPegen_expect_token(p, 12)) ++ && ++ (elem = _tmp_126_rule(p)) ++ ) ++ { ++ res = elem; ++ if (res == NULL && PyErr_Occurred()) { ++ p->error_indicator = 1; ++ PyMem_Free(children); ++ return NULL; ++ } ++ if (n == children_capacity) { ++ children_capacity *= 2; ++ children = PyMem_Realloc(children, children_capacity*sizeof(void *)); ++ if (!children) { ++ PyErr_Format(PyExc_MemoryError, "realloc None"); ++ return NULL; ++ } ++ } ++ children[n++] = res; ++ mark = p->mark; ++ } ++ p->mark = mark; ++ } ++ asdl_seq *seq = _Py_asdl_seq_new(n, p->arena); ++ if (!seq) { ++ PyErr_Format(PyExc_MemoryError, "asdl_seq_new _loop0_55"); ++ PyMem_Free(children); ++ return NULL; ++ } ++ for (int i = 0; i < n; i++) asdl_seq_SET(seq, i, children[i]); ++ PyMem_Free(children); ++ _PyPegen_insert_memo(p, start_mark, _loop0_55_type, seq); ++ return seq; ++} ++ ++// _gather_54: (plain_name !'=') _loop0_55 ++static asdl_seq * ++_gather_54_rule(Parser *p) ++{ ++ if (p->error_indicator) { ++ return NULL; ++ } ++ asdl_seq * res = NULL; ++ int mark = p->mark; ++ { // (plain_name !'=') _loop0_55 ++ void *elem; ++ asdl_seq * seq; ++ if ( ++ (elem = _tmp_126_rule(p)) ++ && ++ (seq = _loop0_55_rule(p)) ++ ) ++ { ++ res = _PyPegen_seq_insert_in_front(p, elem, seq); ++ goto done; ++ } ++ p->mark = mark; ++ } ++ res = NULL; ++ done: ++ return res; ++} ++ ++// _tmp_56: ':' annotation ++static void * ++_tmp_56_rule(Parser *p) ++{ ++ if (p->error_indicator) { ++ return NULL; ++ } ++ void * res = NULL; ++ int mark = p->mark; ++ { // ':' annotation ++ void *literal; ++ expr_ty z; ++ if ( ++ (literal = _PyPegen_expect_token(p, 11)) ++ && ++ (z = annotation_rule(p)) ++ ) ++ { ++ res = z; ++ if (res == NULL && PyErr_Occurred()) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ goto done; ++ } ++ p->mark = mark; ++ } ++ res = NULL; ++ done: ++ return res; ++} ++ ++// _loop1_57: ('@' named_expression NEWLINE) ++static asdl_seq * ++_loop1_57_rule(Parser *p) ++{ ++ if (p->error_indicator) { ++ return NULL; ++ } ++ void *res = NULL; ++ int mark = p->mark; ++ int start_mark = p->mark; ++ void **children = PyMem_Malloc(sizeof(void *)); ++ if (!children) { ++ PyErr_Format(PyExc_MemoryError, "Parser out of memory"); ++ return NULL; ++ } ++ ssize_t children_capacity = 1; ++ ssize_t n = 0; ++ { // ('@' named_expression NEWLINE) ++ void *_tmp_127_var; ++ while ( ++ (_tmp_127_var = _tmp_127_rule(p)) ++ ) ++ { ++ res = _tmp_127_var; ++ if (n == children_capacity) { ++ children_capacity *= 2; ++ children = PyMem_Realloc(children, children_capacity*sizeof(void *)); ++ if (!children) { ++ PyErr_Format(PyExc_MemoryError, "realloc None"); ++ return NULL; ++ } ++ } ++ children[n++] = res; ++ mark = p->mark; ++ } ++ p->mark = mark; ++ } ++ if (n == 0) { ++ PyMem_Free(children); ++ return NULL; ++ } ++ asdl_seq *seq = _Py_asdl_seq_new(n, p->arena); ++ if (!seq) { ++ PyErr_Format(PyExc_MemoryError, "asdl_seq_new _loop1_57"); ++ PyMem_Free(children); ++ return NULL; ++ } ++ for (int i = 0; i < n; i++) asdl_seq_SET(seq, i, children[i]); ++ PyMem_Free(children); ++ _PyPegen_insert_memo(p, start_mark, _loop1_57_type, seq); ++ return seq; ++} ++ ++// _tmp_58: '(' arguments? ')' ++static void * ++_tmp_58_rule(Parser *p) ++{ ++ if (p->error_indicator) { ++ return NULL; ++ } ++ void * res = NULL; ++ int mark = p->mark; ++ { // '(' arguments? ')' ++ void *literal; ++ void *literal_1; ++ void *z; ++ if ( ++ (literal = _PyPegen_expect_token(p, 7)) ++ && ++ (z = arguments_rule(p), 1) ++ && ++ (literal_1 = _PyPegen_expect_token(p, 8)) ++ ) ++ { ++ res = z; ++ if (res == NULL && PyErr_Occurred()) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ goto done; ++ } ++ p->mark = mark; ++ } ++ res = NULL; ++ done: ++ return res; ++} ++ ++// _loop0_60: ',' star_expression ++static asdl_seq * ++_loop0_60_rule(Parser *p) ++{ ++ if (p->error_indicator) { ++ return NULL; ++ } ++ void *res = NULL; ++ int mark = p->mark; ++ int start_mark = p->mark; ++ void **children = PyMem_Malloc(sizeof(void *)); ++ if (!children) { ++ PyErr_Format(PyExc_MemoryError, "Parser out of memory"); ++ return NULL; ++ } ++ ssize_t children_capacity = 1; ++ ssize_t n = 0; ++ { // ',' star_expression ++ expr_ty elem; ++ void *literal; ++ while ( ++ (literal = _PyPegen_expect_token(p, 12)) ++ && ++ (elem = star_expression_rule(p)) ++ ) ++ { ++ res = elem; ++ if (res == NULL && PyErr_Occurred()) { ++ p->error_indicator = 1; ++ PyMem_Free(children); ++ return NULL; ++ } ++ if (n == children_capacity) { ++ children_capacity *= 2; ++ children = PyMem_Realloc(children, children_capacity*sizeof(void *)); ++ if (!children) { ++ PyErr_Format(PyExc_MemoryError, "realloc None"); ++ return NULL; ++ } ++ } ++ children[n++] = res; ++ mark = p->mark; ++ } ++ p->mark = mark; ++ } ++ asdl_seq *seq = _Py_asdl_seq_new(n, p->arena); ++ if (!seq) { ++ PyErr_Format(PyExc_MemoryError, "asdl_seq_new _loop0_60"); ++ PyMem_Free(children); ++ return NULL; ++ } ++ for (int i = 0; i < n; i++) asdl_seq_SET(seq, i, children[i]); ++ PyMem_Free(children); ++ _PyPegen_insert_memo(p, start_mark, _loop0_60_type, seq); ++ return seq; ++} ++ ++// _gather_59: star_expression _loop0_60 ++static asdl_seq * ++_gather_59_rule(Parser *p) ++{ ++ if (p->error_indicator) { ++ return NULL; ++ } ++ asdl_seq * res = NULL; ++ int mark = p->mark; ++ { // star_expression _loop0_60 ++ expr_ty elem; ++ asdl_seq * seq; ++ if ( ++ (elem = star_expression_rule(p)) ++ && ++ (seq = _loop0_60_rule(p)) ++ ) ++ { ++ res = _PyPegen_seq_insert_in_front(p, elem, seq); ++ goto done; ++ } ++ p->mark = mark; ++ } ++ res = NULL; ++ done: ++ return res; ++} ++ ++// _loop1_61: (',' star_expression) ++static asdl_seq * ++_loop1_61_rule(Parser *p) ++{ ++ if (p->error_indicator) { ++ return NULL; ++ } ++ void *res = NULL; ++ int mark = p->mark; ++ int start_mark = p->mark; ++ void **children = PyMem_Malloc(sizeof(void *)); ++ if (!children) { ++ PyErr_Format(PyExc_MemoryError, "Parser out of memory"); ++ return NULL; ++ } ++ ssize_t children_capacity = 1; ++ ssize_t n = 0; ++ { // (',' star_expression) ++ void *_tmp_128_var; ++ while ( ++ (_tmp_128_var = _tmp_128_rule(p)) ++ ) ++ { ++ res = _tmp_128_var; ++ if (n == children_capacity) { ++ children_capacity *= 2; ++ children = PyMem_Realloc(children, children_capacity*sizeof(void *)); ++ if (!children) { ++ PyErr_Format(PyExc_MemoryError, "realloc None"); ++ return NULL; ++ } ++ } ++ children[n++] = res; ++ mark = p->mark; ++ } ++ p->mark = mark; ++ } ++ if (n == 0) { ++ PyMem_Free(children); ++ return NULL; ++ } ++ asdl_seq *seq = _Py_asdl_seq_new(n, p->arena); ++ if (!seq) { ++ PyErr_Format(PyExc_MemoryError, "asdl_seq_new _loop1_61"); ++ PyMem_Free(children); ++ return NULL; ++ } ++ for (int i = 0; i < n; i++) asdl_seq_SET(seq, i, children[i]); ++ PyMem_Free(children); ++ _PyPegen_insert_memo(p, start_mark, _loop1_61_type, seq); ++ return seq; ++} ++ ++// _loop0_63: ',' star_named_expression ++static asdl_seq * ++_loop0_63_rule(Parser *p) ++{ ++ if (p->error_indicator) { ++ return NULL; ++ } ++ void *res = NULL; ++ int mark = p->mark; ++ int start_mark = p->mark; ++ void **children = PyMem_Malloc(sizeof(void *)); ++ if (!children) { ++ PyErr_Format(PyExc_MemoryError, "Parser out of memory"); ++ return NULL; ++ } ++ ssize_t children_capacity = 1; ++ ssize_t n = 0; ++ { // ',' star_named_expression ++ expr_ty elem; ++ void *literal; ++ while ( ++ (literal = _PyPegen_expect_token(p, 12)) ++ && ++ (elem = star_named_expression_rule(p)) ++ ) ++ { ++ res = elem; ++ if (res == NULL && PyErr_Occurred()) { ++ p->error_indicator = 1; ++ PyMem_Free(children); ++ return NULL; ++ } ++ if (n == children_capacity) { ++ children_capacity *= 2; ++ children = PyMem_Realloc(children, children_capacity*sizeof(void *)); ++ if (!children) { ++ PyErr_Format(PyExc_MemoryError, "realloc None"); ++ return NULL; ++ } ++ } ++ children[n++] = res; ++ mark = p->mark; ++ } ++ p->mark = mark; ++ } ++ asdl_seq *seq = _Py_asdl_seq_new(n, p->arena); ++ if (!seq) { ++ PyErr_Format(PyExc_MemoryError, "asdl_seq_new _loop0_63"); ++ PyMem_Free(children); ++ return NULL; ++ } ++ for (int i = 0; i < n; i++) asdl_seq_SET(seq, i, children[i]); ++ PyMem_Free(children); ++ _PyPegen_insert_memo(p, start_mark, _loop0_63_type, seq); ++ return seq; ++} ++ ++// _gather_62: star_named_expression _loop0_63 ++static asdl_seq * ++_gather_62_rule(Parser *p) ++{ ++ if (p->error_indicator) { ++ return NULL; ++ } ++ asdl_seq * res = NULL; ++ int mark = p->mark; ++ { // star_named_expression _loop0_63 ++ expr_ty elem; ++ asdl_seq * seq; ++ if ( ++ (elem = star_named_expression_rule(p)) ++ && ++ (seq = _loop0_63_rule(p)) ++ ) ++ { ++ res = _PyPegen_seq_insert_in_front(p, elem, seq); ++ goto done; ++ } ++ p->mark = mark; ++ } ++ res = NULL; ++ done: ++ return res; ++} ++ ++// _loop1_64: (',' expression) ++static asdl_seq * ++_loop1_64_rule(Parser *p) ++{ ++ if (p->error_indicator) { ++ return NULL; ++ } ++ void *res = NULL; ++ int mark = p->mark; ++ int start_mark = p->mark; ++ void **children = PyMem_Malloc(sizeof(void *)); ++ if (!children) { ++ PyErr_Format(PyExc_MemoryError, "Parser out of memory"); ++ return NULL; ++ } ++ ssize_t children_capacity = 1; ++ ssize_t n = 0; ++ { // (',' expression) ++ void *_tmp_129_var; ++ while ( ++ (_tmp_129_var = _tmp_129_rule(p)) ++ ) ++ { ++ res = _tmp_129_var; ++ if (n == children_capacity) { ++ children_capacity *= 2; ++ children = PyMem_Realloc(children, children_capacity*sizeof(void *)); ++ if (!children) { ++ PyErr_Format(PyExc_MemoryError, "realloc None"); ++ return NULL; ++ } ++ } ++ children[n++] = res; ++ mark = p->mark; ++ } ++ p->mark = mark; ++ } ++ if (n == 0) { ++ PyMem_Free(children); ++ return NULL; ++ } ++ asdl_seq *seq = _Py_asdl_seq_new(n, p->arena); ++ if (!seq) { ++ PyErr_Format(PyExc_MemoryError, "asdl_seq_new _loop1_64"); ++ PyMem_Free(children); ++ return NULL; ++ } ++ for (int i = 0; i < n; i++) asdl_seq_SET(seq, i, children[i]); ++ PyMem_Free(children); ++ _PyPegen_insert_memo(p, start_mark, _loop1_64_type, seq); ++ return seq; ++} ++ ++// _tmp_65: ',' lambda_plain_names ++static void * ++_tmp_65_rule(Parser *p) ++{ ++ if (p->error_indicator) { ++ return NULL; ++ } ++ void * res = NULL; ++ int mark = p->mark; ++ { // ',' lambda_plain_names ++ void *literal; ++ asdl_seq* x; ++ if ( ++ (literal = _PyPegen_expect_token(p, 12)) ++ && ++ (x = lambda_plain_names_rule(p)) ++ ) ++ { ++ res = x; ++ if (res == NULL && PyErr_Occurred()) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ goto done; ++ } ++ p->mark = mark; ++ } ++ res = NULL; ++ done: ++ return res; ++} ++ ++// _tmp_66: ',' lambda_names_with_default ++static void * ++_tmp_66_rule(Parser *p) ++{ ++ if (p->error_indicator) { ++ return NULL; ++ } ++ void * res = NULL; ++ int mark = p->mark; ++ { // ',' lambda_names_with_default ++ void *literal; ++ asdl_seq* y; ++ if ( ++ (literal = _PyPegen_expect_token(p, 12)) ++ && ++ (y = lambda_names_with_default_rule(p)) ++ ) ++ { ++ res = y; ++ if (res == NULL && PyErr_Occurred()) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ goto done; ++ } ++ p->mark = mark; ++ } ++ res = NULL; ++ done: ++ return res; ++} ++ ++// _tmp_67: ',' lambda_star_etc? ++static void * ++_tmp_67_rule(Parser *p) ++{ ++ if (p->error_indicator) { ++ return NULL; ++ } ++ void * res = NULL; ++ int mark = p->mark; ++ { // ',' lambda_star_etc? ++ void *literal; ++ void *z; ++ if ( ++ (literal = _PyPegen_expect_token(p, 12)) ++ && ++ (z = lambda_star_etc_rule(p), 1) ++ ) ++ { ++ res = z; ++ if (res == NULL && PyErr_Occurred()) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ goto done; ++ } ++ p->mark = mark; ++ } ++ res = NULL; ++ done: ++ return res; ++} ++ ++// _tmp_68: ',' lambda_names_with_default ++static void * ++_tmp_68_rule(Parser *p) ++{ ++ if (p->error_indicator) { ++ return NULL; ++ } ++ void * res = NULL; ++ int mark = p->mark; ++ { // ',' lambda_names_with_default ++ void *literal; ++ asdl_seq* y; ++ if ( ++ (literal = _PyPegen_expect_token(p, 12)) ++ && ++ (y = lambda_names_with_default_rule(p)) ++ ) ++ { ++ res = y; ++ if (res == NULL && PyErr_Occurred()) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ goto done; ++ } ++ p->mark = mark; ++ } ++ res = NULL; ++ done: ++ return res; ++} ++ ++// _tmp_69: ',' lambda_star_etc? ++static void * ++_tmp_69_rule(Parser *p) ++{ ++ if (p->error_indicator) { ++ return NULL; ++ } ++ void * res = NULL; ++ int mark = p->mark; ++ { // ',' lambda_star_etc? ++ void *literal; ++ void *z; ++ if ( ++ (literal = _PyPegen_expect_token(p, 12)) ++ && ++ (z = lambda_star_etc_rule(p), 1) ++ ) ++ { ++ res = z; ++ if (res == NULL && PyErr_Occurred()) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ goto done; ++ } ++ p->mark = mark; ++ } ++ res = NULL; ++ done: ++ return res; ++} ++ ++// _tmp_70: ',' lambda_names_with_default ++static void * ++_tmp_70_rule(Parser *p) ++{ ++ if (p->error_indicator) { ++ return NULL; ++ } ++ void * res = NULL; ++ int mark = p->mark; ++ { // ',' lambda_names_with_default ++ void *literal; ++ asdl_seq* y; ++ if ( ++ (literal = _PyPegen_expect_token(p, 12)) ++ && ++ (y = lambda_names_with_default_rule(p)) ++ ) ++ { ++ res = y; ++ if (res == NULL && PyErr_Occurred()) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ goto done; ++ } ++ p->mark = mark; ++ } ++ res = NULL; ++ done: ++ return res; ++} ++ ++// _tmp_71: ',' lambda_star_etc? ++static void * ++_tmp_71_rule(Parser *p) ++{ ++ if (p->error_indicator) { ++ return NULL; ++ } ++ void * res = NULL; ++ int mark = p->mark; ++ { // ',' lambda_star_etc? ++ void *literal; ++ void *z; ++ if ( ++ (literal = _PyPegen_expect_token(p, 12)) ++ && ++ (z = lambda_star_etc_rule(p), 1) ++ ) ++ { ++ res = z; ++ if (res == NULL && PyErr_Occurred()) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ goto done; ++ } ++ p->mark = mark; ++ } ++ res = NULL; ++ done: ++ return res; ++} ++ ++// _tmp_72: ',' lambda_star_etc? ++static void * ++_tmp_72_rule(Parser *p) ++{ ++ if (p->error_indicator) { ++ return NULL; ++ } ++ void * res = NULL; ++ int mark = p->mark; ++ { // ',' lambda_star_etc? ++ void *literal; ++ void *z; ++ if ( ++ (literal = _PyPegen_expect_token(p, 12)) ++ && ++ (z = lambda_star_etc_rule(p), 1) ++ ) ++ { ++ res = z; ++ if (res == NULL && PyErr_Occurred()) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ goto done; ++ } ++ p->mark = mark; ++ } ++ res = NULL; ++ done: ++ return res; ++} ++ ++// _tmp_73: lambda_plain_names ',' ++static void * ++_tmp_73_rule(Parser *p) ++{ ++ if (p->error_indicator) { ++ return NULL; ++ } ++ void * res = NULL; ++ int mark = p->mark; ++ { // lambda_plain_names ',' ++ void *literal; ++ asdl_seq* n; ++ if ( ++ (n = lambda_plain_names_rule(p)) ++ && ++ (literal = _PyPegen_expect_token(p, 12)) ++ ) ++ { ++ res = n; ++ if (res == NULL && PyErr_Occurred()) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ goto done; ++ } ++ p->mark = mark; ++ } ++ res = NULL; ++ done: ++ return res; ++} ++ ++// _loop0_74: lambda_name_with_optional_default ++static asdl_seq * ++_loop0_74_rule(Parser *p) ++{ ++ if (p->error_indicator) { ++ return NULL; ++ } ++ void *res = NULL; ++ int mark = p->mark; ++ int start_mark = p->mark; ++ void **children = PyMem_Malloc(sizeof(void *)); ++ if (!children) { ++ PyErr_Format(PyExc_MemoryError, "Parser out of memory"); ++ return NULL; ++ } ++ ssize_t children_capacity = 1; ++ ssize_t n = 0; ++ { // lambda_name_with_optional_default ++ NameDefaultPair* lambda_name_with_optional_default_var; ++ while ( ++ (lambda_name_with_optional_default_var = lambda_name_with_optional_default_rule(p)) ++ ) ++ { ++ res = lambda_name_with_optional_default_var; ++ if (n == children_capacity) { ++ children_capacity *= 2; ++ children = PyMem_Realloc(children, children_capacity*sizeof(void *)); ++ if (!children) { ++ PyErr_Format(PyExc_MemoryError, "realloc None"); ++ return NULL; ++ } ++ } ++ children[n++] = res; ++ mark = p->mark; ++ } ++ p->mark = mark; ++ } ++ asdl_seq *seq = _Py_asdl_seq_new(n, p->arena); ++ if (!seq) { ++ PyErr_Format(PyExc_MemoryError, "asdl_seq_new _loop0_74"); ++ PyMem_Free(children); ++ return NULL; ++ } ++ for (int i = 0; i < n; i++) asdl_seq_SET(seq, i, children[i]); ++ PyMem_Free(children); ++ _PyPegen_insert_memo(p, start_mark, _loop0_74_type, seq); ++ return seq; ++} ++ ++// _tmp_75: ',' lambda_kwds ++static void * ++_tmp_75_rule(Parser *p) ++{ ++ if (p->error_indicator) { ++ return NULL; ++ } ++ void * res = NULL; ++ int mark = p->mark; ++ { // ',' lambda_kwds ++ arg_ty d; ++ void *literal; ++ if ( ++ (literal = _PyPegen_expect_token(p, 12)) ++ && ++ (d = lambda_kwds_rule(p)) ++ ) ++ { ++ res = d; ++ if (res == NULL && PyErr_Occurred()) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ goto done; ++ } ++ p->mark = mark; ++ } ++ res = NULL; ++ done: ++ return res; ++} ++ ++// _loop1_76: lambda_name_with_optional_default ++static asdl_seq * ++_loop1_76_rule(Parser *p) ++{ ++ if (p->error_indicator) { ++ return NULL; ++ } ++ void *res = NULL; ++ int mark = p->mark; ++ int start_mark = p->mark; ++ void **children = PyMem_Malloc(sizeof(void *)); ++ if (!children) { ++ PyErr_Format(PyExc_MemoryError, "Parser out of memory"); ++ return NULL; ++ } ++ ssize_t children_capacity = 1; ++ ssize_t n = 0; ++ { // lambda_name_with_optional_default ++ NameDefaultPair* lambda_name_with_optional_default_var; ++ while ( ++ (lambda_name_with_optional_default_var = lambda_name_with_optional_default_rule(p)) ++ ) ++ { ++ res = lambda_name_with_optional_default_var; ++ if (n == children_capacity) { ++ children_capacity *= 2; ++ children = PyMem_Realloc(children, children_capacity*sizeof(void *)); ++ if (!children) { ++ PyErr_Format(PyExc_MemoryError, "realloc None"); ++ return NULL; ++ } ++ } ++ children[n++] = res; ++ mark = p->mark; ++ } ++ p->mark = mark; ++ } ++ if (n == 0) { ++ PyMem_Free(children); ++ return NULL; ++ } ++ asdl_seq *seq = _Py_asdl_seq_new(n, p->arena); ++ if (!seq) { ++ PyErr_Format(PyExc_MemoryError, "asdl_seq_new _loop1_76"); ++ PyMem_Free(children); ++ return NULL; ++ } ++ for (int i = 0; i < n; i++) asdl_seq_SET(seq, i, children[i]); ++ PyMem_Free(children); ++ _PyPegen_insert_memo(p, start_mark, _loop1_76_type, seq); ++ return seq; ++} ++ ++// _tmp_77: ',' lambda_kwds ++static void * ++_tmp_77_rule(Parser *p) ++{ ++ if (p->error_indicator) { ++ return NULL; ++ } ++ void * res = NULL; ++ int mark = p->mark; ++ { // ',' lambda_kwds ++ arg_ty d; ++ void *literal; ++ if ( ++ (literal = _PyPegen_expect_token(p, 12)) ++ && ++ (d = lambda_kwds_rule(p)) ++ ) ++ { ++ res = d; ++ if (res == NULL && PyErr_Occurred()) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ goto done; ++ } ++ p->mark = mark; ++ } ++ res = NULL; ++ done: ++ return res; ++} ++ ++// _tmp_78: '=' expression ++static void * ++_tmp_78_rule(Parser *p) ++{ ++ if (p->error_indicator) { ++ return NULL; ++ } ++ void * res = NULL; ++ int mark = p->mark; ++ { // '=' expression ++ expr_ty e; ++ void *literal; ++ if ( ++ (literal = _PyPegen_expect_token(p, 22)) ++ && ++ (e = expression_rule(p)) ++ ) ++ { ++ res = e; ++ if (res == NULL && PyErr_Occurred()) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ goto done; ++ } ++ p->mark = mark; ++ } ++ res = NULL; ++ done: ++ return res; ++} ++ ++// _loop0_80: ',' lambda_name_with_default ++static asdl_seq * ++_loop0_80_rule(Parser *p) ++{ ++ if (p->error_indicator) { ++ return NULL; ++ } ++ void *res = NULL; ++ int mark = p->mark; ++ int start_mark = p->mark; ++ void **children = PyMem_Malloc(sizeof(void *)); ++ if (!children) { ++ PyErr_Format(PyExc_MemoryError, "Parser out of memory"); ++ return NULL; ++ } ++ ssize_t children_capacity = 1; ++ ssize_t n = 0; ++ { // ',' lambda_name_with_default ++ NameDefaultPair* elem; ++ void *literal; ++ while ( ++ (literal = _PyPegen_expect_token(p, 12)) ++ && ++ (elem = lambda_name_with_default_rule(p)) ++ ) ++ { ++ res = elem; ++ if (res == NULL && PyErr_Occurred()) { ++ p->error_indicator = 1; ++ PyMem_Free(children); ++ return NULL; ++ } ++ if (n == children_capacity) { ++ children_capacity *= 2; ++ children = PyMem_Realloc(children, children_capacity*sizeof(void *)); ++ if (!children) { ++ PyErr_Format(PyExc_MemoryError, "realloc None"); ++ return NULL; ++ } ++ } ++ children[n++] = res; ++ mark = p->mark; ++ } ++ p->mark = mark; ++ } ++ asdl_seq *seq = _Py_asdl_seq_new(n, p->arena); ++ if (!seq) { ++ PyErr_Format(PyExc_MemoryError, "asdl_seq_new _loop0_80"); ++ PyMem_Free(children); ++ return NULL; ++ } ++ for (int i = 0; i < n; i++) asdl_seq_SET(seq, i, children[i]); ++ PyMem_Free(children); ++ _PyPegen_insert_memo(p, start_mark, _loop0_80_type, seq); ++ return seq; ++} ++ ++// _gather_79: lambda_name_with_default _loop0_80 ++static asdl_seq * ++_gather_79_rule(Parser *p) ++{ ++ if (p->error_indicator) { ++ return NULL; ++ } ++ asdl_seq * res = NULL; ++ int mark = p->mark; ++ { // lambda_name_with_default _loop0_80 ++ NameDefaultPair* elem; ++ asdl_seq * seq; ++ if ( ++ (elem = lambda_name_with_default_rule(p)) ++ && ++ (seq = _loop0_80_rule(p)) ++ ) ++ { ++ res = _PyPegen_seq_insert_in_front(p, elem, seq); ++ goto done; ++ } ++ p->mark = mark; ++ } ++ res = NULL; ++ done: ++ return res; ++} ++ ++// _loop0_82: ',' (lambda_plain_name !'=') ++static asdl_seq * ++_loop0_82_rule(Parser *p) ++{ ++ if (p->error_indicator) { ++ return NULL; ++ } ++ void *res = NULL; ++ int mark = p->mark; ++ int start_mark = p->mark; ++ void **children = PyMem_Malloc(sizeof(void *)); ++ if (!children) { ++ PyErr_Format(PyExc_MemoryError, "Parser out of memory"); ++ return NULL; ++ } ++ ssize_t children_capacity = 1; ++ ssize_t n = 0; ++ { // ',' (lambda_plain_name !'=') ++ void *elem; ++ void *literal; ++ while ( ++ (literal = _PyPegen_expect_token(p, 12)) ++ && ++ (elem = _tmp_130_rule(p)) ++ ) ++ { ++ res = elem; ++ if (res == NULL && PyErr_Occurred()) { ++ p->error_indicator = 1; ++ PyMem_Free(children); ++ return NULL; ++ } ++ if (n == children_capacity) { ++ children_capacity *= 2; ++ children = PyMem_Realloc(children, children_capacity*sizeof(void *)); ++ if (!children) { ++ PyErr_Format(PyExc_MemoryError, "realloc None"); ++ return NULL; ++ } ++ } ++ children[n++] = res; ++ mark = p->mark; ++ } ++ p->mark = mark; ++ } ++ asdl_seq *seq = _Py_asdl_seq_new(n, p->arena); ++ if (!seq) { ++ PyErr_Format(PyExc_MemoryError, "asdl_seq_new _loop0_82"); ++ PyMem_Free(children); ++ return NULL; ++ } ++ for (int i = 0; i < n; i++) asdl_seq_SET(seq, i, children[i]); ++ PyMem_Free(children); ++ _PyPegen_insert_memo(p, start_mark, _loop0_82_type, seq); ++ return seq; ++} ++ ++// _gather_81: (lambda_plain_name !'=') _loop0_82 ++static asdl_seq * ++_gather_81_rule(Parser *p) ++{ ++ if (p->error_indicator) { ++ return NULL; ++ } ++ asdl_seq * res = NULL; ++ int mark = p->mark; ++ { // (lambda_plain_name !'=') _loop0_82 ++ void *elem; ++ asdl_seq * seq; ++ if ( ++ (elem = _tmp_130_rule(p)) ++ && ++ (seq = _loop0_82_rule(p)) ++ ) ++ { ++ res = _PyPegen_seq_insert_in_front(p, elem, seq); ++ goto done; ++ } ++ p->mark = mark; ++ } ++ res = NULL; ++ done: ++ return res; ++} ++ ++// _loop1_83: ('or' conjunction) ++static asdl_seq * ++_loop1_83_rule(Parser *p) ++{ ++ if (p->error_indicator) { ++ return NULL; ++ } ++ void *res = NULL; ++ int mark = p->mark; ++ int start_mark = p->mark; ++ void **children = PyMem_Malloc(sizeof(void *)); ++ if (!children) { ++ PyErr_Format(PyExc_MemoryError, "Parser out of memory"); ++ return NULL; ++ } ++ ssize_t children_capacity = 1; ++ ssize_t n = 0; ++ { // ('or' conjunction) ++ void *_tmp_131_var; ++ while ( ++ (_tmp_131_var = _tmp_131_rule(p)) ++ ) ++ { ++ res = _tmp_131_var; ++ if (n == children_capacity) { ++ children_capacity *= 2; ++ children = PyMem_Realloc(children, children_capacity*sizeof(void *)); ++ if (!children) { ++ PyErr_Format(PyExc_MemoryError, "realloc None"); ++ return NULL; ++ } ++ } ++ children[n++] = res; ++ mark = p->mark; ++ } ++ p->mark = mark; ++ } ++ if (n == 0) { ++ PyMem_Free(children); ++ return NULL; ++ } ++ asdl_seq *seq = _Py_asdl_seq_new(n, p->arena); ++ if (!seq) { ++ PyErr_Format(PyExc_MemoryError, "asdl_seq_new _loop1_83"); ++ PyMem_Free(children); ++ return NULL; ++ } ++ for (int i = 0; i < n; i++) asdl_seq_SET(seq, i, children[i]); ++ PyMem_Free(children); ++ _PyPegen_insert_memo(p, start_mark, _loop1_83_type, seq); ++ return seq; ++} ++ ++// _loop1_84: ('and' inversion) ++static asdl_seq * ++_loop1_84_rule(Parser *p) ++{ ++ if (p->error_indicator) { ++ return NULL; ++ } ++ void *res = NULL; ++ int mark = p->mark; ++ int start_mark = p->mark; ++ void **children = PyMem_Malloc(sizeof(void *)); ++ if (!children) { ++ PyErr_Format(PyExc_MemoryError, "Parser out of memory"); ++ return NULL; ++ } ++ ssize_t children_capacity = 1; ++ ssize_t n = 0; ++ { // ('and' inversion) ++ void *_tmp_132_var; ++ while ( ++ (_tmp_132_var = _tmp_132_rule(p)) ++ ) ++ { ++ res = _tmp_132_var; ++ if (n == children_capacity) { ++ children_capacity *= 2; ++ children = PyMem_Realloc(children, children_capacity*sizeof(void *)); ++ if (!children) { ++ PyErr_Format(PyExc_MemoryError, "realloc None"); ++ return NULL; ++ } ++ } ++ children[n++] = res; ++ mark = p->mark; ++ } ++ p->mark = mark; ++ } ++ if (n == 0) { ++ PyMem_Free(children); ++ return NULL; ++ } ++ asdl_seq *seq = _Py_asdl_seq_new(n, p->arena); ++ if (!seq) { ++ PyErr_Format(PyExc_MemoryError, "asdl_seq_new _loop1_84"); ++ PyMem_Free(children); ++ return NULL; ++ } ++ for (int i = 0; i < n; i++) asdl_seq_SET(seq, i, children[i]); ++ PyMem_Free(children); ++ _PyPegen_insert_memo(p, start_mark, _loop1_84_type, seq); ++ return seq; ++} ++ ++// _loop1_85: compare_op_bitwise_or_pair ++static asdl_seq * ++_loop1_85_rule(Parser *p) ++{ ++ if (p->error_indicator) { ++ return NULL; ++ } ++ void *res = NULL; ++ int mark = p->mark; ++ int start_mark = p->mark; ++ void **children = PyMem_Malloc(sizeof(void *)); ++ if (!children) { ++ PyErr_Format(PyExc_MemoryError, "Parser out of memory"); ++ return NULL; ++ } ++ ssize_t children_capacity = 1; ++ ssize_t n = 0; ++ { // compare_op_bitwise_or_pair ++ CmpopExprPair* compare_op_bitwise_or_pair_var; ++ while ( ++ (compare_op_bitwise_or_pair_var = compare_op_bitwise_or_pair_rule(p)) ++ ) ++ { ++ res = compare_op_bitwise_or_pair_var; ++ if (n == children_capacity) { ++ children_capacity *= 2; ++ children = PyMem_Realloc(children, children_capacity*sizeof(void *)); ++ if (!children) { ++ PyErr_Format(PyExc_MemoryError, "realloc None"); ++ return NULL; ++ } ++ } ++ children[n++] = res; ++ mark = p->mark; ++ } ++ p->mark = mark; ++ } ++ if (n == 0) { ++ PyMem_Free(children); ++ return NULL; ++ } ++ asdl_seq *seq = _Py_asdl_seq_new(n, p->arena); ++ if (!seq) { ++ PyErr_Format(PyExc_MemoryError, "asdl_seq_new _loop1_85"); ++ PyMem_Free(children); ++ return NULL; ++ } ++ for (int i = 0; i < n; i++) asdl_seq_SET(seq, i, children[i]); ++ PyMem_Free(children); ++ _PyPegen_insert_memo(p, start_mark, _loop1_85_type, seq); ++ return seq; ++} ++ ++// _loop0_87: ',' slice ++static asdl_seq * ++_loop0_87_rule(Parser *p) ++{ ++ if (p->error_indicator) { ++ return NULL; ++ } ++ void *res = NULL; ++ int mark = p->mark; ++ int start_mark = p->mark; ++ void **children = PyMem_Malloc(sizeof(void *)); ++ if (!children) { ++ PyErr_Format(PyExc_MemoryError, "Parser out of memory"); ++ return NULL; ++ } ++ ssize_t children_capacity = 1; ++ ssize_t n = 0; ++ { // ',' slice ++ expr_ty elem; ++ void *literal; ++ while ( ++ (literal = _PyPegen_expect_token(p, 12)) ++ && ++ (elem = slice_rule(p)) ++ ) ++ { ++ res = elem; ++ if (res == NULL && PyErr_Occurred()) { ++ p->error_indicator = 1; ++ PyMem_Free(children); ++ return NULL; ++ } ++ if (n == children_capacity) { ++ children_capacity *= 2; ++ children = PyMem_Realloc(children, children_capacity*sizeof(void *)); ++ if (!children) { ++ PyErr_Format(PyExc_MemoryError, "realloc None"); ++ return NULL; ++ } ++ } ++ children[n++] = res; ++ mark = p->mark; ++ } ++ p->mark = mark; ++ } ++ asdl_seq *seq = _Py_asdl_seq_new(n, p->arena); ++ if (!seq) { ++ PyErr_Format(PyExc_MemoryError, "asdl_seq_new _loop0_87"); ++ PyMem_Free(children); ++ return NULL; ++ } ++ for (int i = 0; i < n; i++) asdl_seq_SET(seq, i, children[i]); ++ PyMem_Free(children); ++ _PyPegen_insert_memo(p, start_mark, _loop0_87_type, seq); ++ return seq; ++} ++ ++// _gather_86: slice _loop0_87 ++static asdl_seq * ++_gather_86_rule(Parser *p) ++{ ++ if (p->error_indicator) { ++ return NULL; ++ } ++ asdl_seq * res = NULL; ++ int mark = p->mark; ++ { // slice _loop0_87 ++ expr_ty elem; ++ asdl_seq * seq; ++ if ( ++ (elem = slice_rule(p)) ++ && ++ (seq = _loop0_87_rule(p)) ++ ) ++ { ++ res = _PyPegen_seq_insert_in_front(p, elem, seq); ++ goto done; ++ } ++ p->mark = mark; ++ } ++ res = NULL; ++ done: ++ return res; ++} ++ ++// _tmp_88: ':' expression? ++static void * ++_tmp_88_rule(Parser *p) ++{ ++ if (p->error_indicator) { ++ return NULL; ++ } ++ void * res = NULL; ++ int mark = p->mark; ++ { // ':' expression? ++ void *d; ++ void *literal; ++ if ( ++ (literal = _PyPegen_expect_token(p, 11)) ++ && ++ (d = expression_rule(p), 1) ++ ) ++ { ++ res = d; ++ if (res == NULL && PyErr_Occurred()) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ goto done; ++ } ++ p->mark = mark; ++ } ++ res = NULL; ++ done: ++ return res; ++} ++ ++// _tmp_89: tuple | group | genexp ++static void * ++_tmp_89_rule(Parser *p) ++{ ++ if (p->error_indicator) { ++ return NULL; ++ } ++ void * res = NULL; ++ int mark = p->mark; ++ { // tuple ++ expr_ty tuple_var; ++ if ( ++ (tuple_var = tuple_rule(p)) ++ ) ++ { ++ res = tuple_var; ++ goto done; ++ } ++ p->mark = mark; ++ } ++ { // group ++ expr_ty group_var; ++ if ( ++ (group_var = group_rule(p)) ++ ) ++ { ++ res = group_var; ++ goto done; ++ } ++ p->mark = mark; ++ } ++ { // genexp ++ expr_ty genexp_var; ++ if ( ++ (genexp_var = genexp_rule(p)) ++ ) ++ { ++ res = genexp_var; ++ goto done; ++ } ++ p->mark = mark; ++ } ++ res = NULL; ++ done: ++ return res; ++} ++ ++// _tmp_90: list | listcomp ++static void * ++_tmp_90_rule(Parser *p) ++{ ++ if (p->error_indicator) { ++ return NULL; ++ } ++ void * res = NULL; ++ int mark = p->mark; ++ { // list ++ expr_ty list_var; ++ if ( ++ (list_var = list_rule(p)) ++ ) ++ { ++ res = list_var; ++ goto done; ++ } ++ p->mark = mark; ++ } ++ { // listcomp ++ expr_ty listcomp_var; ++ if ( ++ (listcomp_var = listcomp_rule(p)) ++ ) ++ { ++ res = listcomp_var; ++ goto done; ++ } ++ p->mark = mark; ++ } ++ res = NULL; ++ done: ++ return res; ++} ++ ++// _tmp_91: dict | set | dictcomp | setcomp ++static void * ++_tmp_91_rule(Parser *p) ++{ ++ if (p->error_indicator) { ++ return NULL; ++ } ++ void * res = NULL; ++ int mark = p->mark; ++ { // dict ++ expr_ty dict_var; ++ if ( ++ (dict_var = dict_rule(p)) ++ ) ++ { ++ res = dict_var; ++ goto done; ++ } ++ p->mark = mark; ++ } ++ { // set ++ expr_ty set_var; ++ if ( ++ (set_var = set_rule(p)) ++ ) ++ { ++ res = set_var; ++ goto done; ++ } ++ p->mark = mark; ++ } ++ { // dictcomp ++ expr_ty dictcomp_var; ++ if ( ++ (dictcomp_var = dictcomp_rule(p)) ++ ) ++ { ++ res = dictcomp_var; ++ goto done; ++ } ++ p->mark = mark; ++ } ++ { // setcomp ++ expr_ty setcomp_var; ++ if ( ++ (setcomp_var = setcomp_rule(p)) ++ ) ++ { ++ res = setcomp_var; ++ goto done; ++ } ++ p->mark = mark; ++ } ++ res = NULL; ++ done: ++ return res; ++} ++ ++// _loop1_92: STRING ++static asdl_seq * ++_loop1_92_rule(Parser *p) ++{ ++ if (p->error_indicator) { ++ return NULL; ++ } ++ void *res = NULL; ++ int mark = p->mark; ++ int start_mark = p->mark; ++ void **children = PyMem_Malloc(sizeof(void *)); ++ if (!children) { ++ PyErr_Format(PyExc_MemoryError, "Parser out of memory"); ++ return NULL; ++ } ++ ssize_t children_capacity = 1; ++ ssize_t n = 0; ++ { // STRING ++ expr_ty string_var; ++ while ( ++ (string_var = _PyPegen_string_token(p)) ++ ) ++ { ++ res = string_var; ++ if (n == children_capacity) { ++ children_capacity *= 2; ++ children = PyMem_Realloc(children, children_capacity*sizeof(void *)); ++ if (!children) { ++ PyErr_Format(PyExc_MemoryError, "realloc None"); ++ return NULL; ++ } ++ } ++ children[n++] = res; ++ mark = p->mark; ++ } ++ p->mark = mark; ++ } ++ if (n == 0) { ++ PyMem_Free(children); ++ return NULL; ++ } ++ asdl_seq *seq = _Py_asdl_seq_new(n, p->arena); ++ if (!seq) { ++ PyErr_Format(PyExc_MemoryError, "asdl_seq_new _loop1_92"); ++ PyMem_Free(children); ++ return NULL; ++ } ++ for (int i = 0; i < n; i++) asdl_seq_SET(seq, i, children[i]); ++ PyMem_Free(children); ++ _PyPegen_insert_memo(p, start_mark, _loop1_92_type, seq); ++ return seq; ++} ++ ++// _tmp_93: star_named_expression ',' star_named_expressions? ++static void * ++_tmp_93_rule(Parser *p) ++{ ++ if (p->error_indicator) { ++ return NULL; ++ } ++ void * res = NULL; ++ int mark = p->mark; ++ { // star_named_expression ',' star_named_expressions? ++ void *literal; ++ expr_ty y; ++ void *z; ++ if ( ++ (y = star_named_expression_rule(p)) ++ && ++ (literal = _PyPegen_expect_token(p, 12)) ++ && ++ (z = star_named_expressions_rule(p), 1) ++ ) ++ { ++ res = _PyPegen_seq_insert_in_front ( p , y , z ); ++ if (res == NULL && PyErr_Occurred()) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ goto done; ++ } ++ p->mark = mark; ++ } ++ res = NULL; ++ done: ++ return res; ++} ++ ++// _tmp_94: yield_expr | named_expression ++static void * ++_tmp_94_rule(Parser *p) ++{ ++ if (p->error_indicator) { ++ return NULL; ++ } ++ void * res = NULL; ++ int mark = p->mark; ++ { // yield_expr ++ expr_ty yield_expr_var; ++ if ( ++ (yield_expr_var = yield_expr_rule(p)) ++ ) ++ { ++ res = yield_expr_var; ++ goto done; ++ } ++ p->mark = mark; ++ } ++ { // named_expression ++ expr_ty named_expression_var; ++ if ( ++ (named_expression_var = named_expression_rule(p)) ++ ) ++ { ++ res = named_expression_var; ++ goto done; ++ } ++ p->mark = mark; ++ } ++ res = NULL; ++ done: ++ return res; ++} ++ ++// _loop0_96: ',' kvpair ++static asdl_seq * ++_loop0_96_rule(Parser *p) ++{ ++ if (p->error_indicator) { ++ return NULL; ++ } ++ void *res = NULL; ++ int mark = p->mark; ++ int start_mark = p->mark; ++ void **children = PyMem_Malloc(sizeof(void *)); ++ if (!children) { ++ PyErr_Format(PyExc_MemoryError, "Parser out of memory"); ++ return NULL; ++ } ++ ssize_t children_capacity = 1; ++ ssize_t n = 0; ++ { // ',' kvpair ++ KeyValuePair* elem; ++ void *literal; ++ while ( ++ (literal = _PyPegen_expect_token(p, 12)) ++ && ++ (elem = kvpair_rule(p)) ++ ) ++ { ++ res = elem; ++ if (res == NULL && PyErr_Occurred()) { ++ p->error_indicator = 1; ++ PyMem_Free(children); ++ return NULL; ++ } ++ if (n == children_capacity) { ++ children_capacity *= 2; ++ children = PyMem_Realloc(children, children_capacity*sizeof(void *)); ++ if (!children) { ++ PyErr_Format(PyExc_MemoryError, "realloc None"); ++ return NULL; ++ } ++ } ++ children[n++] = res; ++ mark = p->mark; ++ } ++ p->mark = mark; ++ } ++ asdl_seq *seq = _Py_asdl_seq_new(n, p->arena); ++ if (!seq) { ++ PyErr_Format(PyExc_MemoryError, "asdl_seq_new _loop0_96"); ++ PyMem_Free(children); ++ return NULL; ++ } ++ for (int i = 0; i < n; i++) asdl_seq_SET(seq, i, children[i]); ++ PyMem_Free(children); ++ _PyPegen_insert_memo(p, start_mark, _loop0_96_type, seq); ++ return seq; ++} ++ ++// _gather_95: kvpair _loop0_96 ++static asdl_seq * ++_gather_95_rule(Parser *p) ++{ ++ if (p->error_indicator) { ++ return NULL; ++ } ++ asdl_seq * res = NULL; ++ int mark = p->mark; ++ { // kvpair _loop0_96 ++ KeyValuePair* elem; ++ asdl_seq * seq; ++ if ( ++ (elem = kvpair_rule(p)) ++ && ++ (seq = _loop0_96_rule(p)) ++ ) ++ { ++ res = _PyPegen_seq_insert_in_front(p, elem, seq); ++ goto done; ++ } ++ p->mark = mark; ++ } ++ res = NULL; ++ done: ++ return res; ++} ++ ++// _loop1_97: (ASYNC? 'for' star_targets 'in' disjunction (('if' disjunction))*) ++static asdl_seq * ++_loop1_97_rule(Parser *p) ++{ ++ if (p->error_indicator) { ++ return NULL; ++ } ++ void *res = NULL; ++ int mark = p->mark; ++ int start_mark = p->mark; ++ void **children = PyMem_Malloc(sizeof(void *)); ++ if (!children) { ++ PyErr_Format(PyExc_MemoryError, "Parser out of memory"); ++ return NULL; ++ } ++ ssize_t children_capacity = 1; ++ ssize_t n = 0; ++ { // (ASYNC? 'for' star_targets 'in' disjunction (('if' disjunction))*) ++ void *_tmp_133_var; ++ while ( ++ (_tmp_133_var = _tmp_133_rule(p)) ++ ) ++ { ++ res = _tmp_133_var; ++ if (n == children_capacity) { ++ children_capacity *= 2; ++ children = PyMem_Realloc(children, children_capacity*sizeof(void *)); ++ if (!children) { ++ PyErr_Format(PyExc_MemoryError, "realloc None"); ++ return NULL; ++ } ++ } ++ children[n++] = res; ++ mark = p->mark; ++ } ++ p->mark = mark; ++ } ++ if (n == 0) { ++ PyMem_Free(children); ++ return NULL; ++ } ++ asdl_seq *seq = _Py_asdl_seq_new(n, p->arena); ++ if (!seq) { ++ PyErr_Format(PyExc_MemoryError, "asdl_seq_new _loop1_97"); ++ PyMem_Free(children); ++ return NULL; ++ } ++ for (int i = 0; i < n; i++) asdl_seq_SET(seq, i, children[i]); ++ PyMem_Free(children); ++ _PyPegen_insert_memo(p, start_mark, _loop1_97_type, seq); ++ return seq; ++} ++ ++// _tmp_98: ',' args ++static void * ++_tmp_98_rule(Parser *p) ++{ ++ if (p->error_indicator) { ++ return NULL; ++ } ++ void * res = NULL; ++ int mark = p->mark; ++ { // ',' args ++ expr_ty c; ++ void *literal; ++ if ( ++ (literal = _PyPegen_expect_token(p, 12)) ++ && ++ (c = args_rule(p)) ++ ) ++ { ++ res = c; ++ if (res == NULL && PyErr_Occurred()) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ goto done; ++ } ++ p->mark = mark; ++ } ++ res = NULL; ++ done: ++ return res; ++} ++ ++// _tmp_99: ',' args ++static void * ++_tmp_99_rule(Parser *p) ++{ ++ if (p->error_indicator) { ++ return NULL; ++ } ++ void * res = NULL; ++ int mark = p->mark; ++ { // ',' args ++ expr_ty c; ++ void *literal; ++ if ( ++ (literal = _PyPegen_expect_token(p, 12)) ++ && ++ (c = args_rule(p)) ++ ) ++ { ++ res = c; ++ if (res == NULL && PyErr_Occurred()) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ goto done; ++ } ++ p->mark = mark; ++ } ++ res = NULL; ++ done: ++ return res; ++} ++ ++// _loop0_101: ',' kwarg_or_starred ++static asdl_seq * ++_loop0_101_rule(Parser *p) ++{ ++ if (p->error_indicator) { ++ return NULL; ++ } ++ void *res = NULL; ++ int mark = p->mark; ++ int start_mark = p->mark; ++ void **children = PyMem_Malloc(sizeof(void *)); ++ if (!children) { ++ PyErr_Format(PyExc_MemoryError, "Parser out of memory"); ++ return NULL; ++ } ++ ssize_t children_capacity = 1; ++ ssize_t n = 0; ++ { // ',' kwarg_or_starred ++ KeywordOrStarred* elem; ++ void *literal; ++ while ( ++ (literal = _PyPegen_expect_token(p, 12)) ++ && ++ (elem = kwarg_or_starred_rule(p)) ++ ) ++ { ++ res = elem; ++ if (res == NULL && PyErr_Occurred()) { ++ p->error_indicator = 1; ++ PyMem_Free(children); ++ return NULL; ++ } ++ if (n == children_capacity) { ++ children_capacity *= 2; ++ children = PyMem_Realloc(children, children_capacity*sizeof(void *)); ++ if (!children) { ++ PyErr_Format(PyExc_MemoryError, "realloc None"); ++ return NULL; ++ } ++ } ++ children[n++] = res; ++ mark = p->mark; ++ } ++ p->mark = mark; ++ } ++ asdl_seq *seq = _Py_asdl_seq_new(n, p->arena); ++ if (!seq) { ++ PyErr_Format(PyExc_MemoryError, "asdl_seq_new _loop0_101"); ++ PyMem_Free(children); ++ return NULL; ++ } ++ for (int i = 0; i < n; i++) asdl_seq_SET(seq, i, children[i]); ++ PyMem_Free(children); ++ _PyPegen_insert_memo(p, start_mark, _loop0_101_type, seq); ++ return seq; ++} ++ ++// _gather_100: kwarg_or_starred _loop0_101 ++static asdl_seq * ++_gather_100_rule(Parser *p) ++{ ++ if (p->error_indicator) { ++ return NULL; ++ } ++ asdl_seq * res = NULL; ++ int mark = p->mark; ++ { // kwarg_or_starred _loop0_101 ++ KeywordOrStarred* elem; ++ asdl_seq * seq; ++ if ( ++ (elem = kwarg_or_starred_rule(p)) ++ && ++ (seq = _loop0_101_rule(p)) ++ ) ++ { ++ res = _PyPegen_seq_insert_in_front(p, elem, seq); ++ goto done; ++ } ++ p->mark = mark; ++ } ++ res = NULL; ++ done: ++ return res; ++} ++ ++// _loop0_103: ',' kwarg_or_double_starred ++static asdl_seq * ++_loop0_103_rule(Parser *p) ++{ ++ if (p->error_indicator) { ++ return NULL; ++ } ++ void *res = NULL; ++ int mark = p->mark; ++ int start_mark = p->mark; ++ void **children = PyMem_Malloc(sizeof(void *)); ++ if (!children) { ++ PyErr_Format(PyExc_MemoryError, "Parser out of memory"); ++ return NULL; ++ } ++ ssize_t children_capacity = 1; ++ ssize_t n = 0; ++ { // ',' kwarg_or_double_starred ++ KeywordOrStarred* elem; ++ void *literal; ++ while ( ++ (literal = _PyPegen_expect_token(p, 12)) ++ && ++ (elem = kwarg_or_double_starred_rule(p)) ++ ) ++ { ++ res = elem; ++ if (res == NULL && PyErr_Occurred()) { ++ p->error_indicator = 1; ++ PyMem_Free(children); ++ return NULL; ++ } ++ if (n == children_capacity) { ++ children_capacity *= 2; ++ children = PyMem_Realloc(children, children_capacity*sizeof(void *)); ++ if (!children) { ++ PyErr_Format(PyExc_MemoryError, "realloc None"); ++ return NULL; ++ } ++ } ++ children[n++] = res; ++ mark = p->mark; ++ } ++ p->mark = mark; ++ } ++ asdl_seq *seq = _Py_asdl_seq_new(n, p->arena); ++ if (!seq) { ++ PyErr_Format(PyExc_MemoryError, "asdl_seq_new _loop0_103"); ++ PyMem_Free(children); ++ return NULL; ++ } ++ for (int i = 0; i < n; i++) asdl_seq_SET(seq, i, children[i]); ++ PyMem_Free(children); ++ _PyPegen_insert_memo(p, start_mark, _loop0_103_type, seq); ++ return seq; ++} ++ ++// _gather_102: kwarg_or_double_starred _loop0_103 ++static asdl_seq * ++_gather_102_rule(Parser *p) ++{ ++ if (p->error_indicator) { ++ return NULL; ++ } ++ asdl_seq * res = NULL; ++ int mark = p->mark; ++ { // kwarg_or_double_starred _loop0_103 ++ KeywordOrStarred* elem; ++ asdl_seq * seq; ++ if ( ++ (elem = kwarg_or_double_starred_rule(p)) ++ && ++ (seq = _loop0_103_rule(p)) ++ ) ++ { ++ res = _PyPegen_seq_insert_in_front(p, elem, seq); ++ goto done; ++ } ++ p->mark = mark; ++ } ++ res = NULL; ++ done: ++ return res; ++} ++ ++// _loop0_105: ',' kwarg_or_starred ++static asdl_seq * ++_loop0_105_rule(Parser *p) ++{ ++ if (p->error_indicator) { ++ return NULL; ++ } ++ void *res = NULL; ++ int mark = p->mark; ++ int start_mark = p->mark; ++ void **children = PyMem_Malloc(sizeof(void *)); ++ if (!children) { ++ PyErr_Format(PyExc_MemoryError, "Parser out of memory"); ++ return NULL; ++ } ++ ssize_t children_capacity = 1; ++ ssize_t n = 0; ++ { // ',' kwarg_or_starred ++ KeywordOrStarred* elem; ++ void *literal; ++ while ( ++ (literal = _PyPegen_expect_token(p, 12)) ++ && ++ (elem = kwarg_or_starred_rule(p)) ++ ) ++ { ++ res = elem; ++ if (res == NULL && PyErr_Occurred()) { ++ p->error_indicator = 1; ++ PyMem_Free(children); ++ return NULL; ++ } ++ if (n == children_capacity) { ++ children_capacity *= 2; ++ children = PyMem_Realloc(children, children_capacity*sizeof(void *)); ++ if (!children) { ++ PyErr_Format(PyExc_MemoryError, "realloc None"); ++ return NULL; ++ } ++ } ++ children[n++] = res; ++ mark = p->mark; ++ } ++ p->mark = mark; ++ } ++ asdl_seq *seq = _Py_asdl_seq_new(n, p->arena); ++ if (!seq) { ++ PyErr_Format(PyExc_MemoryError, "asdl_seq_new _loop0_105"); ++ PyMem_Free(children); ++ return NULL; ++ } ++ for (int i = 0; i < n; i++) asdl_seq_SET(seq, i, children[i]); ++ PyMem_Free(children); ++ _PyPegen_insert_memo(p, start_mark, _loop0_105_type, seq); ++ return seq; ++} ++ ++// _gather_104: kwarg_or_starred _loop0_105 ++static asdl_seq * ++_gather_104_rule(Parser *p) ++{ ++ if (p->error_indicator) { ++ return NULL; ++ } ++ asdl_seq * res = NULL; ++ int mark = p->mark; ++ { // kwarg_or_starred _loop0_105 ++ KeywordOrStarred* elem; ++ asdl_seq * seq; ++ if ( ++ (elem = kwarg_or_starred_rule(p)) ++ && ++ (seq = _loop0_105_rule(p)) ++ ) ++ { ++ res = _PyPegen_seq_insert_in_front(p, elem, seq); ++ goto done; ++ } ++ p->mark = mark; ++ } ++ res = NULL; ++ done: ++ return res; ++} ++ ++// _loop0_107: ',' kwarg_or_double_starred ++static asdl_seq * ++_loop0_107_rule(Parser *p) ++{ ++ if (p->error_indicator) { ++ return NULL; ++ } ++ void *res = NULL; ++ int mark = p->mark; ++ int start_mark = p->mark; ++ void **children = PyMem_Malloc(sizeof(void *)); ++ if (!children) { ++ PyErr_Format(PyExc_MemoryError, "Parser out of memory"); ++ return NULL; ++ } ++ ssize_t children_capacity = 1; ++ ssize_t n = 0; ++ { // ',' kwarg_or_double_starred ++ KeywordOrStarred* elem; ++ void *literal; ++ while ( ++ (literal = _PyPegen_expect_token(p, 12)) ++ && ++ (elem = kwarg_or_double_starred_rule(p)) ++ ) ++ { ++ res = elem; ++ if (res == NULL && PyErr_Occurred()) { ++ p->error_indicator = 1; ++ PyMem_Free(children); ++ return NULL; ++ } ++ if (n == children_capacity) { ++ children_capacity *= 2; ++ children = PyMem_Realloc(children, children_capacity*sizeof(void *)); ++ if (!children) { ++ PyErr_Format(PyExc_MemoryError, "realloc None"); ++ return NULL; ++ } ++ } ++ children[n++] = res; ++ mark = p->mark; ++ } ++ p->mark = mark; ++ } ++ asdl_seq *seq = _Py_asdl_seq_new(n, p->arena); ++ if (!seq) { ++ PyErr_Format(PyExc_MemoryError, "asdl_seq_new _loop0_107"); ++ PyMem_Free(children); ++ return NULL; ++ } ++ for (int i = 0; i < n; i++) asdl_seq_SET(seq, i, children[i]); ++ PyMem_Free(children); ++ _PyPegen_insert_memo(p, start_mark, _loop0_107_type, seq); ++ return seq; ++} ++ ++// _gather_106: kwarg_or_double_starred _loop0_107 ++static asdl_seq * ++_gather_106_rule(Parser *p) ++{ ++ if (p->error_indicator) { ++ return NULL; ++ } ++ asdl_seq * res = NULL; ++ int mark = p->mark; ++ { // kwarg_or_double_starred _loop0_107 ++ KeywordOrStarred* elem; ++ asdl_seq * seq; ++ if ( ++ (elem = kwarg_or_double_starred_rule(p)) ++ && ++ (seq = _loop0_107_rule(p)) ++ ) ++ { ++ res = _PyPegen_seq_insert_in_front(p, elem, seq); ++ goto done; ++ } ++ p->mark = mark; ++ } ++ res = NULL; ++ done: ++ return res; ++} ++ ++// _loop0_108: (',' star_target) ++static asdl_seq * ++_loop0_108_rule(Parser *p) ++{ ++ if (p->error_indicator) { ++ return NULL; ++ } ++ void *res = NULL; ++ int mark = p->mark; ++ int start_mark = p->mark; ++ void **children = PyMem_Malloc(sizeof(void *)); ++ if (!children) { ++ PyErr_Format(PyExc_MemoryError, "Parser out of memory"); ++ return NULL; ++ } ++ ssize_t children_capacity = 1; ++ ssize_t n = 0; ++ { // (',' star_target) ++ void *_tmp_134_var; ++ while ( ++ (_tmp_134_var = _tmp_134_rule(p)) ++ ) ++ { ++ res = _tmp_134_var; ++ if (n == children_capacity) { ++ children_capacity *= 2; ++ children = PyMem_Realloc(children, children_capacity*sizeof(void *)); ++ if (!children) { ++ PyErr_Format(PyExc_MemoryError, "realloc None"); ++ return NULL; ++ } ++ } ++ children[n++] = res; ++ mark = p->mark; ++ } ++ p->mark = mark; ++ } ++ asdl_seq *seq = _Py_asdl_seq_new(n, p->arena); ++ if (!seq) { ++ PyErr_Format(PyExc_MemoryError, "asdl_seq_new _loop0_108"); ++ PyMem_Free(children); ++ return NULL; ++ } ++ for (int i = 0; i < n; i++) asdl_seq_SET(seq, i, children[i]); ++ PyMem_Free(children); ++ _PyPegen_insert_memo(p, start_mark, _loop0_108_type, seq); ++ return seq; ++} ++ ++// _loop0_110: ',' star_target ++static asdl_seq * ++_loop0_110_rule(Parser *p) ++{ ++ if (p->error_indicator) { ++ return NULL; ++ } ++ void *res = NULL; ++ int mark = p->mark; ++ int start_mark = p->mark; ++ void **children = PyMem_Malloc(sizeof(void *)); ++ if (!children) { ++ PyErr_Format(PyExc_MemoryError, "Parser out of memory"); ++ return NULL; ++ } ++ ssize_t children_capacity = 1; ++ ssize_t n = 0; ++ { // ',' star_target ++ expr_ty elem; ++ void *literal; ++ while ( ++ (literal = _PyPegen_expect_token(p, 12)) ++ && ++ (elem = star_target_rule(p)) ++ ) ++ { ++ res = elem; ++ if (res == NULL && PyErr_Occurred()) { ++ p->error_indicator = 1; ++ PyMem_Free(children); ++ return NULL; ++ } ++ if (n == children_capacity) { ++ children_capacity *= 2; ++ children = PyMem_Realloc(children, children_capacity*sizeof(void *)); ++ if (!children) { ++ PyErr_Format(PyExc_MemoryError, "realloc None"); ++ return NULL; ++ } ++ } ++ children[n++] = res; ++ mark = p->mark; ++ } ++ p->mark = mark; ++ } ++ asdl_seq *seq = _Py_asdl_seq_new(n, p->arena); ++ if (!seq) { ++ PyErr_Format(PyExc_MemoryError, "asdl_seq_new _loop0_110"); ++ PyMem_Free(children); ++ return NULL; ++ } ++ for (int i = 0; i < n; i++) asdl_seq_SET(seq, i, children[i]); ++ PyMem_Free(children); ++ _PyPegen_insert_memo(p, start_mark, _loop0_110_type, seq); ++ return seq; ++} ++ ++// _gather_109: star_target _loop0_110 ++static asdl_seq * ++_gather_109_rule(Parser *p) ++{ ++ if (p->error_indicator) { ++ return NULL; ++ } ++ asdl_seq * res = NULL; ++ int mark = p->mark; ++ { // star_target _loop0_110 ++ expr_ty elem; ++ asdl_seq * seq; ++ if ( ++ (elem = star_target_rule(p)) ++ && ++ (seq = _loop0_110_rule(p)) ++ ) ++ { ++ res = _PyPegen_seq_insert_in_front(p, elem, seq); ++ goto done; ++ } ++ p->mark = mark; ++ } ++ res = NULL; ++ done: ++ return res; ++} ++ ++// _tmp_111: !'*' star_target ++static void * ++_tmp_111_rule(Parser *p) ++{ ++ if (p->error_indicator) { ++ return NULL; ++ } ++ void * res = NULL; ++ int mark = p->mark; ++ { // !'*' star_target ++ expr_ty star_target_var; ++ if ( ++ _PyPegen_lookahead_with_int(0, _PyPegen_expect_token, p, 16) ++ && ++ (star_target_var = star_target_rule(p)) ++ ) ++ { ++ res = star_target_var; ++ goto done; ++ } ++ p->mark = mark; ++ } ++ res = NULL; ++ done: ++ return res; ++} ++ ++// _loop0_113: ',' del_target ++static asdl_seq * ++_loop0_113_rule(Parser *p) ++{ ++ if (p->error_indicator) { ++ return NULL; ++ } ++ void *res = NULL; ++ int mark = p->mark; ++ int start_mark = p->mark; ++ void **children = PyMem_Malloc(sizeof(void *)); ++ if (!children) { ++ PyErr_Format(PyExc_MemoryError, "Parser out of memory"); ++ return NULL; ++ } ++ ssize_t children_capacity = 1; ++ ssize_t n = 0; ++ { // ',' del_target ++ expr_ty elem; ++ void *literal; ++ while ( ++ (literal = _PyPegen_expect_token(p, 12)) ++ && ++ (elem = del_target_rule(p)) ++ ) ++ { ++ res = elem; ++ if (res == NULL && PyErr_Occurred()) { ++ p->error_indicator = 1; ++ PyMem_Free(children); ++ return NULL; ++ } ++ if (n == children_capacity) { ++ children_capacity *= 2; ++ children = PyMem_Realloc(children, children_capacity*sizeof(void *)); ++ if (!children) { ++ PyErr_Format(PyExc_MemoryError, "realloc None"); ++ return NULL; ++ } ++ } ++ children[n++] = res; ++ mark = p->mark; ++ } ++ p->mark = mark; ++ } ++ asdl_seq *seq = _Py_asdl_seq_new(n, p->arena); ++ if (!seq) { ++ PyErr_Format(PyExc_MemoryError, "asdl_seq_new _loop0_113"); ++ PyMem_Free(children); ++ return NULL; ++ } ++ for (int i = 0; i < n; i++) asdl_seq_SET(seq, i, children[i]); ++ PyMem_Free(children); ++ _PyPegen_insert_memo(p, start_mark, _loop0_113_type, seq); ++ return seq; ++} ++ ++// _gather_112: del_target _loop0_113 ++static asdl_seq * ++_gather_112_rule(Parser *p) ++{ ++ if (p->error_indicator) { ++ return NULL; ++ } ++ asdl_seq * res = NULL; ++ int mark = p->mark; ++ { // del_target _loop0_113 ++ expr_ty elem; ++ asdl_seq * seq; ++ if ( ++ (elem = del_target_rule(p)) ++ && ++ (seq = _loop0_113_rule(p)) ++ ) ++ { ++ res = _PyPegen_seq_insert_in_front(p, elem, seq); ++ goto done; ++ } ++ p->mark = mark; ++ } ++ res = NULL; ++ done: ++ return res; ++} ++ ++// _loop0_115: ',' target ++static asdl_seq * ++_loop0_115_rule(Parser *p) ++{ ++ if (p->error_indicator) { ++ return NULL; ++ } ++ void *res = NULL; ++ int mark = p->mark; ++ int start_mark = p->mark; ++ void **children = PyMem_Malloc(sizeof(void *)); ++ if (!children) { ++ PyErr_Format(PyExc_MemoryError, "Parser out of memory"); ++ return NULL; ++ } ++ ssize_t children_capacity = 1; ++ ssize_t n = 0; ++ { // ',' target ++ expr_ty elem; ++ void *literal; ++ while ( ++ (literal = _PyPegen_expect_token(p, 12)) ++ && ++ (elem = target_rule(p)) ++ ) ++ { ++ res = elem; ++ if (res == NULL && PyErr_Occurred()) { ++ p->error_indicator = 1; ++ PyMem_Free(children); ++ return NULL; ++ } ++ if (n == children_capacity) { ++ children_capacity *= 2; ++ children = PyMem_Realloc(children, children_capacity*sizeof(void *)); ++ if (!children) { ++ PyErr_Format(PyExc_MemoryError, "realloc None"); ++ return NULL; ++ } ++ } ++ children[n++] = res; ++ mark = p->mark; ++ } ++ p->mark = mark; ++ } ++ asdl_seq *seq = _Py_asdl_seq_new(n, p->arena); ++ if (!seq) { ++ PyErr_Format(PyExc_MemoryError, "asdl_seq_new _loop0_115"); ++ PyMem_Free(children); ++ return NULL; ++ } ++ for (int i = 0; i < n; i++) asdl_seq_SET(seq, i, children[i]); ++ PyMem_Free(children); ++ _PyPegen_insert_memo(p, start_mark, _loop0_115_type, seq); ++ return seq; ++} ++ ++// _gather_114: target _loop0_115 ++static asdl_seq * ++_gather_114_rule(Parser *p) ++{ ++ if (p->error_indicator) { ++ return NULL; ++ } ++ asdl_seq * res = NULL; ++ int mark = p->mark; ++ { // target _loop0_115 ++ expr_ty elem; ++ asdl_seq * seq; ++ if ( ++ (elem = target_rule(p)) ++ && ++ (seq = _loop0_115_rule(p)) ++ ) ++ { ++ res = _PyPegen_seq_insert_in_front(p, elem, seq); ++ goto done; ++ } ++ p->mark = mark; ++ } ++ res = NULL; ++ done: ++ return res; ++} ++ ++// _tmp_116: args | expression for_if_clauses ++static void * ++_tmp_116_rule(Parser *p) ++{ ++ if (p->error_indicator) { ++ return NULL; ++ } ++ void * res = NULL; ++ int mark = p->mark; ++ { // args ++ expr_ty args_var; ++ if ( ++ (args_var = args_rule(p)) ++ ) ++ { ++ res = args_var; ++ goto done; ++ } ++ p->mark = mark; ++ } ++ { // expression for_if_clauses ++ expr_ty expression_var; ++ asdl_seq* for_if_clauses_var; ++ if ( ++ (expression_var = expression_rule(p)) ++ && ++ (for_if_clauses_var = for_if_clauses_rule(p)) ++ ) ++ { ++ res = _PyPegen_dummy_name(p, expression_var, for_if_clauses_var); ++ goto done; ++ } ++ p->mark = mark; ++ } ++ res = NULL; ++ done: ++ return res; ++} ++ ++// _tmp_117: '=' annotated_rhs ++static void * ++_tmp_117_rule(Parser *p) ++{ ++ if (p->error_indicator) { ++ return NULL; ++ } ++ void * res = NULL; ++ int mark = p->mark; ++ { // '=' annotated_rhs ++ expr_ty annotated_rhs_var; ++ void *literal; ++ if ( ++ (literal = _PyPegen_expect_token(p, 22)) ++ && ++ (annotated_rhs_var = annotated_rhs_rule(p)) ++ ) ++ { ++ res = _PyPegen_dummy_name(p, literal, annotated_rhs_var); ++ goto done; ++ } ++ p->mark = mark; ++ } ++ res = NULL; ++ done: ++ return res; ++} ++ ++// _tmp_118: '=' | augassign ++static void * ++_tmp_118_rule(Parser *p) ++{ ++ if (p->error_indicator) { ++ return NULL; ++ } ++ void * res = NULL; ++ int mark = p->mark; ++ { // '=' ++ void *literal; ++ if ( ++ (literal = _PyPegen_expect_token(p, 22)) ++ ) ++ { ++ res = literal; ++ goto done; ++ } ++ p->mark = mark; ++ } ++ { // augassign ++ AugOperator* augassign_var; ++ if ( ++ (augassign_var = augassign_rule(p)) ++ ) ++ { ++ res = augassign_var; ++ goto done; ++ } ++ p->mark = mark; ++ } ++ res = NULL; ++ done: ++ return res; ++} ++ ++// _tmp_119: yield_expr | star_expressions ++static void * ++_tmp_119_rule(Parser *p) ++{ ++ if (p->error_indicator) { ++ return NULL; ++ } ++ void * res = NULL; ++ int mark = p->mark; ++ { // yield_expr ++ expr_ty yield_expr_var; ++ if ( ++ (yield_expr_var = yield_expr_rule(p)) ++ ) ++ { ++ res = yield_expr_var; ++ goto done; ++ } ++ p->mark = mark; ++ } ++ { // star_expressions ++ expr_ty star_expressions_var; ++ if ( ++ (star_expressions_var = star_expressions_rule(p)) ++ ) ++ { ++ res = star_expressions_var; ++ goto done; ++ } ++ p->mark = mark; ++ } ++ res = NULL; ++ done: ++ return res; ++} ++ ++// _tmp_120: '[' | '(' | '{' ++static void * ++_tmp_120_rule(Parser *p) ++{ ++ if (p->error_indicator) { ++ return NULL; ++ } ++ void * res = NULL; ++ int mark = p->mark; ++ { // '[' ++ void *literal; ++ if ( ++ (literal = _PyPegen_expect_token(p, 9)) ++ ) ++ { ++ res = literal; ++ goto done; ++ } ++ p->mark = mark; ++ } ++ { // '(' ++ void *literal; ++ if ( ++ (literal = _PyPegen_expect_token(p, 7)) ++ ) ++ { ++ res = literal; ++ goto done; ++ } ++ p->mark = mark; ++ } ++ { // '{' ++ void *literal; ++ if ( ++ (literal = _PyPegen_expect_token(p, 25)) ++ ) ++ { ++ res = literal; ++ goto done; ++ } ++ p->mark = mark; ++ } ++ res = NULL; ++ done: ++ return res; ++} ++ ++// _tmp_121: plain_names ',' ++static void * ++_tmp_121_rule(Parser *p) ++{ ++ if (p->error_indicator) { ++ return NULL; ++ } ++ void * res = NULL; ++ int mark = p->mark; ++ { // plain_names ',' ++ void *literal; ++ asdl_seq* plain_names_var; ++ if ( ++ (plain_names_var = plain_names_rule(p)) ++ && ++ (literal = _PyPegen_expect_token(p, 12)) ++ ) ++ { ++ res = _PyPegen_dummy_name(p, plain_names_var, literal); ++ goto done; ++ } ++ p->mark = mark; ++ } ++ res = NULL; ++ done: ++ return res; ++} ++ ++// _tmp_122: slash_with_default | names_with_default ++static void * ++_tmp_122_rule(Parser *p) ++{ ++ if (p->error_indicator) { ++ return NULL; ++ } ++ void * res = NULL; ++ int mark = p->mark; ++ { // slash_with_default ++ SlashWithDefault* slash_with_default_var; ++ if ( ++ (slash_with_default_var = slash_with_default_rule(p)) ++ ) ++ { ++ res = slash_with_default_var; ++ goto done; ++ } ++ p->mark = mark; ++ } ++ { // names_with_default ++ asdl_seq* names_with_default_var; ++ if ( ++ (names_with_default_var = names_with_default_rule(p)) ++ ) ++ { ++ res = names_with_default_var; ++ goto done; ++ } ++ p->mark = mark; ++ } ++ res = NULL; ++ done: ++ return res; ++} ++ ++// _tmp_123: star_targets '=' ++static void * ++_tmp_123_rule(Parser *p) ++{ ++ if (p->error_indicator) { ++ return NULL; ++ } ++ void * res = NULL; ++ int mark = p->mark; ++ { // star_targets '=' ++ void *literal; ++ expr_ty z; ++ if ( ++ (z = star_targets_rule(p)) ++ && ++ (literal = _PyPegen_expect_token(p, 22)) ++ ) ++ { ++ res = z; ++ if (res == NULL && PyErr_Occurred()) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ goto done; ++ } ++ p->mark = mark; ++ } ++ res = NULL; ++ done: ++ return res; ++} ++ ++// _tmp_124: '.' | '...' ++static void * ++_tmp_124_rule(Parser *p) ++{ ++ if (p->error_indicator) { ++ return NULL; ++ } ++ void * res = NULL; ++ int mark = p->mark; ++ { // '.' ++ void *literal; ++ if ( ++ (literal = _PyPegen_expect_token(p, 23)) ++ ) ++ { ++ res = literal; ++ goto done; ++ } ++ p->mark = mark; ++ } ++ { // '...' ++ void *literal; ++ if ( ++ (literal = _PyPegen_expect_token(p, 52)) ++ ) ++ { ++ res = literal; ++ goto done; ++ } ++ p->mark = mark; ++ } ++ res = NULL; ++ done: ++ return res; ++} ++ ++// _tmp_125: '.' | '...' ++static void * ++_tmp_125_rule(Parser *p) ++{ ++ if (p->error_indicator) { ++ return NULL; ++ } ++ void * res = NULL; ++ int mark = p->mark; ++ { // '.' ++ void *literal; ++ if ( ++ (literal = _PyPegen_expect_token(p, 23)) ++ ) ++ { ++ res = literal; ++ goto done; ++ } ++ p->mark = mark; ++ } ++ { // '...' ++ void *literal; ++ if ( ++ (literal = _PyPegen_expect_token(p, 52)) ++ ) ++ { ++ res = literal; ++ goto done; ++ } ++ p->mark = mark; ++ } ++ res = NULL; ++ done: ++ return res; ++} ++ ++// _tmp_126: plain_name !'=' ++static void * ++_tmp_126_rule(Parser *p) ++{ ++ if (p->error_indicator) { ++ return NULL; ++ } ++ void * res = NULL; ++ int mark = p->mark; ++ { // plain_name !'=' ++ arg_ty plain_name_var; ++ if ( ++ (plain_name_var = plain_name_rule(p)) ++ && ++ _PyPegen_lookahead_with_int(0, _PyPegen_expect_token, p, 22) ++ ) ++ { ++ res = plain_name_var; ++ goto done; ++ } ++ p->mark = mark; ++ } ++ res = NULL; ++ done: ++ return res; ++} ++ ++// _tmp_127: '@' named_expression NEWLINE ++static void * ++_tmp_127_rule(Parser *p) ++{ ++ if (p->error_indicator) { ++ return NULL; ++ } ++ void * res = NULL; ++ int mark = p->mark; ++ { // '@' named_expression NEWLINE ++ expr_ty f; ++ void *literal; ++ void *newline_var; ++ if ( ++ (literal = _PyPegen_expect_token(p, 49)) ++ && ++ (f = named_expression_rule(p)) ++ && ++ (newline_var = _PyPegen_newline_token(p)) ++ ) ++ { ++ res = f; ++ if (res == NULL && PyErr_Occurred()) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ goto done; ++ } ++ p->mark = mark; ++ } ++ res = NULL; ++ done: ++ return res; ++} ++ ++// _tmp_128: ',' star_expression ++static void * ++_tmp_128_rule(Parser *p) ++{ ++ if (p->error_indicator) { ++ return NULL; ++ } ++ void * res = NULL; ++ int mark = p->mark; ++ { // ',' star_expression ++ expr_ty c; ++ void *literal; ++ if ( ++ (literal = _PyPegen_expect_token(p, 12)) ++ && ++ (c = star_expression_rule(p)) ++ ) ++ { ++ res = c; ++ if (res == NULL && PyErr_Occurred()) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ goto done; ++ } ++ p->mark = mark; ++ } ++ res = NULL; ++ done: ++ return res; ++} ++ ++// _tmp_129: ',' expression ++static void * ++_tmp_129_rule(Parser *p) ++{ ++ if (p->error_indicator) { ++ return NULL; ++ } ++ void * res = NULL; ++ int mark = p->mark; ++ { // ',' expression ++ expr_ty c; ++ void *literal; ++ if ( ++ (literal = _PyPegen_expect_token(p, 12)) ++ && ++ (c = expression_rule(p)) ++ ) ++ { ++ res = c; ++ if (res == NULL && PyErr_Occurred()) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ goto done; ++ } ++ p->mark = mark; ++ } ++ res = NULL; ++ done: ++ return res; ++} ++ ++// _tmp_130: lambda_plain_name !'=' ++static void * ++_tmp_130_rule(Parser *p) ++{ ++ if (p->error_indicator) { ++ return NULL; ++ } ++ void * res = NULL; ++ int mark = p->mark; ++ { // lambda_plain_name !'=' ++ arg_ty lambda_plain_name_var; ++ if ( ++ (lambda_plain_name_var = lambda_plain_name_rule(p)) ++ && ++ _PyPegen_lookahead_with_int(0, _PyPegen_expect_token, p, 22) ++ ) ++ { ++ res = lambda_plain_name_var; ++ goto done; ++ } ++ p->mark = mark; ++ } ++ res = NULL; ++ done: ++ return res; ++} ++ ++// _tmp_131: 'or' conjunction ++static void * ++_tmp_131_rule(Parser *p) ++{ ++ if (p->error_indicator) { ++ return NULL; ++ } ++ void * res = NULL; ++ int mark = p->mark; ++ { // 'or' conjunction ++ expr_ty c; ++ void *keyword; ++ if ( ++ (keyword = _PyPegen_expect_token(p, 532)) ++ && ++ (c = conjunction_rule(p)) ++ ) ++ { ++ res = c; ++ if (res == NULL && PyErr_Occurred()) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ goto done; ++ } ++ p->mark = mark; ++ } ++ res = NULL; ++ done: ++ return res; ++} ++ ++// _tmp_132: 'and' inversion ++static void * ++_tmp_132_rule(Parser *p) ++{ ++ if (p->error_indicator) { ++ return NULL; ++ } ++ void * res = NULL; ++ int mark = p->mark; ++ { // 'and' inversion ++ expr_ty c; ++ void *keyword; ++ if ( ++ (keyword = _PyPegen_expect_token(p, 533)) ++ && ++ (c = inversion_rule(p)) ++ ) ++ { ++ res = c; ++ if (res == NULL && PyErr_Occurred()) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ goto done; ++ } ++ p->mark = mark; ++ } ++ res = NULL; ++ done: ++ return res; ++} ++ ++// _tmp_133: ASYNC? 'for' star_targets 'in' disjunction (('if' disjunction))* ++static void * ++_tmp_133_rule(Parser *p) ++{ ++ if (p->error_indicator) { ++ return NULL; ++ } ++ void * res = NULL; ++ int mark = p->mark; ++ { // ASYNC? 'for' star_targets 'in' disjunction (('if' disjunction))* ++ expr_ty a; ++ expr_ty b; ++ asdl_seq * c; ++ void *keyword; ++ void *keyword_1; ++ void *y; ++ if ( ++ (y = _PyPegen_async_token(p), 1) ++ && ++ (keyword = _PyPegen_expect_token(p, 517)) ++ && ++ (a = star_targets_rule(p)) ++ && ++ (keyword_1 = _PyPegen_expect_token(p, 518)) ++ && ++ (b = disjunction_rule(p)) ++ && ++ (c = _loop0_135_rule(p)) ++ ) ++ { ++ res = _Py_comprehension ( a , b , c , y != NULL , p -> arena ); ++ if (res == NULL && PyErr_Occurred()) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ goto done; ++ } ++ p->mark = mark; ++ } ++ res = NULL; ++ done: ++ return res; ++} ++ ++// _tmp_134: ',' star_target ++static void * ++_tmp_134_rule(Parser *p) ++{ ++ if (p->error_indicator) { ++ return NULL; ++ } ++ void * res = NULL; ++ int mark = p->mark; ++ { // ',' star_target ++ expr_ty c; ++ void *literal; ++ if ( ++ (literal = _PyPegen_expect_token(p, 12)) ++ && ++ (c = star_target_rule(p)) ++ ) ++ { ++ res = c; ++ if (res == NULL && PyErr_Occurred()) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ goto done; ++ } ++ p->mark = mark; ++ } ++ res = NULL; ++ done: ++ return res; ++} ++ ++// _loop0_135: ('if' disjunction) ++static asdl_seq * ++_loop0_135_rule(Parser *p) ++{ ++ if (p->error_indicator) { ++ return NULL; ++ } ++ void *res = NULL; ++ int mark = p->mark; ++ int start_mark = p->mark; ++ void **children = PyMem_Malloc(sizeof(void *)); ++ if (!children) { ++ PyErr_Format(PyExc_MemoryError, "Parser out of memory"); ++ return NULL; ++ } ++ ssize_t children_capacity = 1; ++ ssize_t n = 0; ++ { // ('if' disjunction) ++ void *_tmp_136_var; ++ while ( ++ (_tmp_136_var = _tmp_136_rule(p)) ++ ) ++ { ++ res = _tmp_136_var; ++ if (n == children_capacity) { ++ children_capacity *= 2; ++ children = PyMem_Realloc(children, children_capacity*sizeof(void *)); ++ if (!children) { ++ PyErr_Format(PyExc_MemoryError, "realloc None"); ++ return NULL; ++ } ++ } ++ children[n++] = res; ++ mark = p->mark; ++ } ++ p->mark = mark; ++ } ++ asdl_seq *seq = _Py_asdl_seq_new(n, p->arena); ++ if (!seq) { ++ PyErr_Format(PyExc_MemoryError, "asdl_seq_new _loop0_135"); ++ PyMem_Free(children); ++ return NULL; ++ } ++ for (int i = 0; i < n; i++) asdl_seq_SET(seq, i, children[i]); ++ PyMem_Free(children); ++ _PyPegen_insert_memo(p, start_mark, _loop0_135_type, seq); ++ return seq; ++} ++ ++// _tmp_136: 'if' disjunction ++static void * ++_tmp_136_rule(Parser *p) ++{ ++ if (p->error_indicator) { ++ return NULL; ++ } ++ void * res = NULL; ++ int mark = p->mark; ++ { // 'if' disjunction ++ void *keyword; ++ expr_ty z; ++ if ( ++ (keyword = _PyPegen_expect_token(p, 510)) ++ && ++ (z = disjunction_rule(p)) ++ ) ++ { ++ res = z; ++ if (res == NULL && PyErr_Occurred()) { ++ p->error_indicator = 1; ++ return NULL; ++ } ++ goto done; ++ } ++ p->mark = mark; ++ } ++ res = NULL; ++ done: ++ return res; ++} ++ ++void * ++_PyPegen_parse(Parser *p) ++{ ++ // Initialize keywords ++ p->keywords = reserved_keywords; ++ p->n_keyword_lists = n_keyword_lists; ++ ++ // Run parser ++ void *result = NULL; ++ if (p->start_rule == Py_file_input) { ++ result = file_rule(p); ++ } else if (p->start_rule == Py_single_input) { ++ result = interactive_rule(p); ++ } else if (p->start_rule == Py_eval_input) { ++ result = eval_rule(p); ++ } else if (p->start_rule == Py_fstring_input) { ++ result = fstring_rule(p); ++ } ++ ++ return result; ++} ++ ++// The end +diff --git a/Parser/pegen/parse_string.c b/Parser/pegen/parse_string.c +new file mode 100644 +--- /dev/null ++++ b/Parser/pegen/parse_string.c +@@ -0,0 +1,1387 @@ ++#include ++ ++#include "../tokenizer.h" ++#include "pegen.h" ++#include "parse_string.h" ++ ++//// STRING HANDLING FUNCTIONS //// ++ ++// These functions are ported directly from Python/ast.c with some modifications ++// to account for the use of "Parser *p", the fact that don't have parser nodes ++// to pass around and the usage of some specialized APIs present only in this ++// file (like "_PyPegen_raise_syntax_error"). ++ ++static int ++warn_invalid_escape_sequence(Parser *p, unsigned char first_invalid_escape_char) ++{ ++ PyObject *msg = ++ PyUnicode_FromFormat("invalid escape sequence \\%c", first_invalid_escape_char); ++ if (msg == NULL) { ++ return -1; ++ } ++ if (PyErr_WarnExplicitObject(PyExc_DeprecationWarning, msg, p->tok->filename, ++ p->tok->lineno, NULL, NULL) < 0) { ++ if (PyErr_ExceptionMatches(PyExc_DeprecationWarning)) { ++ /* Replace the DeprecationWarning exception with a SyntaxError ++ to get a more accurate error report */ ++ PyErr_Clear(); ++ RAISE_SYNTAX_ERROR("invalid escape sequence \\%c", first_invalid_escape_char); ++ } ++ Py_DECREF(msg); ++ return -1; ++ } ++ Py_DECREF(msg); ++ return 0; ++} ++ ++static PyObject * ++decode_utf8(const char **sPtr, const char *end) ++{ ++ const char *s, *t; ++ t = s = *sPtr; ++ while (s < end && (*s & 0x80)) { ++ s++; ++ } ++ *sPtr = s; ++ return PyUnicode_DecodeUTF8(t, s - t, NULL); ++} ++ ++static PyObject * ++decode_unicode_with_escapes(Parser *parser, const char *s, size_t len) ++{ ++ PyObject *v, *u; ++ char *buf; ++ char *p; ++ const char *end; ++ ++ /* check for integer overflow */ ++ if (len > SIZE_MAX / 6) { ++ return NULL; ++ } ++ /* "ä" (2 bytes) may become "\U000000E4" (10 bytes), or 1:5 ++ "\ä" (3 bytes) may become "\u005c\U000000E4" (16 bytes), or ~1:6 */ ++ u = PyBytes_FromStringAndSize((char *)NULL, len * 6); ++ if (u == NULL) { ++ return NULL; ++ } ++ p = buf = PyBytes_AsString(u); ++ end = s + len; ++ while (s < end) { ++ if (*s == '\\') { ++ *p++ = *s++; ++ if (s >= end || *s & 0x80) { ++ strcpy(p, "u005c"); ++ p += 5; ++ if (s >= end) { ++ break; ++ } ++ } ++ } ++ if (*s & 0x80) { ++ PyObject *w; ++ int kind; ++ void *data; ++ Py_ssize_t len, i; ++ w = decode_utf8(&s, end); ++ if (w == NULL) { ++ Py_DECREF(u); ++ return NULL; ++ } ++ kind = PyUnicode_KIND(w); ++ data = PyUnicode_DATA(w); ++ len = PyUnicode_GET_LENGTH(w); ++ for (i = 0; i < len; i++) { ++ Py_UCS4 chr = PyUnicode_READ(kind, data, i); ++ sprintf(p, "\\U%08x", chr); ++ p += 10; ++ } ++ /* Should be impossible to overflow */ ++ assert(p - buf <= PyBytes_GET_SIZE(u)); ++ Py_DECREF(w); ++ } ++ else { ++ *p++ = *s++; ++ } ++ } ++ len = p - buf; ++ s = buf; ++ ++ const char *first_invalid_escape; ++ v = _PyUnicode_DecodeUnicodeEscape(s, len, NULL, &first_invalid_escape); ++ ++ if (v != NULL && first_invalid_escape != NULL) { ++ if (warn_invalid_escape_sequence(parser, *first_invalid_escape) < 0) { ++ /* We have not decref u before because first_invalid_escape points ++ inside u. */ ++ Py_XDECREF(u); ++ Py_DECREF(v); ++ return NULL; ++ } ++ } ++ Py_XDECREF(u); ++ return v; ++} ++ ++static PyObject * ++decode_bytes_with_escapes(Parser *p, const char *s, Py_ssize_t len) ++{ ++ const char *first_invalid_escape; ++ PyObject *result = _PyBytes_DecodeEscape(s, len, NULL, &first_invalid_escape); ++ if (result == NULL) { ++ return NULL; ++ } ++ ++ if (first_invalid_escape != NULL) { ++ if (warn_invalid_escape_sequence(p, *first_invalid_escape) < 0) { ++ Py_DECREF(result); ++ return NULL; ++ } ++ } ++ return result; ++} ++ ++/* s must include the bracketing quote characters, and r, b, u, ++ &/or f prefixes (if any), and embedded escape sequences (if any). ++ _PyPegen_parsestr parses it, and sets *result to decoded Python string object. ++ If the string is an f-string, set *fstr and *fstrlen to the unparsed ++ string object. Return 0 if no errors occurred. */ ++int ++_PyPegen_parsestr(Parser *p, const char *s, int *bytesmode, int *rawmode, PyObject **result, ++ const char **fstr, Py_ssize_t *fstrlen) ++{ ++ size_t len; ++ int quote = Py_CHARMASK(*s); ++ int fmode = 0; ++ *bytesmode = 0; ++ *rawmode = 0; ++ *result = NULL; ++ *fstr = NULL; ++ if (Py_ISALPHA(quote)) { ++ while (!*bytesmode || !*rawmode) { ++ if (quote == 'b' || quote == 'B') { ++ quote = *++s; ++ *bytesmode = 1; ++ } ++ else if (quote == 'u' || quote == 'U') { ++ quote = *++s; ++ } ++ else if (quote == 'r' || quote == 'R') { ++ quote = *++s; ++ *rawmode = 1; ++ } ++ else if (quote == 'f' || quote == 'F') { ++ quote = *++s; ++ fmode = 1; ++ } ++ else { ++ break; ++ } ++ } ++ } ++ ++ if (fmode && *bytesmode) { ++ PyErr_BadInternalCall(); ++ return -1; ++ } ++ if (quote != '\'' && quote != '\"') { ++ PyErr_BadInternalCall(); ++ return -1; ++ } ++ /* Skip the leading quote char. */ ++ s++; ++ len = strlen(s); ++ if (len > INT_MAX) { ++ PyErr_SetString(PyExc_OverflowError, "string to parse is too long"); ++ return -1; ++ } ++ if (s[--len] != quote) { ++ /* Last quote char must match the first. */ ++ PyErr_BadInternalCall(); ++ return -1; ++ } ++ if (len >= 4 && s[0] == quote && s[1] == quote) { ++ /* A triple quoted string. We've already skipped one quote at ++ the start and one at the end of the string. Now skip the ++ two at the start. */ ++ s += 2; ++ len -= 2; ++ /* And check that the last two match. */ ++ if (s[--len] != quote || s[--len] != quote) { ++ PyErr_BadInternalCall(); ++ return -1; ++ } ++ } ++ ++ if (fmode) { ++ /* Just return the bytes. The caller will parse the resulting ++ string. */ ++ *fstr = s; ++ *fstrlen = len; ++ return 0; ++ } ++ ++ /* Not an f-string. */ ++ /* Avoid invoking escape decoding routines if possible. */ ++ *rawmode = *rawmode || strchr(s, '\\') == NULL; ++ if (*bytesmode) { ++ /* Disallow non-ASCII characters. */ ++ const char *ch; ++ for (ch = s; *ch; ch++) { ++ if (Py_CHARMASK(*ch) >= 0x80) { ++ RAISE_SYNTAX_ERROR( ++ "bytes can only contain ASCII " ++ "literal characters."); ++ return -1; ++ } ++ } ++ if (*rawmode) { ++ *result = PyBytes_FromStringAndSize(s, len); ++ } ++ else { ++ *result = decode_bytes_with_escapes(p, s, len); ++ } ++ } ++ else { ++ if (*rawmode) { ++ *result = PyUnicode_DecodeUTF8Stateful(s, len, NULL, NULL); ++ } ++ else { ++ *result = decode_unicode_with_escapes(p, s, len); ++ } ++ } ++ return *result == NULL ? -1 : 0; ++} ++ ++ ++ ++// FSTRING STUFF ++ ++static void fstring_shift_expr_locations(expr_ty n, int lineno, int col_offset); ++static void fstring_shift_argument(expr_ty parent, arg_ty args, int lineno, int col_offset); ++ ++ ++static inline void shift_expr(expr_ty parent, expr_ty n, int line, int col) { ++ if (parent->lineno < n->lineno) { ++ col = 0; ++ } ++ fstring_shift_expr_locations(n, line, col); ++} ++ ++static inline void shift_arg(expr_ty parent, arg_ty n, int line, int col) { ++ if (parent->lineno < n->lineno) { ++ col = 0; ++ } ++ fstring_shift_argument(parent, n, line, col); ++} ++ ++static void fstring_shift_seq_locations(expr_ty parent, asdl_seq *seq, int lineno, int col_offset) { ++ for (Py_ssize_t i = 0, l = asdl_seq_LEN(seq); i < l; i++) { ++ expr_ty expr = asdl_seq_GET(seq, i); ++ if (expr == NULL){ ++ continue; ++ } ++ shift_expr(parent, expr, lineno, col_offset); ++ } ++} ++ ++static void fstring_shift_slice_locations(expr_ty parent, expr_ty slice, int lineno, int col_offset) { ++ switch (slice->kind) { ++ case Slice_kind: ++ if (slice->v.Slice.lower) { ++ shift_expr(parent, slice->v.Slice.lower, lineno, col_offset); ++ } ++ if (slice->v.Slice.upper) { ++ shift_expr(parent, slice->v.Slice.upper, lineno, col_offset); ++ } ++ if (slice->v.Slice.step) { ++ shift_expr(parent, slice->v.Slice.step, lineno, col_offset); ++ } ++ break; ++ case Tuple_kind: ++ fstring_shift_seq_locations(parent, slice->v.Tuple.elts, lineno, col_offset); ++ break; ++ default: ++ break; ++ } ++} ++ ++static void fstring_shift_comprehension(expr_ty parent, comprehension_ty comp, int lineno, int col_offset) { ++ shift_expr(parent, comp->target, lineno, col_offset); ++ shift_expr(parent, comp->iter, lineno, col_offset); ++ fstring_shift_seq_locations(parent, comp->ifs, lineno, col_offset); ++} ++ ++static void fstring_shift_argument(expr_ty parent, arg_ty arg, int lineno, int col_offset) { ++ if (arg->annotation != NULL){ ++ shift_expr(parent, arg->annotation, lineno, col_offset); ++ } ++ arg->col_offset = arg->col_offset + col_offset; ++ arg->end_col_offset = arg->end_col_offset + col_offset; ++ arg->lineno = arg->lineno + lineno; ++ arg->end_lineno = arg->end_lineno + lineno; ++} ++ ++static void fstring_shift_arguments(expr_ty parent, arguments_ty args, int lineno, int col_offset) { ++ for (Py_ssize_t i = 0, l = asdl_seq_LEN(args->posonlyargs); i < l; i++) { ++ arg_ty arg = asdl_seq_GET(args->posonlyargs, i); ++ shift_arg(parent, arg, lineno, col_offset); ++ } ++ ++ for (Py_ssize_t i = 0, l = asdl_seq_LEN(args->args); i < l; i++) { ++ arg_ty arg = asdl_seq_GET(args->args, i); ++ shift_arg(parent, arg, lineno, col_offset); ++ } ++ ++ if (args->vararg != NULL) { ++ shift_arg(parent, args->vararg, lineno, col_offset); ++ } ++ ++ for (Py_ssize_t i = 0, l = asdl_seq_LEN(args->kwonlyargs); i < l; i++) { ++ arg_ty arg = asdl_seq_GET(args->kwonlyargs, i); ++ shift_arg(parent, arg, lineno, col_offset); ++ } ++ ++ fstring_shift_seq_locations(parent, args->kw_defaults, lineno, col_offset); ++ ++ if (args->kwarg != NULL) { ++ shift_arg(parent, args->kwarg, lineno, col_offset); ++ } ++ ++ fstring_shift_seq_locations(parent, args->defaults, lineno, col_offset); ++} ++ ++static void fstring_shift_children_locations(expr_ty n, int lineno, int col_offset) { ++ switch (n->kind) { ++ case BoolOp_kind: ++ fstring_shift_seq_locations(n, n->v.BoolOp.values, lineno, col_offset); ++ break; ++ case NamedExpr_kind: ++ shift_expr(n, n->v.NamedExpr.target, lineno, col_offset); ++ shift_expr(n, n->v.NamedExpr.value, lineno, col_offset); ++ break; ++ case BinOp_kind: ++ shift_expr(n, n->v.BinOp.left, lineno, col_offset); ++ shift_expr(n, n->v.BinOp.right, lineno, col_offset); ++ break; ++ case UnaryOp_kind: ++ shift_expr(n, n->v.UnaryOp.operand, lineno, col_offset); ++ break; ++ case Lambda_kind: ++ fstring_shift_arguments(n, n->v.Lambda.args, lineno, col_offset); ++ shift_expr(n, n->v.Lambda.body, lineno, col_offset); ++ break; ++ case IfExp_kind: ++ shift_expr(n, n->v.IfExp.test, lineno, col_offset); ++ shift_expr(n, n->v.IfExp.body, lineno, col_offset); ++ shift_expr(n, n->v.IfExp.orelse, lineno, col_offset); ++ break; ++ case Dict_kind: ++ fstring_shift_seq_locations(n, n->v.Dict.keys, lineno, col_offset); ++ fstring_shift_seq_locations(n, n->v.Dict.values, lineno, col_offset); ++ break; ++ case Set_kind: ++ fstring_shift_seq_locations(n, n->v.Set.elts, lineno, col_offset); ++ break; ++ case ListComp_kind: ++ shift_expr(n, n->v.ListComp.elt, lineno, col_offset); ++ for (Py_ssize_t i = 0, l = asdl_seq_LEN(n->v.ListComp.generators); i < l; i++) { ++ comprehension_ty comp = asdl_seq_GET(n->v.ListComp.generators, i); ++ fstring_shift_comprehension(n, comp, lineno, col_offset); ++ } ++ break; ++ case SetComp_kind: ++ shift_expr(n, n->v.SetComp.elt, lineno, col_offset); ++ for (Py_ssize_t i = 0, l = asdl_seq_LEN(n->v.SetComp.generators); i < l; i++) { ++ comprehension_ty comp = asdl_seq_GET(n->v.SetComp.generators, i); ++ fstring_shift_comprehension(n, comp, lineno, col_offset); ++ } ++ break; ++ case DictComp_kind: ++ shift_expr(n, n->v.DictComp.key, lineno, col_offset); ++ shift_expr(n, n->v.DictComp.value, lineno, col_offset); ++ for (Py_ssize_t i = 0, l = asdl_seq_LEN(n->v.DictComp.generators); i < l; i++) { ++ comprehension_ty comp = asdl_seq_GET(n->v.DictComp.generators, i); ++ fstring_shift_comprehension(n, comp, lineno, col_offset); ++ } ++ break; ++ case GeneratorExp_kind: ++ shift_expr(n, n->v.GeneratorExp.elt, lineno, col_offset); ++ for (Py_ssize_t i = 0, l = asdl_seq_LEN(n->v.GeneratorExp.generators); i < l; i++) { ++ comprehension_ty comp = asdl_seq_GET(n->v.GeneratorExp.generators, i); ++ fstring_shift_comprehension(n, comp, lineno, col_offset); ++ } ++ break; ++ case Await_kind: ++ shift_expr(n, n->v.Await.value, lineno, col_offset); ++ break; ++ case Yield_kind: ++ shift_expr(n, n->v.Yield.value, lineno, col_offset); ++ break; ++ case YieldFrom_kind: ++ shift_expr(n, n->v.YieldFrom.value, lineno, col_offset); ++ break; ++ case Compare_kind: ++ shift_expr(n, n->v.Compare.left, lineno, col_offset); ++ fstring_shift_seq_locations(n, n->v.Compare.comparators, lineno, col_offset); ++ break; ++ case Call_kind: ++ shift_expr(n, n->v.Call.func, lineno, col_offset); ++ fstring_shift_seq_locations(n, n->v.Call.args, lineno, col_offset); ++ for (Py_ssize_t i = 0, l = asdl_seq_LEN(n->v.Call.keywords); i < l; i++) { ++ keyword_ty keyword = asdl_seq_GET(n->v.Call.keywords, i); ++ shift_expr(n, keyword->value, lineno, col_offset); ++ } ++ break; ++ case Attribute_kind: ++ shift_expr(n, n->v.Attribute.value, lineno, col_offset); ++ break; ++ case Subscript_kind: ++ shift_expr(n, n->v.Subscript.value, lineno, col_offset); ++ fstring_shift_slice_locations(n, n->v.Subscript.slice, lineno, col_offset); ++ shift_expr(n, n->v.Subscript.slice, lineno, col_offset); ++ break; ++ case Starred_kind: ++ shift_expr(n, n->v.Starred.value, lineno, col_offset); ++ break; ++ case List_kind: ++ fstring_shift_seq_locations(n, n->v.List.elts, lineno, col_offset); ++ break; ++ case Tuple_kind: ++ fstring_shift_seq_locations(n, n->v.Tuple.elts, lineno, col_offset); ++ break; ++ default: ++ return; ++ } ++} ++ ++/* Shift locations for the given node and all its children by adding `lineno` ++ and `col_offset` to existing locations. Note that n is the already parsed ++ expression. */ ++static void fstring_shift_expr_locations(expr_ty n, int lineno, int col_offset) ++{ ++ n->col_offset = n->col_offset + col_offset; ++ ++ // The following is needed, in order for nodes spanning across multiple lines ++ // to be shifted correctly. An example of such a node is a Call node, the closing ++ // parenthesis of which is not on the same line as its name. ++ if (n->lineno == n->end_lineno) { ++ n->end_col_offset = n->end_col_offset + col_offset; ++ } ++ ++ fstring_shift_children_locations(n, lineno, col_offset); ++ n->lineno = n->lineno + lineno; ++ n->end_lineno = n->end_lineno + lineno; ++} ++ ++/* Fix locations for the given node and its children. ++ ++ `parent` is the enclosing node. ++ `n` is the node which locations are going to be fixed relative to parent. ++ `expr_str` is the child node's string representation, including braces. ++*/ ++static void ++fstring_fix_expr_location(Token *parent, expr_ty n, char *expr_str) ++{ ++ char *substr = NULL; ++ char *start; ++ int lines = 0; ++ int cols = 0; ++ ++ if (parent && parent->bytes) { ++ char *parent_str = PyBytes_AsString(parent->bytes); ++ if (!parent_str) { ++ return; ++ } ++ substr = strstr(parent_str, expr_str); ++ if (substr) { ++ // The following is needed, in order to correctly shift the column ++ // offset, in the case that (disregarding any whitespace) a newline ++ // immediately follows the opening curly brace of the fstring expression. ++ int newline_after_brace = 1; ++ start = substr + 1; ++ while (start && *start != '}' && *start != '\n') { ++ if (*start != ' ' && *start != '\t' && *start != '\f') { ++ newline_after_brace = 0; ++ break; ++ } ++ start++; ++ } ++ ++ // Account for the characters from the last newline character to our ++ // left until the beginning of substr. ++ if (!newline_after_brace) { ++ start = substr; ++ while (start > parent_str && *start != '\n') { ++ start--; ++ } ++ cols += (int)(substr - start); ++ } ++ /* adjust the start based on the number of newlines encountered ++ before the f-string expression */ ++ for (char* p = parent_str; p < substr; p++) { ++ if (*p == '\n') { ++ lines++; ++ } ++ } ++ } ++ } ++ fstring_shift_expr_locations(n, lines, cols); ++} ++ ++ ++/* Compile this expression in to an expr_ty. Add parens around the ++ expression, in order to allow leading spaces in the expression. */ ++static expr_ty ++fstring_compile_expr(Parser *p, const char *expr_start, const char *expr_end, ++ Token *t) ++{ ++ expr_ty expr = NULL; ++ char *str; ++ Py_ssize_t len; ++ const char *s; ++ expr_ty result = NULL; ++ ++ assert(expr_end >= expr_start); ++ assert(*(expr_start-1) == '{'); ++ assert(*expr_end == '}' || *expr_end == '!' || *expr_end == ':' || ++ *expr_end == '='); ++ ++ /* If the substring is all whitespace, it's an error. We need to catch this ++ here, and not when we call PyParser_SimpleParseStringFlagsFilename, ++ because turning the expression '' in to '()' would go from being invalid ++ to valid. */ ++ for (s = expr_start; s != expr_end; s++) { ++ char c = *s; ++ /* The Python parser ignores only the following whitespace ++ characters (\r already is converted to \n). */ ++ if (!(c == ' ' || c == '\t' || c == '\n' || c == '\f')) { ++ break; ++ } ++ } ++ if (s == expr_end) { ++ RAISE_SYNTAX_ERROR("f-string: empty expression not allowed"); ++ return NULL; ++ } ++ ++ len = expr_end - expr_start; ++ /* Allocate 3 extra bytes: open paren, close paren, null byte. */ ++ str = PyMem_RawMalloc(len + 3); ++ if (str == NULL) { ++ PyErr_NoMemory(); ++ return NULL; ++ } ++ ++ str[0] = '('; ++ memcpy(str+1, expr_start, len); ++ str[len+1] = ')'; ++ str[len+2] = 0; ++ ++ struct tok_state* tok = PyTokenizer_FromString(str, 1); ++ if (tok == NULL) { ++ return NULL; ++ } ++ tok->filename = PyUnicode_FromString(""); ++ if (!tok->filename) { ++ PyTokenizer_Free(tok); ++ return NULL; ++ } ++ ++ Parser *p2 = _PyPegen_Parser_New(tok, Py_fstring_input, NULL, p->arena); ++ p2->starting_lineno = p->starting_lineno + p->tok->first_lineno - 1; ++ p2->starting_col_offset = p->tok->first_lineno == p->tok->lineno ++ ? p->starting_col_offset + t->col_offset : 0; ++ ++ expr = _PyPegen_run_parser(p2); ++ ++ if (expr == NULL) { ++ goto exit; ++ } ++ ++ /* Reuse str to find the correct column offset. */ ++ str[0] = '{'; ++ str[len+1] = '}'; ++ fstring_fix_expr_location(t, expr, str); ++ ++ result = expr; ++ ++exit: ++ _PyPegen_Parser_Free(p2); ++ PyTokenizer_Free(tok); ++ return result; ++} ++ ++/* Return -1 on error. ++ ++ Return 0 if we reached the end of the literal. ++ ++ Return 1 if we haven't reached the end of the literal, but we want ++ the caller to process the literal up to this point. Used for ++ doubled braces. ++*/ ++static int ++fstring_find_literal(Parser *p, const char **str, const char *end, int raw, ++ PyObject **literal, int recurse_lvl) ++{ ++ /* Get any literal string. It ends when we hit an un-doubled left ++ brace (which isn't part of a unicode name escape such as ++ "\N{EULER CONSTANT}"), or the end of the string. */ ++ ++ const char *s = *str; ++ const char *literal_start = s; ++ int result = 0; ++ ++ assert(*literal == NULL); ++ while (s < end) { ++ char ch = *s++; ++ if (!raw && ch == '\\' && s < end) { ++ ch = *s++; ++ if (ch == 'N') { ++ if (s < end && *s++ == '{') { ++ while (s < end && *s++ != '}') { ++ } ++ continue; ++ } ++ break; ++ } ++ if (ch == '{' && warn_invalid_escape_sequence(p, ch) < 0) { ++ return -1; ++ } ++ } ++ if (ch == '{' || ch == '}') { ++ /* Check for doubled braces, but only at the top level. If ++ we checked at every level, then f'{0:{3}}' would fail ++ with the two closing braces. */ ++ if (recurse_lvl == 0) { ++ if (s < end && *s == ch) { ++ /* We're going to tell the caller that the literal ends ++ here, but that they should continue scanning. But also ++ skip over the second brace when we resume scanning. */ ++ *str = s + 1; ++ result = 1; ++ goto done; ++ } ++ ++ /* Where a single '{' is the start of a new expression, a ++ single '}' is not allowed. */ ++ if (ch == '}') { ++ *str = s - 1; ++ RAISE_SYNTAX_ERROR("f-string: single '}' is not allowed"); ++ return -1; ++ } ++ } ++ /* We're either at a '{', which means we're starting another ++ expression; or a '}', which means we're at the end of this ++ f-string (for a nested format_spec). */ ++ s--; ++ break; ++ } ++ } ++ *str = s; ++ assert(s <= end); ++ assert(s == end || *s == '{' || *s == '}'); ++done: ++ if (literal_start != s) { ++ if (raw) ++ *literal = PyUnicode_DecodeUTF8Stateful(literal_start, ++ s - literal_start, ++ NULL, NULL); ++ else ++ *literal = decode_unicode_with_escapes(p, literal_start, ++ s - literal_start); ++ if (!*literal) ++ return -1; ++ } ++ return result; ++} ++ ++/* Forward declaration because parsing is recursive. */ ++static expr_ty ++fstring_parse(Parser *p, const char **str, const char *end, int raw, int recurse_lvl, ++ Token *first_token, Token* t, Token *last_token); ++ ++/* Parse the f-string at *str, ending at end. We know *str starts an ++ expression (so it must be a '{'). Returns the FormattedValue node, which ++ includes the expression, conversion character, format_spec expression, and ++ optionally the text of the expression (if = is used). ++ ++ Note that I don't do a perfect job here: I don't make sure that a ++ closing brace doesn't match an opening paren, for example. It ++ doesn't need to error on all invalid expressions, just correctly ++ find the end of all valid ones. Any errors inside the expression ++ will be caught when we parse it later. ++ ++ *expression is set to the expression. For an '=' "debug" expression, ++ *expr_text is set to the debug text (the original text of the expression, ++ including the '=' and any whitespace around it, as a string object). If ++ not a debug expression, *expr_text set to NULL. */ ++static int ++fstring_find_expr(Parser *p, const char **str, const char *end, int raw, int recurse_lvl, ++ PyObject **expr_text, expr_ty *expression, Token *first_token, ++ Token *t, Token *last_token) ++{ ++ /* Return -1 on error, else 0. */ ++ ++ const char *expr_start; ++ const char *expr_end; ++ expr_ty simple_expression; ++ expr_ty format_spec = NULL; /* Optional format specifier. */ ++ int conversion = -1; /* The conversion char. Use default if not ++ specified, or !r if using = and no format ++ spec. */ ++ ++ /* 0 if we're not in a string, else the quote char we're trying to ++ match (single or double quote). */ ++ char quote_char = 0; ++ ++ /* If we're inside a string, 1=normal, 3=triple-quoted. */ ++ int string_type = 0; ++ ++ /* Keep track of nesting level for braces/parens/brackets in ++ expressions. */ ++ Py_ssize_t nested_depth = 0; ++ char parenstack[MAXLEVEL]; ++ ++ *expr_text = NULL; ++ ++ /* Can only nest one level deep. */ ++ if (recurse_lvl >= 2) { ++ RAISE_SYNTAX_ERROR("f-string: expressions nested too deeply"); ++ goto error; ++ } ++ ++ /* The first char must be a left brace, or we wouldn't have gotten ++ here. Skip over it. */ ++ assert(**str == '{'); ++ *str += 1; ++ ++ expr_start = *str; ++ for (; *str < end; (*str)++) { ++ char ch; ++ ++ /* Loop invariants. */ ++ assert(nested_depth >= 0); ++ assert(*str >= expr_start && *str < end); ++ if (quote_char) ++ assert(string_type == 1 || string_type == 3); ++ else ++ assert(string_type == 0); ++ ++ ch = **str; ++ /* Nowhere inside an expression is a backslash allowed. */ ++ if (ch == '\\') { ++ /* Error: can't include a backslash character, inside ++ parens or strings or not. */ ++ RAISE_SYNTAX_ERROR( ++ "f-string expression part " ++ "cannot include a backslash"); ++ goto error; ++ } ++ if (quote_char) { ++ /* We're inside a string. See if we're at the end. */ ++ /* This code needs to implement the same non-error logic ++ as tok_get from tokenizer.c, at the letter_quote ++ label. To actually share that code would be a ++ nightmare. But, it's unlikely to change and is small, ++ so duplicate it here. Note we don't need to catch all ++ of the errors, since they'll be caught when parsing the ++ expression. We just need to match the non-error ++ cases. Thus we can ignore \n in single-quoted strings, ++ for example. Or non-terminated strings. */ ++ if (ch == quote_char) { ++ /* Does this match the string_type (single or triple ++ quoted)? */ ++ if (string_type == 3) { ++ if (*str+2 < end && *(*str+1) == ch && *(*str+2) == ch) { ++ /* We're at the end of a triple quoted string. */ ++ *str += 2; ++ string_type = 0; ++ quote_char = 0; ++ continue; ++ } ++ } else { ++ /* We're at the end of a normal string. */ ++ quote_char = 0; ++ string_type = 0; ++ continue; ++ } ++ } ++ } else if (ch == '\'' || ch == '"') { ++ /* Is this a triple quoted string? */ ++ if (*str+2 < end && *(*str+1) == ch && *(*str+2) == ch) { ++ string_type = 3; ++ *str += 2; ++ } else { ++ /* Start of a normal string. */ ++ string_type = 1; ++ } ++ /* Start looking for the end of the string. */ ++ quote_char = ch; ++ } else if (ch == '[' || ch == '{' || ch == '(') { ++ if (nested_depth >= MAXLEVEL) { ++ RAISE_SYNTAX_ERROR("f-string: too many nested parenthesis"); ++ goto error; ++ } ++ parenstack[nested_depth] = ch; ++ nested_depth++; ++ } else if (ch == '#') { ++ /* Error: can't include a comment character, inside parens ++ or not. */ ++ RAISE_SYNTAX_ERROR("f-string expression part cannot include '#'"); ++ goto error; ++ } else if (nested_depth == 0 && ++ (ch == '!' || ch == ':' || ch == '}' || ++ ch == '=' || ch == '>' || ch == '<')) { ++ /* See if there's a next character. */ ++ if (*str+1 < end) { ++ char next = *(*str+1); ++ ++ /* For "!=". since '=' is not an allowed conversion character, ++ nothing is lost in this test. */ ++ if ((ch == '!' && next == '=') || /* != */ ++ (ch == '=' && next == '=') || /* == */ ++ (ch == '<' && next == '=') || /* <= */ ++ (ch == '>' && next == '=') /* >= */ ++ ) { ++ *str += 1; ++ continue; ++ } ++ /* Don't get out of the loop for these, if they're single ++ chars (not part of 2-char tokens). If by themselves, they ++ don't end an expression (unlike say '!'). */ ++ if (ch == '>' || ch == '<') { ++ continue; ++ } ++ } ++ ++ /* Normal way out of this loop. */ ++ break; ++ } else if (ch == ']' || ch == '}' || ch == ')') { ++ if (!nested_depth) { ++ RAISE_SYNTAX_ERROR("f-string: unmatched '%c'", ch); ++ goto error; ++ } ++ nested_depth--; ++ int opening = parenstack[nested_depth]; ++ if (!((opening == '(' && ch == ')') || ++ (opening == '[' && ch == ']') || ++ (opening == '{' && ch == '}'))) ++ { ++ RAISE_SYNTAX_ERROR( ++ "f-string: closing parenthesis '%c' " ++ "does not match opening parenthesis '%c'", ++ ch, opening); ++ goto error; ++ } ++ } else { ++ /* Just consume this char and loop around. */ ++ } ++ } ++ expr_end = *str; ++ /* If we leave this loop in a string or with mismatched parens, we ++ don't care. We'll get a syntax error when compiling the ++ expression. But, we can produce a better error message, so ++ let's just do that.*/ ++ if (quote_char) { ++ RAISE_SYNTAX_ERROR("f-string: unterminated string"); ++ goto error; ++ } ++ if (nested_depth) { ++ int opening = parenstack[nested_depth - 1]; ++ RAISE_SYNTAX_ERROR("f-string: unmatched '%c'", opening); ++ goto error; ++ } ++ ++ if (*str >= end) ++ goto unexpected_end_of_string; ++ ++ /* Compile the expression as soon as possible, so we show errors ++ related to the expression before errors related to the ++ conversion or format_spec. */ ++ simple_expression = fstring_compile_expr(p, expr_start, expr_end, t); ++ if (!simple_expression) ++ goto error; ++ ++ /* Check for =, which puts the text value of the expression in ++ expr_text. */ ++ if (**str == '=') { ++ *str += 1; ++ ++ /* Skip over ASCII whitespace. No need to test for end of string ++ here, since we know there's at least a trailing quote somewhere ++ ahead. */ ++ while (Py_ISSPACE(**str)) { ++ *str += 1; ++ } ++ ++ /* Set *expr_text to the text of the expression. */ ++ *expr_text = PyUnicode_FromStringAndSize(expr_start, *str-expr_start); ++ if (!*expr_text) { ++ goto error; ++ } ++ } ++ ++ /* Check for a conversion char, if present. */ ++ if (**str == '!') { ++ *str += 1; ++ if (*str >= end) ++ goto unexpected_end_of_string; ++ ++ conversion = **str; ++ *str += 1; ++ ++ /* Validate the conversion. */ ++ if (!(conversion == 's' || conversion == 'r' || conversion == 'a')) { ++ RAISE_SYNTAX_ERROR( ++ "f-string: invalid conversion character: " ++ "expected 's', 'r', or 'a'"); ++ goto error; ++ } ++ ++ } ++ ++ /* Check for the format spec, if present. */ ++ if (*str >= end) ++ goto unexpected_end_of_string; ++ if (**str == ':') { ++ *str += 1; ++ if (*str >= end) ++ goto unexpected_end_of_string; ++ ++ /* Parse the format spec. */ ++ format_spec = fstring_parse(p, str, end, raw, recurse_lvl+1, ++ first_token, t, last_token); ++ if (!format_spec) ++ goto error; ++ } ++ ++ if (*str >= end || **str != '}') ++ goto unexpected_end_of_string; ++ ++ /* We're at a right brace. Consume it. */ ++ assert(*str < end); ++ assert(**str == '}'); ++ *str += 1; ++ ++ /* If we're in = mode (detected by non-NULL expr_text), and have no format ++ spec and no explicit conversion, set the conversion to 'r'. */ ++ if (*expr_text && format_spec == NULL && conversion == -1) { ++ conversion = 'r'; ++ } ++ ++ /* And now create the FormattedValue node that represents this ++ entire expression with the conversion and format spec. */ ++ //TODO: Fix this ++ *expression = FormattedValue(simple_expression, conversion, ++ format_spec, first_token->lineno, ++ first_token->col_offset, last_token->end_lineno, ++ last_token->end_col_offset, p->arena); ++ if (!*expression) ++ goto error; ++ ++ return 0; ++ ++unexpected_end_of_string: ++ RAISE_SYNTAX_ERROR("f-string: expecting '}'"); ++ /* Falls through to error. */ ++ ++error: ++ Py_XDECREF(*expr_text); ++ return -1; ++ ++} ++ ++/* Return -1 on error. ++ ++ Return 0 if we have a literal (possible zero length) and an ++ expression (zero length if at the end of the string. ++ ++ Return 1 if we have a literal, but no expression, and we want the ++ caller to call us again. This is used to deal with doubled ++ braces. ++ ++ When called multiple times on the string 'a{{b{0}c', this function ++ will return: ++ ++ 1. the literal 'a{' with no expression, and a return value ++ of 1. Despite the fact that there's no expression, the return ++ value of 1 means we're not finished yet. ++ ++ 2. the literal 'b' and the expression '0', with a return value of ++ 0. The fact that there's an expression means we're not finished. ++ ++ 3. literal 'c' with no expression and a return value of 0. The ++ combination of the return value of 0 with no expression means ++ we're finished. ++*/ ++static int ++fstring_find_literal_and_expr(Parser *p, const char **str, const char *end, int raw, ++ int recurse_lvl, PyObject **literal, ++ PyObject **expr_text, expr_ty *expression, ++ Token *first_token, Token *t, Token *last_token) ++{ ++ int result; ++ ++ assert(*literal == NULL && *expression == NULL); ++ ++ /* Get any literal string. */ ++ result = fstring_find_literal(p, str, end, raw, literal, recurse_lvl); ++ if (result < 0) ++ goto error; ++ ++ assert(result == 0 || result == 1); ++ ++ if (result == 1) ++ /* We have a literal, but don't look at the expression. */ ++ return 1; ++ ++ if (*str >= end || **str == '}') ++ /* We're at the end of the string or the end of a nested ++ f-string: no expression. The top-level error case where we ++ expect to be at the end of the string but we're at a '}' is ++ handled later. */ ++ return 0; ++ ++ /* We must now be the start of an expression, on a '{'. */ ++ assert(**str == '{'); ++ ++ if (fstring_find_expr(p, str, end, raw, recurse_lvl, expr_text, ++ expression, first_token, t, last_token) < 0) ++ goto error; ++ ++ return 0; ++ ++error: ++ Py_CLEAR(*literal); ++ return -1; ++} ++ ++#ifdef NDEBUG ++#define ExprList_check_invariants(l) ++#else ++static void ++ExprList_check_invariants(ExprList *l) ++{ ++ /* Check our invariants. Make sure this object is "live", and ++ hasn't been deallocated. */ ++ assert(l->size >= 0); ++ assert(l->p != NULL); ++ if (l->size <= EXPRLIST_N_CACHED) ++ assert(l->data == l->p); ++} ++#endif ++ ++static void ++ExprList_Init(ExprList *l) ++{ ++ l->allocated = EXPRLIST_N_CACHED; ++ l->size = 0; ++ ++ /* Until we start allocating dynamically, p points to data. */ ++ l->p = l->data; ++ ++ ExprList_check_invariants(l); ++} ++ ++static int ++ExprList_Append(ExprList *l, expr_ty exp) ++{ ++ ExprList_check_invariants(l); ++ if (l->size >= l->allocated) { ++ /* We need to alloc (or realloc) the memory. */ ++ Py_ssize_t new_size = l->allocated * 2; ++ ++ /* See if we've ever allocated anything dynamically. */ ++ if (l->p == l->data) { ++ Py_ssize_t i; ++ /* We're still using the cached data. Switch to ++ alloc-ing. */ ++ l->p = PyMem_RawMalloc(sizeof(expr_ty) * new_size); ++ if (!l->p) ++ return -1; ++ /* Copy the cached data into the new buffer. */ ++ for (i = 0; i < l->size; i++) ++ l->p[i] = l->data[i]; ++ } else { ++ /* Just realloc. */ ++ expr_ty *tmp = PyMem_RawRealloc(l->p, sizeof(expr_ty) * new_size); ++ if (!tmp) { ++ PyMem_RawFree(l->p); ++ l->p = NULL; ++ return -1; ++ } ++ l->p = tmp; ++ } ++ ++ l->allocated = new_size; ++ assert(l->allocated == 2 * l->size); ++ } ++ ++ l->p[l->size++] = exp; ++ ++ ExprList_check_invariants(l); ++ return 0; ++} ++ ++static void ++ExprList_Dealloc(ExprList *l) ++{ ++ ExprList_check_invariants(l); ++ ++ /* If there's been an error, or we've never dynamically allocated, ++ do nothing. */ ++ if (!l->p || l->p == l->data) { ++ /* Do nothing. */ ++ } else { ++ /* We have dynamically allocated. Free the memory. */ ++ PyMem_RawFree(l->p); ++ } ++ l->p = NULL; ++ l->size = -1; ++} ++ ++static asdl_seq * ++ExprList_Finish(ExprList *l, PyArena *arena) ++{ ++ asdl_seq *seq; ++ ++ ExprList_check_invariants(l); ++ ++ /* Allocate the asdl_seq and copy the expressions in to it. */ ++ seq = _Py_asdl_seq_new(l->size, arena); ++ if (seq) { ++ Py_ssize_t i; ++ for (i = 0; i < l->size; i++) ++ asdl_seq_SET(seq, i, l->p[i]); ++ } ++ ExprList_Dealloc(l); ++ return seq; ++} ++ ++#ifdef NDEBUG ++#define FstringParser_check_invariants(state) ++#else ++static void ++FstringParser_check_invariants(FstringParser *state) ++{ ++ if (state->last_str) ++ assert(PyUnicode_CheckExact(state->last_str)); ++ ExprList_check_invariants(&state->expr_list); ++} ++#endif ++ ++void ++_PyPegen_FstringParser_Init(FstringParser *state) ++{ ++ state->last_str = NULL; ++ state->fmode = 0; ++ ExprList_Init(&state->expr_list); ++ FstringParser_check_invariants(state); ++} ++ ++void ++_PyPegen_FstringParser_Dealloc(FstringParser *state) ++{ ++ FstringParser_check_invariants(state); ++ ++ Py_XDECREF(state->last_str); ++ ExprList_Dealloc(&state->expr_list); ++} ++ ++/* Make a Constant node, but decref the PyUnicode object being added. */ ++static expr_ty ++make_str_node_and_del(Parser *p, PyObject **str, Token* first_token, Token *last_token) ++{ ++ PyObject *s = *str; ++ PyObject *kind = NULL; ++ *str = NULL; ++ assert(PyUnicode_CheckExact(s)); ++ if (PyArena_AddPyObject(p->arena, s) < 0) { ++ Py_DECREF(s); ++ return NULL; ++ } ++ const char* the_str = PyBytes_AsString(first_token->bytes); ++ if (the_str && the_str[0] == 'u') { ++ kind = _PyPegen_new_identifier(p, "u"); ++ } ++ ++ if (kind == NULL && PyErr_Occurred()) { ++ return NULL; ++ } ++ ++ return Constant(s, kind, first_token->lineno, first_token->col_offset, ++ last_token->end_lineno, last_token->end_col_offset, p->arena); ++ ++} ++ ++ ++/* Add a non-f-string (that is, a regular literal string). str is ++ decref'd. */ ++int ++_PyPegen_FstringParser_ConcatAndDel(FstringParser *state, PyObject *str) ++{ ++ FstringParser_check_invariants(state); ++ ++ assert(PyUnicode_CheckExact(str)); ++ ++ if (PyUnicode_GET_LENGTH(str) == 0) { ++ Py_DECREF(str); ++ return 0; ++ } ++ ++ if (!state->last_str) { ++ /* We didn't have a string before, so just remember this one. */ ++ state->last_str = str; ++ } else { ++ /* Concatenate this with the previous string. */ ++ PyUnicode_AppendAndDel(&state->last_str, str); ++ if (!state->last_str) ++ return -1; ++ } ++ FstringParser_check_invariants(state); ++ return 0; ++} ++ ++/* Parse an f-string. The f-string is in *str to end, with no ++ 'f' or quotes. */ ++int ++_PyPegen_FstringParser_ConcatFstring(Parser *p, FstringParser *state, const char **str, ++ const char *end, int raw, int recurse_lvl, ++ Token *first_token, Token* t, Token *last_token) ++{ ++ FstringParser_check_invariants(state); ++ state->fmode = 1; ++ ++ /* Parse the f-string. */ ++ while (1) { ++ PyObject *literal = NULL; ++ PyObject *expr_text = NULL; ++ expr_ty expression = NULL; ++ ++ /* If there's a zero length literal in front of the ++ expression, literal will be NULL. If we're at the end of ++ the f-string, expression will be NULL (unless result == 1, ++ see below). */ ++ int result = fstring_find_literal_and_expr(p, str, end, raw, recurse_lvl, ++ &literal, &expr_text, ++ &expression, first_token, t, last_token); ++ if (result < 0) ++ return -1; ++ ++ /* Add the literal, if any. */ ++ if (literal && _PyPegen_FstringParser_ConcatAndDel(state, literal) < 0) { ++ Py_XDECREF(expr_text); ++ return -1; ++ } ++ /* Add the expr_text, if any. */ ++ if (expr_text && _PyPegen_FstringParser_ConcatAndDel(state, expr_text) < 0) { ++ return -1; ++ } ++ ++ /* We've dealt with the literal and expr_text, their ownership has ++ been transferred to the state object. Don't look at them again. */ ++ ++ /* See if we should just loop around to get the next literal ++ and expression, while ignoring the expression this ++ time. This is used for un-doubling braces, as an ++ optimization. */ ++ if (result == 1) ++ continue; ++ ++ if (!expression) ++ /* We're done with this f-string. */ ++ break; ++ ++ /* We know we have an expression. Convert any existing string ++ to a Constant node. */ ++ if (!state->last_str) { ++ /* Do nothing. No previous literal. */ ++ } else { ++ /* Convert the existing last_str literal to a Constant node. */ ++ expr_ty str = make_str_node_and_del(p, &state->last_str, first_token, last_token); ++ if (!str || ExprList_Append(&state->expr_list, str) < 0) ++ return -1; ++ } ++ ++ if (ExprList_Append(&state->expr_list, expression) < 0) ++ return -1; ++ } ++ ++ /* If recurse_lvl is zero, then we must be at the end of the ++ string. Otherwise, we must be at a right brace. */ ++ ++ if (recurse_lvl == 0 && *str < end-1) { ++ RAISE_SYNTAX_ERROR("f-string: unexpected end of string"); ++ return -1; ++ } ++ if (recurse_lvl != 0 && **str != '}') { ++ RAISE_SYNTAX_ERROR("f-string: expecting '}'"); ++ return -1; ++ } ++ ++ FstringParser_check_invariants(state); ++ return 0; ++} ++ ++/* Convert the partial state reflected in last_str and expr_list to an ++ expr_ty. The expr_ty can be a Constant, or a JoinedStr. */ ++expr_ty ++_PyPegen_FstringParser_Finish(Parser *p, FstringParser *state, Token* first_token, ++ Token *last_token) ++{ ++ asdl_seq *seq; ++ ++ FstringParser_check_invariants(state); ++ ++ /* If we're just a constant string with no expressions, return ++ that. */ ++ if (!state->fmode) { ++ assert(!state->expr_list.size); ++ if (!state->last_str) { ++ /* Create a zero length string. */ ++ state->last_str = PyUnicode_FromStringAndSize(NULL, 0); ++ if (!state->last_str) ++ goto error; ++ } ++ return make_str_node_and_del(p, &state->last_str, first_token, last_token); ++ } ++ ++ /* Create a Constant node out of last_str, if needed. It will be the ++ last node in our expression list. */ ++ if (state->last_str) { ++ expr_ty str = make_str_node_and_del(p, &state->last_str, first_token, last_token); ++ if (!str || ExprList_Append(&state->expr_list, str) < 0) ++ goto error; ++ } ++ /* This has already been freed. */ ++ assert(state->last_str == NULL); ++ ++ seq = ExprList_Finish(&state->expr_list, p->arena); ++ if (!seq) ++ goto error; ++ ++ return _Py_JoinedStr(seq, first_token->lineno, first_token->col_offset, ++ last_token->end_lineno, last_token->end_col_offset, p->arena); ++ ++error: ++ _PyPegen_FstringParser_Dealloc(state); ++ return NULL; ++} ++ ++/* Given an f-string (with no 'f' or quotes) that's in *str and ends ++ at end, parse it into an expr_ty. Return NULL on error. Adjust ++ str to point past the parsed portion. */ ++static expr_ty ++fstring_parse(Parser *p, const char **str, const char *end, int raw, ++ int recurse_lvl, Token *first_token, Token* t, Token *last_token) ++{ ++ FstringParser state; ++ ++ _PyPegen_FstringParser_Init(&state); ++ if (_PyPegen_FstringParser_ConcatFstring(p, &state, str, end, raw, recurse_lvl, ++ first_token, t, last_token) < 0) { ++ _PyPegen_FstringParser_Dealloc(&state); ++ return NULL; ++ } ++ ++ return _PyPegen_FstringParser_Finish(p, &state, t, t); ++} +diff --git a/Parser/pegen/parse_string.h b/Parser/pegen/parse_string.h +new file mode 100644 +--- /dev/null ++++ b/Parser/pegen/parse_string.h +@@ -0,0 +1,46 @@ ++#ifndef STRINGS_H ++#define STRINGS_H ++ ++#include ++#include ++#include "pegen.h" ++ ++#define EXPRLIST_N_CACHED 64 ++ ++typedef struct { ++ /* Incrementally build an array of expr_ty, so be used in an ++ asdl_seq. Cache some small but reasonably sized number of ++ expr_ty's, and then after that start dynamically allocating, ++ doubling the number allocated each time. Note that the f-string ++ f'{0}a{1}' contains 3 expr_ty's: 2 FormattedValue's, and one ++ Constant for the literal 'a'. So you add expr_ty's about twice as ++ fast as you add expressions in an f-string. */ ++ ++ Py_ssize_t allocated; /* Number we've allocated. */ ++ Py_ssize_t size; /* Number we've used. */ ++ expr_ty *p; /* Pointer to the memory we're actually ++ using. Will point to 'data' until we ++ start dynamically allocating. */ ++ expr_ty data[EXPRLIST_N_CACHED]; ++} ExprList; ++ ++/* The FstringParser is designed to add a mix of strings and ++ f-strings, and concat them together as needed. Ultimately, it ++ generates an expr_ty. */ ++typedef struct { ++ PyObject *last_str; ++ ExprList expr_list; ++ int fmode; ++} FstringParser; ++ ++void _PyPegen_FstringParser_Init(FstringParser *); ++int _PyPegen_parsestr(Parser *, const char *, int *, int *, PyObject **, ++ const char **, Py_ssize_t *); ++int _PyPegen_FstringParser_ConcatFstring(Parser *, FstringParser *, const char **, ++ const char *, int, int, Token *, Token *, ++ Token *); ++int _PyPegen_FstringParser_ConcatAndDel(FstringParser *, PyObject *); ++expr_ty _PyPegen_FstringParser_Finish(Parser *, FstringParser *, Token *, Token *); ++void _PyPegen_FstringParser_Dealloc(FstringParser *); ++ ++#endif +diff --git a/Parser/pegen/peg_api.c b/Parser/pegen/peg_api.c +new file mode 100644 +--- /dev/null ++++ b/Parser/pegen/peg_api.c +@@ -0,0 +1,134 @@ ++#include ++ ++#include "../tokenizer.h" ++#include "pegen.h" ++ ++mod_ty ++PyPegen_ASTFromString(const char *str, int mode, PyCompilerFlags *flags, PyArena *arena) ++{ ++ PyObject *filename_ob = PyUnicode_FromString(""); ++ if (filename_ob == NULL) { ++ return NULL; ++ } ++ mod_ty result = PyPegen_ASTFromStringObject(str, filename_ob, mode, flags, arena); ++ Py_XDECREF(filename_ob); ++ return result; ++} ++ ++mod_ty ++PyPegen_ASTFromStringObject(const char *str, PyObject* filename, int mode, PyCompilerFlags *flags, PyArena *arena) ++{ ++ if (PySys_Audit("compile", "yO", str, filename) < 0) { ++ return NULL; ++ } ++ ++ int iflags = flags != NULL ? flags->cf_flags : PyCF_IGNORE_COOKIE; ++ mod_ty result = _PyPegen_run_parser_from_string(str, mode, filename, iflags, arena); ++ return result; ++} ++ ++mod_ty ++PyPegen_ASTFromFile(const char *filename, int mode, PyArena *arena) ++{ ++ PyObject *filename_ob = PyUnicode_FromString(filename); ++ if (filename_ob == NULL) { ++ return NULL; ++ } ++ ++ mod_ty result = _PyPegen_run_parser_from_file(filename, mode, filename_ob, arena); ++ Py_XDECREF(filename_ob); ++ return result; ++} ++ ++mod_ty ++PyPegen_ASTFromFileObject(FILE *fp, PyObject *filename_ob, int mode, ++ const char *enc, const char *ps1, const char* ps2, ++ int *errcode, PyArena *arena) ++{ ++ if (PySys_Audit("compile", "OO", Py_None, filename_ob) < 0) { ++ return NULL; ++ } ++ return _PyPegen_run_parser_from_file_pointer(fp, mode, filename_ob, enc, ps1, ps2, ++ errcode, arena); ++} ++ ++PyCodeObject * ++PyPegen_CodeObjectFromString(const char *str, int mode, PyCompilerFlags *flags) ++{ ++ PyArena *arena = PyArena_New(); ++ if (arena == NULL) { ++ return NULL; ++ } ++ ++ PyCodeObject *result = NULL; ++ ++ PyObject *filename_ob = PyUnicode_FromString(""); ++ if (filename_ob == NULL) { ++ goto error; ++ } ++ ++ mod_ty res = PyPegen_ASTFromString(str, mode, flags, arena); ++ if (res == NULL) { ++ goto error; ++ } ++ ++ result = PyAST_CompileObject(res, filename_ob, NULL, -1, arena); ++ ++error: ++ Py_XDECREF(filename_ob); ++ PyArena_Free(arena); ++ return result; ++} ++ ++PyCodeObject * ++PyPegen_CodeObjectFromFile(const char *filename, int mode) ++{ ++ PyArena *arena = PyArena_New(); ++ if (arena == NULL) { ++ return NULL; ++ } ++ ++ PyCodeObject *result = NULL; ++ ++ PyObject *filename_ob = PyUnicode_FromString(filename); ++ if (filename_ob == NULL) { ++ goto error; ++ } ++ ++ mod_ty res = PyPegen_ASTFromFile(filename, mode, arena); ++ if (res == NULL) { ++ goto error; ++ } ++ ++ result = PyAST_CompileObject(res, filename_ob, NULL, -1, arena); ++ ++error: ++ Py_XDECREF(filename_ob); ++ PyArena_Free(arena); ++ return result; ++} ++ ++PyCodeObject * ++PyPegen_CodeObjectFromFileObject(FILE *fp, PyObject *filename_ob, int mode, ++ const char *ps1, const char *ps2, const char *enc, ++ int *errcode) ++{ ++ PyArena *arena = PyArena_New(); ++ if (arena == NULL) { ++ return NULL; ++ } ++ ++ PyCodeObject *result = NULL; ++ ++ mod_ty res = PyPegen_ASTFromFileObject(fp, filename_ob, mode, enc, ps1, ps2, ++ errcode, arena); ++ if (res == NULL) { ++ goto error; ++ } ++ ++ result = PyAST_CompileObject(res, filename_ob, NULL, -1, arena); ++ ++error: ++ PyArena_Free(arena); ++ return result; ++} +diff --git a/Parser/pegen/pegen.c b/Parser/pegen/pegen.c +new file mode 100644 +--- /dev/null ++++ b/Parser/pegen/pegen.c +@@ -0,0 +1,1865 @@ ++#include ++#include ++#include "../tokenizer.h" ++ ++#include "pegen.h" ++#include "parse_string.h" ++ ++static int ++init_normalization(Parser *p) ++{ ++ PyObject *m = PyImport_ImportModuleNoBlock("unicodedata"); ++ if (!m) ++ { ++ return 0; ++ } ++ p->normalize = PyObject_GetAttrString(m, "normalize"); ++ Py_DECREF(m); ++ if (!p->normalize) ++ { ++ return 0; ++ } ++ return 1; ++} ++ ++PyObject * ++_PyPegen_new_identifier(Parser *p, char *n) ++{ ++ PyObject *id = PyUnicode_DecodeUTF8(n, strlen(n), NULL); ++ if (!id) { ++ goto error; ++ } ++ /* PyUnicode_DecodeUTF8 should always return a ready string. */ ++ assert(PyUnicode_IS_READY(id)); ++ /* Check whether there are non-ASCII characters in the ++ identifier; if so, normalize to NFKC. */ ++ if (!PyUnicode_IS_ASCII(id)) ++ { ++ PyObject *id2; ++ if (!p->normalize && !init_normalization(p)) ++ { ++ Py_DECREF(id); ++ goto error; ++ } ++ PyObject *form = PyUnicode_InternFromString("NFKC"); ++ if (form == NULL) ++ { ++ Py_DECREF(id); ++ goto error; ++ } ++ PyObject *args[2] = {form, id}; ++ id2 = _PyObject_FastCall(p->normalize, args, 2); ++ Py_DECREF(id); ++ Py_DECREF(form); ++ if (!id2) { ++ goto error; ++ } ++ if (!PyUnicode_Check(id2)) ++ { ++ PyErr_Format(PyExc_TypeError, ++ "unicodedata.normalize() must return a string, not " ++ "%.200s", ++ _PyType_Name(Py_TYPE(id2))); ++ Py_DECREF(id2); ++ goto error; ++ } ++ id = id2; ++ } ++ PyUnicode_InternInPlace(&id); ++ if (PyArena_AddPyObject(p->arena, id) < 0) ++ { ++ Py_DECREF(id); ++ goto error; ++ } ++ return id; ++ ++error: ++ p->error_indicator = 1; ++ return NULL; ++} ++ ++static PyObject * ++_create_dummy_identifier(Parser *p) ++{ ++ return _PyPegen_new_identifier(p, ""); ++} ++ ++static inline Py_ssize_t ++byte_offset_to_character_offset(PyObject *line, int col_offset) ++{ ++ const char *str = PyUnicode_AsUTF8(line); ++ PyObject *text = PyUnicode_DecodeUTF8(str, col_offset, NULL); ++ if (!text) { ++ return 0; ++ } ++ Py_ssize_t size = PyUnicode_GET_LENGTH(text); ++ Py_DECREF(text); ++ return size; ++} ++ ++const char * ++_PyPegen_get_expr_name(expr_ty e) ++{ ++ switch (e->kind) { ++ case Attribute_kind: ++ return "attribute"; ++ case Subscript_kind: ++ return "subscript"; ++ case Starred_kind: ++ return "starred"; ++ case Name_kind: ++ return "name"; ++ case List_kind: ++ return "list"; ++ case Tuple_kind: ++ return "tuple"; ++ case Lambda_kind: ++ return "lambda"; ++ case Call_kind: ++ return "function call"; ++ case BoolOp_kind: ++ case BinOp_kind: ++ case UnaryOp_kind: ++ return "operator"; ++ case GeneratorExp_kind: ++ return "generator expression"; ++ case Yield_kind: ++ case YieldFrom_kind: ++ return "yield expression"; ++ case Await_kind: ++ return "await expression"; ++ case ListComp_kind: ++ return "list comprehension"; ++ case SetComp_kind: ++ return "set comprehension"; ++ case DictComp_kind: ++ return "dict comprehension"; ++ case Dict_kind: ++ return "dict display"; ++ case Set_kind: ++ return "set display"; ++ case JoinedStr_kind: ++ case FormattedValue_kind: ++ return "f-string expression"; ++ case Constant_kind: { ++ PyObject *value = e->v.Constant.value; ++ if (value == Py_None) { ++ return "None"; ++ } ++ if (value == Py_False) { ++ return "False"; ++ } ++ if (value == Py_True) { ++ return "True"; ++ } ++ if (value == Py_Ellipsis) { ++ return "Ellipsis"; ++ } ++ return "literal"; ++ } ++ case Compare_kind: ++ return "comparison"; ++ case IfExp_kind: ++ return "conditional expression"; ++ case NamedExpr_kind: ++ return "named expression"; ++ default: ++ PyErr_Format(PyExc_SystemError, ++ "unexpected expression in assignment %d (line %d)", ++ e->kind, e->lineno); ++ return NULL; ++ } ++} ++ ++static void ++raise_decode_error(Parser *p) ++{ ++ const char *errtype = NULL; ++ if (PyErr_ExceptionMatches(PyExc_UnicodeError)) { ++ errtype = "unicode error"; ++ } ++ else if (PyErr_ExceptionMatches(PyExc_ValueError)) { ++ errtype = "value error"; ++ } ++ if (errtype) { ++ PyObject *type, *value, *tback, *errstr; ++ PyErr_Fetch(&type, &value, &tback); ++ errstr = PyObject_Str(value); ++ if (errstr) { ++ RAISE_SYNTAX_ERROR("(%s) %U", errtype, errstr); ++ Py_DECREF(errstr); ++ } ++ else { ++ PyErr_Clear(); ++ RAISE_SYNTAX_ERROR("(%s) unknown error", errtype); ++ } ++ Py_XDECREF(type); ++ Py_XDECREF(value); ++ Py_XDECREF(tback); ++ } ++} ++ ++static void ++raise_tokenizer_init_error(PyObject *filename) ++{ ++ if (!(PyErr_ExceptionMatches(PyExc_LookupError) ++ || PyErr_ExceptionMatches(PyExc_ValueError) ++ || PyErr_ExceptionMatches(PyExc_UnicodeDecodeError))) { ++ return; ++ } ++ PyObject *type, *value, *tback, *errstr; ++ PyErr_Fetch(&type, &value, &tback); ++ errstr = PyObject_Str(value); ++ ++ Py_INCREF(Py_None); ++ PyObject *tmp = Py_BuildValue("(OiiN)", filename, 0, -1, Py_None); ++ if (!tmp) { ++ goto error; ++ } ++ ++ value = PyTuple_Pack(2, errstr, tmp); ++ Py_DECREF(tmp); ++ if (!value) { ++ goto error; ++ } ++ PyErr_SetObject(PyExc_SyntaxError, value); ++ ++error: ++ Py_XDECREF(type); ++ Py_XDECREF(value); ++ Py_XDECREF(tback); ++} ++ ++static inline PyObject * ++get_error_line(char *buffer) ++{ ++ char *newline = strchr(buffer, '\n'); ++ if (newline) { ++ return PyUnicode_FromStringAndSize(buffer, newline - buffer); ++ } ++ else { ++ return PyUnicode_FromString(buffer); ++ } ++} ++ ++static int ++tokenizer_error_with_col_offset(Parser *p, PyObject *errtype, const char *errmsg) ++{ ++ PyObject *errstr = NULL; ++ PyObject *value = NULL; ++ int col_number = -1; ++ ++ errstr = PyUnicode_FromString(errmsg); ++ if (!errstr) { ++ return -1; ++ } ++ ++ PyObject *loc = NULL; ++ if (p->start_rule == Py_file_input) { ++ loc = PyErr_ProgramTextObject(p->tok->filename, p->tok->lineno); ++ } ++ if (!loc) { ++ loc = get_error_line(p->tok->buf); ++ } ++ ++ if (loc) { ++ col_number = p->tok->cur - p->tok->buf; ++ } ++ else { ++ Py_INCREF(Py_None); ++ loc = Py_None; ++ } ++ ++ PyObject *tmp = Py_BuildValue("(OiiN)", p->tok->filename, p->tok->lineno, ++ col_number, loc); ++ if (!tmp) { ++ goto error; ++ } ++ ++ value = PyTuple_Pack(2, errstr, tmp); ++ Py_DECREF(tmp); ++ if (!value) { ++ goto error; ++ } ++ PyErr_SetObject(errtype, value); ++ ++ Py_XDECREF(value); ++ Py_XDECREF(errstr); ++ return -1; ++ ++error: ++ Py_XDECREF(errstr); ++ Py_XDECREF(loc); ++ return -1; ++} ++ ++static int ++tokenizer_error(Parser *p) ++{ ++ if (PyErr_Occurred()) { ++ return -1; ++ } ++ ++ const char *msg = NULL; ++ PyObject* errtype = PyExc_SyntaxError; ++ switch (p->tok->done) { ++ case E_TOKEN: ++ msg = "invalid token"; ++ break; ++ case E_IDENTIFIER: ++ msg = "invalid character in identifier"; ++ break; ++ case E_BADPREFIX: ++ return tokenizer_error_with_col_offset(p, ++ PyExc_SyntaxError, "invalid string prefix"); ++ case E_EOFS: ++ return tokenizer_error_with_col_offset(p, ++ PyExc_SyntaxError, "EOF while scanning triple-quoted string literal"); ++ case E_EOLS: ++ return tokenizer_error_with_col_offset(p, ++ PyExc_SyntaxError, "EOL while scanning string literal"); ++ case E_DEDENT: ++ return tokenizer_error_with_col_offset(p, ++ PyExc_IndentationError, "unindent does not match any outer indentation level"); ++ case E_INTR: ++ if (!PyErr_Occurred()) { ++ PyErr_SetNone(PyExc_KeyboardInterrupt); ++ } ++ return -1; ++ case E_NOMEM: ++ PyErr_NoMemory(); ++ return -1; ++ case E_TABSPACE: ++ errtype = PyExc_TabError; ++ msg = "inconsistent use of tabs and spaces in indentation"; ++ break; ++ case E_TOODEEP: ++ errtype = PyExc_IndentationError; ++ msg = "too many levels of indentation"; ++ break; ++ case E_DECODE: ++ raise_decode_error(p); ++ return -1; ++ case E_LINECONT: ++ msg = "unexpected character after line continuation character"; ++ break; ++ default: ++ msg = "unknown parsing error"; ++ } ++ ++ PyErr_Format(errtype, msg); ++ // There is no reliable column information for this error ++ PyErr_SyntaxLocationObject(p->tok->filename, p->tok->lineno, 0); ++ ++ return -1; ++} ++ ++void * ++_PyPegen_raise_error(Parser *p, PyObject *errtype, const char *errmsg, ...) ++{ ++ PyObject *value = NULL; ++ PyObject *errstr = NULL; ++ PyObject *loc = NULL; ++ PyObject *tmp = NULL; ++ Token *t = p->tokens[p->fill - 1]; ++ Py_ssize_t col_number = 0; ++ va_list va; ++ ++ va_start(va, errmsg); ++ errstr = PyUnicode_FromFormatV(errmsg, va); ++ va_end(va); ++ if (!errstr) { ++ goto error; ++ } ++ ++ if (p->start_rule == Py_file_input) { ++ loc = PyErr_ProgramTextObject(p->tok->filename, t->lineno); ++ } ++ ++ if (!loc) { ++ loc = get_error_line(p->tok->buf); ++ } ++ ++ if (loc) { ++ int col_offset = t->col_offset == -1 ? 0 : t->col_offset; ++ col_number = byte_offset_to_character_offset(loc, col_offset) + 1; ++ } ++ else { ++ Py_INCREF(Py_None); ++ loc = Py_None; ++ } ++ ++ ++ tmp = Py_BuildValue("(OiiN)", p->tok->filename, t->lineno, col_number, loc); ++ if (!tmp) { ++ goto error; ++ } ++ value = PyTuple_Pack(2, errstr, tmp); ++ Py_DECREF(tmp); ++ if (!value) { ++ goto error; ++ } ++ PyErr_SetObject(errtype, value); ++ ++ Py_DECREF(errstr); ++ Py_DECREF(value); ++ return NULL; ++ ++error: ++ Py_XDECREF(errstr); ++ Py_XDECREF(loc); ++ return NULL; ++} ++ ++void *_PyPegen_arguments_parsing_error(Parser *p, expr_ty e) { ++ int kwarg_unpacking = 0; ++ for (Py_ssize_t i = 0, l = asdl_seq_LEN(e->v.Call.keywords); i < l; i++) { ++ keyword_ty keyword = asdl_seq_GET(e->v.Call.keywords, i); ++ if (!keyword->arg) { ++ kwarg_unpacking = 1; ++ } ++ } ++ ++ const char *msg = NULL; ++ if (kwarg_unpacking) { ++ msg = "positional argument follows keyword argument unpacking"; ++ } else { ++ msg = "positional argument follows keyword argument"; ++ } ++ ++ return RAISE_SYNTAX_ERROR(msg); ++} ++ ++#if 0 ++static const char * ++token_name(int type) ++{ ++ if (0 <= type && type <= N_TOKENS) { ++ return _PyParser_TokenNames[type]; ++ } ++ return ""; ++} ++#endif ++ ++// Here, mark is the start of the node, while p->mark is the end. ++// If node==NULL, they should be the same. ++int ++_PyPegen_insert_memo(Parser *p, int mark, int type, void *node) ++{ ++ // Insert in front ++ Memo *m = PyArena_Malloc(p->arena, sizeof(Memo)); ++ if (m == NULL) { ++ return -1; ++ } ++ m->type = type; ++ m->node = node; ++ m->mark = p->mark; ++ m->next = p->tokens[mark]->memo; ++ p->tokens[mark]->memo = m; ++ return 0; ++} ++ ++// Like _PyPegen_insert_memo(), but updates an existing node if found. ++int ++_PyPegen_update_memo(Parser *p, int mark, int type, void *node) ++{ ++ for (Memo *m = p->tokens[mark]->memo; m != NULL; m = m->next) { ++ if (m->type == type) { ++ // Update existing node. ++ m->node = node; ++ m->mark = p->mark; ++ return 0; ++ } ++ } ++ // Insert new node. ++ return _PyPegen_insert_memo(p, mark, type, node); ++} ++ ++// Return dummy NAME. ++void * ++_PyPegen_dummy_name(Parser *p, ...) ++{ ++ static void *cache = NULL; ++ ++ if (cache != NULL) { ++ return cache; ++ } ++ ++ PyObject *id = _create_dummy_identifier(p); ++ if (!id) { ++ return NULL; ++ } ++ cache = Name(id, Load, 1, 0, 1, 0, p->arena); ++ return cache; ++} ++ ++static int ++_get_keyword_or_name_type(Parser *p, const char *name, int name_len) ++{ ++ if (name_len >= p->n_keyword_lists || p->keywords[name_len] == NULL) { ++ return NAME; ++ } ++ for (KeywordToken *k = p->keywords[name_len]; k->type != -1; k++) { ++ if (strncmp(k->str, name, name_len) == 0) { ++ return k->type; ++ } ++ } ++ return NAME; ++} ++ ++int ++_PyPegen_fill_token(Parser *p) ++{ ++ const char *start, *end; ++ int type = PyTokenizer_Get(p->tok, &start, &end); ++ if (type == ERRORTOKEN) { ++ return tokenizer_error(p); ++ } ++ if (type == ENDMARKER && p->start_rule == Py_single_input && p->parsing_started) { ++ type = NEWLINE; /* Add an extra newline */ ++ p->parsing_started = 0; ++ ++ if (p->tok->indent) { ++ p->tok->pendin = -p->tok->indent; ++ p->tok->indent = 0; ++ } ++ } ++ else { ++ p->parsing_started = 1; ++ } ++ ++ if (p->fill == p->size) { ++ int newsize = p->size * 2; ++ p->tokens = PyMem_Realloc(p->tokens, newsize * sizeof(Token *)); ++ if (p->tokens == NULL) { ++ PyErr_Format(PyExc_MemoryError, "Realloc tokens failed"); ++ return -1; ++ } ++ for (int i = p->size; i < newsize; i++) { ++ p->tokens[i] = PyMem_Malloc(sizeof(Token)); ++ memset(p->tokens[i], '\0', sizeof(Token)); ++ } ++ p->size = newsize; ++ } ++ ++ Token *t = p->tokens[p->fill]; ++ t->type = (type == NAME) ? _get_keyword_or_name_type(p, start, (int)(end - start)) : type; ++ t->bytes = PyBytes_FromStringAndSize(start, end - start); ++ if (t->bytes == NULL) { ++ return -1; ++ } ++ PyArena_AddPyObject(p->arena, t->bytes); ++ ++ int lineno = type == STRING ? p->tok->first_lineno : p->tok->lineno; ++ const char *line_start = type == STRING ? p->tok->multi_line_start : p->tok->line_start; ++ int end_lineno = p->tok->lineno; ++ int col_offset = -1, end_col_offset = -1; ++ if (start != NULL && start >= line_start) { ++ col_offset = start - line_start; ++ } ++ if (end != NULL && end >= p->tok->line_start) { ++ end_col_offset = end - p->tok->line_start; ++ } ++ ++ t->lineno = p->starting_lineno + lineno; ++ t->col_offset = p->tok->lineno == 1 ? p->starting_col_offset + col_offset : col_offset; ++ t->end_lineno = p->starting_lineno + end_lineno; ++ t->end_col_offset = p->tok->lineno == 1 ? p->starting_col_offset + end_col_offset : end_col_offset; ++ ++ // if (p->fill % 100 == 0) fprintf(stderr, "Filled at %d: %s \"%s\"\n", p->fill, ++ // token_name(type), PyBytes_AsString(t->bytes)); ++ p->fill += 1; ++ return 0; ++} ++ ++// Instrumentation to count the effectiveness of memoization. ++// The array counts the number of tokens skipped by memoization, ++// indexed by type. ++ ++#define NSTATISTICS 2000 ++static long memo_statistics[NSTATISTICS]; ++ ++void ++_PyPegen_clear_memo_statistics() ++{ ++ for (int i = 0; i < NSTATISTICS; i++) { ++ memo_statistics[i] = 0; ++ } ++} ++ ++PyObject * ++_PyPegen_get_memo_statistics() ++{ ++ PyObject *ret = PyList_New(NSTATISTICS); ++ if (ret == NULL) { ++ return NULL; ++ } ++ for (int i = 0; i < NSTATISTICS; i++) { ++ PyObject *value = PyLong_FromLong(memo_statistics[i]); ++ if (value == NULL) { ++ Py_DECREF(ret); ++ return NULL; ++ } ++ // PyList_SetItem borrows a reference to value. ++ if (PyList_SetItem(ret, i, value) < 0) { ++ Py_DECREF(ret); ++ return NULL; ++ } ++ } ++ return ret; ++} ++ ++int // bool ++_PyPegen_is_memoized(Parser *p, int type, void *pres) ++{ ++ if (p->mark == p->fill) { ++ if (_PyPegen_fill_token(p) < 0) { ++ return -1; ++ } ++ } ++ ++ Token *t = p->tokens[p->mark]; ++ ++ for (Memo *m = t->memo; m != NULL; m = m->next) { ++ if (m->type == type) { ++ if (0 <= type && type < NSTATISTICS) { ++ long count = m->mark - p->mark; ++ // A memoized negative result counts for one. ++ if (count <= 0) { ++ count = 1; ++ } ++ memo_statistics[type] += count; ++ } ++ p->mark = m->mark; ++ *(void **)(pres) = m->node; ++ // fprintf(stderr, "%d < %d: memoized!\n", p->mark, p->fill); ++ return 1; ++ } ++ } ++ // fprintf(stderr, "%d < %d: not memoized\n", p->mark, p->fill); ++ return 0; ++} ++ ++int ++_PyPegen_lookahead_with_string(int positive, void *(func)(Parser *, const char *), Parser *p, ++ const char *arg) ++{ ++ int mark = p->mark; ++ void *res = func(p, arg); ++ p->mark = mark; ++ return (res != NULL) == positive; ++} ++ ++int ++_PyPegen_lookahead_with_int(int positive, Token *(func)(Parser *, int), Parser *p, int arg) ++{ ++ int mark = p->mark; ++ void *res = func(p, arg); ++ p->mark = mark; ++ return (res != NULL) == positive; ++} ++ ++int ++_PyPegen_lookahead(int positive, void *(func)(Parser *), Parser *p) ++{ ++ int mark = p->mark; ++ void *res = func(p); ++ p->mark = mark; ++ return (res != NULL) == positive; ++} ++ ++Token * ++_PyPegen_expect_token(Parser *p, int type) ++{ ++ if (p->mark == p->fill) { ++ if (_PyPegen_fill_token(p) < 0) { ++ return NULL; ++ } ++ } ++ Token *t = p->tokens[p->mark]; ++ if (t->type != type) { ++ // fprintf(stderr, "No %s at %d\n", token_name(type), p->mark); ++ return NULL; ++ } ++ p->mark += 1; ++ // fprintf(stderr, "Got %s at %d: %s\n", token_name(type), p->mark, ++ // PyBytes_AsString(t->bytes)); ++ ++ return t; ++} ++ ++Token * ++_PyPegen_get_last_nonnwhitespace_token(Parser *p) ++{ ++ assert(p->mark >= 0); ++ Token *token = NULL; ++ for (int m = p->mark - 1; m >= 0; m--) { ++ token = p->tokens[m]; ++ if (token->type != ENDMARKER && (token->type < NEWLINE || token->type > DEDENT)) { ++ break; ++ } ++ } ++ return token; ++} ++ ++void * ++_PyPegen_async_token(Parser *p) ++{ ++ return _PyPegen_expect_token(p, ASYNC); ++} ++ ++void * ++_PyPegen_await_token(Parser *p) ++{ ++ return _PyPegen_expect_token(p, AWAIT); ++} ++ ++void * ++_PyPegen_endmarker_token(Parser *p) ++{ ++ return _PyPegen_expect_token(p, ENDMARKER); ++} ++ ++expr_ty ++_PyPegen_name_token(Parser *p) ++{ ++ Token *t = _PyPegen_expect_token(p, NAME); ++ if (t == NULL) { ++ return NULL; ++ } ++ char* s = PyBytes_AsString(t->bytes); ++ if (!s) { ++ return NULL; ++ } ++ PyObject *id = _PyPegen_new_identifier(p, s); ++ if (id == NULL) { ++ return NULL; ++ } ++ return Name(id, Load, t->lineno, t->col_offset, t->end_lineno, t->end_col_offset, ++ p->arena); ++} ++ ++void * ++_PyPegen_string_token(Parser *p) ++{ ++ return _PyPegen_expect_token(p, STRING); ++} ++ ++void * ++_PyPegen_newline_token(Parser *p) ++{ ++ return _PyPegen_expect_token(p, NEWLINE); ++} ++ ++void * ++_PyPegen_indent_token(Parser *p) ++{ ++ return _PyPegen_expect_token(p, INDENT); ++} ++ ++void * ++_PyPegen_dedent_token(Parser *p) ++{ ++ return _PyPegen_expect_token(p, DEDENT); ++} ++ ++static PyObject * ++parsenumber_raw(const char *s) ++{ ++ const char *end; ++ long x; ++ double dx; ++ Py_complex compl; ++ int imflag; ++ ++ assert(s != NULL); ++ errno = 0; ++ end = s + strlen(s) - 1; ++ imflag = *end == 'j' || *end == 'J'; ++ if (s[0] == '0') { ++ x = (long)PyOS_strtoul(s, (char **)&end, 0); ++ if (x < 0 && errno == 0) { ++ return PyLong_FromString(s, (char **)0, 0); ++ } ++ } ++ else ++ x = PyOS_strtol(s, (char **)&end, 0); ++ if (*end == '\0') { ++ if (errno != 0) ++ return PyLong_FromString(s, (char **)0, 0); ++ return PyLong_FromLong(x); ++ } ++ /* XXX Huge floats may silently fail */ ++ if (imflag) { ++ compl.real = 0.; ++ compl.imag = PyOS_string_to_double(s, (char **)&end, NULL); ++ if (compl.imag == -1.0 && PyErr_Occurred()) ++ return NULL; ++ return PyComplex_FromCComplex(compl); ++ } ++ else { ++ dx = PyOS_string_to_double(s, NULL, NULL); ++ if (dx == -1.0 && PyErr_Occurred()) ++ return NULL; ++ return PyFloat_FromDouble(dx); ++ } ++} ++ ++static PyObject * ++parsenumber(const char *s) ++{ ++ char *dup, *end; ++ PyObject *res = NULL; ++ ++ assert(s != NULL); ++ ++ if (strchr(s, '_') == NULL) { ++ return parsenumber_raw(s); ++ } ++ /* Create a duplicate without underscores. */ ++ dup = PyMem_Malloc(strlen(s) + 1); ++ if (dup == NULL) { ++ return PyErr_NoMemory(); ++ } ++ end = dup; ++ for (; *s; s++) { ++ if (*s != '_') { ++ *end++ = *s; ++ } ++ } ++ *end = '\0'; ++ res = parsenumber_raw(dup); ++ PyMem_Free(dup); ++ return res; ++} ++ ++expr_ty ++_PyPegen_number_token(Parser *p) ++{ ++ Token *t = _PyPegen_expect_token(p, NUMBER); ++ if (t == NULL) { ++ return NULL; ++ } ++ ++ char *num_raw = PyBytes_AsString(t->bytes); ++ ++ if (num_raw == NULL) { ++ return NULL; ++ } ++ ++ PyObject *c = parsenumber(num_raw); ++ ++ if (c == NULL) { ++ return NULL; ++ } ++ ++ if (PyArena_AddPyObject(p->arena, c) < 0) { ++ Py_DECREF(c); ++ return NULL; ++ } ++ ++ return Constant(c, NULL, t->lineno, t->col_offset, t->end_lineno, t->end_col_offset, ++ p->arena); ++} ++ ++void ++_PyPegen_Parser_Free(Parser *p) ++{ ++ Py_XDECREF(p->normalize); ++ for (int i = 0; i < p->size; i++) { ++ PyMem_Free(p->tokens[i]); ++ } ++ PyMem_Free(p->tokens); ++ PyMem_Free(p); ++} ++ ++Parser * ++_PyPegen_Parser_New(struct tok_state *tok, int start_rule, int *errcode, PyArena *arena) ++{ ++ Parser *p = PyMem_Malloc(sizeof(Parser)); ++ if (p == NULL) { ++ PyErr_Format(PyExc_MemoryError, "Out of memory for Parser"); ++ return NULL; ++ } ++ assert(tok != NULL); ++ p->tok = tok; ++ p->keywords = NULL; ++ p->n_keyword_lists = -1; ++ p->tokens = PyMem_Malloc(sizeof(Token *)); ++ if (!p->tokens) { ++ PyMem_Free(p); ++ PyErr_Format(PyExc_MemoryError, "Out of memory for tokens"); ++ return NULL; ++ } ++ p->tokens[0] = PyMem_Malloc(sizeof(Token)); ++ memset(p->tokens[0], '\0', sizeof(Token)); ++ p->mark = 0; ++ p->fill = 0; ++ p->size = 1; ++ ++ p->errcode = errcode; ++ p->arena = arena; ++ p->start_rule = start_rule; ++ p->parsing_started = 0; ++ p->normalize = NULL; ++ p->error_indicator = 0; ++ ++ p->starting_lineno = 0; ++ p->starting_col_offset = 0; ++ ++ return p; ++} ++ ++void * ++_PyPegen_run_parser(Parser *p) ++{ ++ void *res = _PyPegen_parse(p); ++ if (res == NULL) { ++ if (PyErr_Occurred()) { ++ return NULL; ++ } ++ if (p->fill == 0) { ++ RAISE_SYNTAX_ERROR("error at start before reading any input"); ++ } ++ else if (p->tok->done == E_EOF) { ++ RAISE_SYNTAX_ERROR("unexpected EOF while parsing"); ++ } ++ else { ++ if (p->tokens[p->fill-1]->type == INDENT) { ++ RAISE_INDENTATION_ERROR("unexpected indent"); ++ } ++ else if (p->tokens[p->fill-1]->type == DEDENT) { ++ RAISE_INDENTATION_ERROR("unexpected unindent"); ++ } ++ else { ++ RAISE_SYNTAX_ERROR("invalid syntax"); ++ } ++ } ++ return NULL; ++ } ++ ++ return res; ++} ++ ++mod_ty ++_PyPegen_run_parser_from_file_pointer(FILE *fp, int start_rule, PyObject *filename_ob, ++ const char *enc, const char *ps1, const char *ps2, ++ int *errcode, PyArena *arena) ++{ ++ struct tok_state *tok = PyTokenizer_FromFile(fp, enc, ps1, ps2); ++ if (tok == NULL) { ++ if (PyErr_Occurred()) { ++ raise_tokenizer_init_error(filename_ob); ++ return NULL; ++ } ++ return NULL; ++ } ++ // This transfers the ownership to the tokenizer ++ tok->filename = filename_ob; ++ Py_INCREF(filename_ob); ++ ++ // From here on we need to clean up even if there's an error ++ mod_ty result = NULL; ++ ++ Parser *p = _PyPegen_Parser_New(tok, start_rule, errcode, arena); ++ if (p == NULL) { ++ goto error; ++ } ++ ++ result = _PyPegen_run_parser(p); ++ _PyPegen_Parser_Free(p); ++ ++error: ++ PyTokenizer_Free(tok); ++ return result; ++} ++ ++mod_ty ++_PyPegen_run_parser_from_file(const char *filename, int start_rule, ++ PyObject *filename_ob, PyArena *arena) ++{ ++ FILE *fp = fopen(filename, "rb"); ++ if (fp == NULL) { ++ PyErr_SetFromErrnoWithFilename(PyExc_OSError, filename); ++ return NULL; ++ } ++ ++ mod_ty result = _PyPegen_run_parser_from_file_pointer(fp, start_rule, filename_ob, ++ NULL, NULL, NULL, NULL, arena); ++ ++ fclose(fp); ++ return result; ++} ++ ++mod_ty ++_PyPegen_run_parser_from_string(const char *str, int start_rule, PyObject *filename_ob, ++ int iflags, PyArena *arena) ++{ ++ int exec_input = start_rule == Py_file_input; ++ ++ struct tok_state *tok; ++ if (iflags & PyCF_IGNORE_COOKIE) { ++ tok = PyTokenizer_FromUTF8(str, exec_input); ++ } else { ++ tok = PyTokenizer_FromString(str, exec_input); ++ } ++ if (tok == NULL) { ++ if (PyErr_Occurred()) { ++ raise_tokenizer_init_error(filename_ob); ++ } ++ return NULL; ++ } ++ // This transfers the ownership to the tokenizer ++ tok->filename = filename_ob; ++ Py_INCREF(filename_ob); ++ ++ // We need to clear up from here on ++ mod_ty result = NULL; ++ ++ Parser *p = _PyPegen_Parser_New(tok, start_rule, NULL, arena); ++ if (p == NULL) { ++ goto error; ++ } ++ ++ result = _PyPegen_run_parser(p); ++ _PyPegen_Parser_Free(p); ++ ++error: ++ PyTokenizer_Free(tok); ++ return result; ++} ++ ++void * ++_PyPegen_interactive_exit(Parser *p) ++{ ++ if (p->errcode) { ++ *(p->errcode) = E_EOF; ++ } ++ return NULL; ++} ++ ++/* Creates a single-element asdl_seq* that contains a */ ++asdl_seq * ++_PyPegen_singleton_seq(Parser *p, void *a) ++{ ++ assert(a != NULL); ++ asdl_seq *seq = _Py_asdl_seq_new(1, p->arena); ++ if (!seq) { ++ return NULL; ++ } ++ asdl_seq_SET(seq, 0, a); ++ return seq; ++} ++ ++/* Creates a copy of seq and prepends a to it */ ++asdl_seq * ++_PyPegen_seq_insert_in_front(Parser *p, void *a, asdl_seq *seq) ++{ ++ assert(a != NULL); ++ if (!seq) { ++ return _PyPegen_singleton_seq(p, a); ++ } ++ ++ asdl_seq *new_seq = _Py_asdl_seq_new(asdl_seq_LEN(seq) + 1, p->arena); ++ if (!new_seq) { ++ return NULL; ++ } ++ ++ asdl_seq_SET(new_seq, 0, a); ++ for (int i = 1, l = asdl_seq_LEN(new_seq); i < l; i++) { ++ asdl_seq_SET(new_seq, i, asdl_seq_GET(seq, i - 1)); ++ } ++ return new_seq; ++} ++ ++static int ++_get_flattened_seq_size(asdl_seq *seqs) ++{ ++ int size = 0; ++ for (Py_ssize_t i = 0, l = asdl_seq_LEN(seqs); i < l; i++) { ++ asdl_seq *inner_seq = asdl_seq_GET(seqs, i); ++ size += asdl_seq_LEN(inner_seq); ++ } ++ return size; ++} ++ ++/* Flattens an asdl_seq* of asdl_seq*s */ ++asdl_seq * ++_PyPegen_seq_flatten(Parser *p, asdl_seq *seqs) ++{ ++ int flattened_seq_size = _get_flattened_seq_size(seqs); ++ assert(flattened_seq_size > 0); ++ ++ asdl_seq *flattened_seq = _Py_asdl_seq_new(flattened_seq_size, p->arena); ++ if (!flattened_seq) { ++ return NULL; ++ } ++ ++ int flattened_seq_idx = 0; ++ for (Py_ssize_t i = 0, l = asdl_seq_LEN(seqs); i < l; i++) { ++ asdl_seq *inner_seq = asdl_seq_GET(seqs, i); ++ for (int j = 0, li = asdl_seq_LEN(inner_seq); j < li; j++) { ++ asdl_seq_SET(flattened_seq, flattened_seq_idx++, asdl_seq_GET(inner_seq, j)); ++ } ++ } ++ assert(flattened_seq_idx == flattened_seq_size); ++ ++ return flattened_seq; ++} ++ ++/* Creates a new name of the form . */ ++expr_ty ++_PyPegen_join_names_with_dot(Parser *p, expr_ty first_name, expr_ty second_name) ++{ ++ assert(first_name != NULL && second_name != NULL); ++ PyObject *first_identifier = first_name->v.Name.id; ++ PyObject *second_identifier = second_name->v.Name.id; ++ ++ if (PyUnicode_READY(first_identifier) == -1) { ++ return NULL; ++ } ++ if (PyUnicode_READY(second_identifier) == -1) { ++ return NULL; ++ } ++ const char *first_str = PyUnicode_AsUTF8(first_identifier); ++ if (!first_str) { ++ return NULL; ++ } ++ const char *second_str = PyUnicode_AsUTF8(second_identifier); ++ if (!second_str) { ++ return NULL; ++ } ++ ssize_t len = strlen(first_str) + strlen(second_str) + 1; // +1 for the dot ++ ++ PyObject *str = PyBytes_FromStringAndSize(NULL, len); ++ if (!str) { ++ return NULL; ++ } ++ ++ char *s = PyBytes_AS_STRING(str); ++ if (!s) { ++ return NULL; ++ } ++ ++ strcpy(s, first_str); ++ s += strlen(first_str); ++ *s++ = '.'; ++ strcpy(s, second_str); ++ s += strlen(second_str); ++ *s = '\0'; ++ ++ PyObject *uni = PyUnicode_DecodeUTF8(PyBytes_AS_STRING(str), PyBytes_GET_SIZE(str), NULL); ++ Py_DECREF(str); ++ if (!uni) { ++ return NULL; ++ } ++ PyUnicode_InternInPlace(&uni); ++ if (PyArena_AddPyObject(p->arena, uni) < 0) { ++ Py_DECREF(uni); ++ return NULL; ++ } ++ ++ return _Py_Name(uni, Load, EXTRA_EXPR(first_name, second_name)); ++} ++ ++/* Counts the total number of dots in seq's tokens */ ++int ++_PyPegen_seq_count_dots(asdl_seq *seq) ++{ ++ int number_of_dots = 0; ++ for (Py_ssize_t i = 0, l = asdl_seq_LEN(seq); i < l; i++) { ++ Token *current_expr = asdl_seq_GET(seq, i); ++ switch (current_expr->type) { ++ case ELLIPSIS: ++ number_of_dots += 3; ++ break; ++ case DOT: ++ number_of_dots += 1; ++ break; ++ default: ++ assert(current_expr->type == ELLIPSIS || current_expr->type == DOT); ++ } ++ } ++ ++ return number_of_dots; ++} ++ ++/* Creates an alias with '*' as the identifier name */ ++alias_ty ++_PyPegen_alias_for_star(Parser *p) ++{ ++ PyObject *str = PyUnicode_InternFromString("*"); ++ if (!str) { ++ return NULL; ++ } ++ if (PyArena_AddPyObject(p->arena, str) < 0) { ++ Py_DECREF(str); ++ return NULL; ++ } ++ return alias(str, NULL, p->arena); ++} ++ ++/* Creates a new asdl_seq* with the identifiers of all the names in seq */ ++asdl_seq * ++_PyPegen_map_names_to_ids(Parser *p, asdl_seq *seq) ++{ ++ int len = asdl_seq_LEN(seq); ++ assert(len > 0); ++ ++ asdl_seq *new_seq = _Py_asdl_seq_new(len, p->arena); ++ if (!new_seq) { ++ return NULL; ++ } ++ for (Py_ssize_t i = 0; i < len; i++) { ++ expr_ty e = asdl_seq_GET(seq, i); ++ asdl_seq_SET(new_seq, i, e->v.Name.id); ++ } ++ return new_seq; ++} ++ ++/* Constructs a CmpopExprPair */ ++CmpopExprPair * ++_PyPegen_cmpop_expr_pair(Parser *p, cmpop_ty cmpop, expr_ty expr) ++{ ++ assert(expr != NULL); ++ CmpopExprPair *a = PyArena_Malloc(p->arena, sizeof(CmpopExprPair)); ++ if (!a) { ++ return NULL; ++ } ++ a->cmpop = cmpop; ++ a->expr = expr; ++ return a; ++} ++ ++asdl_int_seq * ++_PyPegen_get_cmpops(Parser *p, asdl_seq *seq) ++{ ++ int len = asdl_seq_LEN(seq); ++ assert(len > 0); ++ ++ asdl_int_seq *new_seq = _Py_asdl_int_seq_new(len, p->arena); ++ if (!new_seq) { ++ return NULL; ++ } ++ for (Py_ssize_t i = 0; i < len; i++) { ++ CmpopExprPair *pair = asdl_seq_GET(seq, i); ++ asdl_seq_SET(new_seq, i, pair->cmpop); ++ } ++ return new_seq; ++} ++ ++asdl_seq * ++_PyPegen_get_exprs(Parser *p, asdl_seq *seq) ++{ ++ int len = asdl_seq_LEN(seq); ++ assert(len > 0); ++ ++ asdl_seq *new_seq = _Py_asdl_seq_new(len, p->arena); ++ if (!new_seq) { ++ return NULL; ++ } ++ for (Py_ssize_t i = 0; i < len; i++) { ++ CmpopExprPair *pair = asdl_seq_GET(seq, i); ++ asdl_seq_SET(new_seq, i, pair->expr); ++ } ++ return new_seq; ++} ++ ++/* Creates an asdl_seq* where all the elements have been changed to have ctx as context */ ++static asdl_seq * ++_set_seq_context(Parser *p, asdl_seq *seq, expr_context_ty ctx) ++{ ++ int len = asdl_seq_LEN(seq); ++ if (len == 0) { ++ return NULL; ++ } ++ ++ asdl_seq *new_seq = _Py_asdl_seq_new(len, p->arena); ++ if (!new_seq) { ++ return NULL; ++ } ++ for (Py_ssize_t i = 0; i < len; i++) { ++ expr_ty e = asdl_seq_GET(seq, i); ++ asdl_seq_SET(new_seq, i, _PyPegen_set_expr_context(p, e, ctx)); ++ } ++ return new_seq; ++} ++ ++static expr_ty ++_set_name_context(Parser *p, expr_ty e, expr_context_ty ctx) ++{ ++ return _Py_Name(e->v.Name.id, ctx, EXTRA_EXPR(e, e)); ++} ++ ++static expr_ty ++_set_tuple_context(Parser *p, expr_ty e, expr_context_ty ctx) ++{ ++ return _Py_Tuple(_set_seq_context(p, e->v.Tuple.elts, ctx), ctx, EXTRA_EXPR(e, e)); ++} ++ ++static expr_ty ++_set_list_context(Parser *p, expr_ty e, expr_context_ty ctx) ++{ ++ return _Py_List(_set_seq_context(p, e->v.List.elts, ctx), ctx, EXTRA_EXPR(e, e)); ++} ++ ++static expr_ty ++_set_subscript_context(Parser *p, expr_ty e, expr_context_ty ctx) ++{ ++ return _Py_Subscript(e->v.Subscript.value, e->v.Subscript.slice, ctx, EXTRA_EXPR(e, e)); ++} ++ ++static expr_ty ++_set_attribute_context(Parser *p, expr_ty e, expr_context_ty ctx) ++{ ++ return _Py_Attribute(e->v.Attribute.value, e->v.Attribute.attr, ctx, EXTRA_EXPR(e, e)); ++} ++ ++static expr_ty ++_set_starred_context(Parser *p, expr_ty e, expr_context_ty ctx) ++{ ++ return _Py_Starred(_PyPegen_set_expr_context(p, e->v.Starred.value, ctx), ctx, EXTRA_EXPR(e, e)); ++} ++ ++/* Creates an `expr_ty` equivalent to `expr` but with `ctx` as context */ ++expr_ty ++_PyPegen_set_expr_context(Parser *p, expr_ty expr, expr_context_ty ctx) ++{ ++ assert(expr != NULL); ++ ++ expr_ty new = NULL; ++ switch (expr->kind) { ++ case Name_kind: ++ new = _set_name_context(p, expr, ctx); ++ break; ++ case Tuple_kind: ++ new = _set_tuple_context(p, expr, ctx); ++ break; ++ case List_kind: ++ new = _set_list_context(p, expr, ctx); ++ break; ++ case Subscript_kind: ++ new = _set_subscript_context(p, expr, ctx); ++ break; ++ case Attribute_kind: ++ new = _set_attribute_context(p, expr, ctx); ++ break; ++ case Starred_kind: ++ new = _set_starred_context(p, expr, ctx); ++ break; ++ default: ++ new = expr; ++ } ++ return new; ++} ++ ++/* Constructs a KeyValuePair that is used when parsing a dict's key value pairs */ ++KeyValuePair * ++_PyPegen_key_value_pair(Parser *p, expr_ty key, expr_ty value) ++{ ++ KeyValuePair *a = PyArena_Malloc(p->arena, sizeof(KeyValuePair)); ++ if (!a) { ++ return NULL; ++ } ++ a->key = key; ++ a->value = value; ++ return a; ++} ++ ++/* Extracts all keys from an asdl_seq* of KeyValuePair*'s */ ++asdl_seq * ++_PyPegen_get_keys(Parser *p, asdl_seq *seq) ++{ ++ int len = asdl_seq_LEN(seq); ++ asdl_seq *new_seq = _Py_asdl_seq_new(len, p->arena); ++ if (!new_seq) { ++ return NULL; ++ } ++ for (Py_ssize_t i = 0; i < len; i++) { ++ KeyValuePair *pair = asdl_seq_GET(seq, i); ++ asdl_seq_SET(new_seq, i, pair->key); ++ } ++ return new_seq; ++} ++ ++/* Extracts all values from an asdl_seq* of KeyValuePair*'s */ ++asdl_seq * ++_PyPegen_get_values(Parser *p, asdl_seq *seq) ++{ ++ int len = asdl_seq_LEN(seq); ++ asdl_seq *new_seq = _Py_asdl_seq_new(len, p->arena); ++ if (!new_seq) { ++ return NULL; ++ } ++ for (Py_ssize_t i = 0; i < len; i++) { ++ KeyValuePair *pair = asdl_seq_GET(seq, i); ++ asdl_seq_SET(new_seq, i, pair->value); ++ } ++ return new_seq; ++} ++ ++/* Constructs a NameDefaultPair */ ++NameDefaultPair * ++_PyPegen_name_default_pair(Parser *p, arg_ty arg, expr_ty value) ++{ ++ NameDefaultPair *a = PyArena_Malloc(p->arena, sizeof(NameDefaultPair)); ++ if (!a) { ++ return NULL; ++ } ++ a->arg = arg; ++ a->value = value; ++ return a; ++} ++ ++/* Constructs a SlashWithDefault */ ++SlashWithDefault * ++_PyPegen_slash_with_default(Parser *p, asdl_seq *plain_names, asdl_seq *names_with_defaults) ++{ ++ SlashWithDefault *a = PyArena_Malloc(p->arena, sizeof(SlashWithDefault)); ++ if (!a) { ++ return NULL; ++ } ++ a->plain_names = plain_names; ++ a->names_with_defaults = names_with_defaults; ++ return a; ++} ++ ++/* Constructs a StarEtc */ ++StarEtc * ++_PyPegen_star_etc(Parser *p, arg_ty vararg, asdl_seq *kwonlyargs, arg_ty kwarg) ++{ ++ StarEtc *a = PyArena_Malloc(p->arena, sizeof(StarEtc)); ++ if (!a) { ++ return NULL; ++ } ++ a->vararg = vararg; ++ a->kwonlyargs = kwonlyargs; ++ a->kwarg = kwarg; ++ return a; ++} ++ ++asdl_seq * ++_PyPegen_join_sequences(Parser *p, asdl_seq *a, asdl_seq *b) ++{ ++ int first_len = asdl_seq_LEN(a); ++ int second_len = asdl_seq_LEN(b); ++ asdl_seq *new_seq = _Py_asdl_seq_new(first_len + second_len, p->arena); ++ if (!new_seq) { ++ return NULL; ++ } ++ ++ int k = 0; ++ for (Py_ssize_t i = 0; i < first_len; i++) { ++ asdl_seq_SET(new_seq, k++, asdl_seq_GET(a, i)); ++ } ++ for (Py_ssize_t i = 0; i < second_len; i++) { ++ asdl_seq_SET(new_seq, k++, asdl_seq_GET(b, i)); ++ } ++ ++ return new_seq; ++} ++ ++static asdl_seq * ++_get_names(Parser *p, asdl_seq *names_with_defaults) ++{ ++ int len = asdl_seq_LEN(names_with_defaults); ++ asdl_seq *seq = _Py_asdl_seq_new(len, p->arena); ++ if (!seq) { ++ return NULL; ++ } ++ for (Py_ssize_t i = 0; i < len; i++) { ++ NameDefaultPair *pair = asdl_seq_GET(names_with_defaults, i); ++ asdl_seq_SET(seq, i, pair->arg); ++ } ++ return seq; ++} ++ ++static asdl_seq * ++_get_defaults(Parser *p, asdl_seq *names_with_defaults) ++{ ++ int len = asdl_seq_LEN(names_with_defaults); ++ asdl_seq *seq = _Py_asdl_seq_new(len, p->arena); ++ if (!seq) { ++ return NULL; ++ } ++ for (Py_ssize_t i = 0; i < len; i++) { ++ NameDefaultPair *pair = asdl_seq_GET(names_with_defaults, i); ++ asdl_seq_SET(seq, i, pair->value); ++ } ++ return seq; ++} ++ ++/* Constructs an arguments_ty object out of all the parsed constructs in the parameters rule */ ++arguments_ty ++_PyPegen_make_arguments(Parser *p, asdl_seq *slash_without_default, ++ SlashWithDefault *slash_with_default, asdl_seq *plain_names, ++ asdl_seq *names_with_default, StarEtc *star_etc) ++{ ++ asdl_seq *posonlyargs; ++ if (slash_without_default != NULL) { ++ posonlyargs = slash_without_default; ++ } ++ else if (slash_with_default != NULL) { ++ asdl_seq *slash_with_default_names = ++ _get_names(p, slash_with_default->names_with_defaults); ++ if (!slash_with_default_names) { ++ return NULL; ++ } ++ posonlyargs = _PyPegen_join_sequences(p, slash_with_default->plain_names, slash_with_default_names); ++ if (!posonlyargs) { ++ return NULL; ++ } ++ } ++ else { ++ posonlyargs = _Py_asdl_seq_new(0, p->arena); ++ if (!posonlyargs) { ++ return NULL; ++ } ++ } ++ ++ asdl_seq *posargs; ++ if (plain_names != NULL && names_with_default != NULL) { ++ asdl_seq *names_with_default_names = _get_names(p, names_with_default); ++ if (!names_with_default_names) { ++ return NULL; ++ } ++ posargs = _PyPegen_join_sequences(p, plain_names, names_with_default_names); ++ if (!posargs) { ++ return NULL; ++ } ++ } ++ else if (plain_names == NULL && names_with_default != NULL) { ++ posargs = _get_names(p, names_with_default); ++ if (!posargs) { ++ return NULL; ++ } ++ } ++ else if (plain_names != NULL && names_with_default == NULL) { ++ posargs = plain_names; ++ } ++ else { ++ posargs = _Py_asdl_seq_new(0, p->arena); ++ if (!posargs) { ++ return NULL; ++ } ++ } ++ ++ asdl_seq *posdefaults; ++ if (slash_with_default != NULL && names_with_default != NULL) { ++ asdl_seq *slash_with_default_values = ++ _get_defaults(p, slash_with_default->names_with_defaults); ++ if (!slash_with_default_values) { ++ return NULL; ++ } ++ asdl_seq *names_with_default_values = _get_defaults(p, names_with_default); ++ if (!names_with_default_values) { ++ return NULL; ++ } ++ posdefaults = _PyPegen_join_sequences(p, slash_with_default_values, names_with_default_values); ++ if (!posdefaults) { ++ return NULL; ++ } ++ } ++ else if (slash_with_default == NULL && names_with_default != NULL) { ++ posdefaults = _get_defaults(p, names_with_default); ++ if (!posdefaults) { ++ return NULL; ++ } ++ } ++ else if (slash_with_default != NULL && names_with_default == NULL) { ++ posdefaults = _get_defaults(p, slash_with_default->names_with_defaults); ++ if (!posdefaults) { ++ return NULL; ++ } ++ } ++ else { ++ posdefaults = _Py_asdl_seq_new(0, p->arena); ++ if (!posdefaults) { ++ return NULL; ++ } ++ } ++ ++ arg_ty vararg = NULL; ++ if (star_etc != NULL && star_etc->vararg != NULL) { ++ vararg = star_etc->vararg; ++ } ++ ++ asdl_seq *kwonlyargs; ++ if (star_etc != NULL && star_etc->kwonlyargs != NULL) { ++ kwonlyargs = _get_names(p, star_etc->kwonlyargs); ++ if (!kwonlyargs) { ++ return NULL; ++ } ++ } ++ else { ++ kwonlyargs = _Py_asdl_seq_new(0, p->arena); ++ if (!kwonlyargs) { ++ return NULL; ++ } ++ } ++ ++ asdl_seq *kwdefaults; ++ if (star_etc != NULL && star_etc->kwonlyargs != NULL) { ++ kwdefaults = _get_defaults(p, star_etc->kwonlyargs); ++ if (!kwdefaults) { ++ return NULL; ++ } ++ } ++ else { ++ kwdefaults = _Py_asdl_seq_new(0, p->arena); ++ if (!kwdefaults) { ++ return NULL; ++ } ++ } ++ ++ arg_ty kwarg = NULL; ++ if (star_etc != NULL && star_etc->kwarg != NULL) { ++ kwarg = star_etc->kwarg; ++ } ++ ++ return _Py_arguments(posonlyargs, posargs, vararg, kwonlyargs, kwdefaults, kwarg, ++ posdefaults, p->arena); ++} ++ ++/* Constructs an empty arguments_ty object, that gets used when a function accepts no ++ * arguments. */ ++arguments_ty ++_PyPegen_empty_arguments(Parser *p) ++{ ++ asdl_seq *posonlyargs = _Py_asdl_seq_new(0, p->arena); ++ if (!posonlyargs) { ++ return NULL; ++ } ++ asdl_seq *posargs = _Py_asdl_seq_new(0, p->arena); ++ if (!posargs) { ++ return NULL; ++ } ++ asdl_seq *posdefaults = _Py_asdl_seq_new(0, p->arena); ++ if (!posdefaults) { ++ return NULL; ++ } ++ asdl_seq *kwonlyargs = _Py_asdl_seq_new(0, p->arena); ++ if (!kwonlyargs) { ++ return NULL; ++ } ++ asdl_seq *kwdefaults = _Py_asdl_seq_new(0, p->arena); ++ if (!kwdefaults) { ++ return NULL; ++ } ++ ++ return _Py_arguments(posonlyargs, posargs, NULL, kwonlyargs, kwdefaults, NULL, kwdefaults, ++ p->arena); ++} ++ ++/* Encapsulates the value of an operator_ty into an AugOperator struct */ ++AugOperator * ++_PyPegen_augoperator(Parser *p, operator_ty kind) ++{ ++ AugOperator *a = PyArena_Malloc(p->arena, sizeof(AugOperator)); ++ if (!a) { ++ return NULL; ++ } ++ a->kind = kind; ++ return a; ++} ++ ++/* Construct a FunctionDef equivalent to function_def, but with decorators */ ++stmt_ty ++_PyPegen_function_def_decorators(Parser *p, asdl_seq *decorators, stmt_ty function_def) ++{ ++ assert(function_def != NULL); ++ if (function_def->kind == AsyncFunctionDef_kind) { ++ return _Py_AsyncFunctionDef( ++ function_def->v.FunctionDef.name, function_def->v.FunctionDef.args, ++ function_def->v.FunctionDef.body, decorators, function_def->v.FunctionDef.returns, ++ function_def->v.FunctionDef.type_comment, function_def->lineno, ++ function_def->col_offset, function_def->end_lineno, function_def->end_col_offset, ++ p->arena); ++ } ++ ++ return _Py_FunctionDef(function_def->v.FunctionDef.name, function_def->v.FunctionDef.args, ++ function_def->v.FunctionDef.body, decorators, ++ function_def->v.FunctionDef.returns, ++ function_def->v.FunctionDef.type_comment, function_def->lineno, ++ function_def->col_offset, function_def->end_lineno, ++ function_def->end_col_offset, p->arena); ++} ++ ++/* Construct a ClassDef equivalent to class_def, but with decorators */ ++stmt_ty ++_PyPegen_class_def_decorators(Parser *p, asdl_seq *decorators, stmt_ty class_def) ++{ ++ assert(class_def != NULL); ++ return _Py_ClassDef(class_def->v.ClassDef.name, class_def->v.ClassDef.bases, ++ class_def->v.ClassDef.keywords, class_def->v.ClassDef.body, decorators, ++ class_def->lineno, class_def->col_offset, class_def->end_lineno, ++ class_def->end_col_offset, p->arena); ++} ++ ++/* Construct a KeywordOrStarred */ ++KeywordOrStarred * ++_PyPegen_keyword_or_starred(Parser *p, void *element, int is_keyword) ++{ ++ KeywordOrStarred *a = PyArena_Malloc(p->arena, sizeof(KeywordOrStarred)); ++ if (!a) { ++ return NULL; ++ } ++ a->element = element; ++ a->is_keyword = is_keyword; ++ return a; ++} ++ ++/* Get the number of starred expressions in an asdl_seq* of KeywordOrStarred*s */ ++static int ++_seq_number_of_starred_exprs(asdl_seq *seq) ++{ ++ int n = 0; ++ for (Py_ssize_t i = 0, l = asdl_seq_LEN(seq); i < l; i++) { ++ KeywordOrStarred *k = asdl_seq_GET(seq, i); ++ if (!k->is_keyword) { ++ n++; ++ } ++ } ++ return n; ++} ++ ++/* Extract the starred expressions of an asdl_seq* of KeywordOrStarred*s */ ++asdl_seq * ++_PyPegen_seq_extract_starred_exprs(Parser *p, asdl_seq *kwargs) ++{ ++ int new_len = _seq_number_of_starred_exprs(kwargs); ++ if (new_len == 0) { ++ return NULL; ++ } ++ asdl_seq *new_seq = _Py_asdl_seq_new(new_len, p->arena); ++ if (!new_seq) { ++ return NULL; ++ } ++ ++ int idx = 0; ++ for (Py_ssize_t i = 0, len = asdl_seq_LEN(kwargs); i < len; i++) { ++ KeywordOrStarred *k = asdl_seq_GET(kwargs, i); ++ if (!k->is_keyword) { ++ asdl_seq_SET(new_seq, idx++, k->element); ++ } ++ } ++ return new_seq; ++} ++ ++/* Return a new asdl_seq* with only the keywords in kwargs */ ++asdl_seq * ++_PyPegen_seq_delete_starred_exprs(Parser *p, asdl_seq *kwargs) ++{ ++ int len = asdl_seq_LEN(kwargs); ++ int new_len = len - _seq_number_of_starred_exprs(kwargs); ++ if (new_len == 0) { ++ return NULL; ++ } ++ asdl_seq *new_seq = _Py_asdl_seq_new(new_len, p->arena); ++ if (!new_seq) { ++ return NULL; ++ } ++ ++ int idx = 0; ++ for (Py_ssize_t i = 0; i < len; i++) { ++ KeywordOrStarred *k = asdl_seq_GET(kwargs, i); ++ if (k->is_keyword) { ++ asdl_seq_SET(new_seq, idx++, k->element); ++ } ++ } ++ return new_seq; ++} ++ ++expr_ty ++_PyPegen_concatenate_strings(Parser *p, asdl_seq *strings) ++{ ++ int len = asdl_seq_LEN(strings); ++ assert(len > 0); ++ ++ Token *first = asdl_seq_GET(strings, 0); ++ Token *last = asdl_seq_GET(strings, len - 1); ++ ++ int bytesmode = 0; ++ PyObject *bytes_str = NULL; ++ ++ FstringParser state; ++ _PyPegen_FstringParser_Init(&state); ++ ++ for (Py_ssize_t i = 0; i < len; i++) { ++ Token *t = asdl_seq_GET(strings, i); ++ ++ int this_bytesmode; ++ int this_rawmode; ++ PyObject *s; ++ const char *fstr; ++ Py_ssize_t fstrlen = -1; ++ ++ char *this_str = PyBytes_AsString(t->bytes); ++ if (!this_str) { ++ goto error; ++ } ++ ++ if (_PyPegen_parsestr(p, this_str, &this_bytesmode, &this_rawmode, &s, &fstr, &fstrlen) != 0) { ++ goto error; ++ } ++ ++ /* Check that we are not mixing bytes with unicode. */ ++ if (i != 0 && bytesmode != this_bytesmode) { ++ RAISE_SYNTAX_ERROR("cannot mix bytes and nonbytes literals"); ++ Py_XDECREF(s); ++ goto error; ++ } ++ bytesmode = this_bytesmode; ++ ++ if (fstr != NULL) { ++ assert(s == NULL && !bytesmode); ++ ++ int result = _PyPegen_FstringParser_ConcatFstring(p, &state, &fstr, fstr + fstrlen, ++ this_rawmode, 0, first, t, last); ++ if (result < 0) { ++ goto error; ++ } ++ } ++ else { ++ /* String or byte string. */ ++ assert(s != NULL && fstr == NULL); ++ assert(bytesmode ? PyBytes_CheckExact(s) : PyUnicode_CheckExact(s)); ++ ++ if (bytesmode) { ++ if (i == 0) { ++ bytes_str = s; ++ } ++ else { ++ PyBytes_ConcatAndDel(&bytes_str, s); ++ if (!bytes_str) { ++ goto error; ++ } ++ } ++ } ++ else { ++ /* This is a regular string. Concatenate it. */ ++ if (_PyPegen_FstringParser_ConcatAndDel(&state, s) < 0) { ++ goto error; ++ } ++ } ++ } ++ } ++ ++ if (bytesmode) { ++ if (PyArena_AddPyObject(p->arena, bytes_str) < 0) { ++ goto error; ++ } ++ return Constant(bytes_str, NULL, first->lineno, first->col_offset, last->end_lineno, ++ last->end_col_offset, p->arena); ++ } ++ ++ return _PyPegen_FstringParser_Finish(p, &state, first, last); ++ ++error: ++ Py_XDECREF(bytes_str); ++ _PyPegen_FstringParser_Dealloc(&state); ++ if (PyErr_Occurred()) { ++ raise_decode_error(p); ++ } ++ return NULL; ++} +diff --git a/Parser/pegen/pegen.h b/Parser/pegen/pegen.h +new file mode 100644 +--- /dev/null ++++ b/Parser/pegen/pegen.h +@@ -0,0 +1,179 @@ ++#ifndef PEGEN_H ++#define PEGEN_H ++ ++#define PY_SSIZE_T_CLEAN ++#include ++#include ++#include ++#include ++ ++typedef struct _memo { ++ int type; ++ void *node; ++ int mark; ++ struct _memo *next; ++} Memo; ++ ++typedef struct { ++ int type; ++ PyObject *bytes; ++ int lineno, col_offset, end_lineno, end_col_offset; ++ Memo *memo; ++} Token; ++ ++typedef struct { ++ char *str; ++ int type; ++} KeywordToken; ++ ++typedef struct { ++ struct tok_state *tok; ++ Token **tokens; ++ int mark; ++ int fill, size; ++ PyArena *arena; ++ KeywordToken **keywords; ++ int n_keyword_lists; ++ int start_rule; ++ int *errcode; ++ int parsing_started; ++ PyObject* normalize; ++ int starting_lineno; ++ int starting_col_offset; ++ int error_indicator; ++} Parser; ++ ++typedef struct { ++ cmpop_ty cmpop; ++ expr_ty expr; ++} CmpopExprPair; ++ ++typedef struct { ++ expr_ty key; ++ expr_ty value; ++} KeyValuePair; ++ ++typedef struct { ++ arg_ty arg; ++ expr_ty value; ++} NameDefaultPair; ++ ++typedef struct { ++ asdl_seq *plain_names; ++ asdl_seq *names_with_defaults; // asdl_seq* of NameDefaultsPair's ++} SlashWithDefault; ++ ++typedef struct { ++ arg_ty vararg; ++ asdl_seq *kwonlyargs; // asdl_seq* of NameDefaultsPair's ++ arg_ty kwarg; ++} StarEtc; ++ ++typedef struct { ++ operator_ty kind; ++} AugOperator; ++ ++typedef struct { ++ void *element; ++ int is_keyword; ++} KeywordOrStarred; ++ ++void _PyPegen_clear_memo_statistics(void); ++PyObject *_PyPegen_get_memo_statistics(void); ++ ++int _PyPegen_insert_memo(Parser *p, int mark, int type, void *node); ++int _PyPegen_update_memo(Parser *p, int mark, int type, void *node); ++int _PyPegen_is_memoized(Parser *p, int type, void *pres); ++ ++int _PyPegen_lookahead_with_string(int, void *(func)(Parser *, const char *), Parser *, const char *); ++int _PyPegen_lookahead_with_int(int, Token *(func)(Parser *, int), Parser *, int); ++int _PyPegen_lookahead(int, void *(func)(Parser *), Parser *); ++ ++Token *_PyPegen_expect_token(Parser *p, int type); ++Token *_PyPegen_get_last_nonnwhitespace_token(Parser *); ++int _PyPegen_fill_token(Parser *p); ++void *_PyPegen_async_token(Parser *p); ++void *_PyPegen_await_token(Parser *p); ++void *_PyPegen_endmarker_token(Parser *p); ++expr_ty _PyPegen_name_token(Parser *p); ++void *_PyPegen_newline_token(Parser *p); ++void *_PyPegen_indent_token(Parser *p); ++void *_PyPegen_dedent_token(Parser *p); ++expr_ty _PyPegen_number_token(Parser *p); ++void *_PyPegen_string_token(Parser *p); ++const char *_PyPegen_get_expr_name(expr_ty); ++void *_PyPegen_raise_error(Parser *p, PyObject *, const char *errmsg, ...); ++void *_PyPegen_dummy_name(Parser *p, ...); ++ ++#define UNUSED(expr) do { (void)(expr); } while (0) ++#define EXTRA_EXPR(head, tail) head->lineno, head->col_offset, tail->end_lineno, tail->end_col_offset, p->arena ++#define EXTRA start_lineno, start_col_offset, end_lineno, end_col_offset, p->arena ++#define RAISE_SYNTAX_ERROR(msg, ...) _PyPegen_raise_error(p, PyExc_SyntaxError, msg, ##__VA_ARGS__) ++#define RAISE_INDENTATION_ERROR(msg, ...) _PyPegen_raise_error(p, PyExc_IndentationError, msg, ##__VA_ARGS__) ++ ++Py_LOCAL_INLINE(void *) ++CHECK_CALL(Parser *p, void *result) ++{ ++ if (result == NULL) { ++ assert(PyErr_Occurred()); ++ p->error_indicator = 1; ++ } ++ return result; ++} ++ ++/* This is needed for helper functions that are allowed to ++ return NULL without an error. Example: _PyPegen_seq_extract_starred_exprs */ ++Py_LOCAL_INLINE(void *) ++CHECK_CALL_NULL_ALLOWED(Parser *p, void *result) ++{ ++ if (result == NULL && PyErr_Occurred()) { ++ p->error_indicator = 1; ++ } ++ return result; ++} ++ ++#define CHECK(result) CHECK_CALL(p, result) ++#define CHECK_NULL_ALLOWED(result) CHECK_CALL_NULL_ALLOWED(p, result) ++ ++PyObject *_PyPegen_new_identifier(Parser *, char *); ++Parser *_PyPegen_Parser_New(struct tok_state *, int, int *, PyArena *); ++void _PyPegen_Parser_Free(Parser *); ++mod_ty _PyPegen_run_parser_from_file_pointer(FILE *, int, PyObject *, const char *, ++ const char *, const char *, int *, PyArena *); ++void *_PyPegen_run_parser(Parser *); ++mod_ty _PyPegen_run_parser_from_file(const char *, int, PyObject *, PyArena *); ++mod_ty _PyPegen_run_parser_from_string(const char *, int, PyObject *, int, PyArena *); ++void *_PyPegen_interactive_exit(Parser *); ++asdl_seq *_PyPegen_singleton_seq(Parser *, void *); ++asdl_seq *_PyPegen_seq_insert_in_front(Parser *, void *, asdl_seq *); ++asdl_seq *_PyPegen_seq_flatten(Parser *, asdl_seq *); ++expr_ty _PyPegen_join_names_with_dot(Parser *, expr_ty, expr_ty); ++int _PyPegen_seq_count_dots(asdl_seq *); ++alias_ty _PyPegen_alias_for_star(Parser *); ++asdl_seq *_PyPegen_map_names_to_ids(Parser *, asdl_seq *); ++CmpopExprPair *_PyPegen_cmpop_expr_pair(Parser *, cmpop_ty, expr_ty); ++asdl_int_seq *_PyPegen_get_cmpops(Parser *p, asdl_seq *); ++asdl_seq *_PyPegen_get_exprs(Parser *, asdl_seq *); ++expr_ty _PyPegen_set_expr_context(Parser *, expr_ty, expr_context_ty); ++KeyValuePair *_PyPegen_key_value_pair(Parser *, expr_ty, expr_ty); ++asdl_seq *_PyPegen_get_keys(Parser *, asdl_seq *); ++asdl_seq *_PyPegen_get_values(Parser *, asdl_seq *); ++NameDefaultPair *_PyPegen_name_default_pair(Parser *, arg_ty, expr_ty); ++SlashWithDefault *_PyPegen_slash_with_default(Parser *, asdl_seq *, asdl_seq *); ++StarEtc *_PyPegen_star_etc(Parser *, arg_ty, asdl_seq *, arg_ty); ++arguments_ty _PyPegen_make_arguments(Parser *, asdl_seq *, SlashWithDefault *, ++ asdl_seq *, asdl_seq *, StarEtc *); ++arguments_ty _PyPegen_empty_arguments(Parser *); ++AugOperator *_PyPegen_augoperator(Parser*, operator_ty type); ++stmt_ty _PyPegen_function_def_decorators(Parser *, asdl_seq *, stmt_ty); ++stmt_ty _PyPegen_class_def_decorators(Parser *, asdl_seq *, stmt_ty); ++KeywordOrStarred *_PyPegen_keyword_or_starred(Parser *, void *, int); ++asdl_seq *_PyPegen_seq_extract_starred_exprs(Parser *, asdl_seq *); ++asdl_seq *_PyPegen_seq_delete_starred_exprs(Parser *, asdl_seq *); ++expr_ty _PyPegen_concatenate_strings(Parser *p, asdl_seq *); ++asdl_seq *_PyPegen_join_sequences(Parser *, asdl_seq *, asdl_seq *); ++void *_PyPegen_arguments_parsing_error(Parser *, expr_ty); ++ ++void *_PyPegen_parse(Parser *); ++ ++#endif +diff --git a/Programs/_testembed.c b/Programs/_testembed.c +--- a/Programs/_testembed.c ++++ b/Programs/_testembed.c +@@ -485,6 +485,9 @@ static int test_init_from_config(void) + + config.install_signal_handlers = 0; + ++ putenv("PYTHONOLDPARSER="); ++ config.use_peg = 0; ++ + /* FIXME: test use_environment */ + + putenv("PYTHONHASHSEED=42"); +diff --git a/Python/ast_opt.c b/Python/ast_opt.c +--- a/Python/ast_opt.c ++++ b/Python/ast_opt.c +@@ -563,7 +563,8 @@ astfold_expr(expr_ty node_, PyArena *ctx_, _PyASTOptimizeState *state) + CALL(fold_tuple, expr_ty, node_); + break; + case Name_kind: +- if (_PyUnicode_EqualToASCIIString(node_->v.Name.id, "__debug__")) { ++ if (node_->v.Name.ctx == Load && ++ _PyUnicode_EqualToASCIIString(node_->v.Name.id, "__debug__")) { + return make_const(node_, PyBool_FromLong(!state->optimize), ctx_); + } + break; +diff --git a/Python/bltinmodule.c b/Python/bltinmodule.c +--- a/Python/bltinmodule.c ++++ b/Python/bltinmodule.c +@@ -816,7 +816,12 @@ builtin_compile_impl(PyObject *module, PyObject *source, PyObject *filename, + if (str == NULL) + goto error; + ++ int current_use_peg = PyInterpreterState_Get()->config.use_peg; ++ if (flags & PyCF_TYPE_COMMENTS || feature_version >= 0) { ++ PyInterpreterState_Get()->config.use_peg = 0; ++ } + result = Py_CompileStringObject(str, filename, start[compile_mode], &cf, optimize); ++ PyInterpreterState_Get()->config.use_peg = current_use_peg; + Py_XDECREF(source_copy); + goto finally; + +diff --git a/Python/compile.c b/Python/compile.c +--- a/Python/compile.c ++++ b/Python/compile.c +@@ -2152,6 +2152,55 @@ compiler_default_arguments(struct compiler *c, arguments_ty args) + return funcflags; + } + ++static int ++forbidden_name(struct compiler *c, identifier name, expr_context_ty ctx) ++{ ++ ++ if (ctx == Store && _PyUnicode_EqualToASCIIString(name, "__debug__")) { ++ compiler_error(c, "cannot assign to __debug__"); ++ return 1; ++ } ++ return 0; ++} ++ ++static int ++compiler_check_debug_one_arg(struct compiler *c, arg_ty arg) ++{ ++ if (arg != NULL) { ++ if (forbidden_name(c, arg->arg, Store)) ++ return 0; ++ } ++ return 1; ++} ++ ++static int ++compiler_check_debug_args_seq(struct compiler *c, asdl_seq *args) ++{ ++ if (args != NULL) { ++ for (int i = 0, n = asdl_seq_LEN(args); i < n; i++) { ++ if (!compiler_check_debug_one_arg(c, asdl_seq_GET(args, i))) ++ return 0; ++ } ++ } ++ return 1; ++} ++ ++static int ++compiler_check_debug_args(struct compiler *c, arguments_ty args) ++{ ++ if (!compiler_check_debug_args_seq(c, args->posonlyargs)) ++ return 0; ++ if (!compiler_check_debug_args_seq(c, args->args)) ++ return 0; ++ if (!compiler_check_debug_one_arg(c, args->vararg)) ++ return 0; ++ if (!compiler_check_debug_args_seq(c, args->kwonlyargs)) ++ return 0; ++ if (!compiler_check_debug_one_arg(c, args->kwarg)) ++ return 0; ++ return 1; ++} ++ + static int + compiler_function(struct compiler *c, stmt_ty s, int is_async) + { +@@ -2189,6 +2238,9 @@ compiler_function(struct compiler *c, stmt_ty s, int is_async) + scope_type = COMPILER_SCOPE_FUNCTION; + } + ++ if (!compiler_check_debug_args(c, args)) ++ return 0; ++ + if (!compiler_decorators(c, decos)) + return 0; + +@@ -2596,6 +2648,9 @@ compiler_lambda(struct compiler *c, expr_ty e) + arguments_ty args = e->v.Lambda.args; + assert(e->kind == Lambda_kind); + ++ if (!compiler_check_debug_args(c, args)) ++ return 0; ++ + if (!name) { + name = PyUnicode_InternFromString(""); + if (!name) +@@ -3505,6 +3560,9 @@ compiler_nameop(struct compiler *c, identifier name, expr_context_ty ctx) + !_PyUnicode_EqualToASCIIString(name, "True") && + !_PyUnicode_EqualToASCIIString(name, "False")); + ++ if (forbidden_name(c, name, ctx)) ++ return 0; ++ + mangled = _Py_Mangle(c->u->u_private, name); + if (!mangled) + return 0; +@@ -4056,6 +4114,9 @@ validate_keywords(struct compiler *c, asdl_seq *keywords) + if (key->arg == NULL) { + continue; + } ++ if (forbidden_name(c, key->arg, Store)) { ++ return -1; ++ } + for (Py_ssize_t j = i + 1; j < nkeywords; j++) { + keyword_ty other = ((keyword_ty)asdl_seq_GET(keywords, j)); + if (other->arg && !PyUnicode_Compare(key->arg, other->arg)) { +@@ -5013,6 +5074,8 @@ compiler_visit_expr1(struct compiler *c, expr_ty e) + ADDOP_NAME(c, LOAD_ATTR, e->v.Attribute.attr, names); + break; + case Store: ++ if (forbidden_name(c, e->v.Attribute.attr, e->v.Attribute.ctx)) ++ return 0; + ADDOP_NAME(c, STORE_ATTR, e->v.Attribute.attr, names); + break; + case Del: +@@ -5183,6 +5246,8 @@ compiler_annassign(struct compiler *c, stmt_ty s) + } + switch (targ->kind) { + case Name_kind: ++ if (forbidden_name(c, targ->v.Name.id, Store)) ++ return 0; + /* If we have a simple name in a module or class, store annotation. */ + if (s->v.AnnAssign.simple && + (c->u->u_scope_type == COMPILER_SCOPE_MODULE || +@@ -5200,6 +5265,8 @@ compiler_annassign(struct compiler *c, stmt_ty s) + } + break; + case Attribute_kind: ++ if (forbidden_name(c, targ->v.Attribute.attr, Store)) ++ return 0; + if (!s->v.AnnAssign.value && + !check_ann_expr(c, targ->v.Attribute.value)) { + return 0; +diff --git a/Python/importlib.h b/Python/importlib.h +--- a/Python/importlib.h ++++ b/Python/importlib.h +@@ -1594,50 +1594,51 @@ const unsigned char _Py_M__importlib_bootstrap[] = { + 0,218,1,120,90,5,119,104,101,114,101,90,9,102,114,111, + 109,95,110,97,109,101,90,3,101,120,99,114,10,0,0,0, + 114,10,0,0,0,114,11,0,0,0,114,215,0,0,0,9, +- 4,0,0,115,44,0,0,0,0,10,8,1,10,1,4,1, +- 12,2,4,1,28,2,8,1,14,1,10,1,2,255,8,2, +- 10,1,14,1,2,1,14,1,14,4,10,1,16,255,2,2, +- 12,1,26,1,114,215,0,0,0,99,1,0,0,0,0,0, +- 0,0,0,0,0,0,3,0,0,0,6,0,0,0,67,0, +- 0,0,115,146,0,0,0,124,0,160,0,100,1,161,1,125, +- 1,124,0,160,0,100,2,161,1,125,2,124,1,100,3,117, +- 1,114,82,124,2,100,3,117,1,114,78,124,1,124,2,106, +- 1,107,3,114,78,116,2,106,3,100,4,124,1,155,2,100, +- 5,124,2,106,1,155,2,100,6,157,5,116,4,100,7,100, +- 8,141,3,1,0,124,1,83,0,124,2,100,3,117,1,114, +- 96,124,2,106,1,83,0,116,2,106,3,100,9,116,4,100, +- 7,100,8,141,3,1,0,124,0,100,10,25,0,125,1,100, +- 11,124,0,118,1,114,142,124,1,160,5,100,12,161,1,100, +- 13,25,0,125,1,124,1,83,0,41,14,122,167,67,97,108, +- 99,117,108,97,116,101,32,119,104,97,116,32,95,95,112,97, +- 99,107,97,103,101,95,95,32,115,104,111,117,108,100,32,98, +- 101,46,10,10,32,32,32,32,95,95,112,97,99,107,97,103, +- 101,95,95,32,105,115,32,110,111,116,32,103,117,97,114,97, +- 110,116,101,101,100,32,116,111,32,98,101,32,100,101,102,105, +- 110,101,100,32,111,114,32,99,111,117,108,100,32,98,101,32, +- 115,101,116,32,116,111,32,78,111,110,101,10,32,32,32,32, +- 116,111,32,114,101,112,114,101,115,101,110,116,32,116,104,97, +- 116,32,105,116,115,32,112,114,111,112,101,114,32,118,97,108, +- 117,101,32,105,115,32,117,110,107,110,111,119,110,46,10,10, +- 32,32,32,32,114,146,0,0,0,114,106,0,0,0,78,122, +- 32,95,95,112,97,99,107,97,103,101,95,95,32,33,61,32, +- 95,95,115,112,101,99,95,95,46,112,97,114,101,110,116,32, +- 40,122,4,32,33,61,32,250,1,41,233,3,0,0,0,41, +- 1,90,10,115,116,97,99,107,108,101,118,101,108,122,89,99, +- 97,110,39,116,32,114,101,115,111,108,118,101,32,112,97,99, +- 107,97,103,101,32,102,114,111,109,32,95,95,115,112,101,99, +- 95,95,32,111,114,32,95,95,112,97,99,107,97,103,101,95, +- 95,44,32,102,97,108,108,105,110,103,32,98,97,99,107,32, +- 111,110,32,95,95,110,97,109,101,95,95,32,97,110,100,32, +- 95,95,112,97,116,104,95,95,114,1,0,0,0,114,142,0, +- 0,0,114,129,0,0,0,114,22,0,0,0,41,6,114,35, +- 0,0,0,114,131,0,0,0,114,193,0,0,0,114,194,0, +- 0,0,114,195,0,0,0,114,130,0,0,0,41,3,218,7, +- 103,108,111,98,97,108,115,114,187,0,0,0,114,96,0,0, +- 0,114,10,0,0,0,114,10,0,0,0,114,11,0,0,0, +- 218,17,95,99,97,108,99,95,95,95,112,97,99,107,97,103, +- 101,95,95,46,4,0,0,115,34,0,0,0,0,7,10,1, +- 10,1,8,1,18,1,22,2,4,254,6,3,4,1,8,1, ++ 4,0,0,115,52,0,0,0,0,10,8,1,10,1,4,1, ++ 12,2,4,1,4,1,2,255,4,1,8,255,10,2,8,1, ++ 14,1,10,1,2,255,8,2,10,1,14,1,2,1,14,1, ++ 14,4,10,1,16,255,2,2,12,1,26,1,114,215,0,0, ++ 0,99,1,0,0,0,0,0,0,0,0,0,0,0,3,0, ++ 0,0,6,0,0,0,67,0,0,0,115,146,0,0,0,124, ++ 0,160,0,100,1,161,1,125,1,124,0,160,0,100,2,161, ++ 1,125,2,124,1,100,3,117,1,114,82,124,2,100,3,117, ++ 1,114,78,124,1,124,2,106,1,107,3,114,78,116,2,106, ++ 3,100,4,124,1,155,2,100,5,124,2,106,1,155,2,100, ++ 6,157,5,116,4,100,7,100,8,141,3,1,0,124,1,83, ++ 0,124,2,100,3,117,1,114,96,124,2,106,1,83,0,116, ++ 2,106,3,100,9,116,4,100,7,100,8,141,3,1,0,124, ++ 0,100,10,25,0,125,1,100,11,124,0,118,1,114,142,124, ++ 1,160,5,100,12,161,1,100,13,25,0,125,1,124,1,83, ++ 0,41,14,122,167,67,97,108,99,117,108,97,116,101,32,119, ++ 104,97,116,32,95,95,112,97,99,107,97,103,101,95,95,32, ++ 115,104,111,117,108,100,32,98,101,46,10,10,32,32,32,32, ++ 95,95,112,97,99,107,97,103,101,95,95,32,105,115,32,110, ++ 111,116,32,103,117,97,114,97,110,116,101,101,100,32,116,111, ++ 32,98,101,32,100,101,102,105,110,101,100,32,111,114,32,99, ++ 111,117,108,100,32,98,101,32,115,101,116,32,116,111,32,78, ++ 111,110,101,10,32,32,32,32,116,111,32,114,101,112,114,101, ++ 115,101,110,116,32,116,104,97,116,32,105,116,115,32,112,114, ++ 111,112,101,114,32,118,97,108,117,101,32,105,115,32,117,110, ++ 107,110,111,119,110,46,10,10,32,32,32,32,114,146,0,0, ++ 0,114,106,0,0,0,78,122,32,95,95,112,97,99,107,97, ++ 103,101,95,95,32,33,61,32,95,95,115,112,101,99,95,95, ++ 46,112,97,114,101,110,116,32,40,122,4,32,33,61,32,250, ++ 1,41,233,3,0,0,0,41,1,90,10,115,116,97,99,107, ++ 108,101,118,101,108,122,89,99,97,110,39,116,32,114,101,115, ++ 111,108,118,101,32,112,97,99,107,97,103,101,32,102,114,111, ++ 109,32,95,95,115,112,101,99,95,95,32,111,114,32,95,95, ++ 112,97,99,107,97,103,101,95,95,44,32,102,97,108,108,105, ++ 110,103,32,98,97,99,107,32,111,110,32,95,95,110,97,109, ++ 101,95,95,32,97,110,100,32,95,95,112,97,116,104,95,95, ++ 114,1,0,0,0,114,142,0,0,0,114,129,0,0,0,114, ++ 22,0,0,0,41,6,114,35,0,0,0,114,131,0,0,0, ++ 114,193,0,0,0,114,194,0,0,0,114,195,0,0,0,114, ++ 130,0,0,0,41,3,218,7,103,108,111,98,97,108,115,114, ++ 187,0,0,0,114,96,0,0,0,114,10,0,0,0,114,10, ++ 0,0,0,114,11,0,0,0,218,17,95,99,97,108,99,95, ++ 95,95,112,97,99,107,97,103,101,95,95,46,4,0,0,115, ++ 42,0,0,0,0,7,10,1,10,1,8,1,18,1,6,1, ++ 2,255,4,1,4,255,6,2,4,254,6,3,4,1,8,1, + 6,2,6,2,4,254,6,3,8,1,8,1,14,1,114,221, + 0,0,0,114,10,0,0,0,99,5,0,0,0,0,0,0, + 0,0,0,0,0,9,0,0,0,5,0,0,0,67,0,0, +diff --git a/Python/importlib_external.h b/Python/importlib_external.h +--- a/Python/importlib_external.h ++++ b/Python/importlib_external.h +@@ -481,10 +481,11 @@ const unsigned char _Py_M__importlib_bootstrap_external[] = { + 108,101,118,101,108,90,13,98,97,115,101,95,102,105,108,101, + 110,97,109,101,114,5,0,0,0,114,5,0,0,0,114,8, + 0,0,0,218,17,115,111,117,114,99,101,95,102,114,111,109, +- 95,99,97,99,104,101,116,1,0,0,115,52,0,0,0,0, ++ 95,99,97,99,104,101,116,1,0,0,115,68,0,0,0,0, + 9,12,1,8,1,10,1,12,1,4,1,10,1,12,1,14, +- 1,16,1,4,1,4,1,12,1,8,1,18,2,10,1,8, +- 1,16,1,10,1,16,1,10,1,14,2,16,1,10,1,16, ++ 1,16,1,4,1,4,1,12,1,8,1,2,1,2,255,4, ++ 1,2,255,8,2,10,1,8,1,16,1,10,1,16,1,10, ++ 1,4,1,2,255,8,2,16,1,10,1,4,1,2,255,10, + 2,14,1,114,102,0,0,0,99,1,0,0,0,0,0,0, + 0,0,0,0,0,5,0,0,0,9,0,0,0,67,0,0, + 0,115,124,0,0,0,116,0,124,0,131,1,100,1,107,2, +diff --git a/Python/initconfig.c b/Python/initconfig.c +--- a/Python/initconfig.c ++++ b/Python/initconfig.c +@@ -68,6 +68,7 @@ static const char usage_3[] = "\ + -X opt : set implementation-specific option. The following options are available:\n\ + \n\ + -X faulthandler: enable faulthandler\n\ ++ -X oldparser: enable the traditional LL(1) parser; also PYTHONOLDPARSER\n\ + -X showrefcount: output the total reference count and number of used\n\ + memory blocks when the program finishes or after each statement in the\n\ + interactive interpreter. This only works on debug builds\n\ +@@ -634,6 +635,7 @@ _PyConfig_InitCompatConfig(PyConfig *config) + #ifdef MS_WINDOWS + config->legacy_windows_stdio = -1; + #endif ++ config->use_peg = 1; + } + + +@@ -791,6 +793,7 @@ _PyConfig_Copy(PyConfig *config, const PyConfig *config2) + COPY_ATTR(isolated); + COPY_ATTR(use_environment); + COPY_ATTR(dev_mode); ++ COPY_ATTR(use_peg); + COPY_ATTR(install_signal_handlers); + COPY_ATTR(use_hash_seed); + COPY_ATTR(hash_seed); +@@ -894,6 +897,7 @@ config_as_dict(const PyConfig *config) + SET_ITEM_INT(isolated); + SET_ITEM_INT(use_environment); + SET_ITEM_INT(dev_mode); ++ SET_ITEM_INT(use_peg); + SET_ITEM_INT(install_signal_handlers); + SET_ITEM_INT(use_hash_seed); + SET_ITEM_UINT(hash_seed); +@@ -1428,6 +1432,11 @@ config_read_complex_options(PyConfig *config) + config->import_time = 1; + } + ++ if (config_get_env(config, "PYTHONOLDPARSER") ++ || config_get_xoption(config, L"oldparser")) { ++ config->use_peg = 0; ++ } ++ + PyStatus status; + if (config->tracemalloc < 0) { + status = config_init_tracemalloc(config); +@@ -2507,6 +2516,7 @@ PyConfig_Read(PyConfig *config) + assert(config->isolated >= 0); + assert(config->use_environment >= 0); + assert(config->dev_mode >= 0); ++ assert(config->use_peg >= 0); + assert(config->install_signal_handlers >= 0); + assert(config->use_hash_seed >= 0); + assert(config->faulthandler >= 0); +diff --git a/Python/pythonrun.c b/Python/pythonrun.c +--- a/Python/pythonrun.c ++++ b/Python/pythonrun.c +@@ -29,6 +29,8 @@ + #include "ast.h" // PyAST_FromNodeObject() + #include "marshal.h" // PyMarshal_ReadLongFromFile() + ++#include // PyPegen_ASTFrom* ++ + #ifdef MS_WINDOWS + # include "malloc.h" // alloca() + #endif +@@ -183,6 +185,7 @@ PyRun_InteractiveOneObjectEx(FILE *fp, PyObject *filename, + PyArena *arena; + const char *ps1 = "", *ps2 = "", *enc = NULL; + int errcode = 0; ++ int use_peg = _PyInterpreterState_GET()->config.use_peg; + _Py_IDENTIFIER(encoding); + _Py_IDENTIFIER(__main__); + +@@ -235,9 +238,17 @@ PyRun_InteractiveOneObjectEx(FILE *fp, PyObject *filename, + Py_XDECREF(oenc); + return -1; + } +- mod = PyParser_ASTFromFileObject(fp, filename, enc, +- Py_single_input, ps1, ps2, +- flags, &errcode, arena); ++ ++ if (use_peg) { ++ mod = PyPegen_ASTFromFileObject(fp, filename, Py_single_input, ++ enc, ps1, ps2, &errcode, arena); ++ } ++ else { ++ mod = PyParser_ASTFromFileObject(fp, filename, enc, ++ Py_single_input, ps1, ps2, ++ flags, &errcode, arena); ++ } ++ + Py_XDECREF(v); + Py_XDECREF(w); + Py_XDECREF(oenc); +@@ -1019,6 +1030,7 @@ PyRun_StringFlags(const char *str, int start, PyObject *globals, + mod_ty mod; + PyArena *arena; + PyObject *filename; ++ int use_peg = _PyInterpreterState_GET()->config.use_peg; + + filename = _PyUnicode_FromId(&PyId_string); /* borrowed */ + if (filename == NULL) +@@ -1028,7 +1040,13 @@ PyRun_StringFlags(const char *str, int start, PyObject *globals, + if (arena == NULL) + return NULL; + +- mod = PyParser_ASTFromStringObject(str, filename, start, flags, arena); ++ if (use_peg) { ++ mod = PyPegen_ASTFromStringObject(str, filename, start, flags, arena); ++ } ++ else { ++ mod = PyParser_ASTFromStringObject(str, filename, start, flags, arena); ++ } ++ + if (mod != NULL) + ret = run_mod(mod, filename, globals, locals, flags, arena); + PyArena_Free(arena); +@@ -1043,6 +1061,7 @@ PyRun_FileExFlags(FILE *fp, const char *filename_str, int start, PyObject *globa + mod_ty mod; + PyArena *arena = NULL; + PyObject *filename; ++ int use_peg = _PyInterpreterState_GET()->config.use_peg; + + filename = PyUnicode_DecodeFSDefault(filename_str); + if (filename == NULL) +@@ -1052,8 +1071,15 @@ PyRun_FileExFlags(FILE *fp, const char *filename_str, int start, PyObject *globa + if (arena == NULL) + goto exit; + +- mod = PyParser_ASTFromFileObject(fp, filename, NULL, start, 0, 0, +- flags, NULL, arena); ++ if (use_peg) { ++ mod = PyPegen_ASTFromFileObject(fp, filename, start, NULL, NULL, NULL, ++ NULL, arena); ++ } ++ else { ++ mod = PyParser_ASTFromFileObject(fp, filename, NULL, start, 0, 0, ++ flags, NULL, arena); ++ } ++ + if (closeit) + fclose(fp); + if (mod == NULL) { +@@ -1196,11 +1222,17 @@ Py_CompileStringObject(const char *str, PyObject *filename, int start, + { + PyCodeObject *co; + mod_ty mod; ++ int use_peg = _PyInterpreterState_GET()->config.use_peg; + PyArena *arena = PyArena_New(); + if (arena == NULL) + return NULL; + +- mod = PyParser_ASTFromStringObject(str, filename, start, flags, arena); ++ if (use_peg) { ++ mod = PyPegen_ASTFromStringObject(str, filename, start, flags, arena); ++ } ++ else { ++ mod = PyParser_ASTFromStringObject(str, filename, start, flags, arena); ++ } + if (mod == NULL) { + PyArena_Free(arena); + return NULL; +@@ -1297,13 +1329,19 @@ _Py_SymtableStringObjectFlags(const char *str, PyObject *filename, int start, Py + { + struct symtable *st; + mod_ty mod; ++ int use_peg = _PyInterpreterState_GET()->config.use_peg; + PyArena *arena; + + arena = PyArena_New(); + if (arena == NULL) + return NULL; + +- mod = PyParser_ASTFromStringObject(str, filename, start, flags, arena); ++ if (use_peg) { ++ mod = PyPegen_ASTFromStringObject(str, filename, start, flags, arena); ++ } ++ else { ++ mod = PyParser_ASTFromStringObject(str, filename, start, flags, arena); ++ } + if (mod == NULL) { + PyArena_Free(arena); + return NULL; +diff --git a/Python/sysmodule.c b/Python/sysmodule.c +--- a/Python/sysmodule.c ++++ b/Python/sysmodule.c +@@ -2427,6 +2427,7 @@ static PyStructSequence_Field flags_fields[] = { + {"inspect", "-i"}, + {"interactive", "-i"}, + {"optimize", "-O or -OO"}, ++ {"use_peg", "-p old or -p new"}, + {"dont_write_bytecode", "-B"}, + {"no_user_site", "-s"}, + {"no_site", "-S"}, +@@ -2447,7 +2448,7 @@ static PyStructSequence_Desc flags_desc = { + "sys.flags", /* name */ + flags__doc__, /* doc */ + flags_fields, /* fields */ +- 15 ++ 16 + }; + + static PyObject* +@@ -2470,6 +2471,7 @@ make_flags(PyThreadState *tstate) + SetFlag(config->inspect); + SetFlag(config->interactive); + SetFlag(config->optimization_level); ++ SetFlag(config->use_peg); + SetFlag(!config->write_bytecode); + SetFlag(!config->user_site_directory); + SetFlag(!config->site_import); +diff --git a/Tools/peg_generator/.clang-format b/Tools/peg_generator/.clang-format +new file mode 100644 +--- /dev/null ++++ b/Tools/peg_generator/.clang-format +@@ -0,0 +1,17 @@ ++# A clang-format style that approximates Python's PEP 7 ++BasedOnStyle: Google ++AlwaysBreakAfterReturnType: All ++AllowShortIfStatementsOnASingleLine: false ++AlignAfterOpenBracket: Align ++BreakBeforeBraces: Stroustrup ++ColumnLimit: 95 ++DerivePointerAlignment: false ++IndentWidth: 4 ++Language: Cpp ++PointerAlignment: Right ++ReflowComments: true ++SpaceBeforeParens: ControlStatements ++SpacesInParentheses: false ++TabWidth: 4 ++UseTab: Never ++SortIncludes: false +diff --git a/Tools/peg_generator/.gitignore b/Tools/peg_generator/.gitignore +new file mode 100644 +--- /dev/null ++++ b/Tools/peg_generator/.gitignore +@@ -0,0 +1,3 @@ ++peg_extension/parse.c ++data/xxl.py ++@data +diff --git a/Tools/peg_generator/Makefile b/Tools/peg_generator/Makefile +new file mode 100644 +--- /dev/null ++++ b/Tools/peg_generator/Makefile +@@ -0,0 +1,116 @@ ++UNAME_S := $(shell uname -s) ++ifeq ($(UNAME_S),Linux) ++ PYTHON ?= ../../python ++endif ++ifeq ($(UNAME_S),Darwin) ++ PYTHON ?= ../../python.exe ++endif ++ ++CPYTHON ?= ../../Lib ++MYPY ?= mypy ++ ++GRAMMAR = ../../Grammar/python.gram ++TESTFILE = data/cprog.py ++TIMEFILE = data/xxl.py ++TESTDIR = . ++TESTFLAGS = --short ++ ++data/xxl.py: ++ $(PYTHON) -m zipfile -e data/xxl.zip data ++ ++build: peg_extension/parse.c ++ ++peg_extension/parse.c: $(GRAMMAR) pegen/*.py peg_extension/peg_extension.c ../../Parser/pegen/pegen.c ../../Parser/pegen/parse_string.c ../../Parser/pegen/*.h pegen/grammar_parser.py ++ $(PYTHON) -m pegen -q -c $(GRAMMAR) -o peg_extension/parse.c --compile-extension ++ ++clean: ++ -rm -f peg_extension/*.o peg_extension/*.so peg_extension/parse.c ++ -rm -f data/xxl.py ++ ++dump: peg_extension/parse.c ++ cat -n $(TESTFILE) ++ $(PYTHON) -c "from peg_extension import parse; import ast; t = parse.parse_file('$(TESTFILE)', mode=1); print(ast.dump(t))" ++ ++regen-metaparser: pegen/metagrammar.gram pegen/*.py ++ $(PYTHON) -m pegen -q -c pegen/metagrammar.gram -o pegen/grammar_parser.py ++ ++# Note: These targets really depend on the generated shared object in peg_extension/parse.*.so but ++# this has different names in different systems so we are abusing the implicit dependency on ++# parse.c by the use of --compile-extension. ++ ++.PHONY: test ++ ++test: run ++ ++run: peg_extension/parse.c ++ $(PYTHON) -c "from peg_extension import parse; t = parse.parse_file('$(TESTFILE)'); exec(t)" ++ ++compile: peg_extension/parse.c ++ $(PYTHON) -c "from peg_extension import parse; t = parse.parse_file('$(TESTFILE)', mode=2)" ++ ++parse: peg_extension/parse.c ++ $(PYTHON) -c "from peg_extension import parse; t = parse.parse_file('$(TESTFILE)', mode=1)" ++ ++check: peg_extension/parse.c ++ $(PYTHON) -c "from peg_extension import parse; t = parse.parse_file('$(TESTFILE)', mode=0)" ++ ++stats: peg_extension/parse.c data/xxl.py ++ $(PYTHON) -c "from peg_extension import parse; t = parse.parse_file('$(TIMEFILE)', mode=0); parse.dump_memo_stats()" >@data ++ $(PYTHON) scripts/joinstats.py @data ++ ++time: time_compile ++ ++time_compile: peg_extension/parse.c data/xxl.py ++ $(PYTHON) scripts/benchmark.py --parser=pegen --target=xxl compile ++ ++time_parse: peg_extension/parse.c data/xxl.py ++ $(PYTHON) scripts/benchmark.py --parser=pegen --target=xxl parse ++ ++time_check: peg_extension/parse.c data/xxl.py ++ $(PYTHON) scripts/benchmark.py --parser=pegen --target=xxl check ++ ++time_stdlib: time_stdlib_compile ++ ++time_stdlib_compile: data/xxl.py ++ $(PYTHON) scripts/benchmark.py --parser=cpython --target=xxl compile ++ ++time_stdlib_parse: data/xxl.py ++ $(PYTHON) scripts/benchmark.py --parser=cpython --target=xxl parse ++ ++test_local: ++ $(PYTHON) scripts/test_parse_directory.py \ ++ -g $(GRAMMAR) \ ++ -d $(TESTDIR) \ ++ $(TESTFLAGS) \ ++ --exclude "*/failset/*" \ ++ --exclude "*/failset/**" \ ++ --exclude "*/failset/**/*" ++ ++test_global: $(CPYTHON) ++ $(PYTHON) scripts/test_parse_directory.py \ ++ -g $(GRAMMAR) \ ++ -d $(CPYTHON) \ ++ $(TESTFLAGS) \ ++ --exclude "*/test2to3/*" \ ++ --exclude "*/test2to3/**/*" \ ++ --exclude "*/bad*" \ ++ --exclude "*/lib2to3/tests/data/*" ++ ++mypy: regen-metaparser ++ $(MYPY) # For list of files, see mypy.ini ++ ++format-python: ++ black pegen scripts ++ ++bench: ++ $(PYTHON) scripts/benchmark.py --parser=pegen --target=stdlib check ++ ++format: format-python ++ ++find_max_nesting: ++ $(PYTHON) scripts/find_max_nesting.py ++ ++tags: TAGS ++ ++TAGS: pegen/*.py test/test_pegen.py ++ etags pegen/*.py test/test_pegen.py +diff --git a/Tools/peg_generator/data/cprog.py b/Tools/peg_generator/data/cprog.py +new file mode 100644 +--- /dev/null ++++ b/Tools/peg_generator/data/cprog.py +@@ -0,0 +1,10 @@ ++if 1: ++ print("Hello " + "world") ++ if 0: ++ print("then") ++ print("clause") ++ elif 1: ++ pass ++ elif 1: ++ pass ++ else: print("else-clause") +diff --git a/Tools/peg_generator/mypy.ini b/Tools/peg_generator/mypy.ini +new file mode 100644 +--- /dev/null ++++ b/Tools/peg_generator/mypy.ini +@@ -0,0 +1,26 @@ ++[mypy] ++files = pegen, scripts ++ ++follow_imports = error ++no_implicit_optional = True ++strict_optional = True ++ ++#check_untyped_defs = True ++disallow_untyped_calls = True ++disallow_untyped_defs = True ++ ++disallow_any_generics = true ++disallow_any_unimported = True ++disallow_incomplete_defs = True ++disallow_subclassing_any = True ++ ++warn_unused_configs = True ++warn_unused_ignores = true ++warn_redundant_casts = true ++warn_no_return = True ++ ++show_traceback = True ++show_error_codes = True ++ ++[mypy-pegen.grammar_parser] ++strict_optional = False +diff --git a/Tools/peg_generator/peg_extension/peg_extension.c b/Tools/peg_generator/peg_extension/peg_extension.c +new file mode 100644 +--- /dev/null ++++ b/Tools/peg_generator/peg_extension/peg_extension.c +@@ -0,0 +1,153 @@ ++#include "pegen.h" ++ ++PyObject * ++_build_return_object(mod_ty module, int mode, PyObject *filename_ob, PyArena *arena) ++{ ++ PyObject *result = NULL; ++ ++ if (mode == 2) { ++ result = (PyObject *)PyAST_CompileObject(module, filename_ob, NULL, -1, arena); ++ } else if (mode == 1) { ++ result = PyAST_mod2obj(module); ++ } else { ++ result = Py_None; ++ Py_INCREF(result); ++ ++ } ++ ++ return result; ++} ++ ++static PyObject * ++parse_file(PyObject *self, PyObject *args, PyObject *kwds) ++{ ++ static char *keywords[] = {"file", "mode", NULL}; ++ const char *filename; ++ int mode = 2; ++ if (!PyArg_ParseTupleAndKeywords(args, kwds, "s|i", keywords, &filename, &mode)) { ++ return NULL; ++ } ++ if (mode < 0 || mode > 2) { ++ return PyErr_Format(PyExc_ValueError, "Bad mode, must be 0 <= mode <= 2"); ++ } ++ ++ PyArena *arena = PyArena_New(); ++ if (arena == NULL) { ++ return NULL; ++ } ++ ++ PyObject *result = NULL; ++ ++ PyObject *filename_ob = PyUnicode_FromString(filename); ++ if (filename_ob == NULL) { ++ goto error; ++ } ++ ++ mod_ty res = _PyPegen_run_parser_from_file(filename, Py_file_input, filename_ob, arena); ++ if (res == NULL) { ++ goto error; ++ } ++ ++ result = _build_return_object(res, mode, filename_ob, arena); ++ ++error: ++ Py_XDECREF(filename_ob); ++ PyArena_Free(arena); ++ return result; ++} ++ ++static PyObject * ++parse_string(PyObject *self, PyObject *args, PyObject *kwds) ++{ ++ static char *keywords[] = {"str", "mode", NULL}; ++ const char *the_string; ++ int mode = 2; ++ if (!PyArg_ParseTupleAndKeywords(args, kwds, "s|i", keywords, &the_string, &mode)) { ++ return NULL; ++ } ++ if (mode < 0 || mode > 2) { ++ return PyErr_Format(PyExc_ValueError, "Bad mode, must be 0 <= mode <= 2"); ++ } ++ ++ PyArena *arena = PyArena_New(); ++ if (arena == NULL) { ++ return NULL; ++ } ++ ++ PyObject *result = NULL; ++ ++ PyObject *filename_ob = PyUnicode_FromString(""); ++ if (filename_ob == NULL) { ++ goto error; ++ } ++ ++ mod_ty res = _PyPegen_run_parser_from_string(the_string, Py_file_input, filename_ob, ++ PyCF_IGNORE_COOKIE, arena); ++ if (res == NULL) { ++ goto error; ++ } ++ result = _build_return_object(res, mode, filename_ob, arena); ++ ++error: ++ Py_XDECREF(filename_ob); ++ PyArena_Free(arena); ++ return result; ++} ++ ++static PyObject * ++clear_memo_stats() ++{ ++ _PyPegen_clear_memo_statistics(); ++ Py_RETURN_NONE; ++} ++ ++static PyObject * ++get_memo_stats() ++{ ++ return _PyPegen_get_memo_statistics(); ++} ++ ++// TODO: Write to Python's sys.stdout instead of C's stdout. ++static PyObject * ++dump_memo_stats() ++{ ++ PyObject *list = _PyPegen_get_memo_statistics(); ++ if (list == NULL) { ++ return NULL; ++ } ++ Py_ssize_t len = PyList_Size(list); ++ for (Py_ssize_t i = 0; i < len; i++) { ++ PyObject *value = PyList_GetItem(list, i); // Borrowed reference. ++ long count = PyLong_AsLong(value); ++ if (count < 0) { ++ break; ++ } ++ if (count > 0) { ++ printf("%4ld %9ld\n", i, count); ++ } ++ } ++ Py_DECREF(list); ++ Py_RETURN_NONE; ++} ++ ++static PyMethodDef ParseMethods[] = { ++ {"parse_file", (PyCFunction)(void(*)(void))parse_file, METH_VARARGS|METH_KEYWORDS, "Parse a file."}, ++ {"parse_string", (PyCFunction)(void(*)(void))parse_string, METH_VARARGS|METH_KEYWORDS, "Parse a string."}, ++ {"clear_memo_stats", clear_memo_stats, METH_NOARGS}, ++ {"dump_memo_stats", dump_memo_stats, METH_NOARGS}, ++ {"get_memo_stats", get_memo_stats, METH_NOARGS}, ++ {NULL, NULL, 0, NULL} /* Sentinel */ ++}; ++ ++static struct PyModuleDef parsemodule = { ++ PyModuleDef_HEAD_INIT, ++ .m_name = "parse", ++ .m_doc = "A parser.", ++ .m_methods = ParseMethods, ++}; ++ ++PyMODINIT_FUNC ++PyInit_parse(void) ++{ ++ return PyModule_Create(&parsemodule); ++} +diff --git a/Tools/peg_generator/pegen/__init__.py b/Tools/peg_generator/pegen/__init__.py +new file mode 100644 +--- /dev/null ++++ b/Tools/peg_generator/pegen/__init__.py +diff --git a/Tools/peg_generator/pegen/__main__.py b/Tools/peg_generator/pegen/__main__.py +new file mode 100644 +--- /dev/null ++++ b/Tools/peg_generator/pegen/__main__.py +@@ -0,0 +1,136 @@ ++#!/usr/bin/env python3.8 ++ ++"""pegen -- PEG Generator. ++ ++Search the web for PEG Parsers for reference. ++""" ++ ++import argparse ++import sys ++import time ++import token ++import traceback ++ ++from typing import Final ++ ++from pegen.build import build_parser_and_generator ++from pegen.testutil import print_memstats ++ ++ ++argparser = argparse.ArgumentParser( ++ prog="pegen", description="Experimental PEG-like parser generator" ++) ++argparser.add_argument("-q", "--quiet", action="store_true", help="Don't print the parsed grammar") ++argparser.add_argument( ++ "-v", ++ "--verbose", ++ action="count", ++ default=0, ++ help="Print timing stats; repeat for more debug output", ++) ++argparser.add_argument( ++ "-c", "--cpython", action="store_true", help="Generate C code for inclusion into CPython" ++) ++argparser.add_argument( ++ "--compile-extension", ++ action="store_true", ++ help="Compile generated C code into an extension module", ++) ++argparser.add_argument( ++ "-o", ++ "--output", ++ metavar="OUT", ++ help="Where to write the generated parser (default parse.py or parse.c)", ++) ++argparser.add_argument("filename", help="Grammar description") ++argparser.add_argument( ++ "--optimized", action="store_true", help="Compile the extension in optimized mode" ++) ++argparser.add_argument( ++ "--skip-actions", action="store_true", help="Suppress code emission for rule actions", ++) ++ ++ ++def main() -> None: ++ args = argparser.parse_args() ++ verbose = args.verbose ++ verbose_tokenizer = verbose >= 3 ++ verbose_parser = verbose == 2 or verbose >= 4 ++ t0 = time.time() ++ ++ output_file = args.output ++ if not output_file: ++ if args.cpython: ++ output_file = "parse.c" ++ else: ++ output_file = "parse.py" ++ ++ try: ++ grammar, parser, tokenizer, gen = build_parser_and_generator( ++ args.filename, ++ output_file, ++ args.compile_extension, ++ verbose_tokenizer, ++ verbose_parser, ++ args.verbose, ++ keep_asserts_in_extension=False if args.optimized else True, ++ skip_actions=args.skip_actions, ++ ) ++ except Exception as err: ++ if args.verbose: ++ raise # Show traceback ++ traceback.print_exception(err.__class__, err, None) ++ sys.stderr.write("For full traceback, use -v\n") ++ sys.exit(1) ++ ++ if not args.quiet: ++ if args.verbose: ++ print("Raw Grammar:") ++ for line in repr(grammar).splitlines(): ++ print(" ", line) ++ ++ print("Clean Grammar:") ++ for line in str(grammar).splitlines(): ++ print(" ", line) ++ ++ if args.verbose: ++ print("First Graph:") ++ for src, dsts in gen.first_graph.items(): ++ print(f" {src} -> {', '.join(dsts)}") ++ print("First SCCS:") ++ for scc in gen.first_sccs: ++ print(" ", scc, end="") ++ if len(scc) > 1: ++ print( ++ " # Indirectly left-recursive; leaders:", ++ {name for name in scc if grammar.rules[name].leader}, ++ ) ++ else: ++ name = next(iter(scc)) ++ if name in gen.first_graph[name]: ++ print(" # Left-recursive") ++ else: ++ print() ++ ++ t1 = time.time() ++ ++ if args.verbose: ++ dt = t1 - t0 ++ diag = tokenizer.diagnose() ++ nlines = diag.end[0] ++ if diag.type == token.ENDMARKER: ++ nlines -= 1 ++ print(f"Total time: {dt:.3f} sec; {nlines} lines", end="") ++ if dt: ++ print(f"; {nlines / dt:.0f} lines/sec") ++ else: ++ print() ++ print("Caches sizes:") ++ print(f" token array : {len(tokenizer._tokens):10}") ++ print(f" cache : {len(parser._cache):10}") ++ if not print_memstats(): ++ print("(Can't find psutil; install it for memory stats.)") ++ ++ ++if __name__ == "__main__": ++ main() +diff --git a/Tools/peg_generator/pegen/build.py b/Tools/peg_generator/pegen/build.py +new file mode 100644 +--- /dev/null ++++ b/Tools/peg_generator/pegen/build.py +@@ -0,0 +1,169 @@ ++import pathlib ++import shutil ++import tokenize ++ ++from typing import Optional, Tuple ++ ++import distutils.log ++from distutils.core import Distribution, Extension ++from distutils.command.clean import clean # type: ignore ++from distutils.command.build_ext import build_ext # type: ignore ++ ++from pegen.c_generator import CParserGenerator ++from pegen.grammar import Grammar ++from pegen.grammar_parser import GeneratedParser as GrammarParser ++from pegen.parser import Parser ++from pegen.parser_generator import ParserGenerator ++from pegen.python_generator import PythonParserGenerator ++from pegen.tokenizer import Tokenizer ++ ++MOD_DIR = pathlib.Path(__file__).parent ++ ++ ++def compile_c_extension( ++ generated_source_path: str, ++ build_dir: Optional[str] = None, ++ verbose: bool = False, ++ keep_asserts: bool = True, ++) -> str: ++ """Compile the generated source for a parser generator into an extension module. ++ ++ The extension module will be generated in the same directory as the provided path ++ for the generated source, with the same basename (in addition to extension module ++ metadata). For example, for the source mydir/parser.c the generated extension ++ in a darwin system with python 3.8 will be mydir/parser.cpython-38-darwin.so. ++ ++ If *build_dir* is provided, that path will be used as the temporary build directory ++ of distutils (this is useful in case you want to use a temporary directory). ++ """ ++ if verbose: ++ distutils.log.set_verbosity(distutils.log.DEBUG) ++ ++ source_file_path = pathlib.Path(generated_source_path) ++ extension_name = source_file_path.stem ++ extra_compile_args = [] ++ if keep_asserts: ++ extra_compile_args.append("-UNDEBUG") ++ extension = [ ++ Extension( ++ extension_name, ++ sources=[ ++ str(MOD_DIR.parent.parent.parent / "Python" / "Python-ast.c"), ++ str(MOD_DIR.parent.parent.parent / "Python" / "asdl.c"), ++ str(MOD_DIR.parent.parent.parent / "Parser" / "tokenizer.c"), ++ str(MOD_DIR.parent.parent.parent / "Parser" / "pegen" / "pegen.c"), ++ str(MOD_DIR.parent.parent.parent / "Parser" / "pegen" / "parse_string.c"), ++ str(MOD_DIR.parent / "peg_extension" / "peg_extension.c"), ++ generated_source_path, ++ ], ++ include_dirs=[ ++ str(MOD_DIR.parent.parent.parent / "Include" / "internal"), ++ str(MOD_DIR.parent.parent.parent / "Parser"), ++ str(MOD_DIR.parent.parent.parent / "Parser" / "pegen"), ++ ], ++ extra_compile_args=extra_compile_args, ++ ) ++ ] ++ dist = Distribution({"name": extension_name, "ext_modules": extension}) ++ cmd = build_ext(dist) ++ cmd.inplace = True ++ if build_dir: ++ cmd.build_temp = build_dir ++ cmd.ensure_finalized() ++ cmd.run() ++ ++ extension_path = source_file_path.parent / cmd.get_ext_filename(extension_name) ++ shutil.move(cmd.get_ext_fullpath(extension_name), extension_path) ++ ++ cmd = clean(dist) ++ cmd.finalize_options() ++ cmd.run() ++ ++ return extension_path ++ ++ ++def build_parser( ++ grammar_file: str, verbose_tokenizer: bool = False, verbose_parser: bool = False ++) -> Tuple[Grammar, Parser, Tokenizer]: ++ with open(grammar_file) as file: ++ tokenizer = Tokenizer(tokenize.generate_tokens(file.readline), verbose=verbose_tokenizer) ++ parser = GrammarParser(tokenizer, verbose=verbose_parser) ++ grammar = parser.start() ++ ++ if not grammar: ++ raise parser.make_syntax_error(grammar_file) ++ ++ return grammar, parser, tokenizer ++ ++ ++def build_generator( ++ tokenizer: Tokenizer, ++ grammar: Grammar, ++ grammar_file: str, ++ output_file: str, ++ compile_extension: bool = False, ++ verbose_c_extension: bool = False, ++ keep_asserts_in_extension: bool = True, ++ skip_actions: bool = False, ++) -> ParserGenerator: ++ # TODO: Allow other extensions; pass the output type as an argument. ++ if not output_file.endswith((".c", ".py")): ++ raise RuntimeError("Your output file must either be a .c or .py file") ++ with open(output_file, "w") as file: ++ gen: ParserGenerator ++ if output_file.endswith(".c"): ++ gen = CParserGenerator(grammar, file, skip_actions=skip_actions) ++ elif output_file.endswith(".py"): ++ gen = PythonParserGenerator(grammar, file) # TODO: skip_actions ++ else: ++ assert False # Should have been checked above ++ gen.generate(grammar_file) ++ ++ if compile_extension and output_file.endswith(".c"): ++ compile_c_extension( ++ output_file, verbose=verbose_c_extension, keep_asserts=keep_asserts_in_extension ++ ) ++ ++ return gen ++ ++ ++def build_parser_and_generator( ++ grammar_file: str, ++ output_file: str, ++ compile_extension: bool = False, ++ verbose_tokenizer: bool = False, ++ verbose_parser: bool = False, ++ verbose_c_extension: bool = False, ++ keep_asserts_in_extension: bool = True, ++ skip_actions: bool = False, ++) -> Tuple[Grammar, Parser, Tokenizer, ParserGenerator]: ++ """Generate rules, parser, tokenizer, parser generator for a given grammar ++ ++ Args: ++ grammar_file (string): Path for the grammar file ++ output_file (string): Path for the output file ++ compile_extension (bool, optional): Whether to compile the C extension. ++ Defaults to False. ++ verbose_tokenizer (bool, optional): Whether to display additional output ++ when generating the tokenizer. Defaults to False. ++ verbose_parser (bool, optional): Whether to display additional output ++ when generating the parser. Defaults to False. ++ verbose_c_extension (bool, optional): Whether to display additional ++ output when compiling the C extension . Defaults to False. ++ keep_asserts_in_extension (bool, optional): Whether to keep the assert statements ++ when compiling the extension module. Defaults to True. ++ skip_actions (bool, optional): Whether to pretend no rule has any actions. ++ """ ++ grammar, parser, tokenizer = build_parser(grammar_file, verbose_tokenizer, verbose_parser) ++ gen = build_generator( ++ tokenizer, ++ grammar, ++ grammar_file, ++ output_file, ++ compile_extension, ++ verbose_c_extension, ++ keep_asserts_in_extension, ++ skip_actions=skip_actions, ++ ) ++ ++ return grammar, parser, tokenizer, gen +diff --git a/Tools/peg_generator/pegen/c_generator.py b/Tools/peg_generator/pegen/c_generator.py +new file mode 100644 +--- /dev/null ++++ b/Tools/peg_generator/pegen/c_generator.py +@@ -0,0 +1,605 @@ ++import ast ++import re ++from typing import Any, cast, Dict, IO, Optional, List, Text, Tuple ++ ++from pegen.grammar import ( ++ Cut, ++ GrammarVisitor, ++ Rhs, ++ Alt, ++ NamedItem, ++ NameLeaf, ++ StringLeaf, ++ Lookahead, ++ PositiveLookahead, ++ NegativeLookahead, ++ Opt, ++ Repeat0, ++ Repeat1, ++ Gather, ++ Group, ++ Rule, ++) ++from pegen import grammar ++from pegen.parser_generator import dedupe, ParserGenerator ++from pegen.tokenizer import exact_token_types ++ ++EXTENSION_PREFIX = """\ ++#include "pegen.h" ++ ++""" ++ ++EXTENSION_SUFFIX = """ ++void * ++_PyPegen_parse(Parser *p) ++{ ++ // Initialize keywords ++ p->keywords = reserved_keywords; ++ p->n_keyword_lists = n_keyword_lists; ++ ++ return start_rule(p); ++} ++""" ++ ++ ++class CCallMakerVisitor(GrammarVisitor): ++ def __init__(self, parser_generator: ParserGenerator): ++ self.gen = parser_generator ++ self.cache: Dict[Any, Any] = {} ++ self.keyword_cache: Dict[str, int] = {} ++ ++ def keyword_helper(self, keyword: str) -> Tuple[str, str]: ++ if keyword not in self.keyword_cache: ++ self.keyword_cache[keyword] = self.gen.keyword_type() ++ return "keyword", f"_PyPegen_expect_token(p, {self.keyword_cache[keyword]})" ++ ++ def visit_NameLeaf(self, node: NameLeaf) -> Tuple[str, str]: ++ name = node.value ++ if name in ("NAME", "NUMBER", "STRING"): ++ name = name.lower() ++ return f"{name}_var", f"_PyPegen_{name}_token(p)" ++ if name in ("NEWLINE", "DEDENT", "INDENT", "ENDMARKER", "ASYNC", "AWAIT"): ++ name = name.lower() ++ return f"{name}_var", f"_PyPegen_{name}_token(p)" ++ return f"{name}_var", f"{name}_rule(p)" ++ ++ def visit_StringLeaf(self, node: StringLeaf) -> Tuple[str, str]: ++ val = ast.literal_eval(node.value) ++ if re.match(r"[a-zA-Z_]\w*\Z", val): # This is a keyword ++ return self.keyword_helper(val) ++ else: ++ assert val in exact_token_types, f"{node.value} is not a known literal" ++ type = exact_token_types[val] ++ return "literal", f"_PyPegen_expect_token(p, {type})" ++ ++ def visit_Rhs(self, node: Rhs) -> Tuple[Optional[str], str]: ++ if node in self.cache: ++ return self.cache[node] ++ if len(node.alts) == 1 and len(node.alts[0].items) == 1: ++ self.cache[node] = self.visit(node.alts[0].items[0]) ++ else: ++ name = self.gen.name_node(node) ++ self.cache[node] = f"{name}_var", f"{name}_rule(p)" ++ return self.cache[node] ++ ++ def visit_NamedItem(self, node: NamedItem) -> Tuple[Optional[str], str]: ++ name, call = self.visit(node.item) ++ if node.name: ++ name = node.name ++ return name, call ++ ++ def lookahead_call_helper(self, node: Lookahead, positive: int) -> Tuple[None, str]: ++ name, call = self.visit(node.node) ++ func, args = call.split("(", 1) ++ assert args[-1] == ")" ++ args = args[:-1] ++ if not args.startswith("p,"): ++ return None, f"_PyPegen_lookahead({positive}, {func}, {args})" ++ elif args[2:].strip().isalnum(): ++ return None, f"_PyPegen_lookahead_with_int({positive}, {func}, {args})" ++ else: ++ return None, f"_PyPegen_lookahead_with_string({positive}, {func}, {args})" ++ ++ def visit_PositiveLookahead(self, node: PositiveLookahead) -> Tuple[None, str]: ++ return self.lookahead_call_helper(node, 1) ++ ++ def visit_NegativeLookahead(self, node: NegativeLookahead) -> Tuple[None, str]: ++ return self.lookahead_call_helper(node, 0) ++ ++ def visit_Opt(self, node: Opt) -> Tuple[str, str]: ++ name, call = self.visit(node.node) ++ return "opt_var", f"{call}, 1" # Using comma operator! ++ ++ def visit_Repeat0(self, node: Repeat0) -> Tuple[str, str]: ++ if node in self.cache: ++ return self.cache[node] ++ name = self.gen.name_loop(node.node, False) ++ self.cache[node] = f"{name}_var", f"{name}_rule(p)" ++ return self.cache[node] ++ ++ def visit_Repeat1(self, node: Repeat1) -> Tuple[str, str]: ++ if node in self.cache: ++ return self.cache[node] ++ name = self.gen.name_loop(node.node, True) ++ self.cache[node] = f"{name}_var", f"{name}_rule(p)" ++ return self.cache[node] ++ ++ def visit_Gather(self, node: Gather) -> Tuple[str, str]: ++ if node in self.cache: ++ return self.cache[node] ++ name = self.gen.name_gather(node) ++ self.cache[node] = f"{name}_var", f"{name}_rule(p)" ++ return self.cache[node] ++ ++ def visit_Group(self, node: Group) -> Tuple[Optional[str], str]: ++ return self.visit(node.rhs) ++ ++ def visit_Cut(self, node: Cut) -> Tuple[str, str]: ++ return "cut_var", "1" ++ ++ ++class CParserGenerator(ParserGenerator, GrammarVisitor): ++ def __init__( ++ self, ++ grammar: grammar.Grammar, ++ file: Optional[IO[Text]], ++ debug: bool = False, ++ skip_actions: bool = False, ++ ): ++ super().__init__(grammar, file) ++ self.callmakervisitor: CCallMakerVisitor = CCallMakerVisitor(self) ++ self._varname_counter = 0 ++ self.debug = debug ++ self.skip_actions = skip_actions ++ ++ def unique_varname(self, name: str = "tmpvar") -> str: ++ new_var = name + "_" + str(self._varname_counter) ++ self._varname_counter += 1 ++ return new_var ++ ++ def call_with_errorcheck_return(self, call_text: str, returnval: str) -> None: ++ error_var = self.unique_varname() ++ self.print(f"int {error_var} = {call_text};") ++ self.print(f"if ({error_var}) {{") ++ with self.indent(): ++ self.print(f"return {returnval};") ++ self.print(f"}}") ++ ++ def call_with_errorcheck_goto(self, call_text: str, goto_target: str) -> None: ++ error_var = self.unique_varname() ++ self.print(f"int {error_var} = {call_text};") ++ self.print(f"if ({error_var}) {{") ++ with self.indent(): ++ self.print(f"goto {goto_target};") ++ self.print(f"}}") ++ ++ def out_of_memory_return( ++ self, expr: str, returnval: str, message: str = "Parser out of memory", cleanup_code=None ++ ) -> None: ++ self.print(f"if ({expr}) {{") ++ with self.indent(): ++ self.print(f'PyErr_Format(PyExc_MemoryError, "{message}");') ++ if cleanup_code is not None: ++ self.print(cleanup_code) ++ self.print(f"return {returnval};") ++ self.print(f"}}") ++ ++ def out_of_memory_goto( ++ self, expr: str, goto_target: str, message: str = "Parser out of memory" ++ ) -> None: ++ self.print(f"if ({expr}) {{") ++ with self.indent(): ++ self.print(f'PyErr_Format(PyExc_MemoryError, "{message}");') ++ self.print(f"goto {goto_target};") ++ self.print(f"}}") ++ ++ def generate(self, filename: str) -> None: ++ self.collect_todo() ++ self.print(f"// @generated by pegen.py from {filename}") ++ header = self.grammar.metas.get("header", EXTENSION_PREFIX) ++ if header: ++ self.print(header.rstrip("\n")) ++ subheader = self.grammar.metas.get("subheader", "") ++ if subheader: ++ self.print(subheader) ++ self._setup_keywords() ++ for i, (rulename, rule) in enumerate(self.todo.items(), 1000): ++ comment = " // Left-recursive" if rule.left_recursive else "" ++ self.print(f"#define {rulename}_type {i}{comment}") ++ self.print() ++ for rulename, rule in self.todo.items(): ++ if rule.is_loop() or rule.is_gather(): ++ type = "asdl_seq *" ++ elif rule.type: ++ type = rule.type + " " ++ else: ++ type = "void *" ++ self.print(f"static {type}{rulename}_rule(Parser *p);") ++ self.print() ++ while self.todo: ++ for rulename, rule in list(self.todo.items()): ++ del self.todo[rulename] ++ self.print() ++ if rule.left_recursive: ++ self.print("// Left-recursive") ++ self.visit(rule) ++ if self.skip_actions: ++ mode = 0 ++ else: ++ mode = int(self.rules["start"].type == "mod_ty") if "start" in self.rules else 1 ++ if mode == 1 and self.grammar.metas.get("bytecode"): ++ mode += 1 ++ modulename = self.grammar.metas.get("modulename", "parse") ++ trailer = self.grammar.metas.get("trailer", EXTENSION_SUFFIX) ++ keyword_cache = self.callmakervisitor.keyword_cache ++ if trailer: ++ self.print(trailer.rstrip("\n") % dict(mode=mode, modulename=modulename)) ++ ++ def _group_keywords_by_length(self) -> Dict[int, List[Tuple[str, int]]]: ++ groups: Dict[int, List[Tuple[str, int]]] = {} ++ for keyword_str, keyword_type in self.callmakervisitor.keyword_cache.items(): ++ length = len(keyword_str) ++ if length in groups: ++ groups[length].append((keyword_str, keyword_type)) ++ else: ++ groups[length] = [(keyword_str, keyword_type)] ++ return groups ++ ++ def _setup_keywords(self) -> None: ++ keyword_cache = self.callmakervisitor.keyword_cache ++ n_keyword_lists = ( ++ len(max(keyword_cache.keys(), key=len)) + 1 if len(keyword_cache) > 0 else 0 ++ ) ++ self.print(f"static const int n_keyword_lists = {n_keyword_lists};") ++ groups = self._group_keywords_by_length() ++ self.print("static KeywordToken *reserved_keywords[] = {") ++ with self.indent(): ++ num_groups = max(groups) + 1 if groups else 1 ++ for keywords_length in range(num_groups): ++ if keywords_length not in groups.keys(): ++ self.print("NULL,") ++ else: ++ self.print("(KeywordToken[]) {") ++ with self.indent(): ++ for keyword_str, keyword_type in groups[keywords_length]: ++ self.print(f'{{"{keyword_str}", {keyword_type}}},') ++ self.print("{NULL, -1},") ++ self.print("},") ++ self.print("};") ++ ++ def _set_up_token_start_metadata_extraction(self) -> None: ++ self.print("if (p->mark == p->fill && _PyPegen_fill_token(p) < 0) {") ++ with self.indent(): ++ self.print("p->error_indicator = 1;") ++ self.print("return NULL;") ++ self.print("}") ++ self.print("int start_lineno = p->tokens[mark]->lineno;") ++ self.print("UNUSED(start_lineno); // Only used by EXTRA macro") ++ self.print("int start_col_offset = p->tokens[mark]->col_offset;") ++ self.print("UNUSED(start_col_offset); // Only used by EXTRA macro") ++ ++ def _set_up_token_end_metadata_extraction(self) -> None: ++ self.print("Token *token = _PyPegen_get_last_nonnwhitespace_token(p);") ++ self.print("if (token == NULL) {") ++ with self.indent(): ++ self.print("return NULL;") ++ self.print("}") ++ self.print(f"int end_lineno = token->end_lineno;") ++ self.print("UNUSED(end_lineno); // Only used by EXTRA macro") ++ self.print(f"int end_col_offset = token->end_col_offset;") ++ self.print("UNUSED(end_col_offset); // Only used by EXTRA macro") ++ ++ def _set_up_rule_memoization(self, node: Rule, result_type: str) -> None: ++ self.print("{") ++ with self.indent(): ++ self.print(f"{result_type} res = NULL;") ++ self.print(f"if (_PyPegen_is_memoized(p, {node.name}_type, &res))") ++ with self.indent(): ++ self.print("return res;") ++ self.print("int mark = p->mark;") ++ self.print("int resmark = p->mark;") ++ self.print("while (1) {") ++ with self.indent(): ++ self.call_with_errorcheck_return( ++ f"_PyPegen_update_memo(p, mark, {node.name}_type, res)", "res" ++ ) ++ self.print("p->mark = mark;") ++ self.print(f"void *raw = {node.name}_raw(p);") ++ self.print("if (raw == NULL || p->mark <= resmark)") ++ with self.indent(): ++ self.print("break;") ++ self.print("resmark = p->mark;") ++ self.print("res = raw;") ++ self.print("}") ++ self.print("p->mark = resmark;") ++ self.print("return res;") ++ self.print("}") ++ self.print(f"static {result_type}") ++ self.print(f"{node.name}_raw(Parser *p)") ++ ++ def _should_memoize(self, node: Rule) -> bool: ++ return node.memo and not node.left_recursive ++ ++ def _handle_default_rule_body(self, node: Rule, rhs: Rhs, result_type: str) -> None: ++ memoize = self._should_memoize(node) ++ ++ with self.indent(): ++ self.print("if (p->error_indicator) {") ++ with self.indent(): ++ self.print("return NULL;") ++ self.print("}") ++ self.print(f"{result_type} res = NULL;") ++ if memoize: ++ self.print(f"if (_PyPegen_is_memoized(p, {node.name}_type, &res))") ++ with self.indent(): ++ self.print("return res;") ++ self.print("int mark = p->mark;") ++ if any(alt.action and "EXTRA" in alt.action for alt in rhs.alts): ++ self._set_up_token_start_metadata_extraction() ++ self.visit( ++ rhs, ++ is_loop=False, ++ is_gather=node.is_gather(), ++ rulename=node.name if memoize else None, ++ ) ++ if self.debug: ++ self.print(f'fprintf(stderr, "Fail at %d: {node.name}\\n", p->mark);') ++ self.print("res = NULL;") ++ self.print(" done:") ++ with self.indent(): ++ if memoize: ++ self.print(f"_PyPegen_insert_memo(p, mark, {node.name}_type, res);") ++ self.print("return res;") ++ ++ def _handle_loop_rule_body(self, node: Rule, rhs: Rhs) -> None: ++ memoize = self._should_memoize(node) ++ is_repeat1 = node.name.startswith("_loop1") ++ ++ with self.indent(): ++ self.print("if (p->error_indicator) {") ++ with self.indent(): ++ self.print("return NULL;") ++ self.print("}") ++ self.print(f"void *res = NULL;") ++ if memoize: ++ self.print(f"if (_PyPegen_is_memoized(p, {node.name}_type, &res))") ++ with self.indent(): ++ self.print("return res;") ++ self.print("int mark = p->mark;") ++ self.print("int start_mark = p->mark;") ++ self.print("void **children = PyMem_Malloc(sizeof(void *));") ++ self.out_of_memory_return(f"!children", "NULL") ++ self.print("ssize_t children_capacity = 1;") ++ self.print("ssize_t n = 0;") ++ if any(alt.action and "EXTRA" in alt.action for alt in rhs.alts): ++ self._set_up_token_start_metadata_extraction() ++ self.visit( ++ rhs, ++ is_loop=True, ++ is_gather=node.is_gather(), ++ rulename=node.name if memoize else None, ++ ) ++ if is_repeat1: ++ self.print("if (n == 0) {") ++ with self.indent(): ++ self.print("PyMem_Free(children);") ++ self.print("return NULL;") ++ self.print("}") ++ self.print("asdl_seq *seq = _Py_asdl_seq_new(n, p->arena);") ++ self.out_of_memory_return( ++ f"!seq", ++ "NULL", ++ message=f"asdl_seq_new {node.name}", ++ cleanup_code="PyMem_Free(children);", ++ ) ++ self.print("for (int i = 0; i < n; i++) asdl_seq_SET(seq, i, children[i]);") ++ self.print("PyMem_Free(children);") ++ if node.name: ++ self.print(f"_PyPegen_insert_memo(p, start_mark, {node.name}_type, seq);") ++ self.print("return seq;") ++ ++ def visit_Rule(self, node: Rule) -> None: ++ is_loop = node.is_loop() ++ is_gather = node.is_gather() ++ rhs = node.flatten() ++ if is_loop or is_gather: ++ result_type = "asdl_seq *" ++ elif node.type: ++ result_type = node.type ++ else: ++ result_type = "void *" ++ ++ for line in str(node).splitlines(): ++ self.print(f"// {line}") ++ if node.left_recursive and node.leader: ++ self.print(f"static {result_type} {node.name}_raw(Parser *);") ++ ++ self.print(f"static {result_type}") ++ self.print(f"{node.name}_rule(Parser *p)") ++ ++ if node.left_recursive and node.leader: ++ self._set_up_rule_memoization(node, result_type) ++ ++ self.print("{") ++ if is_loop: ++ self._handle_loop_rule_body(node, rhs) ++ else: ++ self._handle_default_rule_body(node, rhs, result_type) ++ self.print("}") ++ ++ def visit_NamedItem(self, node: NamedItem, names: List[str]) -> None: ++ name, call = self.callmakervisitor.visit(node) ++ if not name: ++ self.print(call) ++ else: ++ name = dedupe(name, names) ++ self.print(f"({name} = {call})") ++ ++ def visit_Rhs( ++ self, node: Rhs, is_loop: bool, is_gather: bool, rulename: Optional[str] ++ ) -> None: ++ if is_loop: ++ assert len(node.alts) == 1 ++ for alt in node.alts: ++ self.visit(alt, is_loop=is_loop, is_gather=is_gather, rulename=rulename) ++ ++ def join_conditions(self, keyword: str, node: Any, names: List[str]) -> None: ++ self.print(f"{keyword} (") ++ with self.indent(): ++ first = True ++ for item in node.items: ++ if first: ++ first = False ++ else: ++ self.print("&&") ++ self.visit(item, names=names) ++ self.print(")") ++ ++ def emit_action(self, node: Alt, cleanup_code=None) -> None: ++ self.print(f"res = {node.action};") ++ ++ self.print("if (res == NULL && PyErr_Occurred()) {") ++ with self.indent(): ++ self.print("p->error_indicator = 1;") ++ if cleanup_code: ++ self.print(cleanup_code) ++ self.print("return NULL;") ++ self.print("}") ++ ++ if self.debug: ++ self.print( ++ f'fprintf(stderr, "Hit with action [%d-%d]: %s\\n", mark, p->mark, "{node}");' ++ ) ++ ++ def emit_default_action(self, is_gather: bool, names: List[str], node: Alt) -> None: ++ if len(names) > 1: ++ if is_gather: ++ assert len(names) == 2 ++ self.print(f"res = _PyPegen_seq_insert_in_front(p, {names[0]}, {names[1]});") ++ else: ++ if self.debug: ++ self.print( ++ f'fprintf(stderr, "Hit without action [%d:%d]: %s\\n", mark, p->mark, "{node}");' ++ ) ++ self.print(f"res = _PyPegen_dummy_name(p, {', '.join(names)});") ++ else: ++ if self.debug: ++ self.print( ++ f'fprintf(stderr, "Hit with default action [%d:%d]: %s\\n", mark, p->mark, "{node}");' ++ ) ++ self.print(f"res = {names[0]};") ++ ++ def emit_dummy_action(self) -> None: ++ self.print(f"res = _PyPegen_dummy_name(p);") ++ ++ def handle_alt_normal(self, node: Alt, is_gather: bool, names: List[str]) -> None: ++ self.join_conditions(keyword="if", node=node, names=names) ++ self.print("{") ++ # We have parsed successfully all the conditions for the option. ++ with self.indent(): ++ # Prepare to emmit the rule action and do so ++ if node.action and "EXTRA" in node.action: ++ self._set_up_token_end_metadata_extraction() ++ if self.skip_actions: ++ self.emit_dummy_action() ++ elif node.action: ++ self.emit_action(node) ++ else: ++ self.emit_default_action(is_gather, names, node) ++ ++ # As the current option has parsed correctly, do not continue with the rest. ++ self.print(f"goto done;") ++ self.print("}") ++ ++ def handle_alt_loop( ++ self, node: Alt, is_gather: bool, rulename: Optional[str], names: List[str] ++ ) -> None: ++ # Condition of the main body of the alternative ++ self.join_conditions(keyword="while", node=node, names=names) ++ self.print("{") ++ # We have parsed successfully one item! ++ with self.indent(): ++ # Prepare to emit the rule action and do so ++ if node.action and "EXTRA" in node.action: ++ self._set_up_token_end_metadata_extraction() ++ if self.skip_actions: ++ self.emit_dummy_action() ++ elif node.action: ++ self.emit_action(node, cleanup_code="PyMem_Free(children);") ++ else: ++ self.emit_default_action(is_gather, names, node) ++ ++ # Add the result of rule to the temporary buffer of children. This buffer ++ # will populate later an asdl_seq with all elements to return. ++ self.print("if (n == children_capacity) {") ++ with self.indent(): ++ self.print("children_capacity *= 2;") ++ self.print("children = PyMem_Realloc(children, children_capacity*sizeof(void *));") ++ self.out_of_memory_return(f"!children", "NULL", message=f"realloc {rulename}") ++ self.print("}") ++ self.print(f"children[n++] = res;") ++ self.print("mark = p->mark;") ++ self.print("}") ++ ++ def visit_Alt( ++ self, node: Alt, is_loop: bool, is_gather: bool, rulename: Optional[str] ++ ) -> None: ++ self.print(f"{{ // {node}") ++ with self.indent(): ++ # Prepare variable declarations for the alternative ++ vars = self.collect_vars(node) ++ for v, var_type in sorted(item for item in vars.items() if item[0] is not None): ++ if not var_type: ++ var_type = "void *" ++ else: ++ var_type += " " ++ if v == "cut_var": ++ v += " = 0" # cut_var must be initialized ++ self.print(f"{var_type}{v};") ++ if v == "opt_var": ++ self.print("UNUSED(opt_var); // Silence compiler warnings") ++ ++ names: List[str] = [] ++ if is_loop: ++ self.handle_alt_loop(node, is_gather, rulename, names) ++ else: ++ self.handle_alt_normal(node, is_gather, names) ++ ++ self.print("p->mark = mark;") ++ if "cut_var" in names: ++ self.print("if (cut_var) return NULL;") ++ self.print("}") ++ ++ def collect_vars(self, node: Alt) -> Dict[str, Optional[str]]: ++ names: List[str] = [] ++ types = {} ++ for item in node.items: ++ name, type = self.add_var(item, names) ++ types[name] = type ++ return types ++ ++ def add_var(self, node: NamedItem, names: List[str]) -> Tuple[str, Optional[str]]: ++ name: str ++ call: str ++ name, call = self.callmakervisitor.visit(node.item) ++ type = None ++ if not name: ++ return name, type ++ if name.startswith("cut"): ++ return name, "int" ++ if name.endswith("_var"): ++ rulename = name[:-4] ++ rule = self.rules.get(rulename) ++ if rule is not None: ++ if rule.is_loop() or rule.is_gather(): ++ type = "asdl_seq *" ++ else: ++ type = rule.type ++ elif name.startswith("_loop") or name.startswith("_gather"): ++ type = "asdl_seq *" ++ elif name in ("name_var", "string_var", "number_var"): ++ type = "expr_ty" ++ if node.name: ++ name = node.name ++ name = dedupe(name, names) ++ return name, type +diff --git a/Tools/peg_generator/pegen/first_sets.py b/Tools/peg_generator/pegen/first_sets.py +new file mode 100644 +--- /dev/null ++++ b/Tools/peg_generator/pegen/first_sets.py +@@ -0,0 +1,153 @@ ++#!/usr/bin/env python3.8 ++ ++import argparse ++import collections ++import pprint ++import sys ++from typing import Optional, Set, Dict ++ ++from pegen.build import build_parser ++from pegen.grammar import ( ++ Alt, ++ Cut, ++ Gather, ++ Grammar, ++ GrammarVisitor, ++ Group, ++ Leaf, ++ Lookahead, ++ NamedItem, ++ NameLeaf, ++ NegativeLookahead, ++ Opt, ++ Repeat, ++ Repeat0, ++ Repeat1, ++ Rhs, ++ Rule, ++ StringLeaf, ++ PositiveLookahead, ++) ++ ++argparser = argparse.ArgumentParser( ++ prog="calculate_first_sets", description="Calculate the first sets of a grammar", ++) ++argparser.add_argument("grammar_file", help="The grammar file") ++ ++ ++class FirstSetCalculator(GrammarVisitor): ++ def __init__(self, rules: Dict[str, Rule]) -> None: ++ self.rules = rules ++ for rule in rules.values(): ++ rule.nullable_visit(rules) ++ self.first_sets: Dict[str, Set[str]] = dict() ++ self.in_process: Set[str] = set() ++ ++ def calculate(self) -> Dict[str, Set[str]]: ++ for name, rule in self.rules.items(): ++ self.visit(rule) ++ return self.first_sets ++ ++ def visit_Alt(self, item: Alt) -> Set[str]: ++ result: Set[str] = set() ++ to_remove: Set[str] = set() ++ for other in item.items: ++ new_terminals = self.visit(other) ++ if isinstance(other.item, NegativeLookahead): ++ to_remove |= new_terminals ++ result |= new_terminals ++ if to_remove: ++ result -= to_remove ++ ++ # If the set of new terminals can start with the empty string, ++ # it means that the item is completelly nullable and we should ++ # also considering at least the next item in case the current ++ # one fails to parse. ++ ++ if "" in new_terminals: ++ continue ++ ++ if not isinstance(other.item, (Opt, NegativeLookahead, Repeat0)): ++ break ++ ++ # Do not allow the empty string to propagate. ++ result.discard("") ++ ++ return result ++ ++ def visit_Cut(self, item: Cut) -> Set[str]: ++ return set() ++ ++ def visit_Group(self, item: Group) -> Set[str]: ++ return self.visit(item.rhs) ++ ++ def visit_PositiveLookahead(self, item: Lookahead) -> Set[str]: ++ return self.visit(item.node) ++ ++ def visit_NegativeLookahead(self, item: NegativeLookahead) -> Set[str]: ++ return self.visit(item.node) ++ ++ def visit_NamedItem(self, item: NamedItem) -> Set[str]: ++ return self.visit(item.item) ++ ++ def visit_Opt(self, item: Opt) -> Set[str]: ++ return self.visit(item.node) ++ ++ def visit_Gather(self, item: Gather) -> Set[str]: ++ return self.visit(item.node) ++ ++ def visit_Repeat0(self, item: Repeat0) -> Set[str]: ++ return self.visit(item.node) ++ ++ def visit_Repeat1(self, item: Repeat1) -> Set[str]: ++ return self.visit(item.node) ++ ++ def visit_NameLeaf(self, item: NameLeaf) -> Set[str]: ++ if item.value not in self.rules: ++ return {item.value} ++ ++ if item.value not in self.first_sets: ++ self.first_sets[item.value] = self.visit(self.rules[item.value]) ++ return self.first_sets[item.value] ++ elif item.value in self.in_process: ++ return set() ++ ++ return self.first_sets[item.value] ++ ++ def visit_StringLeaf(self, item: StringLeaf) -> Set[str]: ++ return {item.value} ++ ++ def visit_Rhs(self, item: Rhs) -> Set[str]: ++ result: Set[str] = set() ++ for alt in item.alts: ++ result |= self.visit(alt) ++ return result ++ ++ def visit_Rule(self, item: Rule) -> Set[str]: ++ if item.name in self.in_process: ++ return set() ++ elif item.name not in self.first_sets: ++ self.in_process.add(item.name) ++ terminals = self.visit(item.rhs) ++ if item.nullable: ++ terminals.add("") ++ self.first_sets[item.name] = terminals ++ self.in_process.remove(item.name) ++ return self.first_sets[item.name] ++ ++ ++def main() -> None: ++ args = argparser.parse_args() ++ ++ try: ++ grammar, parser, tokenizer = build_parser(args.grammar_file) ++ except Exception as err: ++ print("ERROR: Failed to parse grammar file", file=sys.stderr) ++ sys.exit(1) ++ ++ firs_sets = FirstSetCalculator(grammar.rules).calculate() ++ pprint.pprint(firs_sets) ++ ++ ++if __name__ == "__main__": ++ main() +diff --git a/Tools/peg_generator/pegen/grammar.py b/Tools/peg_generator/pegen/grammar.py +new file mode 100644 +--- /dev/null ++++ b/Tools/peg_generator/pegen/grammar.py +@@ -0,0 +1,470 @@ ++from __future__ import annotations ++ ++from abc import abstractmethod ++from typing import ( ++ AbstractSet, ++ Any, ++ Callable, ++ Dict, ++ Iterable, ++ Iterator, ++ List, ++ Optional, ++ Set, ++ Tuple, ++ TYPE_CHECKING, ++ TypeVar, ++ Union, ++) ++ ++from pegen.parser import memoize, Parser ++ ++if TYPE_CHECKING: ++ from pegen.parser_generator import ParserGenerator ++ ++ ++class GrammarError(Exception): ++ pass ++ ++ ++class GrammarVisitor: ++ def visit(self, node: Any, *args: Any, **kwargs: Any) -> Any: ++ """Visit a node.""" ++ method = "visit_" + node.__class__.__name__ ++ visitor = getattr(self, method, self.generic_visit) ++ return visitor(node, *args, **kwargs) ++ ++ def generic_visit(self, node: Iterable[Any], *args: Any, **kwargs: Any) -> None: ++ """Called if no explicit visitor function exists for a node.""" ++ for value in node: ++ if isinstance(value, list): ++ for item in value: ++ self.visit(item, *args, **kwargs) ++ else: ++ self.visit(value, *args, **kwargs) ++ ++ ++class Grammar: ++ def __init__(self, rules: Iterable[Rule], metas: Iterable[Tuple[str, Optional[str]]]): ++ self.rules = {rule.name: rule for rule in rules} ++ self.metas = dict(metas) ++ ++ def __str__(self) -> str: ++ return "\n".join(str(rule) for name, rule in self.rules.items()) ++ ++ def __repr__(self) -> str: ++ lines = ["Grammar("] ++ lines.append(" [") ++ for rule in self.rules.values(): ++ lines.append(f" {repr(rule)},") ++ lines.append(" ],") ++ lines.append(" {repr(list(self.metas.items()))}") ++ lines.append(")") ++ return "\n".join(lines) ++ ++ def __iter__(self) -> Iterator[Rule]: ++ yield from self.rules.values() ++ ++ ++# Global flag whether we want actions in __str__() -- default off. ++SIMPLE_STR = True ++ ++ ++class Rule: ++ def __init__(self, name: str, type: Optional[str], rhs: Rhs, memo: Optional[object] = None): ++ self.name = name ++ self.type = type ++ self.rhs = rhs ++ self.memo = bool(memo) ++ self.visited = False ++ self.nullable = False ++ self.left_recursive = False ++ self.leader = False ++ ++ def is_loop(self) -> bool: ++ return self.name.startswith("_loop") ++ ++ def is_gather(self) -> bool: ++ return self.name.startswith("_gather") ++ ++ def __str__(self) -> str: ++ if SIMPLE_STR or self.type is None: ++ res = f"{self.name}: {self.rhs}" ++ else: ++ res = f"{self.name}[{self.type}]: {self.rhs}" ++ if len(res) < 88: ++ return res ++ lines = [res.split(":")[0] + ":"] ++ lines += [f" | {alt}" for alt in self.rhs.alts] ++ return "\n".join(lines) ++ ++ def __repr__(self) -> str: ++ return f"Rule({self.name!r}, {self.type!r}, {self.rhs!r})" ++ ++ def __iter__(self) -> Iterator[Rhs]: ++ yield self.rhs ++ ++ def nullable_visit(self, rules: Dict[str, Rule]) -> bool: ++ if self.visited: ++ # A left-recursive rule is considered non-nullable. ++ return False ++ self.visited = True ++ self.nullable = self.rhs.nullable_visit(rules) ++ return self.nullable ++ ++ def initial_names(self) -> AbstractSet[str]: ++ return self.rhs.initial_names() ++ ++ def flatten(self) -> Rhs: ++ # If it's a single parenthesized group, flatten it. ++ rhs = self.rhs ++ if ( ++ not self.is_loop() ++ and len(rhs.alts) == 1 ++ and len(rhs.alts[0].items) == 1 ++ and isinstance(rhs.alts[0].items[0].item, Group) ++ ): ++ rhs = rhs.alts[0].items[0].item.rhs ++ return rhs ++ ++ def collect_todo(self, gen: ParserGenerator) -> None: ++ rhs = self.flatten() ++ rhs.collect_todo(gen) ++ ++ ++class Leaf: ++ def __init__(self, value: str): ++ self.value = value ++ ++ def __str__(self) -> str: ++ return self.value ++ ++ def __iter__(self) -> Iterable[str]: ++ if False: ++ yield ++ ++ @abstractmethod ++ def nullable_visit(self, rules: Dict[str, Rule]) -> bool: ++ raise NotImplementedError ++ ++ @abstractmethod ++ def initial_names(self) -> AbstractSet[str]: ++ raise NotImplementedError ++ ++ ++class NameLeaf(Leaf): ++ """The value is the name.""" ++ ++ def __str__(self) -> str: ++ if self.value == "ENDMARKER": ++ return "$" ++ return super().__str__() ++ ++ def __repr__(self) -> str: ++ return f"NameLeaf({self.value!r})" ++ ++ def nullable_visit(self, rules: Dict[str, Rule]) -> bool: ++ if self.value in rules: ++ return rules[self.value].nullable_visit(rules) ++ # Token or unknown; never empty. ++ return False ++ ++ def initial_names(self) -> AbstractSet[str]: ++ return {self.value} ++ ++ ++class StringLeaf(Leaf): ++ """The value is a string literal, including quotes.""" ++ ++ def __repr__(self) -> str: ++ return f"StringLeaf({self.value!r})" ++ ++ def nullable_visit(self, rules: Dict[str, Rule]) -> bool: ++ # The string token '' is considered empty. ++ return not self.value ++ ++ def initial_names(self) -> AbstractSet[str]: ++ return set() ++ ++ ++class Rhs: ++ def __init__(self, alts: List[Alt]): ++ self.alts = alts ++ self.memo: Optional[Tuple[Optional[str], str]] = None ++ ++ def __str__(self) -> str: ++ return " | ".join(str(alt) for alt in self.alts) ++ ++ def __repr__(self) -> str: ++ return f"Rhs({self.alts!r})" ++ ++ def __iter__(self) -> Iterator[List[Alt]]: ++ yield self.alts ++ ++ def nullable_visit(self, rules: Dict[str, Rule]) -> bool: ++ for alt in self.alts: ++ if alt.nullable_visit(rules): ++ return True ++ return False ++ ++ def initial_names(self) -> AbstractSet[str]: ++ names: Set[str] = set() ++ for alt in self.alts: ++ names |= alt.initial_names() ++ return names ++ ++ def collect_todo(self, gen: ParserGenerator) -> None: ++ for alt in self.alts: ++ alt.collect_todo(gen) ++ ++ ++class Alt: ++ def __init__(self, items: List[NamedItem], *, icut: int = -1, action: Optional[str] = None): ++ self.items = items ++ self.icut = icut ++ self.action = action ++ ++ def __str__(self) -> str: ++ core = " ".join(str(item) for item in self.items) ++ if not SIMPLE_STR and self.action: ++ return f"{core} {{ {self.action} }}" ++ else: ++ return core ++ ++ def __repr__(self) -> str: ++ args = [repr(self.items)] ++ if self.icut >= 0: ++ args.append(f"icut={self.icut}") ++ if self.action: ++ args.append(f"action={self.action!r}") ++ return f"Alt({', '.join(args)})" ++ ++ def __iter__(self) -> Iterator[List[NamedItem]]: ++ yield self.items ++ ++ def nullable_visit(self, rules: Dict[str, Rule]) -> bool: ++ for item in self.items: ++ if not item.nullable_visit(rules): ++ return False ++ return True ++ ++ def initial_names(self) -> AbstractSet[str]: ++ names: Set[str] = set() ++ for item in self.items: ++ names |= item.initial_names() ++ if not item.nullable: ++ break ++ return names ++ ++ def collect_todo(self, gen: ParserGenerator) -> None: ++ for item in self.items: ++ item.collect_todo(gen) ++ ++ ++class NamedItem: ++ def __init__(self, name: Optional[str], item: Item): ++ self.name = name ++ self.item = item ++ self.nullable = False ++ ++ def __str__(self) -> str: ++ if not SIMPLE_STR and self.name: ++ return f"{self.name}={self.item}" ++ else: ++ return str(self.item) ++ ++ def __repr__(self) -> str: ++ return f"NamedItem({self.name!r}, {self.item!r})" ++ ++ def __iter__(self) -> Iterator[Item]: ++ yield self.item ++ ++ def nullable_visit(self, rules: Dict[str, Rule]) -> bool: ++ self.nullable = self.item.nullable_visit(rules) ++ return self.nullable ++ ++ def initial_names(self) -> AbstractSet[str]: ++ return self.item.initial_names() ++ ++ def collect_todo(self, gen: ParserGenerator) -> None: ++ gen.callmakervisitor.visit(self.item) ++ ++ ++class Lookahead: ++ def __init__(self, node: Plain, sign: str): ++ self.node = node ++ self.sign = sign ++ ++ def __str__(self) -> str: ++ return f"{self.sign}{self.node}" ++ ++ def __iter__(self) -> Iterator[Plain]: ++ yield self.node ++ ++ def nullable_visit(self, rules: Dict[str, Rule]) -> bool: ++ return True ++ ++ def initial_names(self) -> AbstractSet[str]: ++ return set() ++ ++ ++class PositiveLookahead(Lookahead): ++ def __init__(self, node: Plain): ++ super().__init__(node, "&") ++ ++ def __repr__(self) -> str: ++ return f"PositiveLookahead({self.node!r})" ++ ++ ++class NegativeLookahead(Lookahead): ++ def __init__(self, node: Plain): ++ super().__init__(node, "!") ++ ++ def __repr__(self) -> str: ++ return f"NegativeLookahead({self.node!r})" ++ ++ ++class Opt: ++ def __init__(self, node: Item): ++ self.node = node ++ ++ def __str__(self) -> str: ++ s = str(self.node) ++ # TODO: Decide whether to use [X] or X? based on type of X ++ if " " in s: ++ return f"[{s}]" ++ else: ++ return f"{s}?" ++ ++ def __repr__(self) -> str: ++ return f"Opt({self.node!r})" ++ ++ def __iter__(self) -> Iterator[Item]: ++ yield self.node ++ ++ def nullable_visit(self, rules: Dict[str, Rule]) -> bool: ++ return True ++ ++ def initial_names(self) -> AbstractSet[str]: ++ return self.node.initial_names() ++ ++ ++class Repeat: ++ """Shared base class for x* and x+.""" ++ ++ def __init__(self, node: Plain): ++ self.node = node ++ self.memo: Optional[Tuple[Optional[str], str]] = None ++ ++ @abstractmethod ++ def nullable_visit(self, rules: Dict[str, Rule]) -> bool: ++ raise NotImplementedError ++ ++ def __iter__(self) -> Iterator[Plain]: ++ yield self.node ++ ++ def initial_names(self) -> AbstractSet[str]: ++ return self.node.initial_names() ++ ++ ++class Repeat0(Repeat): ++ def __str__(self) -> str: ++ s = str(self.node) ++ # TODO: Decide whether to use (X)* or X* based on type of X ++ if " " in s: ++ return f"({s})*" ++ else: ++ return f"{s}*" ++ ++ def __repr__(self) -> str: ++ return f"Repeat0({self.node!r})" ++ ++ def nullable_visit(self, rules: Dict[str, Rule]) -> bool: ++ return True ++ ++ ++class Repeat1(Repeat): ++ def __str__(self) -> str: ++ s = str(self.node) ++ # TODO: Decide whether to use (X)+ or X+ based on type of X ++ if " " in s: ++ return f"({s})+" ++ else: ++ return f"{s}+" ++ ++ def __repr__(self) -> str: ++ return f"Repeat1({self.node!r})" ++ ++ def nullable_visit(self, rules: Dict[str, Rule]) -> bool: ++ return False ++ ++ ++class Gather(Repeat): ++ def __init__(self, separator: Plain, node: Plain): ++ self.separator = separator ++ self.node = node ++ ++ def __str__(self) -> str: ++ return f"{self.separator!s}.{self.node!s}+" ++ ++ def __repr__(self) -> str: ++ return f"Gather({self.separator!r}, {self.node!r})" ++ ++ def nullable_visit(self, rules: Dict[str, Rule]) -> bool: ++ return False ++ ++ ++class Group: ++ def __init__(self, rhs: Rhs): ++ self.rhs = rhs ++ ++ def __str__(self) -> str: ++ return f"({self.rhs})" ++ ++ def __repr__(self) -> str: ++ return f"Group({self.rhs!r})" ++ ++ def __iter__(self) -> Iterator[Rhs]: ++ yield self.rhs ++ ++ def nullable_visit(self, rules: Dict[str, Rule]) -> bool: ++ return self.rhs.nullable_visit(rules) ++ ++ def initial_names(self) -> AbstractSet[str]: ++ return self.rhs.initial_names() ++ ++ ++class Cut: ++ def __init__(self) -> None: ++ pass ++ ++ def __repr__(self) -> str: ++ return f"Cut()" ++ ++ def __str__(self) -> str: ++ return f"~" ++ ++ def __iter__(self) -> Iterator[Tuple[str, str]]: ++ if False: ++ yield ++ ++ def __eq__(self, other: object) -> bool: ++ if not isinstance(other, Cut): ++ return NotImplemented ++ return True ++ ++ def nullable_visit(self, rules: Dict[str, Rule]) -> bool: ++ return True ++ ++ def initial_names(self) -> AbstractSet[str]: ++ return set() ++ ++ ++Plain = Union[Leaf, Group] ++Item = Union[Plain, Opt, Repeat, Lookahead, Rhs, Cut] ++RuleName = Tuple[str, str] ++MetaTuple = Tuple[str, Optional[str]] ++MetaList = List[MetaTuple] ++RuleList = List[Rule] ++NamedItemList = List[NamedItem] ++LookaheadOrCut = Union[Lookahead, Cut] +diff --git a/Tools/peg_generator/pegen/grammar_parser.py b/Tools/peg_generator/pegen/grammar_parser.py +new file mode 100644 +--- /dev/null ++++ b/Tools/peg_generator/pegen/grammar_parser.py +@@ -0,0 +1,677 @@ ++#!/usr/bin/env python3.8 ++# @generated by pegen from pegen/metagrammar.gram ++ ++import ast ++import sys ++import tokenize ++ ++from typing import Any, Optional ++ ++from pegen.parser import memoize, memoize_left_rec, logger, Parser ++from ast import literal_eval ++ ++from pegen.grammar import ( ++ Alt, ++ Cut, ++ Gather, ++ Group, ++ Item, ++ Lookahead, ++ LookaheadOrCut, ++ MetaTuple, ++ MetaList, ++ NameLeaf, ++ NamedItem, ++ NamedItemList, ++ NegativeLookahead, ++ Opt, ++ Plain, ++ PositiveLookahead, ++ Repeat0, ++ Repeat1, ++ Rhs, ++ Rule, ++ RuleList, ++ RuleName, ++ Grammar, ++ StringLeaf, ++) ++ ++class GeneratedParser(Parser): ++ ++ @memoize ++ def start(self) -> Optional[Grammar]: ++ # start: grammar $ ++ mark = self.mark() ++ cut = False ++ if ( ++ (grammar := self.grammar()) ++ and ++ (endmarker := self.expect('ENDMARKER')) ++ ): ++ return grammar ++ self.reset(mark) ++ if cut: return None ++ return None ++ ++ @memoize ++ def grammar(self) -> Optional[Grammar]: ++ # grammar: metas rules | rules ++ mark = self.mark() ++ cut = False ++ if ( ++ (metas := self.metas()) ++ and ++ (rules := self.rules()) ++ ): ++ return Grammar ( rules , metas ) ++ self.reset(mark) ++ if cut: return None ++ cut = False ++ if ( ++ (rules := self.rules()) ++ ): ++ return Grammar ( rules , [ ] ) ++ self.reset(mark) ++ if cut: return None ++ return None ++ ++ @memoize ++ def metas(self) -> Optional[MetaList]: ++ # metas: meta metas | meta ++ mark = self.mark() ++ cut = False ++ if ( ++ (meta := self.meta()) ++ and ++ (metas := self.metas()) ++ ): ++ return [ meta ] + metas ++ self.reset(mark) ++ if cut: return None ++ cut = False ++ if ( ++ (meta := self.meta()) ++ ): ++ return [ meta ] ++ self.reset(mark) ++ if cut: return None ++ return None ++ ++ @memoize ++ def meta(self) -> Optional[MetaTuple]: ++ # meta: "@" NAME NEWLINE | "@" NAME NAME NEWLINE | "@" NAME STRING NEWLINE ++ mark = self.mark() ++ cut = False ++ if ( ++ (literal := self.expect("@")) ++ and ++ (name := self.name()) ++ and ++ (newline := self.expect('NEWLINE')) ++ ): ++ return ( name . string , None ) ++ self.reset(mark) ++ if cut: return None ++ cut = False ++ if ( ++ (literal := self.expect("@")) ++ and ++ (a := self.name()) ++ and ++ (b := self.name()) ++ and ++ (newline := self.expect('NEWLINE')) ++ ): ++ return ( a . string , b . string ) ++ self.reset(mark) ++ if cut: return None ++ cut = False ++ if ( ++ (literal := self.expect("@")) ++ and ++ (name := self.name()) ++ and ++ (string := self.string()) ++ and ++ (newline := self.expect('NEWLINE')) ++ ): ++ return ( name . string , literal_eval ( string . string ) ) ++ self.reset(mark) ++ if cut: return None ++ return None ++ ++ @memoize ++ def rules(self) -> Optional[RuleList]: ++ # rules: rule rules | rule ++ mark = self.mark() ++ cut = False ++ if ( ++ (rule := self.rule()) ++ and ++ (rules := self.rules()) ++ ): ++ return [ rule ] + rules ++ self.reset(mark) ++ if cut: return None ++ cut = False ++ if ( ++ (rule := self.rule()) ++ ): ++ return [ rule ] ++ self.reset(mark) ++ if cut: return None ++ return None ++ ++ @memoize ++ def rule(self) -> Optional[Rule]: ++ # rule: rulename memoflag? ":" alts NEWLINE INDENT more_alts DEDENT | rulename memoflag? ":" NEWLINE INDENT more_alts DEDENT | rulename memoflag? ":" alts NEWLINE ++ mark = self.mark() ++ cut = False ++ if ( ++ (rulename := self.rulename()) ++ and ++ (opt := self.memoflag(),) ++ and ++ (literal := self.expect(":")) ++ and ++ (alts := self.alts()) ++ and ++ (newline := self.expect('NEWLINE')) ++ and ++ (indent := self.expect('INDENT')) ++ and ++ (more_alts := self.more_alts()) ++ and ++ (dedent := self.expect('DEDENT')) ++ ): ++ return Rule ( rulename [ 0 ] , rulename [ 1 ] , Rhs ( alts . alts + more_alts . alts ) , memo = opt ) ++ self.reset(mark) ++ if cut: return None ++ cut = False ++ if ( ++ (rulename := self.rulename()) ++ and ++ (opt := self.memoflag(),) ++ and ++ (literal := self.expect(":")) ++ and ++ (newline := self.expect('NEWLINE')) ++ and ++ (indent := self.expect('INDENT')) ++ and ++ (more_alts := self.more_alts()) ++ and ++ (dedent := self.expect('DEDENT')) ++ ): ++ return Rule ( rulename [ 0 ] , rulename [ 1 ] , more_alts , memo = opt ) ++ self.reset(mark) ++ if cut: return None ++ cut = False ++ if ( ++ (rulename := self.rulename()) ++ and ++ (opt := self.memoflag(),) ++ and ++ (literal := self.expect(":")) ++ and ++ (alts := self.alts()) ++ and ++ (newline := self.expect('NEWLINE')) ++ ): ++ return Rule ( rulename [ 0 ] , rulename [ 1 ] , alts , memo = opt ) ++ self.reset(mark) ++ if cut: return None ++ return None ++ ++ @memoize ++ def rulename(self) -> Optional[RuleName]: ++ # rulename: NAME '[' NAME '*' ']' | NAME '[' NAME ']' | NAME ++ mark = self.mark() ++ cut = False ++ if ( ++ (name := self.name()) ++ and ++ (literal := self.expect('[')) ++ and ++ (type := self.name()) ++ and ++ (literal_1 := self.expect('*')) ++ and ++ (literal_2 := self.expect(']')) ++ ): ++ return ( name . string , type . string + "*" ) ++ self.reset(mark) ++ if cut: return None ++ cut = False ++ if ( ++ (name := self.name()) ++ and ++ (literal := self.expect('[')) ++ and ++ (type := self.name()) ++ and ++ (literal_1 := self.expect(']')) ++ ): ++ return ( name . string , type . string ) ++ self.reset(mark) ++ if cut: return None ++ cut = False ++ if ( ++ (name := self.name()) ++ ): ++ return ( name . string , None ) ++ self.reset(mark) ++ if cut: return None ++ return None ++ ++ @memoize ++ def memoflag(self) -> Optional[str]: ++ # memoflag: '(' 'memo' ')' ++ mark = self.mark() ++ cut = False ++ if ( ++ (literal := self.expect('(')) ++ and ++ (literal_1 := self.expect('memo')) ++ and ++ (literal_2 := self.expect(')')) ++ ): ++ return "memo" ++ self.reset(mark) ++ if cut: return None ++ return None ++ ++ @memoize ++ def alts(self) -> Optional[Rhs]: ++ # alts: alt "|" alts | alt ++ mark = self.mark() ++ cut = False ++ if ( ++ (alt := self.alt()) ++ and ++ (literal := self.expect("|")) ++ and ++ (alts := self.alts()) ++ ): ++ return Rhs ( [ alt ] + alts . alts ) ++ self.reset(mark) ++ if cut: return None ++ cut = False ++ if ( ++ (alt := self.alt()) ++ ): ++ return Rhs ( [ alt ] ) ++ self.reset(mark) ++ if cut: return None ++ return None ++ ++ @memoize ++ def more_alts(self) -> Optional[Rhs]: ++ # more_alts: "|" alts NEWLINE more_alts | "|" alts NEWLINE ++ mark = self.mark() ++ cut = False ++ if ( ++ (literal := self.expect("|")) ++ and ++ (alts := self.alts()) ++ and ++ (newline := self.expect('NEWLINE')) ++ and ++ (more_alts := self.more_alts()) ++ ): ++ return Rhs ( alts . alts + more_alts . alts ) ++ self.reset(mark) ++ if cut: return None ++ cut = False ++ if ( ++ (literal := self.expect("|")) ++ and ++ (alts := self.alts()) ++ and ++ (newline := self.expect('NEWLINE')) ++ ): ++ return Rhs ( alts . alts ) ++ self.reset(mark) ++ if cut: return None ++ return None ++ ++ @memoize ++ def alt(self) -> Optional[Alt]: ++ # alt: items '$' action | items '$' | items action | items ++ mark = self.mark() ++ cut = False ++ if ( ++ (items := self.items()) ++ and ++ (literal := self.expect('$')) ++ and ++ (action := self.action()) ++ ): ++ return Alt ( items + [ NamedItem ( None , NameLeaf ( 'ENDMARKER' ) ) ] , action = action ) ++ self.reset(mark) ++ if cut: return None ++ cut = False ++ if ( ++ (items := self.items()) ++ and ++ (literal := self.expect('$')) ++ ): ++ return Alt ( items + [ NamedItem ( None , NameLeaf ( 'ENDMARKER' ) ) ] , action = None ) ++ self.reset(mark) ++ if cut: return None ++ cut = False ++ if ( ++ (items := self.items()) ++ and ++ (action := self.action()) ++ ): ++ return Alt ( items , action = action ) ++ self.reset(mark) ++ if cut: return None ++ cut = False ++ if ( ++ (items := self.items()) ++ ): ++ return Alt ( items , action = None ) ++ self.reset(mark) ++ if cut: return None ++ return None ++ ++ @memoize ++ def items(self) -> Optional[NamedItemList]: ++ # items: named_item items | named_item ++ mark = self.mark() ++ cut = False ++ if ( ++ (named_item := self.named_item()) ++ and ++ (items := self.items()) ++ ): ++ return [ named_item ] + items ++ self.reset(mark) ++ if cut: return None ++ cut = False ++ if ( ++ (named_item := self.named_item()) ++ ): ++ return [ named_item ] ++ self.reset(mark) ++ if cut: return None ++ return None ++ ++ @memoize ++ def named_item(self) -> Optional[NamedItem]: ++ # named_item: NAME '=' ~ item | item | lookahead ++ mark = self.mark() ++ cut = False ++ if ( ++ (name := self.name()) ++ and ++ (literal := self.expect('=')) ++ and ++ (cut := True) ++ and ++ (item := self.item()) ++ ): ++ return NamedItem ( name . string , item ) ++ self.reset(mark) ++ if cut: return None ++ cut = False ++ if ( ++ (item := self.item()) ++ ): ++ return NamedItem ( None , item ) ++ self.reset(mark) ++ if cut: return None ++ cut = False ++ if ( ++ (it := self.lookahead()) ++ ): ++ return NamedItem ( None , it ) ++ self.reset(mark) ++ if cut: return None ++ return None ++ ++ @memoize ++ def lookahead(self) -> Optional[LookaheadOrCut]: ++ # lookahead: '&' ~ atom | '!' ~ atom | '~' ++ mark = self.mark() ++ cut = False ++ if ( ++ (literal := self.expect('&')) ++ and ++ (cut := True) ++ and ++ (atom := self.atom()) ++ ): ++ return PositiveLookahead ( atom ) ++ self.reset(mark) ++ if cut: return None ++ cut = False ++ if ( ++ (literal := self.expect('!')) ++ and ++ (cut := True) ++ and ++ (atom := self.atom()) ++ ): ++ return NegativeLookahead ( atom ) ++ self.reset(mark) ++ if cut: return None ++ cut = False ++ if ( ++ (literal := self.expect('~')) ++ ): ++ return Cut ( ) ++ self.reset(mark) ++ if cut: return None ++ return None ++ ++ @memoize ++ def item(self) -> Optional[Item]: ++ # item: '[' ~ alts ']' | atom '?' | atom '*' | atom '+' | atom '.' atom '+' | atom ++ mark = self.mark() ++ cut = False ++ if ( ++ (literal := self.expect('[')) ++ and ++ (cut := True) ++ and ++ (alts := self.alts()) ++ and ++ (literal_1 := self.expect(']')) ++ ): ++ return Opt ( alts ) ++ self.reset(mark) ++ if cut: return None ++ cut = False ++ if ( ++ (atom := self.atom()) ++ and ++ (literal := self.expect('?')) ++ ): ++ return Opt ( atom ) ++ self.reset(mark) ++ if cut: return None ++ cut = False ++ if ( ++ (atom := self.atom()) ++ and ++ (literal := self.expect('*')) ++ ): ++ return Repeat0 ( atom ) ++ self.reset(mark) ++ if cut: return None ++ cut = False ++ if ( ++ (atom := self.atom()) ++ and ++ (literal := self.expect('+')) ++ ): ++ return Repeat1 ( atom ) ++ self.reset(mark) ++ if cut: return None ++ cut = False ++ if ( ++ (sep := self.atom()) ++ and ++ (literal := self.expect('.')) ++ and ++ (node := self.atom()) ++ and ++ (literal_1 := self.expect('+')) ++ ): ++ return Gather ( sep , node ) ++ self.reset(mark) ++ if cut: return None ++ cut = False ++ if ( ++ (atom := self.atom()) ++ ): ++ return atom ++ self.reset(mark) ++ if cut: return None ++ return None ++ ++ @memoize ++ def atom(self) -> Optional[Plain]: ++ # atom: '(' ~ alts ')' | NAME | STRING ++ mark = self.mark() ++ cut = False ++ if ( ++ (literal := self.expect('(')) ++ and ++ (cut := True) ++ and ++ (alts := self.alts()) ++ and ++ (literal_1 := self.expect(')')) ++ ): ++ return Group ( alts ) ++ self.reset(mark) ++ if cut: return None ++ cut = False ++ if ( ++ (name := self.name()) ++ ): ++ return NameLeaf ( name . string ) ++ self.reset(mark) ++ if cut: return None ++ cut = False ++ if ( ++ (string := self.string()) ++ ): ++ return StringLeaf ( string . string ) ++ self.reset(mark) ++ if cut: return None ++ return None ++ ++ @memoize ++ def action(self) -> Optional[str]: ++ # action: "{" ~ target_atoms "}" ++ mark = self.mark() ++ cut = False ++ if ( ++ (literal := self.expect("{")) ++ and ++ (cut := True) ++ and ++ (target_atoms := self.target_atoms()) ++ and ++ (literal_1 := self.expect("}")) ++ ): ++ return target_atoms ++ self.reset(mark) ++ if cut: return None ++ return None ++ ++ @memoize ++ def target_atoms(self) -> Optional[str]: ++ # target_atoms: target_atom target_atoms | target_atom ++ mark = self.mark() ++ cut = False ++ if ( ++ (target_atom := self.target_atom()) ++ and ++ (target_atoms := self.target_atoms()) ++ ): ++ return target_atom + " " + target_atoms ++ self.reset(mark) ++ if cut: return None ++ cut = False ++ if ( ++ (target_atom := self.target_atom()) ++ ): ++ return target_atom ++ self.reset(mark) ++ if cut: return None ++ return None ++ ++ @memoize ++ def target_atom(self) -> Optional[str]: ++ # target_atom: "{" ~ target_atoms "}" | NAME | NUMBER | STRING | "?" | ":" | !"}" OP ++ mark = self.mark() ++ cut = False ++ if ( ++ (literal := self.expect("{")) ++ and ++ (cut := True) ++ and ++ (target_atoms := self.target_atoms()) ++ and ++ (literal_1 := self.expect("}")) ++ ): ++ return "{" + target_atoms + "}" ++ self.reset(mark) ++ if cut: return None ++ cut = False ++ if ( ++ (name := self.name()) ++ ): ++ return name . string ++ self.reset(mark) ++ if cut: return None ++ cut = False ++ if ( ++ (number := self.number()) ++ ): ++ return number . string ++ self.reset(mark) ++ if cut: return None ++ cut = False ++ if ( ++ (string := self.string()) ++ ): ++ return string . string ++ self.reset(mark) ++ if cut: return None ++ cut = False ++ if ( ++ (literal := self.expect("?")) ++ ): ++ return "?" ++ self.reset(mark) ++ if cut: return None ++ cut = False ++ if ( ++ (literal := self.expect(":")) ++ ): ++ return ":" ++ self.reset(mark) ++ if cut: return None ++ cut = False ++ if ( ++ self.negative_lookahead(self.expect, "}") ++ and ++ (op := self.op()) ++ ): ++ return op . string ++ self.reset(mark) ++ if cut: return None ++ return None ++ ++ ++if __name__ == '__main__': ++ from pegen.parser import simple_parser_main ++ simple_parser_main(GeneratedParser) +diff --git a/Tools/peg_generator/pegen/grammar_visualizer.py b/Tools/peg_generator/pegen/grammar_visualizer.py +new file mode 100644 +--- /dev/null ++++ b/Tools/peg_generator/pegen/grammar_visualizer.py +@@ -0,0 +1,65 @@ ++import argparse ++import sys ++ ++from typing import Any, Iterator, Iterable, Callable ++ ++from pegen.build import build_parser ++from pegen.grammar import Grammar, Rule ++ ++argparser = argparse.ArgumentParser( ++ prog="pegen", description="Pretty print the AST for a given PEG grammar" ++) ++argparser.add_argument("filename", help="Grammar description") ++ ++ ++class ASTGrammarPrinter: ++ def children(self, node: Rule) -> Iterator[Any]: ++ for value in node: ++ if isinstance(value, list): ++ yield from value ++ else: ++ yield value ++ ++ def name(self, node: Rule) -> str: ++ if not list(self.children(node)): ++ return repr(node) ++ return node.__class__.__name__ ++ ++ def print_grammar_ast(self, grammar: Grammar, printer: Callable[..., None] = print) -> None: ++ for rule in grammar.rules.values(): ++ printer(self.print_nodes_recursively(rule)) ++ ++ def print_nodes_recursively(self, node: Rule, prefix: str = "", istail: bool = True) -> str: ++ ++ children = list(self.children(node)) ++ value = self.name(node) ++ ++ line = prefix + ("└──" if istail else "├──") + value + "\n" ++ sufix = " " if istail else "│ " ++ ++ if not children: ++ return line ++ ++ *children, last = children ++ for child in children: ++ line += self.print_nodes_recursively(child, prefix + sufix, False) ++ line += self.print_nodes_recursively(last, prefix + sufix, True) ++ ++ return line ++ ++ ++def main() -> None: ++ args = argparser.parse_args() ++ ++ try: ++ grammar, parser, tokenizer = build_parser(args.filename) ++ except Exception as err: ++ print("ERROR: Failed to parse grammar file", file=sys.stderr) ++ sys.exit(1) ++ ++ visitor = ASTGrammarPrinter() ++ visitor.print_grammar_ast(grammar) ++ ++ ++if __name__ == "__main__": ++ main() +diff --git a/Tools/peg_generator/pegen/metagrammar.gram b/Tools/peg_generator/pegen/metagrammar.gram +new file mode 100644 +--- /dev/null ++++ b/Tools/peg_generator/pegen/metagrammar.gram +@@ -0,0 +1,123 @@ ++@subheader """\ ++from ast import literal_eval ++ ++from pegen.grammar import ( ++ Alt, ++ Cut, ++ Gather, ++ Group, ++ Item, ++ Lookahead, ++ LookaheadOrCut, ++ MetaTuple, ++ MetaList, ++ NameLeaf, ++ NamedItem, ++ NamedItemList, ++ NegativeLookahead, ++ Opt, ++ Plain, ++ PositiveLookahead, ++ Repeat0, ++ Repeat1, ++ Rhs, ++ Rule, ++ RuleList, ++ RuleName, ++ Grammar, ++ StringLeaf, ++) ++""" ++ ++start[Grammar]: grammar ENDMARKER { grammar } ++ ++grammar[Grammar]: ++ | metas rules { Grammar(rules, metas) } ++ | rules { Grammar(rules, []) } ++ ++metas[MetaList]: ++ | meta metas { [meta] + metas } ++ | meta { [meta] } ++ ++meta[MetaTuple]: ++ | "@" NAME NEWLINE { (name.string, None) } ++ | "@" a=NAME b=NAME NEWLINE { (a.string, b.string) } ++ | "@" NAME STRING NEWLINE { (name.string, literal_eval(string.string)) } ++ ++rules[RuleList]: ++ | rule rules { [rule] + rules } ++ | rule { [rule] } ++ ++rule[Rule]: ++ | rulename memoflag? ":" alts NEWLINE INDENT more_alts DEDENT { ++ Rule(rulename[0], rulename[1], Rhs(alts.alts + more_alts.alts), memo=opt) } ++ | rulename memoflag? ":" NEWLINE INDENT more_alts DEDENT { ++ Rule(rulename[0], rulename[1], more_alts, memo=opt) } ++ | rulename memoflag? ":" alts NEWLINE { Rule(rulename[0], rulename[1], alts, memo=opt) } ++ ++rulename[RuleName]: ++ | NAME '[' type=NAME '*' ']' { (name.string, type.string+"*") } ++ | NAME '[' type=NAME ']' { (name.string, type.string) } ++ | NAME { (name.string, None) } ++ ++# In the future this may return something more complicated ++memoflag[str]: ++ | '(' 'memo' ')' { "memo" } ++ ++alts[Rhs]: ++ | alt "|" alts { Rhs([alt] + alts.alts)} ++ | alt { Rhs([alt]) } ++ ++more_alts[Rhs]: ++ | "|" alts NEWLINE more_alts { Rhs(alts.alts + more_alts.alts) } ++ | "|" alts NEWLINE { Rhs(alts.alts) } ++ ++alt[Alt]: ++ | items '$' action { Alt(items + [NamedItem(None, NameLeaf('ENDMARKER'))], action=action) } ++ | items '$' { Alt(items + [NamedItem(None, NameLeaf('ENDMARKER'))], action=None) } ++ | items action { Alt(items, action=action) } ++ | items { Alt(items, action=None) } ++ ++items[NamedItemList]: ++ | named_item items { [named_item] + items } ++ | named_item { [named_item] } ++ ++named_item[NamedItem]: ++ | NAME '=' ~ item {NamedItem(name.string, item)} ++ | item {NamedItem(None, item)} ++ | it=lookahead {NamedItem(None, it)} ++ ++lookahead[LookaheadOrCut]: ++ | '&' ~ atom {PositiveLookahead(atom)} ++ | '!' ~ atom {NegativeLookahead(atom)} ++ | '~' {Cut()} ++ ++item[Item]: ++ | '[' ~ alts ']' {Opt(alts)} ++ | atom '?' {Opt(atom)} ++ | atom '*' {Repeat0(atom)} ++ | atom '+' {Repeat1(atom)} ++ | sep=atom '.' node=atom '+' {Gather(sep, node)} ++ | atom {atom} ++ ++atom[Plain]: ++ | '(' ~ alts ')' {Group(alts)} ++ | NAME {NameLeaf(name.string) } ++ | STRING {StringLeaf(string.string)} ++ ++# Mini-grammar for the actions ++ ++action[str]: "{" ~ target_atoms "}" { target_atoms } ++ ++target_atoms[str]: ++ | target_atom target_atoms { target_atom + " " + target_atoms } ++ | target_atom { target_atom } ++ ++target_atom[str]: ++ | "{" ~ target_atoms "}" { "{" + target_atoms + "}" } ++ | NAME { name.string } ++ | NUMBER { number.string } ++ | STRING { string.string } ++ | "?" { "?" } ++ | ":" { ":" } ++ | !"}" OP { op.string } +diff --git a/Tools/peg_generator/pegen/parser.py b/Tools/peg_generator/pegen/parser.py +new file mode 100644 +--- /dev/null ++++ b/Tools/peg_generator/pegen/parser.py +@@ -0,0 +1,310 @@ ++import argparse ++import sys ++import time ++import token ++import tokenize ++import traceback ++ ++from abc import abstractmethod ++from typing import Any, Callable, cast, Dict, Optional, Tuple, Type, TypeVar ++ ++from pegen.tokenizer import exact_token_types ++from pegen.tokenizer import Mark ++from pegen.tokenizer import Tokenizer ++ ++T = TypeVar("T") ++P = TypeVar("P", bound="Parser") ++F = TypeVar("F", bound=Callable[..., Any]) ++ ++ ++def logger(method: F) -> F: ++ """For non-memoized functions that we want to be logged. ++ ++ (In practice this is only non-leader left-recursive functions.) ++ """ ++ method_name = method.__name__ ++ ++ def logger_wrapper(self: P, *args: object) -> T: ++ if not self._verbose: ++ return method(self, *args) ++ argsr = ",".join(repr(arg) for arg in args) ++ fill = " " * self._level ++ print(f"{fill}{method_name}({argsr}) .... (looking at {self.showpeek()})") ++ self._level += 1 ++ tree = method(self, *args) ++ self._level -= 1 ++ print(f"{fill}... {method_name}({argsr}) --> {tree!s:.200}") ++ return tree ++ ++ logger_wrapper.__wrapped__ = method # type: ignore ++ return cast(F, logger_wrapper) ++ ++ ++def memoize(method: F) -> F: ++ """Memoize a symbol method.""" ++ method_name = method.__name__ ++ ++ def memoize_wrapper(self: P, *args: object) -> T: ++ mark = self.mark() ++ key = mark, method_name, args ++ # Fast path: cache hit, and not verbose. ++ if key in self._cache and not self._verbose: ++ tree, endmark = self._cache[key] ++ self.reset(endmark) ++ return tree ++ # Slow path: no cache hit, or verbose. ++ verbose = self._verbose ++ argsr = ",".join(repr(arg) for arg in args) ++ fill = " " * self._level ++ if key not in self._cache: ++ if verbose: ++ print(f"{fill}{method_name}({argsr}) ... (looking at {self.showpeek()})") ++ self._level += 1 ++ tree = method(self, *args) ++ self._level -= 1 ++ if verbose: ++ print(f"{fill}... {method_name}({argsr}) -> {tree!s:.200}") ++ endmark = self.mark() ++ self._cache[key] = tree, endmark ++ else: ++ tree, endmark = self._cache[key] ++ if verbose: ++ print(f"{fill}{method_name}({argsr}) -> {tree!s:.200}") ++ self.reset(endmark) ++ return tree ++ ++ memoize_wrapper.__wrapped__ = method # type: ignore ++ return cast(F, memoize_wrapper) ++ ++ ++def memoize_left_rec(method: Callable[[P], Optional[T]]) -> Callable[[P], Optional[T]]: ++ """Memoize a left-recursive symbol method.""" ++ method_name = method.__name__ ++ ++ def memoize_left_rec_wrapper(self: P) -> Optional[T]: ++ mark = self.mark() ++ key = mark, method_name, () ++ # Fast path: cache hit, and not verbose. ++ if key in self._cache and not self._verbose: ++ tree, endmark = self._cache[key] ++ self.reset(endmark) ++ return tree ++ # Slow path: no cache hit, or verbose. ++ verbose = self._verbose ++ fill = " " * self._level ++ if key not in self._cache: ++ if verbose: ++ print(f"{fill}{method_name} ... (looking at {self.showpeek()})") ++ self._level += 1 ++ ++ # For left-recursive rules we manipulate the cache and ++ # loop until the rule shows no progress, then pick the ++ # previous result. For an explanation why this works, see ++ # https://github.com/PhilippeSigaud/Pegged/wiki/Left-Recursion ++ # (But we use the memoization cache instead of a static ++ # variable; perhaps this is similar to a paper by Warth et al. ++ # (http://web.cs.ucla.edu/~todd/research/pub.php?id=pepm08). ++ ++ # Prime the cache with a failure. ++ self._cache[key] = None, mark ++ lastresult, lastmark = None, mark ++ depth = 0 ++ if verbose: ++ print(f"{fill}Recursive {method_name} at {mark} depth {depth}") ++ ++ while True: ++ self.reset(mark) ++ result = method(self) ++ endmark = self.mark() ++ depth += 1 ++ if verbose: ++ print( ++ f"{fill}Recursive {method_name} at {mark} depth {depth}: {result!s:.200} to {endmark}" ++ ) ++ if not result: ++ if verbose: ++ print(f"{fill}Fail with {lastresult!s:.200} to {lastmark}") ++ break ++ if endmark <= lastmark: ++ if verbose: ++ print(f"{fill}Bailing with {lastresult!s:.200} to {lastmark}") ++ break ++ self._cache[key] = lastresult, lastmark = result, endmark ++ ++ self.reset(lastmark) ++ tree = lastresult ++ ++ self._level -= 1 ++ if verbose: ++ print(f"{fill}{method_name}() -> {tree!s:.200} [cached]") ++ if tree: ++ endmark = self.mark() ++ else: ++ endmark = mark ++ self.reset(endmark) ++ self._cache[key] = tree, endmark ++ else: ++ tree, endmark = self._cache[key] ++ if verbose: ++ print(f"{fill}{method_name}() -> {tree!s:.200} [fresh]") ++ if tree: ++ self.reset(endmark) ++ return tree ++ ++ memoize_left_rec_wrapper.__wrapped__ = method # type: ignore ++ return memoize_left_rec_wrapper ++ ++ ++class Parser: ++ """Parsing base class.""" ++ ++ def __init__(self, tokenizer: Tokenizer, *, verbose: bool = False): ++ self._tokenizer = tokenizer ++ self._verbose = verbose ++ self._level = 0 ++ self._cache: Dict[Tuple[Mark, str, Tuple[Any, ...]], Tuple[Any, Mark]] = {} ++ # Pass through common tokenizer methods. ++ # TODO: Rename to _mark and _reset. ++ self.mark = self._tokenizer.mark ++ self.reset = self._tokenizer.reset ++ ++ @abstractmethod ++ def start(self) -> Any: ++ pass ++ ++ def showpeek(self) -> str: ++ tok = self._tokenizer.peek() ++ return f"{tok.start[0]}.{tok.start[1]}: {token.tok_name[tok.type]}:{tok.string!r}" ++ ++ @memoize ++ def name(self) -> Optional[tokenize.TokenInfo]: ++ tok = self._tokenizer.peek() ++ if tok.type == token.NAME: ++ return self._tokenizer.getnext() ++ return None ++ ++ @memoize ++ def number(self) -> Optional[tokenize.TokenInfo]: ++ tok = self._tokenizer.peek() ++ if tok.type == token.NUMBER: ++ return self._tokenizer.getnext() ++ return None ++ ++ @memoize ++ def string(self) -> Optional[tokenize.TokenInfo]: ++ tok = self._tokenizer.peek() ++ if tok.type == token.STRING: ++ return self._tokenizer.getnext() ++ return None ++ ++ @memoize ++ def op(self) -> Optional[tokenize.TokenInfo]: ++ tok = self._tokenizer.peek() ++ if tok.type == token.OP: ++ return self._tokenizer.getnext() ++ return None ++ ++ @memoize ++ def expect(self, type: str) -> Optional[tokenize.TokenInfo]: ++ tok = self._tokenizer.peek() ++ if tok.string == type: ++ return self._tokenizer.getnext() ++ if type in exact_token_types: ++ if tok.type == exact_token_types[type]: ++ return self._tokenizer.getnext() ++ if type in token.__dict__: ++ if tok.type == token.__dict__[type]: ++ return self._tokenizer.getnext() ++ if tok.type == token.OP and tok.string == type: ++ return self._tokenizer.getnext() ++ return None ++ ++ def positive_lookahead(self, func: Callable[..., T], *args: object) -> T: ++ mark = self.mark() ++ ok = func(*args) ++ self.reset(mark) ++ return ok ++ ++ def negative_lookahead(self, func: Callable[..., object], *args: object) -> bool: ++ mark = self.mark() ++ ok = func(*args) ++ self.reset(mark) ++ return not ok ++ ++ def make_syntax_error(self, filename: str = "") -> SyntaxError: ++ tok = self._tokenizer.diagnose() ++ return SyntaxError( ++ "pegen parse failure", (filename, tok.start[0], 1 + tok.start[1], tok.line) ++ ) ++ ++ ++def simple_parser_main(parser_class: Type[Parser]) -> None: ++ argparser = argparse.ArgumentParser() ++ argparser.add_argument( ++ "-v", ++ "--verbose", ++ action="count", ++ default=0, ++ help="Print timing stats; repeat for more debug output", ++ ) ++ argparser.add_argument( ++ "-q", "--quiet", action="store_true", help="Don't print the parsed program" ++ ) ++ argparser.add_argument("filename", help="Input file ('-' to use stdin)") ++ ++ args = argparser.parse_args() ++ verbose = args.verbose ++ verbose_tokenizer = verbose >= 3 ++ verbose_parser = verbose == 2 or verbose >= 4 ++ ++ t0 = time.time() ++ ++ filename = args.filename ++ if filename == "" or filename == "-": ++ filename = "" ++ file = sys.stdin ++ else: ++ file = open(args.filename) ++ try: ++ tokengen = tokenize.generate_tokens(file.readline) ++ tokenizer = Tokenizer(tokengen, verbose=verbose_tokenizer) ++ parser = parser_class(tokenizer, verbose=verbose_parser) ++ tree = parser.start() ++ try: ++ if file.isatty(): ++ endpos = 0 ++ else: ++ endpos = file.tell() ++ except IOError: ++ endpos = 0 ++ finally: ++ if file is not sys.stdin: ++ file.close() ++ ++ t1 = time.time() ++ ++ if not tree: ++ err = parser.make_syntax_error(filename) ++ traceback.print_exception(err.__class__, err, None) ++ sys.exit(1) ++ ++ if not args.quiet: ++ print(tree) ++ ++ if verbose: ++ dt = t1 - t0 ++ diag = tokenizer.diagnose() ++ nlines = diag.end[0] ++ if diag.type == token.ENDMARKER: ++ nlines -= 1 ++ print(f"Total time: {dt:.3f} sec; {nlines} lines", end="") ++ if endpos: ++ print(f" ({endpos} bytes)", end="") ++ if dt: ++ print(f"; {nlines / dt:.0f} lines/sec") ++ else: ++ print() ++ print("Caches sizes:") ++ print(f" token array : {len(tokenizer._tokens):10}") ++ print(f" cache : {len(parser._cache):10}") ++ ## print_memstats() +diff --git a/Tools/peg_generator/pegen/parser_generator.py b/Tools/peg_generator/pegen/parser_generator.py +new file mode 100644 +--- /dev/null ++++ b/Tools/peg_generator/pegen/parser_generator.py +@@ -0,0 +1,188 @@ ++import contextlib ++import token ++from abc import abstractmethod ++ ++from typing import AbstractSet, Dict, IO, Iterator, List, Optional, Set, Text, Tuple ++ ++from pegen import sccutils ++from pegen.grammar import ( ++ Grammar, ++ Rule, ++ Rhs, ++ Alt, ++ NamedItem, ++ Plain, ++ NameLeaf, ++ StringLeaf, ++ Gather, ++) ++from pegen.grammar import GrammarError, GrammarVisitor ++ ++ ++class RuleCheckingVisitor(GrammarVisitor): ++ def __init__(self, rules: Dict[str, Rule]): ++ self.rules = rules ++ ++ def visit_NameLeaf(self, node: NameLeaf) -> None: ++ if node.value not in self.rules and node.value not in token.tok_name.values(): ++ # TODO: Add line/col info to (leaf) nodes ++ raise GrammarError(f"Dangling reference to rule {node.value!r}") ++ ++ ++class ParserGenerator: ++ ++ callmakervisitor: GrammarVisitor ++ ++ def __init__(self, grammar: Grammar, file: Optional[IO[Text]]): ++ self.grammar = grammar ++ self.rules = grammar.rules ++ if "trailer" not in grammar.metas and "start" not in self.rules: ++ raise GrammarError("Grammar without a trailer must have a 'start' rule") ++ checker = RuleCheckingVisitor(self.rules) ++ for rule in self.rules.values(): ++ checker.visit(rule) ++ self.file = file ++ self.level = 0 ++ compute_nullables(self.rules) ++ self.first_graph, self.first_sccs = compute_left_recursives(self.rules) ++ self.todo = self.rules.copy() # Rules to generate ++ self.counter = 0 # For name_rule()/name_loop() ++ self.keyword_counter = 499 # For keyword_type() ++ ++ @abstractmethod ++ def generate(self, filename: str) -> None: ++ raise NotImplementedError ++ ++ @contextlib.contextmanager ++ def indent(self) -> Iterator[None]: ++ self.level += 1 ++ try: ++ yield ++ finally: ++ self.level -= 1 ++ ++ def print(self, *args: object) -> None: ++ if not args: ++ print(file=self.file) ++ else: ++ print(" " * self.level, end="", file=self.file) ++ print(*args, file=self.file) ++ ++ def printblock(self, lines: str) -> None: ++ for line in lines.splitlines(): ++ self.print(line) ++ ++ def collect_todo(self) -> None: ++ done: Set[str] = set() ++ while True: ++ alltodo = list(self.todo) ++ todo = [i for i in alltodo if i not in done] ++ if not todo: ++ break ++ for rulename in todo: ++ self.todo[rulename].collect_todo(self) ++ done = set(alltodo) ++ ++ def keyword_type(self) -> int: ++ self.keyword_counter += 1 ++ return self.keyword_counter ++ ++ def name_node(self, rhs: Rhs) -> str: ++ self.counter += 1 ++ name = f"_tmp_{self.counter}" # TODO: Pick a nicer name. ++ self.todo[name] = Rule(name, None, rhs) ++ return name ++ ++ def name_loop(self, node: Plain, is_repeat1: bool) -> str: ++ self.counter += 1 ++ if is_repeat1: ++ prefix = "_loop1_" ++ else: ++ prefix = "_loop0_" ++ name = f"{prefix}{self.counter}" # TODO: It's ugly to signal via the name. ++ self.todo[name] = Rule(name, None, Rhs([Alt([NamedItem(None, node)])])) ++ return name ++ ++ def name_gather(self, node: Gather) -> str: ++ self.counter += 1 ++ name = f"_gather_{self.counter}" ++ self.counter += 1 ++ extra_function_name = f"_loop0_{self.counter}" ++ extra_function_alt = Alt( ++ [NamedItem(None, node.separator), NamedItem("elem", node.node),], action="elem", ++ ) ++ self.todo[extra_function_name] = Rule( ++ extra_function_name, None, Rhs([extra_function_alt]), ++ ) ++ alt = Alt( ++ [NamedItem("elem", node.node), NamedItem("seq", NameLeaf(extra_function_name)),], ++ ) ++ self.todo[name] = Rule(name, None, Rhs([alt]),) ++ return name ++ ++ ++def dedupe(name: str, names: List[str]) -> str: ++ origname = name ++ counter = 0 ++ while name in names: ++ counter += 1 ++ name = f"{origname}_{counter}" ++ names.append(name) ++ return name ++ ++ ++def compute_nullables(rules: Dict[str, Rule]) -> None: ++ """Compute which rules in a grammar are nullable. ++ ++ Thanks to TatSu (tatsu/leftrec.py) for inspiration. ++ """ ++ for rule in rules.values(): ++ rule.nullable_visit(rules) ++ ++ ++def compute_left_recursives( ++ rules: Dict[str, Rule] ++) -> Tuple[Dict[str, AbstractSet[str]], List[AbstractSet[str]]]: ++ graph = make_first_graph(rules) ++ sccs = list(sccutils.strongly_connected_components(graph.keys(), graph)) ++ for scc in sccs: ++ if len(scc) > 1: ++ for name in scc: ++ rules[name].left_recursive = True ++ # Try to find a leader such that all cycles go through it. ++ leaders = set(scc) ++ for start in scc: ++ for cycle in sccutils.find_cycles_in_scc(graph, scc, start): ++ ## print("Cycle:", " -> ".join(cycle)) ++ leaders -= scc - set(cycle) ++ if not leaders: ++ raise ValueError( ++ f"SCC {scc} has no leadership candidate (no element is included in all cycles)" ++ ) ++ ## print("Leaders:", leaders) ++ leader = min(leaders) # Pick an arbitrary leader from the candidates. ++ rules[leader].leader = True ++ else: ++ name = min(scc) # The only element. ++ if name in graph[name]: ++ rules[name].left_recursive = True ++ rules[name].leader = True ++ return graph, sccs ++ ++ ++def make_first_graph(rules: Dict[str, Rule]) -> Dict[str, AbstractSet[str]]: ++ """Compute the graph of left-invocations. ++ ++ There's an edge from A to B if A may invoke B at its initial ++ position. ++ ++ Note that this requires the nullable flags to have been computed. ++ """ ++ graph = {} ++ vertices: Set[str] = set() ++ for rulename, rhs in rules.items(): ++ graph[rulename] = names = rhs.initial_names() ++ vertices |= names ++ for vertex in vertices: ++ graph.setdefault(vertex, set()) ++ return graph +diff --git a/Tools/peg_generator/pegen/python_generator.py b/Tools/peg_generator/pegen/python_generator.py +new file mode 100644 +--- /dev/null ++++ b/Tools/peg_generator/pegen/python_generator.py +@@ -0,0 +1,224 @@ ++from typing import Any, Dict, List, Optional, IO, Text, Tuple ++ ++from pegen.grammar import ( ++ Cut, ++ GrammarVisitor, ++ NameLeaf, ++ StringLeaf, ++ Rhs, ++ NamedItem, ++ Lookahead, ++ PositiveLookahead, ++ NegativeLookahead, ++ Opt, ++ Repeat0, ++ Repeat1, ++ Gather, ++ Group, ++ Rule, ++ Alt, ++) ++from pegen import grammar ++from pegen.parser_generator import dedupe, ParserGenerator ++ ++MODULE_PREFIX = """\ ++#!/usr/bin/env python3.8 ++# @generated by pegen from {filename} ++ ++import ast ++import sys ++import tokenize ++ ++from typing import Any, Optional ++ ++from pegen.parser import memoize, memoize_left_rec, logger, Parser ++ ++""" ++MODULE_SUFFIX = """ ++ ++if __name__ == '__main__': ++ from pegen.parser import simple_parser_main ++ simple_parser_main(GeneratedParser) ++""" ++ ++ ++class PythonCallMakerVisitor(GrammarVisitor): ++ def __init__(self, parser_generator: ParserGenerator): ++ self.gen = parser_generator ++ self.cache: Dict[Any, Any] = {} ++ ++ def visit_NameLeaf(self, node: NameLeaf) -> Tuple[Optional[str], str]: ++ name = node.value ++ if name in ("NAME", "NUMBER", "STRING", "OP"): ++ name = name.lower() ++ return name, f"self.{name}()" ++ if name in ("NEWLINE", "DEDENT", "INDENT", "ENDMARKER", "ASYNC", "AWAIT"): ++ return name.lower(), f"self.expect({name!r})" ++ return name, f"self.{name}()" ++ ++ def visit_StringLeaf(self, node: StringLeaf) -> Tuple[str, str]: ++ return "literal", f"self.expect({node.value})" ++ ++ def visit_Rhs(self, node: Rhs) -> Tuple[Optional[str], str]: ++ if node in self.cache: ++ return self.cache[node] ++ if len(node.alts) == 1 and len(node.alts[0].items) == 1: ++ self.cache[node] = self.visit(node.alts[0].items[0]) ++ else: ++ name = self.gen.name_node(node) ++ self.cache[node] = name, f"self.{name}()" ++ return self.cache[node] ++ ++ def visit_NamedItem(self, node: NamedItem) -> Tuple[Optional[str], str]: ++ name, call = self.visit(node.item) ++ if node.name: ++ name = node.name ++ return name, call ++ ++ def lookahead_call_helper(self, node: Lookahead) -> Tuple[str, str]: ++ name, call = self.visit(node.node) ++ head, tail = call.split("(", 1) ++ assert tail[-1] == ")" ++ tail = tail[:-1] ++ return head, tail ++ ++ def visit_PositiveLookahead(self, node: PositiveLookahead) -> Tuple[None, str]: ++ head, tail = self.lookahead_call_helper(node) ++ return None, f"self.positive_lookahead({head}, {tail})" ++ ++ def visit_NegativeLookahead(self, node: NegativeLookahead) -> Tuple[None, str]: ++ head, tail = self.lookahead_call_helper(node) ++ return None, f"self.negative_lookahead({head}, {tail})" ++ ++ def visit_Opt(self, node: Opt) -> Tuple[str, str]: ++ name, call = self.visit(node.node) ++ return "opt", f"{call}," # Note trailing comma! ++ ++ def visit_Repeat0(self, node: Repeat0) -> Tuple[str, str]: ++ if node in self.cache: ++ return self.cache[node] ++ name = self.gen.name_loop(node.node, False) ++ self.cache[node] = name, f"self.{name}()," # Also a trailing comma! ++ return self.cache[node] ++ ++ def visit_Repeat1(self, node: Repeat1) -> Tuple[str, str]: ++ if node in self.cache: ++ return self.cache[node] ++ name = self.gen.name_loop(node.node, True) ++ self.cache[node] = name, f"self.{name}()" # But no trailing comma here! ++ return self.cache[node] ++ ++ def visit_Gather(self, node: Gather) -> Tuple[str, str]: ++ if node in self.cache: ++ return self.cache[node] ++ name = self.gen.name_gather(node) ++ self.cache[node] = name, f"self.{name}()" # No trailing comma here either! ++ return self.cache[node] ++ ++ def visit_Group(self, node: Group) -> Tuple[Optional[str], str]: ++ return self.visit(node.rhs) ++ ++ def visit_Cut(self, node: Cut) -> Tuple[str, str]: ++ return "cut", "True" ++ ++ ++class PythonParserGenerator(ParserGenerator, GrammarVisitor): ++ def __init__(self, grammar: grammar.Grammar, file: Optional[IO[Text]]): ++ super().__init__(grammar, file) ++ self.callmakervisitor = PythonCallMakerVisitor(self) ++ ++ def generate(self, filename: str) -> None: ++ header = self.grammar.metas.get("header", MODULE_PREFIX) ++ if header is not None: ++ self.print(header.rstrip("\n").format(filename=filename)) ++ subheader = self.grammar.metas.get("subheader", "") ++ if subheader: ++ self.print(subheader.format(filename=filename)) ++ self.print("class GeneratedParser(Parser):") ++ while self.todo: ++ for rulename, rule in list(self.todo.items()): ++ del self.todo[rulename] ++ self.print() ++ with self.indent(): ++ self.visit(rule) ++ trailer = self.grammar.metas.get("trailer", MODULE_SUFFIX) ++ if trailer is not None: ++ self.print(trailer.rstrip("\n")) ++ ++ def visit_Rule(self, node: Rule) -> None: ++ is_loop = node.is_loop() ++ is_gather = node.is_gather() ++ rhs = node.flatten() ++ if node.left_recursive: ++ if node.leader: ++ self.print("@memoize_left_rec") ++ else: ++ # Non-leader rules in a cycle are not memoized, ++ # but they must still be logged. ++ self.print("@logger") ++ else: ++ self.print("@memoize") ++ node_type = node.type or "Any" ++ self.print(f"def {node.name}(self) -> Optional[{node_type}]:") ++ with self.indent(): ++ self.print(f"# {node.name}: {rhs}") ++ if node.nullable: ++ self.print(f"# nullable={node.nullable}") ++ self.print("mark = self.mark()") ++ if is_loop: ++ self.print("children = []") ++ self.visit(rhs, is_loop=is_loop, is_gather=is_gather) ++ if is_loop: ++ self.print("return children") ++ else: ++ self.print("return None") ++ ++ def visit_NamedItem(self, node: NamedItem, names: List[str]) -> None: ++ name, call = self.callmakervisitor.visit(node.item) ++ if node.name: ++ name = node.name ++ if not name: ++ self.print(call) ++ else: ++ if name != "cut": ++ name = dedupe(name, names) ++ self.print(f"({name} := {call})") ++ ++ def visit_Rhs(self, node: Rhs, is_loop: bool = False, is_gather: bool = False) -> None: ++ if is_loop: ++ assert len(node.alts) == 1 ++ for alt in node.alts: ++ self.visit(alt, is_loop=is_loop, is_gather=is_gather) ++ ++ def visit_Alt(self, node: Alt, is_loop: bool, is_gather: bool) -> None: ++ names: List[str] = [] ++ self.print("cut = False") # TODO: Only if needed. ++ if is_loop: ++ self.print("while (") ++ else: ++ self.print("if (") ++ with self.indent(): ++ first = True ++ for item in node.items: ++ if first: ++ first = False ++ else: ++ self.print("and") ++ self.visit(item, names=names) ++ self.print("):") ++ with self.indent(): ++ action = node.action ++ if not action: ++ if is_gather: ++ assert len(names) == 2 ++ action = f"[{names[0]}] + {names[1]}" ++ else: ++ action = f"[{', '.join(names)}]" ++ if is_loop: ++ self.print(f"children.append({action})") ++ self.print(f"mark = self.mark()") ++ else: ++ self.print(f"return {action}") ++ self.print("self.reset(mark)") ++ # Skip remaining alternatives if a cut was reached. ++ self.print("if cut: return None") # TODO: Only if needed. +diff --git a/Tools/peg_generator/pegen/sccutils.py b/Tools/peg_generator/pegen/sccutils.py +new file mode 100644 +--- /dev/null ++++ b/Tools/peg_generator/pegen/sccutils.py +@@ -0,0 +1,128 @@ ++# Adapted from mypy (mypy/build.py) under the MIT license. ++ ++from typing import * ++ ++ ++def strongly_connected_components( ++ vertices: AbstractSet[str], edges: Dict[str, AbstractSet[str]] ++) -> Iterator[AbstractSet[str]]: ++ """Compute Strongly Connected Components of a directed graph. ++ ++ Args: ++ vertices: the labels for the vertices ++ edges: for each vertex, gives the target vertices of its outgoing edges ++ ++ Returns: ++ An iterator yielding strongly connected components, each ++ represented as a set of vertices. Each input vertex will occur ++ exactly once; vertices not part of a SCC are returned as ++ singleton sets. ++ ++ From http://code.activestate.com/recipes/578507/. ++ """ ++ identified: Set[str] = set() ++ stack: List[str] = [] ++ index: Dict[str, int] = {} ++ boundaries: List[int] = [] ++ ++ def dfs(v: str) -> Iterator[Set[str]]: ++ index[v] = len(stack) ++ stack.append(v) ++ boundaries.append(index[v]) ++ ++ for w in edges[v]: ++ if w not in index: ++ yield from dfs(w) ++ elif w not in identified: ++ while index[w] < boundaries[-1]: ++ boundaries.pop() ++ ++ if boundaries[-1] == index[v]: ++ boundaries.pop() ++ scc = set(stack[index[v] :]) ++ del stack[index[v] :] ++ identified.update(scc) ++ yield scc ++ ++ for v in vertices: ++ if v not in index: ++ yield from dfs(v) ++ ++ ++def topsort( ++ data: Dict[AbstractSet[str], Set[AbstractSet[str]]] ++) -> Iterable[AbstractSet[AbstractSet[str]]]: ++ """Topological sort. ++ ++ Args: ++ data: A map from SCCs (represented as frozen sets of strings) to ++ sets of SCCs, its dependencies. NOTE: This data structure ++ is modified in place -- for normalization purposes, ++ self-dependencies are removed and entries representing ++ orphans are added. ++ ++ Returns: ++ An iterator yielding sets of SCCs that have an equivalent ++ ordering. NOTE: The algorithm doesn't care about the internal ++ structure of SCCs. ++ ++ Example: ++ Suppose the input has the following structure: ++ ++ {A: {B, C}, B: {D}, C: {D}} ++ ++ This is normalized to: ++ ++ {A: {B, C}, B: {D}, C: {D}, D: {}} ++ ++ The algorithm will yield the following values: ++ ++ {D} ++ {B, C} ++ {A} ++ ++ From http://code.activestate.com/recipes/577413/. ++ """ ++ # TODO: Use a faster algorithm? ++ for k, v in data.items(): ++ v.discard(k) # Ignore self dependencies. ++ for item in set.union(*data.values()) - set(data.keys()): ++ data[item] = set() ++ while True: ++ ready = {item for item, dep in data.items() if not dep} ++ if not ready: ++ break ++ yield ready ++ data = {item: (dep - ready) for item, dep in data.items() if item not in ready} ++ assert not data, "A cyclic dependency exists amongst %r" % data ++ ++ ++def find_cycles_in_scc( ++ graph: Dict[str, AbstractSet[str]], scc: AbstractSet[str], start: str ++) -> Iterable[List[str]]: ++ """Find cycles in SCC emanating from start. ++ ++ Yields lists of the form ['A', 'B', 'C', 'A'], which means there's ++ a path from A -> B -> C -> A. The first item is always the start ++ argument, but the last item may be another element, e.g. ['A', ++ 'B', 'C', 'B'] means there's a path from A to B and there's a ++ cycle from B to C and back. ++ """ ++ # Basic input checks. ++ assert start in scc, (start, scc) ++ assert scc <= graph.keys(), scc - graph.keys() ++ ++ # Reduce the graph to nodes in the SCC. ++ graph = {src: {dst for dst in dsts if dst in scc} for src, dsts in graph.items() if src in scc} ++ assert start in graph ++ ++ # Recursive helper that yields cycles. ++ def dfs(node: str, path: List[str]) -> Iterator[List[str]]: ++ if node in path: ++ yield path + [node] ++ return ++ path = path + [node] # TODO: Make this not quadratic. ++ for child in graph[node]: ++ yield from dfs(child, path) ++ ++ yield from dfs(start, []) +diff --git a/Tools/peg_generator/pegen/tokenizer.py b/Tools/peg_generator/pegen/tokenizer.py +new file mode 100644 +--- /dev/null ++++ b/Tools/peg_generator/pegen/tokenizer.py +@@ -0,0 +1,86 @@ ++import token ++import tokenize ++from typing import List, Iterator ++ ++Mark = int # NewType('Mark', int) ++ ++exact_token_types = token.EXACT_TOKEN_TYPES # type: ignore ++ ++ ++def shorttok(tok: tokenize.TokenInfo) -> str: ++ return "%-25.25s" % f"{tok.start[0]}.{tok.start[1]}: {token.tok_name[tok.type]}:{tok.string!r}" ++ ++ ++class Tokenizer: ++ """Caching wrapper for the tokenize module. ++ ++ This is pretty tied to Python's syntax. ++ """ ++ ++ _tokens: List[tokenize.TokenInfo] ++ ++ def __init__(self, tokengen: Iterator[tokenize.TokenInfo], *, verbose: bool = False): ++ self._tokengen = tokengen ++ self._tokens = [] ++ self._index = 0 ++ self._verbose = verbose ++ if verbose: ++ self.report(False, False) ++ ++ def getnext(self) -> tokenize.TokenInfo: ++ """Return the next token and updates the index.""" ++ cached = True ++ while self._index == len(self._tokens): ++ tok = next(self._tokengen) ++ if tok.type in (tokenize.NL, tokenize.COMMENT): ++ continue ++ if tok.type == token.ERRORTOKEN and tok.string.isspace(): ++ continue ++ self._tokens.append(tok) ++ cached = False ++ tok = self._tokens[self._index] ++ self._index += 1 ++ if self._verbose: ++ self.report(cached, False) ++ return tok ++ ++ def peek(self) -> tokenize.TokenInfo: ++ """Return the next token *without* updating the index.""" ++ while self._index == len(self._tokens): ++ tok = next(self._tokengen) ++ if tok.type in (tokenize.NL, tokenize.COMMENT): ++ continue ++ if tok.type == token.ERRORTOKEN and tok.string.isspace(): ++ continue ++ self._tokens.append(tok) ++ return self._tokens[self._index] ++ ++ def diagnose(self) -> tokenize.TokenInfo: ++ if not self._tokens: ++ self.getnext() ++ return self._tokens[-1] ++ ++ def mark(self) -> Mark: ++ return self._index ++ ++ def reset(self, index: Mark) -> None: ++ if index == self._index: ++ return ++ assert 0 <= index <= len(self._tokens), (index, len(self._tokens)) ++ old_index = self._index ++ self._index = index ++ if self._verbose: ++ self.report(True, index < old_index) ++ ++ def report(self, cached: bool, back: bool) -> None: ++ if back: ++ fill = "-" * self._index + "-" ++ elif cached: ++ fill = "-" * self._index + ">" ++ else: ++ fill = "-" * self._index + "*" ++ if self._index == 0: ++ print(f"{fill} (Bof)") ++ else: ++ tok = self._tokens[self._index - 1] ++ print(f"{fill} {shorttok(tok)}") +diff --git a/Tools/peg_generator/pyproject.toml b/Tools/peg_generator/pyproject.toml +new file mode 100644 +--- /dev/null ++++ b/Tools/peg_generator/pyproject.toml +@@ -0,0 +1,9 @@ ++[tool.black] ++line-length = 99 ++target_version = ['py38'] ++exclude = ''' ++( ++ /pegen/grammar_parser.py # generated file ++ | /test/test_data/ # test files ++) ++''' +diff --git a/Tools/peg_generator/requirements.pip b/Tools/peg_generator/requirements.pip +new file mode 100644 +--- /dev/null ++++ b/Tools/peg_generator/requirements.pip +@@ -0,0 +1,2 @@ ++memory-profiler==0.57.0 ++psutil==5.7.0 +diff --git a/Tools/peg_generator/scripts/__init__.py b/Tools/peg_generator/scripts/__init__.py +new file mode 100644 +--- /dev/null ++++ b/Tools/peg_generator/scripts/__init__.py +@@ -0,0 +1 @@ ++# This exists to let mypy find modules here +diff --git a/Tools/peg_generator/scripts/ast_timings.py b/Tools/peg_generator/scripts/ast_timings.py +new file mode 100644 +--- /dev/null ++++ b/Tools/peg_generator/scripts/ast_timings.py +@@ -0,0 +1,28 @@ ++import ast ++import sys ++import time ++import token ++import tokenize ++ ++from pegen.testutil import print_memstats ++ ++ ++def main() -> None: ++ t0 = time.time() ++ for filename in sys.argv[1:]: ++ print(filename, end="\r") ++ try: ++ with open(filename) as file: ++ source = file.read() ++ tree = ast.parse(source, filename) ++ except Exception as err: ++ print(f"{filename}: {err.__class__.__name__}: {err}", file=sys.stderr) ++ tok = None ++ t1 = time.time() ++ dt = t1 - t0 ++ print(f"Parsed in {dt:.3f} secs", file=sys.stderr) ++ print_memstats() ++ ++ ++if __name__ == "__main__": ++ main() +diff --git a/Tools/peg_generator/scripts/benchmark.py b/Tools/peg_generator/scripts/benchmark.py +new file mode 100644 +--- /dev/null ++++ b/Tools/peg_generator/scripts/benchmark.py +@@ -0,0 +1,140 @@ ++#!/usr/bin/env python3.9 ++ ++import argparse ++import ast ++import sys ++import os ++import resource ++from time import time ++ ++import memory_profiler ++ ++sys.path.insert(0, os.getcwd()) ++from peg_extension import parse ++from pegen.build import build_parser_and_generator ++from scripts.test_parse_directory import parse_directory ++ ++argparser = argparse.ArgumentParser( ++ prog="benchmark", description="Reproduce the various pegen benchmarks" ++) ++argparser.add_argument( ++ "--parser", ++ action="store", ++ choices=["pegen", "cpython"], ++ default="pegen", ++ help="Which parser to benchmark (default is pegen)", ++) ++argparser.add_argument( ++ "--target", ++ action="store", ++ choices=["xxl", "stdlib"], ++ default="xxl", ++ help="Which target to use for the benchmark (default is xxl.py)", ++) ++ ++subcommands = argparser.add_subparsers(title="Benchmarks", dest="subcommand") ++command_compile = subcommands.add_parser( ++ "compile", help="Benchmark parsing and compiling to bytecode" ++) ++command_parse = subcommands.add_parser("parse", help="Benchmark parsing and generating an ast.AST") ++command_check = subcommands.add_parser( ++ "check", help="Benchmark parsing and throwing the tree away" ++) ++ ++ ++def benchmark(func): ++ def wrapper(*args): ++ times = list() ++ for _ in range(3): ++ start = time() ++ result = func(*args) ++ end = time() ++ times.append(end - start) ++ memory = memory_profiler.memory_usage((func, args)) ++ print(f"{func.__name__}") ++ print(f"\tTime: {sum(times)/3:.3f} seconds on an average of 3 runs") ++ print(f"\tMemory: {max(memory)} MiB on an average of 3 runs") ++ return result ++ ++ return wrapper ++ ++ ++@benchmark ++def time_compile(source, parser): ++ if parser == "cpython": ++ return compile(source, os.path.join("data", "xxl.py"), "exec") ++ else: ++ return parse.parse_string(source, mode=2) ++ ++ ++@benchmark ++def time_parse(source, parser): ++ if parser == "cpython": ++ return ast.parse(source, os.path.join("data", "xxl.py"), "exec") ++ else: ++ return parse.parse_string(source, mode=1) ++ ++ ++@benchmark ++def time_check(source): ++ return parse.parse_string(source, mode=0) ++ ++ ++def run_benchmark_xxl(subcommand, parser, source): ++ if subcommand == "compile": ++ time_compile(source, parser) ++ elif subcommand == "parse": ++ time_parse(source, parser) ++ elif subcommand == "check": ++ time_check(source) ++ ++ ++def run_benchmark_stdlib(subcommand, parser): ++ modes = {"compile": 2, "parse": 1, "check": 0} ++ extension = None ++ if parser == "pegen": ++ extension = build_parser_and_generator( ++ "../../Grammar/python.gram", ++ "peg_extension/parse.c", ++ compile_extension=True, ++ skip_actions=False, ++ ) ++ for _ in range(3): ++ parse_directory( ++ "../../Lib", ++ "../../Grammar/python.gram", ++ verbose=False, ++ excluded_files=[ ++ "*/bad*", ++ "*/lib2to3/tests/data/*", ++ ], ++ skip_actions=False, ++ tree_arg=0, ++ short=True, ++ extension=extension, ++ mode=modes[subcommand], ++ parser=parser, ++ ) ++ ++ ++def main(): ++ args = argparser.parse_args() ++ subcommand = args.subcommand ++ parser = args.parser ++ target = args.target ++ ++ if subcommand is None: ++ argparser.error("A benchmark to run is required") ++ if subcommand == "check" and parser == "cpython": ++ argparser.error("Cannot use check target with the CPython parser") ++ ++ if target == "xxl": ++ with open(os.path.join("data", "xxl.py"), "r") as f: ++ source = f.read() ++ run_benchmark_xxl(subcommand, parser, source) ++ elif target == "stdlib": ++ run_benchmark_stdlib(subcommand, parser) ++ ++ ++if __name__ == "__main__": ++ main() +diff --git a/Tools/peg_generator/scripts/download_pypi_packages.py b/Tools/peg_generator/scripts/download_pypi_packages.py +new file mode 100644 +--- /dev/null ++++ b/Tools/peg_generator/scripts/download_pypi_packages.py +@@ -0,0 +1,86 @@ ++#!/usr/bin/env python3.8 ++ ++import argparse ++import os ++import json ++ ++from typing import Dict, Any ++from urllib.request import urlretrieve ++ ++argparser = argparse.ArgumentParser( ++ prog="download_pypi_packages", description="Helper program to download PyPI packages", ++) ++argparser.add_argument( ++ "-n", "--number", type=int, default=100, help="Number of packages to download" ++) ++argparser.add_argument( ++ "-a", "--all", action="store_true", help="Download all packages listed in the json file" ++) ++ ++ ++def load_json(filename: str) -> Dict[Any, Any]: ++ with open(os.path.join("data", f"{filename}.json"), "r") as f: ++ j = json.loads(f.read()) ++ return j ++ ++ ++def remove_json(filename: str) -> None: ++ path = os.path.join("data", f"{filename}.json") ++ os.remove(path) ++ ++ ++def download_package_json(package_name: str) -> None: ++ url = f"https://pypi.org/pypi/{package_name}/json" ++ urlretrieve(url, os.path.join("data", f"{package_name}.json")) ++ ++ ++def download_package_code(name: str, package_json: Dict[Any, Any]) -> None: ++ source_index = -1 ++ for idx, url_info in enumerate(package_json["urls"]): ++ if url_info["python_version"] == "source": ++ source_index = idx ++ break ++ filename = package_json["urls"][source_index]["filename"] ++ url = package_json["urls"][source_index]["url"] ++ urlretrieve(url, os.path.join("data", "pypi", filename)) ++ ++ ++def main() -> None: ++ args = argparser.parse_args() ++ number_packages = args.number ++ all_packages = args.all ++ ++ top_pypi_packages = load_json("top-pypi-packages-365-days") ++ if all_packages: ++ top_pypi_packages = top_pypi_packages["rows"] ++ elif number_packages >= 0 and number_packages <= 4000: ++ top_pypi_packages = top_pypi_packages["rows"][:number_packages] ++ else: ++ raise AssertionError("Unknown value for NUMBER_OF_PACKAGES") ++ ++ try: ++ os.mkdir(os.path.join("data", "pypi")) ++ except FileExistsError: ++ pass ++ ++ for package in top_pypi_packages: ++ package_name = package["project"] ++ ++ print(f"Downloading JSON Data for {package_name}... ", end="") ++ download_package_json(package_name) ++ print("Done") ++ ++ package_json = load_json(package_name) ++ try: ++ print(f"Dowloading and compressing package {package_name} ... ", end="") ++ download_package_code(package_name, package_json) ++ print("Done") ++ except (IndexError, KeyError): ++ print(f"Could not locate source for {package_name}") ++ continue ++ finally: ++ remove_json(package_name) ++ ++ ++if __name__ == "__main__": ++ main() +diff --git a/Tools/peg_generator/scripts/find_max_nesting.py b/Tools/peg_generator/scripts/find_max_nesting.py +new file mode 100644 +--- /dev/null ++++ b/Tools/peg_generator/scripts/find_max_nesting.py +@@ -0,0 +1,61 @@ ++#!/usr/bin/env python3.8 ++"""Find the maximum amount of nesting for an expression that can be parsed ++without causing a parse error. ++ ++Starting at the INITIAL_NESTING_DEPTH, an expression containing n parenthesis ++around a 0 is generated then tested with both the C and Python parsers. We ++continue incrementing the number of parenthesis by 10 until both parsers have ++failed. As soon as a single parser fails, we stop testing that parser. ++ ++The grammar file, initial nesting size, and amount by which the nested size is ++incremented on each success can be controlled by changing the GRAMMAR_FILE, ++INITIAL_NESTING_DEPTH, or NESTED_INCR_AMT variables. ++ ++Usage: python -m scripts.find_max_nesting ++""" ++import os ++import sys ++from tempfile import TemporaryDirectory ++from pathlib import Path ++from typing import Any ++ ++from _peg_parser import parse_string ++ ++GRAMMAR_FILE = "data/python.gram" ++INITIAL_NESTING_DEPTH = 10 ++NESTED_INCR_AMT = 10 ++ ++ ++FAIL = "\033[91m" ++ENDC = "\033[0m" ++ ++ ++def check_nested_expr(nesting_depth: int) -> bool: ++ expr = f"{'(' * nesting_depth}0{')' * nesting_depth}" ++ ++ try: ++ parse_string(expr) ++ print(f"Nesting depth of {nesting_depth} is successful") ++ return True ++ except Exception as err: ++ print(f"{FAIL}(Failed with nesting depth of {nesting_depth}{ENDC}") ++ print(f"{FAIL}\t{err}{ENDC}") ++ return False ++ ++ ++def main() -> None: ++ print(f"Testing {GRAMMAR_FILE} starting at nesting depth of {INITIAL_NESTING_DEPTH}...") ++ ++ nesting_depth = INITIAL_NESTING_DEPTH ++ succeeded = True ++ while succeeded: ++ expr = f"{'(' * nesting_depth}0{')' * nesting_depth}" ++ if succeeded: ++ succeeded = check_nested_expr(nesting_depth) ++ nesting_depth += NESTED_INCR_AMT ++ ++ sys.exit(1) ++ ++ ++if __name__ == "__main__": ++ main() +diff --git a/Tools/peg_generator/scripts/grammar_grapher.py b/Tools/peg_generator/scripts/grammar_grapher.py +new file mode 100644 +--- /dev/null ++++ b/Tools/peg_generator/scripts/grammar_grapher.py +@@ -0,0 +1,111 @@ ++#!/usr/bin/env python3.8 ++ ++""" Convert a grammar into a dot-file suitable for use with GraphViz ++ ++ For example: ++ Generate the GraphViz file: ++ # scripts/grammar_grapher.py data/python.gram > python.gv ++ ++ Then generate the graph... ++ ++ # twopi python.gv -Tpng > python_twopi.png ++ ++ or ++ ++ # dot python.gv -Tpng > python_dot.png ++ ++ NOTE: The _dot_ and _twopi_ tools seem to produce the most useful results. ++ The _circo_ tool is the worst of the bunch. Don't even bother. ++""" ++ ++import argparse ++import sys ++ ++from typing import Any, List ++ ++sys.path.insert(0, ".") ++ ++from pegen.build import build_parser ++from pegen.grammar import ( ++ Alt, ++ Cut, ++ Grammar, ++ Group, ++ Leaf, ++ Lookahead, ++ Rule, ++ NameLeaf, ++ NamedItem, ++ Opt, ++ Repeat, ++ Rhs, ++) ++ ++argparser = argparse.ArgumentParser(prog="graph_grammar", description="Graph a grammar tree",) ++argparser.add_argument("grammar_file", help="The grammar file to graph") ++ ++ ++def references_for_item(item: Any) -> List[Any]: ++ if isinstance(item, Alt): ++ return [_ref for _item in item.items for _ref in references_for_item(_item)] ++ elif isinstance(item, Cut): ++ return [] ++ elif isinstance(item, Group): ++ return references_for_item(item.rhs) ++ elif isinstance(item, Lookahead): ++ return references_for_item(item.node) ++ elif isinstance(item, NamedItem): ++ return references_for_item(item.item) ++ ++ # NOTE NameLeaf must be before Leaf ++ elif isinstance(item, NameLeaf): ++ if item.value == "ENDMARKER": ++ return [] ++ return [item.value] ++ elif isinstance(item, Leaf): ++ return [] ++ ++ elif isinstance(item, Opt): ++ return references_for_item(item.node) ++ elif isinstance(item, Repeat): ++ return references_for_item(item.node) ++ elif isinstance(item, Rhs): ++ return [_ref for alt in item.alts for _ref in references_for_item(alt)] ++ elif isinstance(item, Rule): ++ return references_for_item(item.rhs) ++ else: ++ raise RuntimeError(f"Unknown item: {type(item)}") ++ ++ ++def main() -> None: ++ args = argparser.parse_args() ++ ++ try: ++ grammar, parser, tokenizer = build_parser(args.grammar_file) ++ except Exception as err: ++ print("ERROR: Failed to parse grammar file", file=sys.stderr) ++ sys.exit(1) ++ ++ references = {} ++ for name, rule in grammar.rules.items(): ++ references[name] = set(references_for_item(rule)) ++ ++ # Flatten the start node if has only a single reference ++ root_node = "start" ++ if start := references["start"]: ++ if len(start) == 1: ++ root_node = list(start)[0] ++ del references["start"] ++ ++ print("digraph g1 {") ++ print('\toverlap="scale";') # Force twopi to scale the graph to avoid overlaps ++ print(f'\troot="{root_node}";') ++ print(f"\t{root_node} [color=green, shape=circle]") ++ for name, refs in references.items(): ++ if refs: # Ignore empty sets ++ print(f"\t{name} -> {','.join(refs)};") ++ print("}") ++ ++ ++if __name__ == "__main__": ++ main() +diff --git a/Tools/peg_generator/scripts/joinstats.py b/Tools/peg_generator/scripts/joinstats.py +new file mode 100644 +--- /dev/null ++++ b/Tools/peg_generator/scripts/joinstats.py +@@ -0,0 +1,66 @@ ++#!/usr/bin/env python3.8 ++ ++"""Produce a report about the most-memoable types. ++ ++Reads a list of statistics from stdin. Each line must be two numbers, ++being a type and a count. We then read some other files and produce a ++list sorted by most frequent type. ++ ++There should also be something to recognize left-recursive rules. ++""" ++ ++import os ++import re ++import sys ++ ++from typing import Dict ++ ++reporoot = os.path.dirname(os.path.dirname(__file__)) ++parse_c = os.path.join(reporoot, "peg_extension", "parse.c") ++ ++ ++class TypeMapper: ++ """State used to map types to names.""" ++ ++ def __init__(self, filename: str) -> None: ++ self.table: Dict[int, str] = {} ++ with open(filename) as f: ++ for line in f: ++ match = re.match(r"#define (\w+)_type (\d+)", line) ++ if match: ++ name, type = match.groups() ++ if "left" in line.lower(): ++ name += " // Left-recursive" ++ self.table[int(type)] = name ++ ++ def lookup(self, type: int) -> str: ++ return self.table.get(type, str(type)) ++ ++ ++def main() -> None: ++ mapper = TypeMapper(parse_c) ++ table = [] ++ filename = sys.argv[1] ++ with open(filename) as f: ++ for lineno, line in enumerate(f, 1): ++ line = line.strip() ++ if not line or line.startswith("#"): ++ continue ++ parts = line.split() ++ # Extra fields ignored ++ if len(parts) < 2: ++ print(f"{lineno}: bad input ({line!r})") ++ continue ++ try: ++ type, count = map(int, parts[:2]) ++ except ValueError as err: ++ print(f"{lineno}: non-integer input ({line!r})") ++ continue ++ table.append((type, count)) ++ table.sort(key=lambda values: -values[1]) ++ for type, count in table: ++ print(f"{type:4d} {count:9d} {mapper.lookup(type)}") ++ ++ ++if __name__ == "__main__": ++ main() +diff --git a/Tools/peg_generator/scripts/show_parse.py b/Tools/peg_generator/scripts/show_parse.py +new file mode 100644 +--- /dev/null ++++ b/Tools/peg_generator/scripts/show_parse.py +@@ -0,0 +1,117 @@ ++#!/usr/bin/env python3.8 ++ ++"""Show the parse tree for a given program, nicely formatted. ++ ++Example: ++ ++$ scripts/show_parse.py a+b ++Module( ++ body=[ ++ Expr( ++ value=BinOp( ++ left=Name(id="a", ctx=Load()), op=Add(), right=Name(id="b", ctx=Load()) ++ ) ++ ) ++ ], ++ type_ignores=[], ++) ++$ ++ ++Use -v to show line numbers and column offsets. ++ ++The formatting is done using black. You can also import this module ++and call one of its functions. ++""" ++ ++import argparse ++import ast ++import difflib ++import os ++import sys ++import tempfile ++ ++from typing import List ++ ++parser = argparse.ArgumentParser() ++parser.add_argument( ++ "-d", "--diff", action="store_true", help="show diff between grammar and ast (requires -g)" ++) ++parser.add_argument("-g", "--grammar-file", help="grammar to use (default: use the ast module)") ++parser.add_argument( ++ "-m", ++ "--multiline", ++ action="store_true", ++ help="concatenate program arguments using newline instead of space", ++) ++parser.add_argument("-v", "--verbose", action="store_true", help="show line/column numbers") ++parser.add_argument("program", nargs="+", help="program to parse (will be concatenated)") ++ ++ ++def format_tree(tree: ast.AST, verbose: bool = False) -> str: ++ with tempfile.NamedTemporaryFile("w+") as tf: ++ tf.write(ast.dump(tree, include_attributes=verbose)) ++ tf.write("\n") ++ tf.flush() ++ cmd = f"black -q {tf.name}" ++ sts = os.system(cmd) ++ if sts: ++ raise RuntimeError(f"Command {cmd!r} failed with status 0x{sts:x}") ++ tf.seek(0) ++ return tf.read() ++ ++ ++def diff_trees(a: ast.AST, b: ast.AST, verbose: bool = False) -> List[str]: ++ sa = format_tree(a, verbose) ++ sb = format_tree(b, verbose) ++ la = sa.splitlines() ++ lb = sb.splitlines() ++ return list(difflib.unified_diff(la, lb, "a", "b", lineterm="")) ++ ++ ++def show_parse(source: str, verbose: bool = False) -> str: ++ tree = ast.parse(source) ++ return format_tree(tree, verbose).rstrip("\n") ++ ++ ++def print_parse(source: str, verbose: bool = False) -> None: ++ print(show_parse(source, verbose)) ++ ++ ++def main() -> None: ++ args = parser.parse_args() ++ if args.diff and not args.grammar_file: ++ parser.error("-d/--diff requires -g/--grammar-file") ++ if args.multiline: ++ sep = "\n" ++ else: ++ sep = " " ++ program = sep.join(args.program) ++ if args.grammar_file: ++ sys.path.insert(0, os.curdir) ++ from pegen.build import build_parser_and_generator ++ ++ build_parser_and_generator(args.grammar_file, "peg_parser/parse.c", compile_extension=True) ++ from pegen.parse import parse_string # type: ignore[import] ++ ++ tree = parse_string(program, mode=1) ++ ++ if args.diff: ++ a = tree ++ b = ast.parse(program) ++ diff = diff_trees(a, b, args.verbose) ++ if diff: ++ for line in diff: ++ print(line) ++ else: ++ print("# Trees are the same") ++ else: ++ print(f"# Parsed using {args.grammar_file}") ++ print(format_tree(tree, args.verbose)) ++ else: ++ tree = ast.parse(program) ++ print("# Parse using ast.parse()") ++ print(format_tree(tree, args.verbose)) ++ ++ ++if __name__ == "__main__": ++ main() diff --git a/cpython_1/solution/solve.sh b/cpython_1/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..ec47b6ed6912fea878ed6be9f7d103082605d01e --- /dev/null +++ b/cpython_1/solution/solve.sh @@ -0,0 +1,7 @@ +#!/usr/bin/env bash +set -euo pipefail + +cd /workspace/cpython +patch=${LOLBENCH_ORACLE_PATCH:-/solution/solution.patch} +git apply "$patch" +lolbench-submit diff --git a/cpython_1/task.toml b/cpython_1/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..d413ea9b971ba1cdf5d059c15676737724f4aead --- /dev/null +++ b/cpython_1/task.toml @@ -0,0 +1,60 @@ +schema_version = "1.3" + +[task] +name = "lolbench/cpython_1" +description = "Implement CPython - PEP 617: New PEG parser for CPython." +authors = [{ name = "LoLBench maintainers" }] +keywords = ["lolbench", "coding-agent", "cpython", "c", "python"] + +[metadata] +instance_id = "cpython_1" +source_instance_id = "CPython_PEP-617_New-PEG-parser-for-CPython_PR-19503" +source_slug = "CPython_PEP-617_New-PEG-parser-for-CPython_PR-19503" +docker_slug = "CPython_PEP-617_New-PEG-parser-for-CPython_PR-19503" +dockerhub_image = "smartdub26/lolbench-linux:cpython_1-1.0.0" +project = "cpython" +repo = "python/cpython" +requirement_doc = "https://peps.python.org/pep-0617/" +pr_link = "https://github.com/python/cpython/pull/19503" +base_commit = "a81849b0315277bb3937271174aaaa5059c0b445" +merge_commit = "c5fc15685202cda73f7c3f5c6f299b0945f58508" +test_level = "system" +source_history_policy = "ancestors-only" +lolbench_test_modes = ["orig", "aug", "union"] +default_lolbench_suite = "union" +canonical_lolbench_suite = "union" +augmentation_available = true +verifier_network_policy = "public" +verifier_network_reason = "The Harbor verifier runs in a separate container and may use network access; migrated LoLBench verifier assets are mounted only in the verifier phase." + +[environment] +build_timeout_sec = 3600.0 +docker_image = "smartdub26/lolbench-linux:cpython_1-1.0.0" +network_mode = "public" +os = "linux" +cpus = 4 +memory_mb = 7168 +storage_mb = 20480 + +[agent] +timeout_sec = 21600.0 +user = "agent" +network_mode = "allowlist" +allowed_hosts = ["openrouter.ai", "api.openai.com", "api.anthropic.com"] + +[verifier] +timeout_sec = 5400.0 +user = "root" +environment_mode = "separate" +network_mode = "public" + +[verifier.env] +LOLBENCH_SUITE = "union" + +[verifier.environment] +docker_image = "smartdub26/lolbench-linux:cpython_1-1.0.0" +network_mode = "public" +os = "linux" +cpus = 4 +memory_mb = 7168 +storage_mb = 20480 diff --git a/cpython_1/tests/docker-compose.yaml b/cpython_1/tests/docker-compose.yaml new file mode 100644 index 0000000000000000000000000000000000000000..f5091b9298e127a1efbe69deeed699c907e025c1 --- /dev/null +++ b/cpython_1/tests/docker-compose.yaml @@ -0,0 +1,16 @@ +services: + main: + pull_policy: missing + volumes: + - type: bind + source: . + target: /tests + read_only: true + - type: bind + source: ./private + target: /opt/lolbench/private + read_only: true + - type: bind + source: ../solution + target: /solution + read_only: true diff --git a/cpython_1/tests/private/eval_helpers.patch b/cpython_1/tests/private/eval_helpers.patch new file mode 100644 index 0000000000000000000000000000000000000000..290bc2c41ebfede7fa4382887f17c9902eba637b --- /dev/null +++ b/cpython_1/tests/private/eval_helpers.patch @@ -0,0 +1,131 @@ +diff --git a/Tools/peg_generator/pegen/testutil.py b/Tools/peg_generator/pegen/testutil.py +new file mode 100644 +--- /dev/null ++++ b/Tools/peg_generator/pegen/testutil.py +@@ -0,0 +1,126 @@ ++import importlib.util ++import io ++import os ++import pathlib ++import sys ++import textwrap ++import tokenize ++ ++from typing import Any, cast, Dict, IO, Type, Final ++ ++from pegen.build import compile_c_extension ++from pegen.c_generator import CParserGenerator ++from pegen.grammar import Grammar ++from pegen.grammar_parser import GeneratedParser as GrammarParser ++from pegen.parser import Parser ++from pegen.python_generator import PythonParserGenerator ++from pegen.tokenizer import Tokenizer ++ ++ ++def generate_parser(grammar: Grammar) -> Type[Parser]: ++ # Generate a parser. ++ out = io.StringIO() ++ genr = PythonParserGenerator(grammar, out) ++ genr.generate("") ++ ++ # Load the generated parser class. ++ ns: Dict[str, Any] = {} ++ exec(out.getvalue(), ns) ++ return ns["GeneratedParser"] ++ ++ ++def run_parser(file: IO[bytes], parser_class: Type[Parser], *, verbose: bool = False) -> Any: ++ # Run a parser on a file (stream). ++ tokenizer = Tokenizer(tokenize.generate_tokens(file.readline)) # type: ignore # typeshed issue #3515 ++ parser = parser_class(tokenizer, verbose=verbose) ++ result = parser.start() ++ if result is None: ++ raise parser.make_syntax_error() ++ return result ++ ++ ++def parse_string( ++ source: str, parser_class: Type[Parser], *, dedent: bool = True, verbose: bool = False ++) -> Any: ++ # Run the parser on a string. ++ if dedent: ++ source = textwrap.dedent(source) ++ file = io.StringIO(source) ++ return run_parser(file, parser_class, verbose=verbose) # type: ignore # typeshed issue #3515 ++ ++ ++def make_parser(source: str) -> Type[Parser]: ++ # Combine parse_string() and generate_parser(). ++ grammar = parse_string(source, GrammarParser) ++ return generate_parser(grammar) ++ ++ ++def import_file(full_name: str, path: str) -> Any: ++ """Import a python module from a path""" ++ ++ spec = importlib.util.spec_from_file_location(full_name, path) ++ mod = importlib.util.module_from_spec(spec) ++ ++ # We assume this is not None and has an exec_module() method. ++ # See https://docs.python.org/3/reference/import.html?highlight=exec_module#loading ++ loader = cast(Any, spec.loader) ++ loader.exec_module(mod) ++ return mod ++ ++ ++def generate_c_parser_source(grammar: Grammar) -> str: ++ out = io.StringIO() ++ genr = CParserGenerator(grammar, out) ++ genr.generate("") ++ return out.getvalue() ++ ++ ++def generate_parser_c_extension( ++ grammar: Grammar, path: pathlib.PurePath, debug: bool = False ++) -> Any: ++ """Generate a parser c extension for the given grammar in the given path ++ ++ Returns a module object with a parse_string() method. ++ TODO: express that using a Protocol. ++ """ ++ # Make sure that the working directory is empty: reusing non-empty temporary ++ # directories when generating extensions can lead to segmentation faults. ++ # Check issue #95 (https://github.com/gvanrossum/pegen/issues/95) for more ++ # context. ++ assert not os.listdir(path) ++ source = path / "parse.c" ++ with open(source, "w") as file: ++ genr = CParserGenerator(grammar, file, debug=debug) ++ genr.generate("parse.c") ++ extension_path = compile_c_extension(str(source), build_dir=str(path / "build")) ++ extension = import_file("parse", extension_path) ++ return extension ++ ++ ++def print_memstats() -> bool: ++ MiB: Final = 2 ** 20 ++ try: ++ import psutil # type: ignore ++ except ImportError: ++ return False ++ print("Memory stats:") ++ process = psutil.Process() ++ meminfo = process.memory_info() ++ res = {} ++ res["rss"] = meminfo.rss / MiB ++ res["vms"] = meminfo.vms / MiB ++ if sys.platform == "win32": ++ res["maxrss"] = meminfo.peak_wset / MiB ++ else: ++ # See https://stackoverflow.com/questions/938733/total-memory-used-by-python-process ++ import resource # Since it doesn't exist on Windows. ++ ++ rusage = resource.getrusage(resource.RUSAGE_SELF) ++ if sys.platform == "darwin": ++ factor = 1 ++ else: ++ factor = 1024 # Linux ++ res["maxrss"] = rusage.ru_maxrss * factor / MiB ++ for key, value in res.items(): ++ print(f" {key:12.12s}: {value:10.0f} MiB") ++ return True diff --git a/cpython_1/tests/private/eval_tests.patch b/cpython_1/tests/private/eval_tests.patch new file mode 100644 index 0000000000000000000000000000000000000000..739066c8e19741c323b062b8028d99f25e8c50aa --- /dev/null +++ b/cpython_1/tests/private/eval_tests.patch @@ -0,0 +1,2742 @@ +diff --git a/Lib/test/test_cmd_line_script.py b/Lib/test/test_cmd_line_script.py +--- a/Lib/test/test_cmd_line_script.py ++++ b/Lib/test/test_cmd_line_script.py +@@ -599,7 +599,7 @@ def test_syntaxerror_unindented_caret_position(self): + exitcode, stdout, stderr = assert_python_failure(script_name) + text = io.TextIOWrapper(io.BytesIO(stderr), 'ascii').read() + # Confirm that the caret is located under the first 1 character +- self.assertIn("\n 1 + 1 = 2\n ^", text) ++ self.assertIn("\n 1 + 1 = 2\n ^", text) + + def test_syntaxerror_indented_caret_position(self): + script = textwrap.dedent("""\ +@@ -611,7 +611,7 @@ def test_syntaxerror_indented_caret_position(self): + exitcode, stdout, stderr = assert_python_failure(script_name) + text = io.TextIOWrapper(io.BytesIO(stderr), 'ascii').read() + # Confirm that the caret is located under the first 1 character +- self.assertIn("\n 1 + 1 = 2\n ^", text) ++ self.assertIn("\n 1 + 1 = 2\n ^", text) + + # Try the same with a form feed at the start of the indented line + script = ( +@@ -622,7 +622,7 @@ def test_syntaxerror_indented_caret_position(self): + exitcode, stdout, stderr = assert_python_failure(script_name) + text = io.TextIOWrapper(io.BytesIO(stderr), "ascii").read() + self.assertNotIn("\f", text) +- self.assertIn("\n 1 + 1 = 2\n ^", text) ++ self.assertIn("\n 1 + 1 = 2\n ^", text) + + def test_syntaxerror_multi_line_fstring(self): + script = 'foo = f"""{}\nfoo"""\n' +@@ -632,25 +632,24 @@ def test_syntaxerror_multi_line_fstring(self): + self.assertEqual( + stderr.splitlines()[-3:], + [ +- b' foo = f"""{}', +- b' ^', ++ b' foo"""', ++ b' ^', + b'SyntaxError: f-string: empty expression not allowed', + ], + ) + + def test_syntaxerror_invalid_escape_sequence_multi_line(self): +- script = 'foo = """\\q\n"""\n' ++ script = 'foo = """\\q"""\n' + with support.temp_dir() as script_dir: + script_name = _make_test_script(script_dir, 'script', script) + exitcode, stdout, stderr = assert_python_failure( + '-Werror', script_name, + ) + self.assertEqual( + stderr.splitlines()[-3:], +- [ +- b' foo = """\\q', +- b' ^', +- b'SyntaxError: invalid escape sequence \\q', ++ [ b' foo = """\\q"""', ++ b' ^', ++ b'SyntaxError: invalid escape sequence \\q' + ], + ) + +diff --git a/Lib/test/test_codeop.py b/Lib/test/test_codeop.py +--- a/Lib/test/test_codeop.py ++++ b/Lib/test/test_codeop.py +@@ -2,14 +2,14 @@ + Test cases for codeop.py + Nick Mathewson + """ ++import sys + import unittest + from test.support import is_jython + + from codeop import compile_command, PyCF_DONT_IMPLY_DEDENT + import io + + if is_jython: +- import sys + + def unify_callables(d): + for n,v in d.items(): +@@ -122,6 +122,7 @@ def test_valid(self): + av("def f():\n pass\n#foo\n") + av("@a.b.c\ndef f():\n pass\n") + ++ @unittest.skipIf(sys.flags.use_peg, "Pegen does not support PyCF_DONT_INPLY_DEDENT yet") + def test_incomplete(self): + ai = self.assertIncomplete + +diff --git a/Lib/test/test_compile.py b/Lib/test/test_compile.py +--- a/Lib/test/test_compile.py ++++ b/Lib/test/test_compile.py +@@ -501,6 +501,7 @@ def test_single_statement(self): + self.compile_single("if x:\n f(x)\nelse:\n g(x)") + self.compile_single("class T:\n pass") + ++ @unittest.skipIf(sys.flags.use_peg, 'Pegen does not disallow multiline single stmts') + def test_bad_single_statement(self): + self.assertInvalidSingle('1\n2') + self.assertInvalidSingle('def f(): pass') +diff --git a/Lib/test/test_embed.py b/Lib/test/test_embed.py +--- a/Lib/test/test_embed.py ++++ b/Lib/test/test_embed.py +@@ -347,6 +347,7 @@ class InitConfigTests(EmbeddingTestsMixin, unittest.TestCase): + 'isolated': 0, + 'use_environment': 1, + 'dev_mode': 0, ++ 'use_peg': 1, + + 'install_signal_handlers': 1, + 'use_hash_seed': 0, +@@ -728,6 +729,7 @@ def test_init_from_config(self): + 'import_time': 1, + 'show_ref_count': 1, + 'malloc_stats': 1, ++ 'use_peg': 0, + + 'stdio_encoding': 'iso8859-1', + 'stdio_errors': 'replace', +diff --git a/Lib/test/test_eof.py b/Lib/test/test_eof.py +--- a/Lib/test/test_eof.py ++++ b/Lib/test/test_eof.py +@@ -26,6 +26,7 @@ def test_EOFS(self): + else: + raise support.TestFailed + ++ @unittest.skipIf(sys.flags.use_peg, "TODO for PEG -- fails with new parser") + def test_line_continuation_EOF(self): + """A continuation at the end of input must be an error; bpo2180.""" + expect = 'unexpected EOF while parsing (, line 1)' +@@ -36,6 +37,7 @@ def test_line_continuation_EOF(self): + exec('\\') + self.assertEqual(str(excinfo.exception), expect) + ++ @unittest.skip("TODO for PEG -- fails even with old parser now") + @unittest.skipIf(not sys.executable, "sys.executable required") + def test_line_continuation_EOF_from_file_bpo2180(self): + """Ensure tok_nextc() does not add too many ending newlines.""" +diff --git a/Lib/test/test_exceptions.py b/Lib/test/test_exceptions.py +--- a/Lib/test/test_exceptions.py ++++ b/Lib/test/test_exceptions.py +@@ -178,6 +178,7 @@ def ckmsg(src, msg, exception=SyntaxError): + s = '''if True:\n print()\n\texec "mixed tabs and spaces"''' + ckmsg(s, "inconsistent use of tabs and spaces in indentation", TabError) + ++ @unittest.skipIf(sys.flags.use_peg, "Pegen column offsets might be different") + def testSyntaxErrorOffset(self): + def check(src, lineno, offset, encoding='utf-8'): + with self.assertRaises(SyntaxError) as cm: +diff --git a/Lib/test/test_flufl.py b/Lib/test/test_flufl.py +--- a/Lib/test/test_flufl.py ++++ b/Lib/test/test_flufl.py +@@ -1,6 +1,9 @@ + import __future__ + import unittest ++import sys + ++ ++@unittest.skipIf(sys.flags.use_peg, "Not supported by pegen yet") + class FLUFLTests(unittest.TestCase): + + def test_barry_as_bdfl(self): +diff --git a/Lib/test/test_fstring.py b/Lib/test/test_fstring.py +--- a/Lib/test/test_fstring.py ++++ b/Lib/test/test_fstring.py +@@ -10,6 +10,7 @@ + import ast + import types + import decimal ++import sys + import unittest + + a_global = 'global variable' +@@ -205,7 +206,8 @@ def test_ast_line_numbers_nested(self): + call = binop.right.values[1].value + self.assertEqual(type(call), ast.Call) + self.assertEqual(call.lineno, 3) +- self.assertEqual(call.col_offset, 11) ++ if not sys.flags.use_peg: ++ self.assertEqual(call.col_offset, 11) + + def test_ast_line_numbers_duplicate_expression(self): + """Duplicate expression +diff --git a/Lib/test/test_generators.py b/Lib/test/test_generators.py +--- a/Lib/test/test_generators.py ++++ b/Lib/test/test_generators.py +@@ -1856,10 +1856,11 @@ def printsolution(self, x): + ... + SyntaxError: 'yield' outside function + +->>> def f(): x = yield = y +-Traceback (most recent call last): +- ... +-SyntaxError: assignment to yield expression not possible ++# Pegen does not produce this error message yet ++# >>> def f(): x = yield = y ++# Traceback (most recent call last): ++# ... ++# SyntaxError: assignment to yield expression not possible + + >>> def f(): (yield bar) = y + Traceback (most recent call last): +diff --git a/Lib/test/test_parser.py b/Lib/test/test_parser.py +--- a/Lib/test/test_parser.py ++++ b/Lib/test/test_parser.py +@@ -8,6 +8,7 @@ + import unittest + import operator + import struct ++import sys + from test import support + from test.support.script_helper import assert_python_failure + from test.support.script_helper import assert_python_ok +@@ -899,9 +900,10 @@ def test_deeply_nested_list(self): + st = parser.expr(e) + st.compile() + ++ @unittest.skipIf(sys.flags.use_peg, "Pegen does not trigger memory error with this many parenthesis") + def test_trigger_memory_error(self): + e = self._nested_expression(100) +- rc, out, err = assert_python_failure('-c', e) ++ rc, out, err = assert_python_failure('-Xoldparser', '-c', e) + # parsing the expression will result in an error message + # followed by a MemoryError (see #11963) + self.assertIn(b's_push: parser stack overflow', err) +diff --git a/Lib/test/test_peg_generator/__init__.py b/Lib/test/test_peg_generator/__init__.py +new file mode 100644 +--- /dev/null ++++ b/Lib/test/test_peg_generator/__init__.py +@@ -0,0 +1,7 @@ ++import os ++ ++from test.support import load_package_tests ++ ++# Load all tests in package ++def load_tests(*args): ++ return load_package_tests(os.path.dirname(__file__), *args) +diff --git a/Lib/test/test_peg_generator/__main__.py b/Lib/test/test_peg_generator/__main__.py +new file mode 100644 +--- /dev/null ++++ b/Lib/test/test_peg_generator/__main__.py +@@ -0,0 +1,4 @@ ++import unittest ++from . import load_tests ++ ++unittest.main() +diff --git a/Lib/test/test_peg_generator/ast_dump.py b/Lib/test/test_peg_generator/ast_dump.py +new file mode 100644 +--- /dev/null ++++ b/Lib/test/test_peg_generator/ast_dump.py +@@ -0,0 +1,62 @@ ++""" ++Copy-parse of ast.dump, removing the `isinstance` checks. This is needed, ++because testing pegen requires generating a C extension module, which contains ++a copy of the symbols defined in Python-ast.c. Thus, the isinstance check would ++always fail. We rely on string comparison of the base classes instead. ++TODO: Remove the above-described hack. ++""" ++ ++def ast_dump(node, annotate_fields=True, include_attributes=False, *, indent=None): ++ def _format(node, level=0): ++ if indent is not None: ++ level += 1 ++ prefix = '\n' + indent * level ++ sep = ',\n' + indent * level ++ else: ++ prefix = '' ++ sep = ', ' ++ if any(cls.__name__ == 'AST' for cls in node.__class__.__mro__): ++ cls = type(node) ++ args = [] ++ allsimple = True ++ keywords = annotate_fields ++ for name in node._fields: ++ try: ++ value = getattr(node, name) ++ except AttributeError: ++ keywords = True ++ continue ++ if value is None and getattr(cls, name, ...) is None: ++ keywords = True ++ continue ++ value, simple = _format(value, level) ++ allsimple = allsimple and simple ++ if keywords: ++ args.append('%s=%s' % (name, value)) ++ else: ++ args.append(value) ++ if include_attributes and node._attributes: ++ for name in node._attributes: ++ try: ++ value = getattr(node, name) ++ except AttributeError: ++ continue ++ if value is None and getattr(cls, name, ...) is None: ++ continue ++ value, simple = _format(value, level) ++ allsimple = allsimple and simple ++ args.append('%s=%s' % (name, value)) ++ if allsimple and len(args) <= 3: ++ return '%s(%s)' % (node.__class__.__name__, ', '.join(args)), not args ++ return '%s(%s%s)' % (node.__class__.__name__, prefix, sep.join(args)), False ++ elif isinstance(node, list): ++ if not node: ++ return '[]', True ++ return '[%s%s]' % (prefix, sep.join(_format(x, level)[0] for x in node)), False ++ return repr(node), True ++ ++ if all(cls.__name__ != 'AST' for cls in node.__class__.__mro__): ++ raise TypeError('expected AST, got %r' % node.__class__.__name__) ++ if indent is not None and not isinstance(indent, str): ++ indent = ' ' * indent ++ return _format(node)[0] +diff --git a/Lib/test/test_peg_generator/test_c_parser.py b/Lib/test/test_peg_generator/test_c_parser.py +new file mode 100644 +--- /dev/null ++++ b/Lib/test/test_peg_generator/test_c_parser.py +@@ -0,0 +1,333 @@ ++import ast ++import contextlib ++import traceback ++import tempfile ++import shutil ++import unittest ++import sys ++ ++from test import test_tools ++from test.test_peg_generator.ast_dump import ast_dump ++from pathlib import PurePath, Path ++from typing import Sequence ++ ++test_tools.skip_if_missing('peg_generator') ++with test_tools.imports_under_tool('peg_generator'): ++ from pegen.grammar_parser import GeneratedParser as GrammarParser ++ from pegen.testutil import ( ++ parse_string, ++ generate_parser_c_extension, ++ generate_c_parser_source, ++ ) ++ ++ ++class TestCParser(unittest.TestCase): ++ def setUp(self): ++ self.tmp_path = tempfile.mkdtemp() ++ ++ def tearDown(self): ++ with contextlib.suppress(PermissionError): ++ shutil.rmtree(self.tmp_path) ++ ++ def check_input_strings_for_grammar( ++ self, ++ source: str, ++ tmp_path: PurePath, ++ valid_cases: Sequence[str] = (), ++ invalid_cases: Sequence[str] = (), ++ ) -> None: ++ grammar = parse_string(source, GrammarParser) ++ extension = generate_parser_c_extension(grammar, Path(tmp_path)) ++ ++ if valid_cases: ++ for case in valid_cases: ++ extension.parse_string(case, mode=0) ++ ++ if invalid_cases: ++ for case in invalid_cases: ++ with self.assertRaises(SyntaxError): ++ extension.parse_string(case, mode=0) ++ ++ def verify_ast_generation(self, source: str, stmt: str, tmp_path: PurePath) -> None: ++ grammar = parse_string(source, GrammarParser) ++ extension = generate_parser_c_extension(grammar, Path(tmp_path)) ++ ++ expected_ast = ast.parse(stmt) ++ actual_ast = extension.parse_string(stmt, mode=1) ++ self.assertEqual(ast_dump(expected_ast), ast_dump(actual_ast)) ++ ++ def test_c_parser(self) -> None: ++ grammar_source = """ ++ start[mod_ty]: a=stmt* $ { Module(a, NULL, p->arena) } ++ stmt[stmt_ty]: a=expr_stmt { a } ++ expr_stmt[stmt_ty]: a=expression NEWLINE { _Py_Expr(a, EXTRA) } ++ expression[expr_ty]: ( l=expression '+' r=term { _Py_BinOp(l, Add, r, EXTRA) } ++ | l=expression '-' r=term { _Py_BinOp(l, Sub, r, EXTRA) } ++ | t=term { t } ++ ) ++ term[expr_ty]: ( l=term '*' r=factor { _Py_BinOp(l, Mult, r, EXTRA) } ++ | l=term '/' r=factor { _Py_BinOp(l, Div, r, EXTRA) } ++ | f=factor { f } ++ ) ++ factor[expr_ty]: ('(' e=expression ')' { e } ++ | a=atom { a } ++ ) ++ atom[expr_ty]: ( n=NAME { n } ++ | n=NUMBER { n } ++ | s=STRING { s } ++ ) ++ """ ++ grammar = parse_string(grammar_source, GrammarParser) ++ extension = generate_parser_c_extension(grammar, Path(self.tmp_path)) ++ ++ expressions = [ ++ "4+5", ++ "4-5", ++ "4*5", ++ "1+4*5", ++ "1+4/5", ++ "(1+1) + (1+1)", ++ "(1+1) - (1+1)", ++ "(1+1) * (1+1)", ++ "(1+1) / (1+1)", ++ ] ++ ++ for expr in expressions: ++ the_ast = extension.parse_string(expr, mode=1) ++ expected_ast = ast.parse(expr) ++ self.assertEqual(ast_dump(the_ast), ast_dump(expected_ast)) ++ ++ def test_lookahead(self) -> None: ++ grammar = """ ++ start: NAME &NAME expr NEWLINE? ENDMARKER ++ expr: NAME | NUMBER ++ """ ++ valid_cases = ["foo bar"] ++ invalid_cases = ["foo 34"] ++ self.check_input_strings_for_grammar(grammar, self.tmp_path, valid_cases, invalid_cases) ++ ++ def test_negative_lookahead(self) -> None: ++ grammar = """ ++ start: NAME !NAME expr NEWLINE? ENDMARKER ++ expr: NAME | NUMBER ++ """ ++ valid_cases = ["foo 34"] ++ invalid_cases = ["foo bar"] ++ self.check_input_strings_for_grammar(grammar, self.tmp_path, valid_cases, invalid_cases) ++ ++ def test_cut(self) -> None: ++ grammar = """ ++ start: X ~ Y Z | X Q S ++ X: 'x' ++ Y: 'y' ++ Z: 'z' ++ Q: 'q' ++ S: 's' ++ """ ++ valid_cases = ["x y z"] ++ invalid_cases = ["x q s"] ++ self.check_input_strings_for_grammar(grammar, self.tmp_path, valid_cases, invalid_cases) ++ ++ def test_gather(self) -> None: ++ grammar = """ ++ start: ';'.pass_stmt+ NEWLINE ++ pass_stmt: 'pass' ++ """ ++ valid_cases = ["pass", "pass; pass"] ++ invalid_cases = ["pass;", "pass; pass;"] ++ self.check_input_strings_for_grammar(grammar, self.tmp_path, valid_cases, invalid_cases) ++ ++ def test_left_recursion(self) -> None: ++ grammar = """ ++ start: expr NEWLINE ++ expr: ('-' term | expr '+' term | term) ++ term: NUMBER ++ """ ++ valid_cases = ["-34", "34", "34 + 12", "1 + 1 + 2 + 3"] ++ self.check_input_strings_for_grammar(grammar, self.tmp_path, valid_cases) ++ ++ def test_advanced_left_recursive(self) -> None: ++ grammar = """ ++ start: NUMBER | sign start ++ sign: ['-'] ++ """ ++ valid_cases = ["23", "-34"] ++ self.check_input_strings_for_grammar(grammar, self.tmp_path, valid_cases) ++ ++ def test_mutually_left_recursive(self) -> None: ++ grammar = """ ++ start: foo 'E' ++ foo: bar 'A' | 'B' ++ bar: foo 'C' | 'D' ++ """ ++ valid_cases = ["B E", "D A C A E"] ++ self.check_input_strings_for_grammar(grammar, self.tmp_path, valid_cases) ++ ++ def test_nasty_mutually_left_recursive(self) -> None: ++ grammar = """ ++ start: target '=' ++ target: maybe '+' | NAME ++ maybe: maybe '-' | target ++ """ ++ valid_cases = ["x ="] ++ invalid_cases = ["x - + ="] ++ self.check_input_strings_for_grammar(grammar, self.tmp_path, valid_cases, invalid_cases) ++ ++ def test_return_stmt_noexpr_action(self) -> None: ++ grammar = """ ++ start[mod_ty]: a=[statements] ENDMARKER { Module(a, NULL, p->arena) } ++ statements[asdl_seq*]: a=statement+ { a } ++ statement[stmt_ty]: simple_stmt ++ simple_stmt[stmt_ty]: small_stmt ++ small_stmt[stmt_ty]: return_stmt ++ return_stmt[stmt_ty]: a='return' NEWLINE { _Py_Return(NULL, EXTRA) } ++ """ ++ stmt = "return" ++ self.verify_ast_generation(grammar, stmt, self.tmp_path) ++ ++ def test_gather_action_ast(self) -> None: ++ grammar = """ ++ start[mod_ty]: a=';'.pass_stmt+ NEWLINE ENDMARKER { Module(a, NULL, p->arena) } ++ pass_stmt[stmt_ty]: a='pass' { _Py_Pass(EXTRA)} ++ """ ++ stmt = "pass; pass" ++ self.verify_ast_generation(grammar, stmt, self.tmp_path) ++ ++ def test_pass_stmt_action(self) -> None: ++ grammar = """ ++ start[mod_ty]: a=[statements] ENDMARKER { Module(a, NULL, p->arena) } ++ statements[asdl_seq*]: a=statement+ { a } ++ statement[stmt_ty]: simple_stmt ++ simple_stmt[stmt_ty]: small_stmt ++ small_stmt[stmt_ty]: pass_stmt ++ pass_stmt[stmt_ty]: a='pass' NEWLINE { _Py_Pass(EXTRA) } ++ """ ++ stmt = "pass" ++ self.verify_ast_generation(grammar, stmt, self.tmp_path) ++ ++ def test_if_stmt_action(self) -> None: ++ grammar = """ ++ start[mod_ty]: a=[statements] ENDMARKER { Module(a, NULL, p->arena) } ++ statements[asdl_seq*]: a=statement+ { _PyPegen_seq_flatten(p, a) } ++ statement[asdl_seq*]: a=compound_stmt { _PyPegen_singleton_seq(p, a) } | simple_stmt ++ ++ simple_stmt[asdl_seq*]: a=small_stmt b=further_small_stmt* [';'] NEWLINE { _PyPegen_seq_insert_in_front(p, a, b) } ++ further_small_stmt[stmt_ty]: ';' a=small_stmt { a } ++ ++ block: simple_stmt | NEWLINE INDENT a=statements DEDENT { a } ++ ++ compound_stmt: if_stmt ++ ++ if_stmt: 'if' a=full_expression ':' b=block { _Py_If(a, b, NULL, EXTRA) } ++ ++ small_stmt[stmt_ty]: pass_stmt ++ ++ pass_stmt[stmt_ty]: a='pass' { _Py_Pass(EXTRA) } ++ ++ full_expression: NAME ++ """ ++ stmt = "pass" ++ self.verify_ast_generation(grammar, stmt, self.tmp_path) ++ ++ def test_same_name_different_types(self) -> None: ++ source = """ ++ start[mod_ty]: a=import_from+ NEWLINE ENDMARKER { Module(a, NULL, p->arena)} ++ import_from[stmt_ty]: ( a='from' !'import' c=simple_name 'import' d=import_as_names_from { ++ _Py_ImportFrom(c->v.Name.id, d, 0, EXTRA) } ++ | a='from' '.' 'import' c=import_as_names_from { ++ _Py_ImportFrom(NULL, c, 1, EXTRA) } ++ ) ++ simple_name[expr_ty]: NAME ++ import_as_names_from[asdl_seq*]: a=','.import_as_name_from+ { a } ++ import_as_name_from[alias_ty]: a=NAME 'as' b=NAME { _Py_alias(((expr_ty) a)->v.Name.id, ((expr_ty) b)->v.Name.id, p->arena) } ++ """ ++ grammar = parse_string(source, GrammarParser) ++ extension = generate_parser_c_extension(grammar, Path(self.tmp_path)) ++ ++ for stmt in ("from a import b as c", "from . import a as b"): ++ expected_ast = ast.parse(stmt) ++ actual_ast = extension.parse_string(stmt, mode=1) ++ self.assertEqual(ast_dump(expected_ast), ast_dump(actual_ast)) ++ ++ def test_with_stmt_with_paren(self) -> None: ++ grammar_source = """ ++ start[mod_ty]: a=[statements] ENDMARKER { Module(a, NULL, p->arena) } ++ statements[asdl_seq*]: a=statement+ { _PyPegen_seq_flatten(p, a) } ++ statement[asdl_seq*]: a=compound_stmt { _PyPegen_singleton_seq(p, a) } ++ compound_stmt[stmt_ty]: with_stmt ++ with_stmt[stmt_ty]: ( ++ a='with' '(' b=','.with_item+ ')' ':' c=block { ++ _Py_With(b, _PyPegen_singleton_seq(p, c), NULL, EXTRA) } ++ ) ++ with_item[withitem_ty]: ( ++ e=NAME o=['as' t=NAME { t }] { _Py_withitem(e, _PyPegen_set_expr_context(p, o, Store), p->arena) } ++ ) ++ block[stmt_ty]: a=pass_stmt NEWLINE { a } | NEWLINE INDENT a=pass_stmt DEDENT { a } ++ pass_stmt[stmt_ty]: a='pass' { _Py_Pass(EXTRA) } ++ """ ++ stmt = "with (\n a as b,\n c as d\n): pass" ++ grammar = parse_string(grammar_source, GrammarParser) ++ extension = generate_parser_c_extension(grammar, Path(self.tmp_path)) ++ the_ast = extension.parse_string(stmt, mode=1) ++ self.assertTrue(ast_dump(the_ast).startswith( ++ "Module(body=[With(items=[withitem(context_expr=Name(id='a', ctx=Load()), optional_vars=Name(id='b', ctx=Store())), " ++ "withitem(context_expr=Name(id='c', ctx=Load()), optional_vars=Name(id='d', ctx=Store()))]" ++ )) ++ ++ def test_ternary_operator(self) -> None: ++ grammar_source = """ ++ start[mod_ty]: a=expr ENDMARKER { Module(a, NULL, p->arena) } ++ expr[asdl_seq*]: a=listcomp NEWLINE { _PyPegen_singleton_seq(p, _Py_Expr(a, EXTRA)) } ++ listcomp[expr_ty]: ( ++ a='[' b=NAME c=for_if_clauses d=']' { _Py_ListComp(b, c, EXTRA) } ++ ) ++ for_if_clauses[asdl_seq*]: ( ++ a=(y=[ASYNC] 'for' a=NAME 'in' b=NAME c=('if' z=NAME { z })* ++ { _Py_comprehension(_Py_Name(((expr_ty) a)->v.Name.id, Store, EXTRA), b, c, (y == NULL) ? 0 : 1, p->arena) })+ { a } ++ ) ++ """ ++ stmt = "[i for i in a if b]" ++ self.verify_ast_generation(grammar_source, stmt, self.tmp_path) ++ ++ def test_syntax_error_for_string(self) -> None: ++ grammar_source = """ ++ start: expr+ NEWLINE? ENDMARKER ++ expr: NAME ++ """ ++ grammar = parse_string(grammar_source, GrammarParser) ++ print(list(Path(self.tmp_path).iterdir())) ++ extension = generate_parser_c_extension(grammar, Path(self.tmp_path)) ++ for text in ("a b 42 b a", "名 名 42 名 名"): ++ try: ++ extension.parse_string(text, mode=0) ++ except SyntaxError as e: ++ tb = traceback.format_exc() ++ self.assertTrue('File "", line 1' in tb) ++ self.assertTrue(f"SyntaxError: invalid syntax" in tb) ++ ++ def test_headers_and_trailer(self) -> None: ++ grammar_source = """ ++ @header 'SOME HEADER' ++ @subheader 'SOME SUBHEADER' ++ @trailer 'SOME TRAILER' ++ start: expr+ NEWLINE? ENDMARKER ++ expr: x=NAME ++ """ ++ grammar = parse_string(grammar_source, GrammarParser) ++ parser_source = generate_c_parser_source(grammar) ++ ++ self.assertTrue("SOME HEADER" in parser_source) ++ self.assertTrue("SOME SUBHEADER" in parser_source) ++ self.assertTrue("SOME TRAILER" in parser_source) ++ ++ ++ def test_error_in_rules(self) -> None: ++ grammar_source = """ ++ start: expr+ NEWLINE? ENDMARKER ++ expr: NAME {PyTuple_New(-1)} ++ """ ++ grammar = parse_string(grammar_source, GrammarParser) ++ extension = generate_parser_c_extension(grammar, Path(self.tmp_path)) ++ # PyTuple_New raises SystemError if an invalid argument was passed. ++ with self.assertRaises(SystemError): ++ extension.parse_string("a", mode=0) +diff --git a/Lib/test/test_peg_generator/test_first_sets.py b/Lib/test/test_peg_generator/test_first_sets.py +new file mode 100644 +--- /dev/null ++++ b/Lib/test/test_peg_generator/test_first_sets.py +@@ -0,0 +1,225 @@ ++import unittest ++ ++from test import test_tools ++from typing import Dict, Set ++ ++test_tools.skip_if_missing('peg_generator') ++with test_tools.imports_under_tool('peg_generator'): ++ from pegen.grammar_parser import GeneratedParser as GrammarParser ++ from pegen.testutil import parse_string ++ from pegen.first_sets import FirstSetCalculator ++ from pegen.grammar import Grammar ++ ++ ++class TestFirstSets(unittest.TestCase): ++ def calculate_first_sets(self, grammar_source: str) -> Dict[str, Set[str]]: ++ grammar: Grammar = parse_string(grammar_source, GrammarParser) ++ return FirstSetCalculator(grammar.rules).calculate() ++ ++ def test_alternatives(self) -> None: ++ grammar = """ ++ start: expr NEWLINE? ENDMARKER ++ expr: A | B ++ A: 'a' | '-' ++ B: 'b' | '+' ++ """ ++ self.assertEqual(self.calculate_first_sets(grammar), { ++ "A": {"'a'", "'-'"}, ++ "B": {"'+'", "'b'"}, ++ "expr": {"'+'", "'a'", "'b'", "'-'"}, ++ "start": {"'+'", "'a'", "'b'", "'-'"}, ++ }) ++ ++ def test_optionals(self) -> None: ++ grammar = """ ++ start: expr NEWLINE ++ expr: ['a'] ['b'] 'c' ++ """ ++ self.assertEqual(self.calculate_first_sets(grammar), { ++ "expr": {"'c'", "'a'", "'b'"}, ++ "start": {"'c'", "'a'", "'b'"}, ++ }) ++ ++ def test_repeat_with_separator(self) -> None: ++ grammar = """ ++ start: ','.thing+ NEWLINE ++ thing: NUMBER ++ """ ++ self.assertEqual(self.calculate_first_sets(grammar), {"thing": {"NUMBER"}, "start": {"NUMBER"}}) ++ ++ def test_optional_operator(self) -> None: ++ grammar = """ ++ start: sum NEWLINE ++ sum: (term)? 'b' ++ term: NUMBER ++ """ ++ self.assertEqual(self.calculate_first_sets(grammar), { ++ "term": {"NUMBER"}, ++ "sum": {"NUMBER", "'b'"}, ++ "start": {"'b'", "NUMBER"}, ++ }) ++ ++ def test_optional_literal(self) -> None: ++ grammar = """ ++ start: sum NEWLINE ++ sum: '+' ? term ++ term: NUMBER ++ """ ++ self.assertEqual(self.calculate_first_sets(grammar), { ++ "term": {"NUMBER"}, ++ "sum": {"'+'", "NUMBER"}, ++ "start": {"'+'", "NUMBER"}, ++ }) ++ ++ def test_optional_after(self) -> None: ++ grammar = """ ++ start: term NEWLINE ++ term: NUMBER ['+'] ++ """ ++ self.assertEqual(self.calculate_first_sets(grammar), {"term": {"NUMBER"}, "start": {"NUMBER"}}) ++ ++ def test_optional_before(self) -> None: ++ grammar = """ ++ start: term NEWLINE ++ term: ['+'] NUMBER ++ """ ++ self.assertEqual(self.calculate_first_sets(grammar), {"term": {"NUMBER", "'+'"}, "start": {"NUMBER", "'+'"}}) ++ ++ def test_repeat_0(self) -> None: ++ grammar = """ ++ start: thing* "+" NEWLINE ++ thing: NUMBER ++ """ ++ self.assertEqual(self.calculate_first_sets(grammar), {"thing": {"NUMBER"}, "start": {'"+"', "NUMBER"}}) ++ ++ def test_repeat_0_with_group(self) -> None: ++ grammar = """ ++ start: ('+' '-')* term NEWLINE ++ term: NUMBER ++ """ ++ self.assertEqual(self.calculate_first_sets(grammar), {"term": {"NUMBER"}, "start": {"'+'", "NUMBER"}}) ++ ++ def test_repeat_1(self) -> None: ++ grammar = """ ++ start: thing+ '-' NEWLINE ++ thing: NUMBER ++ """ ++ self.assertEqual(self.calculate_first_sets(grammar), {"thing": {"NUMBER"}, "start": {"NUMBER"}}) ++ ++ def test_repeat_1_with_group(self) -> None: ++ grammar = """ ++ start: ('+' term)+ term NEWLINE ++ term: NUMBER ++ """ ++ self.assertEqual(self.calculate_first_sets(grammar), {"term": {"NUMBER"}, "start": {"'+'"}}) ++ ++ def test_gather(self) -> None: ++ grammar = """ ++ start: ','.thing+ NEWLINE ++ thing: NUMBER ++ """ ++ self.assertEqual(self.calculate_first_sets(grammar), {"thing": {"NUMBER"}, "start": {"NUMBER"}}) ++ ++ def test_positive_lookahead(self) -> None: ++ grammar = """ ++ start: expr NEWLINE ++ expr: &'a' opt ++ opt: 'a' | 'b' | 'c' ++ """ ++ self.assertEqual(self.calculate_first_sets(grammar), { ++ "expr": {"'a'"}, ++ "start": {"'a'"}, ++ "opt": {"'b'", "'c'", "'a'"}, ++ }) ++ ++ def test_negative_lookahead(self) -> None: ++ grammar = """ ++ start: expr NEWLINE ++ expr: !'a' opt ++ opt: 'a' | 'b' | 'c' ++ """ ++ self.assertEqual(self.calculate_first_sets(grammar), { ++ "opt": {"'b'", "'a'", "'c'"}, ++ "expr": {"'b'", "'c'"}, ++ "start": {"'b'", "'c'"}, ++ }) ++ ++ def test_left_recursion(self) -> None: ++ grammar = """ ++ start: expr NEWLINE ++ expr: ('-' term | expr '+' term | term) ++ term: NUMBER ++ foo: 'foo' ++ bar: 'bar' ++ baz: 'baz' ++ """ ++ self.assertEqual(self.calculate_first_sets(grammar), { ++ "expr": {"NUMBER", "'-'"}, ++ "term": {"NUMBER"}, ++ "start": {"NUMBER", "'-'"}, ++ "foo": {"'foo'"}, ++ "bar": {"'bar'"}, ++ "baz": {"'baz'"}, ++ }) ++ ++ def test_advance_left_recursion(self) -> None: ++ grammar = """ ++ start: NUMBER | sign start ++ sign: ['-'] ++ """ ++ self.assertEqual(self.calculate_first_sets(grammar), {"sign": {"'-'", ""}, "start": {"'-'", "NUMBER"}}) ++ ++ def test_mutual_left_recursion(self) -> None: ++ grammar = """ ++ start: foo 'E' ++ foo: bar 'A' | 'B' ++ bar: foo 'C' | 'D' ++ """ ++ self.assertEqual(self.calculate_first_sets(grammar), { ++ "foo": {"'D'", "'B'"}, ++ "bar": {"'D'"}, ++ "start": {"'D'", "'B'"}, ++ }) ++ ++ def test_nasty_left_recursion(self) -> None: ++ # TODO: Validate this ++ grammar = """ ++ start: target '=' ++ target: maybe '+' | NAME ++ maybe: maybe '-' | target ++ """ ++ self.assertEqual(self.calculate_first_sets(grammar), {"maybe": set(), "target": {"NAME"}, "start": {"NAME"}}) ++ ++ def test_nullable_rule(self) -> None: ++ grammar = """ ++ start: sign thing $ ++ sign: ['-'] ++ thing: NUMBER ++ """ ++ self.assertEqual(self.calculate_first_sets(grammar), { ++ "sign": {"", "'-'"}, ++ "thing": {"NUMBER"}, ++ "start": {"NUMBER", "'-'"}, ++ }) ++ ++ def test_epsilon_production_in_start_rule(self) -> None: ++ grammar = """ ++ start: ['-'] $ ++ """ ++ self.assertEqual(self.calculate_first_sets(grammar), {"start": {"ENDMARKER", "'-'"}}) ++ ++ def test_multiple_nullable_rules(self) -> None: ++ grammar = """ ++ start: sign thing other another $ ++ sign: ['-'] ++ thing: ['+'] ++ other: '*' ++ another: '/' ++ """ ++ self.assertEqual(self.calculate_first_sets(grammar), { ++ "sign": {"", "'-'"}, ++ "thing": {"'+'", ""}, ++ "start": {"'+'", "'-'", "'*'"}, ++ "other": {"'*'"}, ++ "another": {"'/'"}, ++ }) +diff --git a/Lib/test/test_peg_generator/test_pegen.py b/Lib/test/test_peg_generator/test_pegen.py +new file mode 100644 +--- /dev/null ++++ b/Lib/test/test_peg_generator/test_pegen.py +@@ -0,0 +1,739 @@ ++import io ++import textwrap ++import unittest ++ ++from test import test_tools ++from typing import Dict, Any ++from tokenize import TokenInfo, NAME, NEWLINE, NUMBER, OP ++ ++test_tools.skip_if_missing('peg_generator') ++with test_tools.imports_under_tool('peg_generator'): ++ from pegen.grammar_parser import GeneratedParser as GrammarParser ++ from pegen.testutil import ( ++ parse_string, ++ generate_parser, ++ make_parser ++ ) ++ from pegen.grammar import GrammarVisitor, GrammarError, Grammar ++ ++ ++class TestPegen(unittest.TestCase): ++ def test_parse_grammar(self) -> None: ++ grammar_source = """ ++ start: sum NEWLINE ++ sum: t1=term '+' t2=term { action } | term ++ term: NUMBER ++ """ ++ expected = """ ++ start: sum NEWLINE ++ sum: term '+' term | term ++ term: NUMBER ++ """ ++ grammar: Grammar = parse_string(grammar_source, GrammarParser) ++ rules = grammar.rules ++ self.assertEqual(str(grammar), textwrap.dedent(expected).strip()) ++ # Check the str() and repr() of a few rules; AST nodes don't support ==. ++ self.assertEqual(str(rules["start"]), "start: sum NEWLINE") ++ self.assertEqual(str(rules["sum"]), "sum: term '+' term | term") ++ expected_repr = "Rule('term', None, Rhs([Alt([NamedItem(None, NameLeaf('NUMBER'))])]))" ++ self.assertEqual(repr(rules["term"]), expected_repr) ++ ++ def test_long_rule_str(self) -> None: ++ grammar_source = """ ++ start: zero | one | one zero | one one | one zero zero | one zero one | one one zero | one one one ++ """ ++ expected = """ ++ start: ++ | zero ++ | one ++ | one zero ++ | one one ++ | one zero zero ++ | one zero one ++ | one one zero ++ | one one one ++ """ ++ grammar: Grammar = parse_string(grammar_source, GrammarParser) ++ self.assertEqual(str(grammar.rules["start"]), textwrap.dedent(expected).strip()) ++ ++ def test_typed_rules(self) -> None: ++ grammar = """ ++ start[int]: sum NEWLINE ++ sum[int]: t1=term '+' t2=term { action } | term ++ term[int]: NUMBER ++ """ ++ rules = parse_string(grammar, GrammarParser).rules ++ # Check the str() and repr() of a few rules; AST nodes don't support ==. ++ self.assertEqual(str(rules["start"]), "start: sum NEWLINE") ++ self.assertEqual(str(rules["sum"]), "sum: term '+' term | term") ++ self.assertEqual( ++ repr(rules["term"]), ++ "Rule('term', 'int', Rhs([Alt([NamedItem(None, NameLeaf('NUMBER'))])]))" ++ ) ++ ++ def test_repeat_with_separator_rules(self) -> None: ++ grammar = """ ++ start: ','.thing+ NEWLINE ++ thing: NUMBER ++ """ ++ rules = parse_string(grammar, GrammarParser).rules ++ self.assertEqual(str(rules["start"]), "start: ','.thing+ NEWLINE") ++ print(repr(rules["start"])) ++ self.assertTrue(repr(rules["start"]).startswith( ++ "Rule('start', None, Rhs([Alt([NamedItem(None, Gather(StringLeaf(\"','\"), NameLeaf('thing'" ++ )) ++ self.assertEqual(str(rules["thing"]), "thing: NUMBER") ++ ++ def test_expr_grammar(self) -> None: ++ grammar = """ ++ start: sum NEWLINE ++ sum: term '+' term | term ++ term: NUMBER ++ """ ++ parser_class = make_parser(grammar) ++ node = parse_string("42\n", parser_class) ++ self.assertEqual(node, [ ++ [[TokenInfo(NUMBER, string="42", start=(1, 0), end=(1, 2), line="42\n")]], ++ TokenInfo(NEWLINE, string="\n", start=(1, 2), end=(1, 3), line="42\n"), ++ ]) ++ ++ def test_optional_operator(self) -> None: ++ grammar = """ ++ start: sum NEWLINE ++ sum: term ('+' term)? ++ term: NUMBER ++ """ ++ parser_class = make_parser(grammar) ++ node = parse_string("1+2\n", parser_class) ++ self.assertEqual(node, [ ++ [ ++ [TokenInfo(NUMBER, string="1", start=(1, 0), end=(1, 1), line="1+2\n")], ++ [ ++ TokenInfo(OP, string="+", start=(1, 1), end=(1, 2), line="1+2\n"), ++ [TokenInfo(NUMBER, string="2", start=(1, 2), end=(1, 3), line="1+2\n")], ++ ], ++ ], ++ TokenInfo(NEWLINE, string="\n", start=(1, 3), end=(1, 4), line="1+2\n"), ++ ]) ++ node = parse_string("1\n", parser_class) ++ self.assertEqual(node, [ ++ [[TokenInfo(NUMBER, string="1", start=(1, 0), end=(1, 1), line="1\n")], None], ++ TokenInfo(NEWLINE, string="\n", start=(1, 1), end=(1, 2), line="1\n"), ++ ]) ++ ++ def test_optional_literal(self) -> None: ++ grammar = """ ++ start: sum NEWLINE ++ sum: term '+' ? ++ term: NUMBER ++ """ ++ parser_class = make_parser(grammar) ++ node = parse_string("1+\n", parser_class) ++ self.assertEqual(node, [ ++ [ ++ [TokenInfo(NUMBER, string="1", start=(1, 0), end=(1, 1), line="1+\n")], ++ TokenInfo(OP, string="+", start=(1, 1), end=(1, 2), line="1+\n"), ++ ], ++ TokenInfo(NEWLINE, string="\n", start=(1, 2), end=(1, 3), line="1+\n"), ++ ]) ++ node = parse_string("1\n", parser_class) ++ self.assertEqual(node, [ ++ [[TokenInfo(NUMBER, string="1", start=(1, 0), end=(1, 1), line="1\n")], None], ++ TokenInfo(NEWLINE, string="\n", start=(1, 1), end=(1, 2), line="1\n"), ++ ]) ++ ++ def test_alt_optional_operator(self) -> None: ++ grammar = """ ++ start: sum NEWLINE ++ sum: term ['+' term] ++ term: NUMBER ++ """ ++ parser_class = make_parser(grammar) ++ node = parse_string("1 + 2\n", parser_class) ++ self.assertEqual(node, [ ++ [ ++ [TokenInfo(NUMBER, string="1", start=(1, 0), end=(1, 1), line="1 + 2\n")], ++ [ ++ TokenInfo(OP, string="+", start=(1, 2), end=(1, 3), line="1 + 2\n"), ++ [TokenInfo(NUMBER, string="2", start=(1, 4), end=(1, 5), line="1 + 2\n")], ++ ], ++ ], ++ TokenInfo(NEWLINE, string="\n", start=(1, 5), end=(1, 6), line="1 + 2\n"), ++ ]) ++ node = parse_string("1\n", parser_class) ++ self.assertEqual(node, [ ++ [[TokenInfo(NUMBER, string="1", start=(1, 0), end=(1, 1), line="1\n")], None], ++ TokenInfo(NEWLINE, string="\n", start=(1, 1), end=(1, 2), line="1\n"), ++ ]) ++ ++ def test_repeat_0_simple(self) -> None: ++ grammar = """ ++ start: thing thing* NEWLINE ++ thing: NUMBER ++ """ ++ parser_class = make_parser(grammar) ++ node = parse_string("1 2 3\n", parser_class) ++ self.assertEqual(node, [ ++ [TokenInfo(NUMBER, string="1", start=(1, 0), end=(1, 1), line="1 2 3\n")], ++ [ ++ [[TokenInfo(NUMBER, string="2", start=(1, 2), end=(1, 3), line="1 2 3\n")]], ++ [[TokenInfo(NUMBER, string="3", start=(1, 4), end=(1, 5), line="1 2 3\n")]], ++ ], ++ TokenInfo(NEWLINE, string="\n", start=(1, 5), end=(1, 6), line="1 2 3\n"), ++ ]) ++ node = parse_string("1\n", parser_class) ++ self.assertEqual(node, [ ++ [TokenInfo(NUMBER, string="1", start=(1, 0), end=(1, 1), line="1\n")], ++ [], ++ TokenInfo(NEWLINE, string="\n", start=(1, 1), end=(1, 2), line="1\n"), ++ ]) ++ ++ def test_repeat_0_complex(self) -> None: ++ grammar = """ ++ start: term ('+' term)* NEWLINE ++ term: NUMBER ++ """ ++ parser_class = make_parser(grammar) ++ node = parse_string("1 + 2 + 3\n", parser_class) ++ self.assertEqual(node, [ ++ [TokenInfo(NUMBER, string="1", start=(1, 0), end=(1, 1), line="1 + 2 + 3\n")], ++ [ ++ [ ++ [ ++ TokenInfo(OP, string="+", start=(1, 2), end=(1, 3), line="1 + 2 + 3\n"), ++ [TokenInfo(NUMBER, string="2", start=(1, 4), end=(1, 5), line="1 + 2 + 3\n")], ++ ] ++ ], ++ [ ++ [ ++ TokenInfo(OP, string="+", start=(1, 6), end=(1, 7), line="1 + 2 + 3\n"), ++ [TokenInfo(NUMBER, string="3", start=(1, 8), end=(1, 9), line="1 + 2 + 3\n")], ++ ] ++ ], ++ ], ++ TokenInfo(NEWLINE, string="\n", start=(1, 9), end=(1, 10), line="1 + 2 + 3\n"), ++ ]) ++ ++ def test_repeat_1_simple(self) -> None: ++ grammar = """ ++ start: thing thing+ NEWLINE ++ thing: NUMBER ++ """ ++ parser_class = make_parser(grammar) ++ node = parse_string("1 2 3\n", parser_class) ++ self.assertEqual(node, [ ++ [TokenInfo(NUMBER, string="1", start=(1, 0), end=(1, 1), line="1 2 3\n")], ++ [ ++ [[TokenInfo(NUMBER, string="2", start=(1, 2), end=(1, 3), line="1 2 3\n")]], ++ [[TokenInfo(NUMBER, string="3", start=(1, 4), end=(1, 5), line="1 2 3\n")]], ++ ], ++ TokenInfo(NEWLINE, string="\n", start=(1, 5), end=(1, 6), line="1 2 3\n"), ++ ]) ++ with self.assertRaises(SyntaxError): ++ parse_string("1\n", parser_class) ++ ++ def test_repeat_1_complex(self) -> None: ++ grammar = """ ++ start: term ('+' term)+ NEWLINE ++ term: NUMBER ++ """ ++ parser_class = make_parser(grammar) ++ node = parse_string("1 + 2 + 3\n", parser_class) ++ self.assertEqual(node, [ ++ [TokenInfo(NUMBER, string="1", start=(1, 0), end=(1, 1), line="1 + 2 + 3\n")], ++ [ ++ [ ++ [ ++ TokenInfo(OP, string="+", start=(1, 2), end=(1, 3), line="1 + 2 + 3\n"), ++ [TokenInfo(NUMBER, string="2", start=(1, 4), end=(1, 5), line="1 + 2 + 3\n")], ++ ] ++ ], ++ [ ++ [ ++ TokenInfo(OP, string="+", start=(1, 6), end=(1, 7), line="1 + 2 + 3\n"), ++ [TokenInfo(NUMBER, string="3", start=(1, 8), end=(1, 9), line="1 + 2 + 3\n")], ++ ] ++ ], ++ ], ++ TokenInfo(NEWLINE, string="\n", start=(1, 9), end=(1, 10), line="1 + 2 + 3\n"), ++ ]) ++ with self.assertRaises(SyntaxError): ++ parse_string("1\n", parser_class) ++ ++ def test_repeat_with_sep_simple(self) -> None: ++ grammar = """ ++ start: ','.thing+ NEWLINE ++ thing: NUMBER ++ """ ++ parser_class = make_parser(grammar) ++ node = parse_string("1, 2, 3\n", parser_class) ++ self.assertEqual(node, [ ++ [ ++ [TokenInfo(NUMBER, string="1", start=(1, 0), end=(1, 1), line="1, 2, 3\n")], ++ [TokenInfo(NUMBER, string="2", start=(1, 3), end=(1, 4), line="1, 2, 3\n")], ++ [TokenInfo(NUMBER, string="3", start=(1, 6), end=(1, 7), line="1, 2, 3\n")], ++ ], ++ TokenInfo(NEWLINE, string="\n", start=(1, 7), end=(1, 8), line="1, 2, 3\n"), ++ ]) ++ ++ def test_left_recursive(self) -> None: ++ grammar_source = """ ++ start: expr NEWLINE ++ expr: ('-' term | expr '+' term | term) ++ term: NUMBER ++ foo: NAME+ ++ bar: NAME* ++ baz: NAME? ++ """ ++ grammar: Grammar = parse_string(grammar_source, GrammarParser) ++ parser_class = generate_parser(grammar) ++ rules = grammar.rules ++ self.assertFalse(rules["start"].left_recursive) ++ self.assertTrue(rules["expr"].left_recursive) ++ self.assertFalse(rules["term"].left_recursive) ++ self.assertFalse(rules["foo"].left_recursive) ++ self.assertFalse(rules["bar"].left_recursive) ++ self.assertFalse(rules["baz"].left_recursive) ++ node = parse_string("1 + 2 + 3\n", parser_class) ++ self.assertEqual(node, [ ++ [ ++ [ ++ [[TokenInfo(NUMBER, string="1", start=(1, 0), end=(1, 1), line="1 + 2 + 3\n")]], ++ TokenInfo(OP, string="+", start=(1, 2), end=(1, 3), line="1 + 2 + 3\n"), ++ [TokenInfo(NUMBER, string="2", start=(1, 4), end=(1, 5), line="1 + 2 + 3\n")], ++ ], ++ TokenInfo(OP, string="+", start=(1, 6), end=(1, 7), line="1 + 2 + 3\n"), ++ [TokenInfo(NUMBER, string="3", start=(1, 8), end=(1, 9), line="1 + 2 + 3\n")], ++ ], ++ TokenInfo(NEWLINE, string="\n", start=(1, 9), end=(1, 10), line="1 + 2 + 3\n"), ++ ]) ++ ++ def test_python_expr(self) -> None: ++ grammar = """ ++ start: expr NEWLINE? $ { ast.Expression(expr, lineno=1, col_offset=0) } ++ expr: ( expr '+' term { ast.BinOp(expr, ast.Add(), term, lineno=expr.lineno, col_offset=expr.col_offset, end_lineno=term.end_lineno, end_col_offset=term.end_col_offset) } ++ | expr '-' term { ast.BinOp(expr, ast.Sub(), term, lineno=expr.lineno, col_offset=expr.col_offset, end_lineno=term.end_lineno, end_col_offset=term.end_col_offset) } ++ | term { term } ++ ) ++ term: ( l=term '*' r=factor { ast.BinOp(l, ast.Mult(), r, lineno=l.lineno, col_offset=l.col_offset, end_lineno=r.end_lineno, end_col_offset=r.end_col_offset) } ++ | l=term '/' r=factor { ast.BinOp(l, ast.Div(), r, lineno=l.lineno, col_offset=l.col_offset, end_lineno=r.end_lineno, end_col_offset=r.end_col_offset) } ++ | factor { factor } ++ ) ++ factor: ( '(' expr ')' { expr } ++ | atom { atom } ++ ) ++ atom: ( n=NAME { ast.Name(id=n.string, ctx=ast.Load(), lineno=n.start[0], col_offset=n.start[1], end_lineno=n.end[0], end_col_offset=n.end[1]) } ++ | n=NUMBER { ast.Constant(value=ast.literal_eval(n.string), lineno=n.start[0], col_offset=n.start[1], end_lineno=n.end[0], end_col_offset=n.end[1]) } ++ ) ++ """ ++ parser_class = make_parser(grammar) ++ node = parse_string("(1 + 2*3 + 5)/(6 - 2)\n", parser_class) ++ code = compile(node, "", "eval") ++ val = eval(code) ++ self.assertEqual(val, 3.0) ++ ++ def test_nullable(self) -> None: ++ grammar_source = """ ++ start: sign NUMBER ++ sign: ['-' | '+'] ++ """ ++ grammar: Grammar = parse_string(grammar_source, GrammarParser) ++ out = io.StringIO() ++ with test_tools.imports_under_tool('peg_generator'): ++ from pegen.python_generator import PythonParserGenerator ++ genr = PythonParserGenerator(grammar, out) ++ rules = grammar.rules ++ self.assertFalse(rules["start"].nullable) # Not None! ++ self.assertTrue(rules["sign"].nullable) ++ ++ def test_advanced_left_recursive(self) -> None: ++ grammar_source = """ ++ start: NUMBER | sign start ++ sign: ['-'] ++ """ ++ grammar: Grammar = parse_string(grammar_source, GrammarParser) ++ out = io.StringIO() ++ with test_tools.imports_under_tool('peg_generator'): ++ from pegen.python_generator import PythonParserGenerator ++ genr = PythonParserGenerator(grammar, out) ++ rules = grammar.rules ++ self.assertFalse(rules["start"].nullable) # Not None! ++ self.assertTrue(rules["sign"].nullable) ++ self.assertTrue(rules["start"].left_recursive) ++ self.assertFalse(rules["sign"].left_recursive) ++ ++ def test_mutually_left_recursive(self) -> None: ++ grammar_source = """ ++ start: foo 'E' ++ foo: bar 'A' | 'B' ++ bar: foo 'C' | 'D' ++ """ ++ grammar: Grammar = parse_string(grammar_source, GrammarParser) ++ out = io.StringIO() ++ with test_tools.imports_under_tool('peg_generator'): ++ from pegen.python_generator import PythonParserGenerator ++ genr = PythonParserGenerator(grammar, out) ++ rules = grammar.rules ++ self.assertFalse(rules["start"].left_recursive) ++ self.assertTrue(rules["foo"].left_recursive) ++ self.assertTrue(rules["bar"].left_recursive) ++ genr.generate("") ++ ns: Dict[str, Any] = {} ++ exec(out.getvalue(), ns) ++ parser_class = ns["GeneratedParser"] ++ node = parse_string("D A C A E", parser_class) ++ self.assertEqual(node, [ ++ [ ++ [ ++ [ ++ [TokenInfo(type=NAME, string="D", start=(1, 0), end=(1, 1), line="D A C A E")], ++ TokenInfo(type=NAME, string="A", start=(1, 2), end=(1, 3), line="D A C A E"), ++ ], ++ TokenInfo(type=NAME, string="C", start=(1, 4), end=(1, 5), line="D A C A E"), ++ ], ++ TokenInfo(type=NAME, string="A", start=(1, 6), end=(1, 7), line="D A C A E"), ++ ], ++ TokenInfo(type=NAME, string="E", start=(1, 8), end=(1, 9), line="D A C A E"), ++ ]) ++ node = parse_string("B C A E", parser_class) ++ self.assertIsNotNone(node) ++ self.assertEqual(node, [ ++ [ ++ [ ++ [TokenInfo(type=NAME, string="B", start=(1, 0), end=(1, 1), line="B C A E")], ++ TokenInfo(type=NAME, string="C", start=(1, 2), end=(1, 3), line="B C A E"), ++ ], ++ TokenInfo(type=NAME, string="A", start=(1, 4), end=(1, 5), line="B C A E"), ++ ], ++ TokenInfo(type=NAME, string="E", start=(1, 6), end=(1, 7), line="B C A E"), ++ ]) ++ ++ def test_nasty_mutually_left_recursive(self) -> None: ++ # This grammar does not recognize 'x - + =', much to my chagrin. ++ # But that's the way PEG works. ++ # [Breathlessly] ++ # The problem is that the toplevel target call ++ # recurses into maybe, which recognizes 'x - +', ++ # and then the toplevel target looks for another '+', ++ # which fails, so it retreats to NAME, ++ # which succeeds, so we end up just recognizing 'x', ++ # and then start fails because there's no '=' after that. ++ grammar_source = """ ++ start: target '=' ++ target: maybe '+' | NAME ++ maybe: maybe '-' | target ++ """ ++ grammar: Grammar = parse_string(grammar_source, GrammarParser) ++ out = io.StringIO() ++ with test_tools.imports_under_tool('peg_generator'): ++ from pegen.python_generator import PythonParserGenerator ++ genr = PythonParserGenerator(grammar, out) ++ genr.generate("") ++ ns: Dict[str, Any] = {} ++ exec(out.getvalue(), ns) ++ parser_class = ns["GeneratedParser"] ++ with self.assertRaises(SyntaxError): ++ parse_string("x - + =", parser_class) ++ ++ def test_lookahead(self) -> None: ++ grammar = """ ++ start: (expr_stmt | assign_stmt) &'.' ++ expr_stmt: !(target '=') expr ++ assign_stmt: target '=' expr ++ expr: term ('+' term)* ++ target: NAME ++ term: NUMBER ++ """ ++ parser_class = make_parser(grammar) ++ node = parse_string("foo = 12 + 12 .", parser_class) ++ self.assertEqual(node, [ ++ [ ++ [ ++ [TokenInfo(NAME, string="foo", start=(1, 0), end=(1, 3), line="foo = 12 + 12 .")], ++ TokenInfo(OP, string="=", start=(1, 4), end=(1, 5), line="foo = 12 + 12 ."), ++ [ ++ [ ++ TokenInfo( ++ NUMBER, string="12", start=(1, 6), end=(1, 8), line="foo = 12 + 12 ." ++ ) ++ ], ++ [ ++ [ ++ [ ++ TokenInfo( ++ OP, ++ string="+", ++ start=(1, 9), ++ end=(1, 10), ++ line="foo = 12 + 12 .", ++ ), ++ [ ++ TokenInfo( ++ NUMBER, ++ string="12", ++ start=(1, 11), ++ end=(1, 13), ++ line="foo = 12 + 12 .", ++ ) ++ ], ++ ] ++ ] ++ ], ++ ], ++ ] ++ ] ++ ]) ++ ++ def test_named_lookahead_error(self) -> None: ++ grammar = """ ++ start: foo=!'x' NAME ++ """ ++ with self.assertRaises(SyntaxError): ++ make_parser(grammar) ++ ++ def test_start_leader(self) -> None: ++ grammar = """ ++ start: attr | NAME ++ attr: start '.' NAME ++ """ ++ # Would assert False without a special case in compute_left_recursives(). ++ make_parser(grammar) ++ ++ def test_left_recursion_too_complex(self) -> None: ++ grammar = """ ++ start: foo ++ foo: bar '+' | baz '+' | '+' ++ bar: baz '-' | foo '-' | '-' ++ baz: foo '*' | bar '*' | '*' ++ """ ++ with self.assertRaises(ValueError) as errinfo: ++ make_parser(grammar) ++ self.assertTrue("no leader" in str(errinfo.exception.value)) ++ ++ def test_cut(self) -> None: ++ grammar = """ ++ start: '(' ~ expr ')' ++ expr: NUMBER ++ """ ++ parser_class = make_parser(grammar) ++ node = parse_string("(1)", parser_class, verbose=True) ++ self.assertEqual(node, [ ++ TokenInfo(OP, string="(", start=(1, 0), end=(1, 1), line="(1)"), ++ [TokenInfo(NUMBER, string="1", start=(1, 1), end=(1, 2), line="(1)")], ++ TokenInfo(OP, string=")", start=(1, 2), end=(1, 3), line="(1)"), ++ ]) ++ ++ def test_dangling_reference(self) -> None: ++ grammar = """ ++ start: foo ENDMARKER ++ foo: bar NAME ++ """ ++ with self.assertRaises(GrammarError): ++ parser_class = make_parser(grammar) ++ ++ def test_bad_token_reference(self) -> None: ++ grammar = """ ++ start: foo ++ foo: NAMEE ++ """ ++ with self.assertRaises(GrammarError): ++ parser_class = make_parser(grammar) ++ ++ def test_missing_start(self) -> None: ++ grammar = """ ++ foo: NAME ++ """ ++ with self.assertRaises(GrammarError): ++ parser_class = make_parser(grammar) ++ ++ ++class TestGrammarVisitor: ++ class Visitor(GrammarVisitor): ++ def __init__(self) -> None: ++ self.n_nodes = 0 ++ ++ def visit(self, node: Any, *args: Any, **kwargs: Any) -> None: ++ self.n_nodes += 1 ++ super().visit(node, *args, **kwargs) ++ ++ def test_parse_trivial_grammar(self) -> None: ++ grammar = """ ++ start: 'a' ++ """ ++ rules = parse_string(grammar, GrammarParser) ++ visitor = self.Visitor() ++ ++ visitor.visit(rules) ++ ++ self.assertEqual(visitor.n_nodes, 6) ++ ++ def test_parse_or_grammar(self) -> None: ++ grammar = """ ++ start: rule ++ rule: 'a' | 'b' ++ """ ++ rules = parse_string(grammar, GrammarParser) ++ visitor = self.Visitor() ++ ++ visitor.visit(rules) ++ ++ # Grammar/Rule/Rhs/Alt/NamedItem/NameLeaf -> 6 ++ # Rule/Rhs/ -> 2 ++ # Alt/NamedItem/StringLeaf -> 3 ++ # Alt/NamedItem/StringLeaf -> 3 ++ ++ self.assertEqual(visitor.n_nodes, 14) ++ ++ def test_parse_repeat1_grammar(self) -> None: ++ grammar = """ ++ start: 'a'+ ++ """ ++ rules = parse_string(grammar, GrammarParser) ++ visitor = self.Visitor() ++ ++ visitor.visit(rules) ++ ++ # Grammar/Rule/Rhs/Alt/NamedItem/Repeat1/StringLeaf -> 6 ++ self.assertEqual(visitor.n_nodes, 7) ++ ++ def test_parse_repeat0_grammar(self) -> None: ++ grammar = """ ++ start: 'a'* ++ """ ++ rules = parse_string(grammar, GrammarParser) ++ visitor = self.Visitor() ++ ++ visitor.visit(rules) ++ ++ # Grammar/Rule/Rhs/Alt/NamedItem/Repeat0/StringLeaf -> 6 ++ ++ self.assertEqual(visitor.n_nodes, 7) ++ ++ def test_parse_optional_grammar(self) -> None: ++ grammar = """ ++ start: 'a' ['b'] ++ """ ++ rules = parse_string(grammar, GrammarParser) ++ visitor = self.Visitor() ++ ++ visitor.visit(rules) ++ ++ # Grammar/Rule/Rhs/Alt/NamedItem/StringLeaf -> 6 ++ # NamedItem/Opt/Rhs/Alt/NamedItem/Stringleaf -> 6 ++ ++ self.assertEqual(visitor.n_nodes, 12) ++ ++ ++class TestGrammarVisualizer(unittest.TestCase): ++ def test_simple_rule(self) -> None: ++ grammar = """ ++ start: 'a' 'b' ++ """ ++ rules = parse_string(grammar, GrammarParser) ++ ++ with test_tools.imports_under_tool('peg_generator'): ++ from pegen.grammar_visualizer import ASTGrammarPrinter ++ printer = ASTGrammarPrinter() ++ lines: List[str] = [] ++ printer.print_grammar_ast(rules, printer=lines.append) ++ ++ output = "\n".join(lines) ++ expected_output = textwrap.dedent( ++ """\ ++ └──Rule ++ └──Rhs ++ └──Alt ++ ├──NamedItem ++ │ └──StringLeaf("'a'") ++ └──NamedItem ++ └──StringLeaf("'b'") ++ """ ++ ) ++ ++ self.assertEqual(output, expected_output) ++ ++ def test_multiple_rules(self) -> None: ++ grammar = """ ++ start: a b ++ a: 'a' ++ b: 'b' ++ """ ++ rules = parse_string(grammar, GrammarParser) ++ ++ with test_tools.imports_under_tool('peg_generator'): ++ from pegen.grammar_visualizer import ASTGrammarPrinter ++ printer = ASTGrammarPrinter() ++ lines: List[str] = [] ++ printer.print_grammar_ast(rules, printer=lines.append) ++ ++ output = "\n".join(lines) ++ expected_output = textwrap.dedent( ++ """\ ++ └──Rule ++ └──Rhs ++ └──Alt ++ ├──NamedItem ++ │ └──NameLeaf('a') ++ └──NamedItem ++ └──NameLeaf('b') ++ ++ └──Rule ++ └──Rhs ++ └──Alt ++ └──NamedItem ++ └──StringLeaf("'a'") ++ ++ └──Rule ++ └──Rhs ++ └──Alt ++ └──NamedItem ++ └──StringLeaf("'b'") ++ """ ++ ) ++ ++ self.assertEqual(output, expected_output) ++ ++ def test_deep_nested_rule(self) -> None: ++ grammar = """ ++ start: 'a' ['b'['c'['d']]] ++ """ ++ rules = parse_string(grammar, GrammarParser) ++ ++ with test_tools.imports_under_tool('peg_generator'): ++ from pegen.grammar_visualizer import ASTGrammarPrinter ++ printer = ASTGrammarPrinter() ++ lines: List[str] = [] ++ printer.print_grammar_ast(rules, printer=lines.append) ++ ++ output = "\n".join(lines) ++ print() ++ print(output) ++ expected_output = textwrap.dedent( ++ """\ ++ └──Rule ++ └──Rhs ++ └──Alt ++ ├──NamedItem ++ │ └──StringLeaf("'a'") ++ └──NamedItem ++ └──Opt ++ └──Rhs ++ └──Alt ++ ├──NamedItem ++ │ └──StringLeaf("'b'") ++ └──NamedItem ++ └──Opt ++ └──Rhs ++ └──Alt ++ ├──NamedItem ++ │ └──StringLeaf("'c'") ++ └──NamedItem ++ └──Opt ++ └──Rhs ++ └──Alt ++ └──NamedItem ++ └──StringLeaf("'d'") ++ """ ++ ) ++ ++ self.assertEqual(output, expected_output) +diff --git a/Lib/test/test_peg_parser.py b/Lib/test/test_peg_parser.py +new file mode 100644 +--- /dev/null ++++ b/Lib/test/test_peg_parser.py +@@ -0,0 +1,764 @@ ++import ast ++import os ++import sys ++import _peg_parser as peg_parser ++import unittest ++from pathlib import PurePath ++from typing import Any, Union, Iterable, Tuple ++from textwrap import dedent ++ ++ ++TEST_CASES = [ ++ ('annotated_assignment', 'x: int = 42'), ++ ('annotated_assignment_with_tuple', 'x: tuple = 1, 2'), ++ ('annotated_assignment_with_parens', '(paren): int = 3+2'), ++ ('annotated_assignment_with_yield', 'x: int = yield 42'), ++ ('annotated_no_assignment', 'x: int'), ++ ('annotation_with_multiple_parens', '((parens)): int'), ++ ('annotation_with_parens', '(parens): int'), ++ ('annotated_assignment_with_attr', 'a.b: int'), ++ ('annotated_assignment_with_subscript', 'a[b]: int'), ++ ('annotated_assignment_with_attr_and_parens', '(a.b): int'), ++ ('annotated_assignment_with_subscript_and_parens', '(a[b]): int'), ++ ('assert', 'assert a'), ++ ('assert_message', 'assert a, b'), ++ ('assignment_false', 'a = False'), ++ ('assignment_none', 'a = None'), ++ ('assignment_true', 'a = True'), ++ ('assignment_paren', '(a) = 42'), ++ ('assignment_paren_multiple', '(a, b) = (0, 1)'), ++ ('asyncfor', ++ ''' ++ async for i in a: ++ pass ++ '''), ++ ('attribute_call', 'a.b()'), ++ ('attribute_multiple_names', 'abcd.efg.hij'), ++ ('attribute_simple', 'a.b'), ++ ('attributes_subscript', 'a.b[0]'), ++ ('augmented_assignment', 'x += 42'), ++ ('binop_add', '1 + 1'), ++ ('binop_add_multiple', '1 + 1 + 1 + 1'), ++ ('binop_all', '1 + 2 * 5 + 3 ** 2 - -3'), ++ ('binop_boolop_comp', '1 + 1 == 2 or 1 + 1 == 3 and not b'), ++ ('boolop_or', 'a or b'), ++ ('boolop_or_multiple', 'a or b or c'), ++ ('class_def_bases', ++ ''' ++ class C(A, B): ++ pass ++ '''), ++ ('class_def_decorators', ++ ''' ++ @a ++ class C: ++ pass ++ '''), ++ ('class_def_decorator_with_expression', ++ ''' ++ @lambda x: 42 ++ class C: ++ pass ++ '''), ++ ('class_def_decorator_with_expression_and_walrus', ++ ''' ++ @x:=lambda x: 42 ++ class C: ++ pass ++ '''), ++ ++ ('class_def_keywords', ++ ''' ++ class C(keyword=a+b, **c): ++ pass ++ '''), ++ ('class_def_mixed', ++ ''' ++ class C(A, B, keyword=0, **a): ++ pass ++ '''), ++ ('class_def_simple', ++ ''' ++ class C: ++ pass ++ '''), ++ ('class_def_starred_and_kwarg', ++ ''' ++ class C(A, B, *x, **y): ++ pass ++ '''), ++ ('class_def_starred_in_kwargs', ++ ''' ++ class C(A, x=2, *[B, C], y=3): ++ pass ++ '''), ++ ('call_attribute', 'f().b'), ++ ('call_genexp', 'f(i for i in a)'), ++ ('call_mixed_args', 'f(a, b, *c, **d)'), ++ ('call_mixed_args_named', 'f(a, b, *c, d=4, **v)'), ++ ('call_one_arg', 'f(a)'), ++ ('call_posarg_genexp', 'f(a, (i for i in a))'), ++ ('call_simple', 'f()'), ++ ('call_subscript', 'f()[0]'), ++ ('comp', 'a == b'), ++ ('comp_multiple', 'a == b == c'), ++ ('comp_paren_end', 'a == (b-1)'), ++ ('comp_paren_start', '(a-1) == b'), ++ ('decorator', ++ ''' ++ @a ++ def f(): ++ pass ++ '''), ++ ('decorator_async', ++ ''' ++ @a ++ async def d(): ++ pass ++ '''), ++ ('decorator_with_expression', ++ ''' ++ @lambda x: 42 ++ def f(): ++ pass ++ '''), ++ ('decorator_with_expression_and_walrus', ++ ''' ++ @x:=lambda x: 42 ++ def f(): ++ pass ++ '''), ++ ('del_attribute', 'del a.b'), ++ ('del_call_attribute', 'del a().c'), ++ ('del_call_genexp_attribute', 'del a(i for i in b).c'), ++ ('del_empty', 'del()'), ++ ('del_list', 'del a, [b, c]'), ++ ('del_mixed', 'del a[0].b().c'), ++ ('del_multiple', 'del a, b'), ++ ('del_multiple_calls_attribute', 'del a()().b'), ++ ('del_paren', 'del(a,b)'), ++ ('del_paren_single_target', 'del(a)'), ++ ('del_subscript_attribute', 'del a[0].b'), ++ ('del_tuple', 'del a, (b, c)'), ++ ('delete', 'del a'), ++ ('dict', ++ ''' ++ { ++ a: 1, ++ b: 2, ++ c: 3 ++ } ++ '''), ++ ('dict_comp', '{x:1 for x in a}'), ++ ('dict_comp_if', '{x:1+2 for x in a if b}'), ++ ('dict_empty', '{}'), ++ ('for', ++ ''' ++ for i in a: ++ pass ++ '''), ++ ('for_else', ++ ''' ++ for i in a: ++ pass ++ else: ++ pass ++ '''), ++ ('for_star_target_in_paren', 'for (a) in b: pass'), ++ ('for_star_targets_attribute', 'for a.b in c: pass'), ++ ('for_star_targets_call_attribute', 'for a().c in b: pass'), ++ ('for_star_targets_empty', 'for () in a: pass'), ++ ('for_star_targets_mixed', 'for a[0].b().c in d: pass'), ++ ('for_star_targets_mixed_starred', ++ ''' ++ for a, *b, (c, d) in e: ++ pass ++ '''), ++ ('for_star_targets_multiple', 'for a, b in c: pass'), ++ ('for_star_targets_nested_starred', 'for *[*a] in b: pass'), ++ ('for_star_targets_starred', 'for *a in b: pass'), ++ ('for_star_targets_subscript_attribute', 'for a[0].b in c: pass'), ++ ('for_star_targets_trailing_comma', ++ ''' ++ for a, (b, c), in d: ++ pass ++ '''), ++ ('for_star_targets_tuple', 'for a, (b, c) in d: pass'), ++ ('for_underscore', ++ ''' ++ for _ in a: ++ pass ++ '''), ++ ('function_return_type', ++ ''' ++ def f() -> Any: ++ pass ++ '''), ++ ('f-string_slice', "f'{x[2]}'"), ++ ('f-string_slice_upper', "f'{x[2:3]}'"), ++ ('f-string_slice_step', "f'{x[2:3:-2]}'"), ++ ('f-string_constant', "f'{42}'"), ++ ('f-string_boolop', "f'{x and y}'"), ++ ('f-string_named_expr', "f'{(x:=42)}'"), ++ ('f-string_binop', "f'{x+y}'"), ++ ('f-string_unaryop', "f'{not x}'"), ++ ('f-string_lambda', "f'{(lambda x, /, y, y2=42 , *z, k1, k2=34, **k3: 42)}'"), ++ ('f-string_lambda_call', "f'{(lambda: 2)(2)}'"), ++ ('f-string_ifexpr', "f'{x if y else z}'"), ++ ('f-string_dict', "f'{ {2:34, 3:34} }'"), ++ ('f-string_set', "f'{ {2,-45} }'"), ++ ('f-string_list', "f'{ [2,-45] }'"), ++ ('f-string_tuple', "f'{ (2,-45) }'"), ++ ('f-string_listcomp', "f'{[x for x in y if z]}'"), ++ ('f-string_setcomp', "f'{ {x for x in y if z} }'"), ++ ('f-string_dictcomp', "f'{ {x:x for x in y if z} }'"), ++ ('f-string_genexpr', "f'{ (x for x in y if z) }'"), ++ ('f-string_yield', "f'{ (yield x) }'"), ++ ('f-string_yieldfrom', "f'{ (yield from x) }'"), ++ ('f-string_await', "f'{ await x }'"), ++ ('f-string_compare', "f'{ x == y }'"), ++ ('f-string_call', "f'{ f(x,y,z) }'"), ++ ('f-string_attribute', "f'{ f.x.y.z }'"), ++ ('f-string_starred', "f'{ *x, }'"), ++ ('f-string_doublestarred', "f'{ {**x} }'"), ++ ('f-string_escape_brace', "f'{{Escape'"), ++ ('f-string_escape_closing_brace', "f'Escape}}'"), ++ ('f-string_repr', "f'{a!r}'"), ++ ('f-string_str', "f'{a!s}'"), ++ ('f-string_ascii', "f'{a!a}'"), ++ ('f-string_debug', "f'{a=}'"), ++ ('f-string_padding', "f'{a:03d}'"), ++ ('f-string_multiline', ++ """ ++ f''' ++ {hello} ++ ''' ++ """), ++ ('f-string_multiline_in_expr', ++ """ ++ f''' ++ { ++ hello ++ } ++ ''' ++ """), ++ ('f-string_multiline_in_call', ++ """ ++ f''' ++ {f( ++ a, b, c ++ )} ++ ''' ++ """), ++ ('global', 'global a, b'), ++ ('group', '(yield a)'), ++ ('if_elif', ++ ''' ++ if a: ++ pass ++ elif b: ++ pass ++ '''), ++ ('if_elif_elif', ++ ''' ++ if a: ++ pass ++ elif b: ++ pass ++ elif c: ++ pass ++ '''), ++ ('if_elif_else', ++ ''' ++ if a: ++ pass ++ elif b: ++ pass ++ else: ++ pass ++ '''), ++ ('if_else', ++ ''' ++ if a: ++ pass ++ else: ++ pass ++ '''), ++ ('if_simple', 'if a: pass'), ++ ('import', 'import a'), ++ ('import_alias', 'import a as b'), ++ ('import_dotted', 'import a.b'), ++ ('import_dotted_alias', 'import a.b as c'), ++ ('import_dotted_multichar', 'import ab.cd'), ++ ('import_from', 'from a import b'), ++ ('import_from_alias', 'from a import b as c'), ++ ('import_from_dotted', 'from a.b import c'), ++ ('import_from_dotted_alias', 'from a.b import c as d'), ++ ('import_from_multiple_aliases', 'from a import b as c, d as e'), ++ ('import_from_one_dot', 'from .a import b'), ++ ('import_from_one_dot_alias', 'from .a import b as c'), ++ ('import_from_star', 'from a import *'), ++ ('import_from_three_dots', 'from ...a import b'), ++ ('import_from_trailing_comma', 'from a import (b,)'), ++ ('kwarg', ++ ''' ++ def f(**a): ++ pass ++ '''), ++ ('kwonly_args', ++ ''' ++ def f(*, a, b): ++ pass ++ '''), ++ ('kwonly_args_with_default', ++ ''' ++ def f(*, a=2, b): ++ pass ++ '''), ++ ('lambda_kwarg', 'lambda **a: 42'), ++ ('lambda_kwonly_args', 'lambda *, a, b: 42'), ++ ('lambda_kwonly_args_with_default', 'lambda *, a=2, b: 42'), ++ ('lambda_mixed_args', 'lambda a, /, b, *, c: 42'), ++ ('lambda_mixed_args_with_default', 'lambda a, b=2, /, c=3, *e, f, **g: 42'), ++ ('lambda_no_args', 'lambda: 42'), ++ ('lambda_pos_args', 'lambda a,b: 42'), ++ ('lambda_pos_args_with_default', 'lambda a, b=2: 42'), ++ ('lambda_pos_only_args', 'lambda a, /: 42'), ++ ('lambda_pos_only_args_with_default', 'lambda a=0, /: 42'), ++ ('lambda_pos_posonly_args', 'lambda a, b, /, c, d: 42'), ++ ('lambda_pos_posonly_args_with_default', 'lambda a, b=0, /, c=2: 42'), ++ ('lambda_vararg', 'lambda *a: 42'), ++ ('lambda_vararg_kwonly_args', 'lambda *a, b: 42'), ++ ('list', '[1, 2, a]'), ++ ('list_comp', '[i for i in a]'), ++ ('list_comp_if', '[i for i in a if b]'), ++ ('list_trailing_comma', '[1+2, a, 3+4,]'), ++ ('mixed_args', ++ ''' ++ def f(a, /, b, *, c): ++ pass ++ '''), ++ ('mixed_args_with_default', ++ ''' ++ def f(a, b=2, /, c=3, *e, f, **g): ++ pass ++ '''), ++ ('multipart_string_bytes', 'b"Hola" b"Hello" b"Bye"'), ++ ('multipart_string_triple', '"""Something here""" "and now"'), ++ ('multipart_string_different_prefixes', 'u"Something" "Other thing" r"last thing"'), ++ ('multiple_assignments', 'x = y = z = 42'), ++ ('multiple_assignments_with_yield', 'x = y = z = yield 42'), ++ ('multiple_pass', ++ ''' ++ pass; pass ++ pass ++ '''), ++ ('namedexpr', '(x := [1, 2, 3])'), ++ ('namedexpr_false', '(x := False)'), ++ ('namedexpr_none', '(x := None)'), ++ ('namedexpr_true', '(x := True)'), ++ ('nonlocal', 'nonlocal a, b'), ++ ('number_complex', '-2.234+1j'), ++ ('number_float', '-34.2333'), ++ ('number_imaginary_literal', '1.1234j'), ++ ('number_integer', '-234'), ++ ('number_underscores', '1_234_567'), ++ ('pass', 'pass'), ++ ('pos_args', ++ ''' ++ def f(a, b): ++ pass ++ '''), ++ ('pos_args_with_default', ++ ''' ++ def f(a, b=2): ++ pass ++ '''), ++ ('pos_only_args', ++ ''' ++ def f(a, /): ++ pass ++ '''), ++ ('pos_only_args_with_default', ++ ''' ++ def f(a=0, /): ++ pass ++ '''), ++ ('pos_posonly_args', ++ ''' ++ def f(a, b, /, c, d): ++ pass ++ '''), ++ ('pos_posonly_args_with_default', ++ ''' ++ def f(a, b=0, /, c=2): ++ pass ++ '''), ++ ('primary_mixed', 'a.b.c().d[0]'), ++ ('raise', 'raise'), ++ ('raise_ellipsis', 'raise ...'), ++ ('raise_expr', 'raise a'), ++ ('raise_from', 'raise a from b'), ++ ('return', 'return'), ++ ('return_expr', 'return a'), ++ ('set', '{1, 2+4, 3+5}'), ++ ('set_comp', '{i for i in a}'), ++ ('set_trailing_comma', '{1, 2, 3,}'), ++ ('simple_assignment', 'x = 42'), ++ ('simple_assignment_with_yield', 'x = yield 42'), ++ ('string_bytes', 'b"hello"'), ++ ('string_concatenation_bytes', 'b"hello" b"world"'), ++ ('string_concatenation_simple', '"abcd" "efgh"'), ++ ('string_format_simple', 'f"hello"'), ++ ('string_format_with_formatted_value', 'f"hello {world}"'), ++ ('string_simple', '"hello"'), ++ ('string_unicode', 'u"hello"'), ++ ('subscript_attribute', 'a[0].b'), ++ ('subscript_call', 'a[b]()'), ++ ('subscript_multiple_slices', 'a[0:a:2, 1]'), ++ ('subscript_simple', 'a[0]'), ++ ('subscript_single_element_tuple', 'a[0,]'), ++ ('subscript_trailing_comma', 'a[0, 1, 2,]'), ++ ('subscript_tuple', 'a[0, 1, 2]'), ++ ('subscript_whole_slice', 'a[0+1:b:c]'), ++ ('try_except', ++ ''' ++ try: ++ pass ++ except: ++ pass ++ '''), ++ ('try_except_else', ++ ''' ++ try: ++ pass ++ except: ++ pass ++ else: ++ pass ++ '''), ++ ('try_except_else_finally', ++ ''' ++ try: ++ pass ++ except: ++ pass ++ else: ++ pass ++ finally: ++ pass ++ '''), ++ ('try_except_expr', ++ ''' ++ try: ++ pass ++ except a: ++ pass ++ '''), ++ ('try_except_expr_target', ++ ''' ++ try: ++ pass ++ except a as b: ++ pass ++ '''), ++ ('try_except_finally', ++ ''' ++ try: ++ pass ++ except: ++ pass ++ finally: ++ pass ++ '''), ++ ('try_finally', ++ ''' ++ try: ++ pass ++ finally: ++ pass ++ '''), ++ ('unpacking_binop', '[*([1, 2, 3] + [3, 4, 5])]'), ++ ('unpacking_call', '[*b()]'), ++ ('unpacking_compare', '[*(x < y)]'), ++ ('unpacking_constant', '[*3]'), ++ ('unpacking_dict', '[*{1: 2, 3: 4}]'), ++ ('unpacking_dict_comprehension', '[*{x:y for x,y in z}]'), ++ ('unpacking_ifexpr', '[*([1, 2, 3] if x else y)]'), ++ ('unpacking_list', '[*[1,2,3]]'), ++ ('unpacking_list_comprehension', '[*[x for x in y]]'), ++ ('unpacking_namedexpr', '[*(x:=[1, 2, 3])]'), ++ ('unpacking_set', '[*{1,2,3}]'), ++ ('unpacking_set_comprehension', '[*{x for x in y}]'), ++ ('unpacking_string', '[*"myvalue"]'), ++ ('unpacking_tuple', '[*(1,2,3)]'), ++ ('unpacking_unaryop', '[*(not [1, 2, 3])]'), ++ ('unpacking_yield', '[*(yield 42)]'), ++ ('unpacking_yieldfrom', '[*(yield from x)]'), ++ ('tuple', '(1, 2, 3)'), ++ ('vararg', ++ ''' ++ def f(*a): ++ pass ++ '''), ++ ('vararg_kwonly_args', ++ ''' ++ def f(*a, b): ++ pass ++ '''), ++ ('while', ++ ''' ++ while a: ++ pass ++ '''), ++ ('while_else', ++ ''' ++ while a: ++ pass ++ else: ++ pass ++ '''), ++ ('with', ++ ''' ++ with a: ++ pass ++ '''), ++ ('with_as', ++ ''' ++ with a as b: ++ pass ++ '''), ++ ('with_as_paren', ++ ''' ++ with a as (b): ++ pass ++ '''), ++ ('with_as_empty', 'with a as (): pass'), ++ ('with_list_recursive', ++ ''' ++ with a as [x, [y, z]]: ++ pass ++ '''), ++ ('with_tuple_recursive', ++ ''' ++ with a as ((x, y), z): ++ pass ++ '''), ++ ('with_tuple_target', ++ ''' ++ with a as (x, y): ++ pass ++ '''), ++ ('yield', 'yield'), ++ ('yield_expr', 'yield a'), ++ ('yield_from', 'yield from a'), ++] ++ ++FAIL_TEST_CASES = [ ++ ("annotation_multiple_targets", "(a, b): int = 42"), ++ ("annotation_nested_tuple", "((a, b)): int"), ++ ("annotation_list", "[a]: int"), ++ ("annotation_lambda", "lambda: int = 42"), ++ ("annotation_tuple", "(a,): int"), ++ ("annotation_tuple_without_paren", "a,: int"), ++ ("assignment_keyword", "a = if"), ++ ("comprehension_lambda", "(a for a in lambda: b)"), ++ ("comprehension_else", "(a for a in b if c else d"), ++ ("del_call", "del a()"), ++ ("del_call_genexp", "del a(i for i in b)"), ++ ("del_subscript_call", "del a[b]()"), ++ ("del_attribute_call", "del a.b()"), ++ ("del_mixed_call", "del a[0].b().c.d()"), ++ ("for_star_targets_call", "for a() in b: pass"), ++ ("for_star_targets_subscript_call", "for a[b]() in c: pass"), ++ ("for_star_targets_attribute_call", "for a.b() in c: pass"), ++ ("for_star_targets_mixed_call", "for a[0].b().c.d() in e: pass"), ++ ("for_star_targets_in", "for a, in in b: pass"), ++ ("f-string_assignment", "f'{x = 42}'"), ++ ("f-string_empty", "f'{}'"), ++ ("f-string_function_def", "f'{def f(): pass}'"), ++ ("f-string_lambda", "f'{lambda x: 42}'"), ++ ("f-string_singe_brace", "f'{'"), ++ ("f-string_single_closing_brace", "f'}'"), ++ ("from_import_invalid", "from import import a"), ++ ("from_import_trailing_comma", "from a import b,"), ++ # This test case checks error paths involving tokens with uninitialized ++ # values of col_offset and end_col_offset. ++ ("invalid indentation", ++ """ ++ def f(): ++ a ++ a ++ """), ++ ("not_terminated_string", "a = 'example"), ++] ++ ++FAIL_SPECIALIZED_MESSAGE_CASES = [ ++ ("f(x, y, z=1, **b, *a", "iterable argument unpacking follows keyword argument unpacking"), ++ ("f(x, y=1, *z, **a, b", "positional argument follows keyword argument unpacking"), ++ ("f(x, y, z=1, a=2, b", "positional argument follows keyword argument"), ++ ("True = 1", "cannot assign to True"), ++ ("a() = 1", "cannot assign to function call"), ++ ("(a, b): int", "only single target (not tuple) can be annotated"), ++ ("[a, b]: int", "only single target (not list) can be annotated"), ++ ("a(): int", "illegal target for annotation"), ++ ("1 += 1", "cannot assign to literal"), ++ ("pass\n pass", "unexpected indent"), ++ ("def f():\npass", "expected an indented block"), ++] ++ ++GOOD_BUT_FAIL_TEST_CASES = [ ++ ('string_concatenation_format', 'f"{hello} world" f"again {and_again}"'), ++ ('string_concatenation_multiple', ++ ''' ++ f"hello" f"{world} again" f"and_again" ++ '''), ++ ('f-string_multiline_comp', ++ """ ++ f''' ++ {(i for i in a ++ if b)} ++ ''' ++ """), ++] ++ ++FSTRINGS_TRACEBACKS = { ++ 'multiline_fstrings_same_line_with_brace': ( ++ """ ++ f''' ++ {a$b} ++ ''' ++ """, ++ '(a$b)', ++ ), ++ 'multiline_fstring_brace_on_next_line': ( ++ """ ++ f''' ++ {a$b ++ }''' ++ """, ++ '(a$b', ++ ), ++ 'multiline_fstring_brace_on_previous_line': ( ++ """ ++ f''' ++ { ++ a$b}''' ++ """, ++ 'a$b)', ++ ), ++} ++ ++EXPRESSIONS_TEST_CASES = [ ++ ("expression_add", "1+1"), ++ ("expression_add_2", "a+b"), ++ ("expression_call", "f(a, b=2, **kw)"), ++ ("expression_tuple", "1, 2, 3"), ++ ("expression_tuple_one_value", "1,") ++] ++ ++ ++def cleanup_source(source: Any) -> str: ++ if isinstance(source, str): ++ result = dedent(source) ++ elif not isinstance(source, (list, tuple)): ++ result = "\n".join(source) ++ else: ++ raise TypeError(f"Invalid type for test source: {source}") ++ return result ++ ++ ++def prepare_test_cases( ++ test_cases: Iterable[Tuple[str, Union[str, Iterable[str]]]] ++) -> Tuple[Iterable[str], Iterable[str]]: ++ ++ test_ids, _test_sources = zip(*test_cases) ++ test_sources = list(_test_sources) ++ for index, source in enumerate(test_sources): ++ result = cleanup_source(source) ++ test_sources[index] = result ++ return test_ids, test_sources ++ ++ ++TEST_IDS, TEST_SOURCES = prepare_test_cases(TEST_CASES) ++ ++GOOD_BUT_FAIL_TEST_IDS, GOOD_BUT_FAIL_SOURCES = prepare_test_cases( ++ GOOD_BUT_FAIL_TEST_CASES ++) ++ ++FAIL_TEST_IDS, FAIL_SOURCES = prepare_test_cases(FAIL_TEST_CASES) ++ ++EXPRESSIONS_TEST_IDS, EXPRESSIONS_TEST_SOURCES = prepare_test_cases( ++ EXPRESSIONS_TEST_CASES ++) ++ ++ ++class ASTGenerationTest(unittest.TestCase): ++ def test_correct_ast_generation_on_source_files(self) -> None: ++ self.maxDiff = None ++ for source in TEST_SOURCES: ++ actual_ast = peg_parser.parse_string(source) ++ expected_ast = ast.parse(source) ++ self.assertEqual( ++ ast.dump(actual_ast, include_attributes=True), ++ ast.dump(expected_ast, include_attributes=True), ++ f"Wrong AST generation for source: {source}", ++ ) ++ ++ def test_incorrect_ast_generation_on_source_files(self) -> None: ++ for source in FAIL_SOURCES: ++ with self.assertRaises(SyntaxError, msg=f"Parsing {source} did not raise an exception"): ++ peg_parser.parse_string(source) ++ ++ def test_incorrect_ast_generation_with_specialized_errors(self) -> None: ++ for source, error_text in FAIL_SPECIALIZED_MESSAGE_CASES: ++ exc = IndentationError if "indent" in error_text else SyntaxError ++ with self.assertRaises(exc) as se: ++ peg_parser.parse_string(source) ++ self.assertTrue( ++ error_text in se.exception.msg, ++ f"Actual error message does not match expexted for {source}" ++ ) ++ ++ @unittest.skipIf(sys.flags.use_peg, "This tests nothing for now, since compile uses pegen as well") ++ @unittest.expectedFailure ++ def test_correct_but_known_to_fail_ast_generation_on_source_files(self) -> None: ++ for source in GOOD_BUT_FAIL_SOURCES: ++ actual_ast = peg_parser.parse_string(source) ++ expected_ast = ast.parse(source) ++ self.assertEqual( ++ ast.dump(actual_ast, include_attributes=True), ++ ast.dump(expected_ast, include_attributes=True), ++ f"Wrong AST generation for source: {source}", ++ ) ++ ++ def test_correct_ast_generation_without_pos_info(self) -> None: ++ for source in GOOD_BUT_FAIL_SOURCES: ++ actual_ast = peg_parser.parse_string(source) ++ expected_ast = ast.parse(source) ++ self.assertEqual( ++ ast.dump(actual_ast), ++ ast.dump(expected_ast), ++ f"Wrong AST generation for source: {source}", ++ ) ++ ++ def test_fstring_parse_error_tracebacks(self) -> None: ++ for source, error_text in FSTRINGS_TRACEBACKS.values(): ++ with self.assertRaises(SyntaxError) as se: ++ peg_parser.parse_string(dedent(source)) ++ self.assertEqual(error_text, se.exception.text) ++ ++ def test_correct_ast_generatrion_eval(self) -> None: ++ for source in EXPRESSIONS_TEST_SOURCES: ++ actual_ast = peg_parser.parse_string(source, mode='eval') ++ expected_ast = ast.parse(source, mode='eval') ++ self.assertEqual( ++ ast.dump(actual_ast, include_attributes=True), ++ ast.dump(expected_ast, include_attributes=True), ++ f"Wrong AST generation for source: {source}", ++ ) ++ ++ def test_tokenizer_errors_are_propagated(self) -> None: ++ n=201 ++ with self.assertRaisesRegex(SyntaxError, "too many nested parentheses"): ++ peg_parser.parse_string(n*'(' + ')'*n) +diff --git a/Lib/test/test_positional_only_arg.py b/Lib/test/test_positional_only_arg.py +--- a/Lib/test/test_positional_only_arg.py ++++ b/Lib/test/test_positional_only_arg.py +@@ -3,6 +3,7 @@ + import dis + import pickle + import unittest ++import sys + + from test.support import check_syntax_error + +@@ -23,10 +24,12 @@ def assertRaisesSyntaxError(self, codestr, regex="invalid syntax"): + compile(codestr + "\n", "", "single") + + def test_invalid_syntax_errors(self): +- check_syntax_error(self, "def f(a, b = 5, /, c): pass", "non-default argument follows default argument") +- check_syntax_error(self, "def f(a = 5, b, /, c): pass", "non-default argument follows default argument") +- check_syntax_error(self, "def f(a = 5, b=1, /, c, *, d=2): pass", "non-default argument follows default argument") +- check_syntax_error(self, "def f(a = 5, b, /): pass", "non-default argument follows default argument") ++ if not sys.flags.use_peg: ++ check_syntax_error(self, "def f(a, b = 5, /, c): pass") ++ check_syntax_error(self, "def f(a = 5, b, /, c): pass") ++ check_syntax_error(self, "def f(a = 5, b=1, /, c, *, d=2): pass") ++ check_syntax_error(self, "def f(a = 5, b, /): pass") ++ + check_syntax_error(self, "def f(*args, /): pass") + check_syntax_error(self, "def f(*args, a, /): pass") + check_syntax_error(self, "def f(**kwargs, /): pass") +@@ -44,10 +47,12 @@ def test_invalid_syntax_errors(self): + check_syntax_error(self, "def f(a, *, c, /, d, e): pass") + + def test_invalid_syntax_errors_async(self): +- check_syntax_error(self, "async def f(a, b = 5, /, c): pass", "non-default argument follows default argument") +- check_syntax_error(self, "async def f(a = 5, b, /, c): pass", "non-default argument follows default argument") +- check_syntax_error(self, "async def f(a = 5, b=1, /, c, d=2): pass", "non-default argument follows default argument") +- check_syntax_error(self, "async def f(a = 5, b, /): pass", "non-default argument follows default argument") ++ if not sys.flags.use_peg: ++ check_syntax_error(self, "async def f(a, b = 5, /, c): pass") ++ check_syntax_error(self, "async def f(a = 5, b, /, c): pass") ++ check_syntax_error(self, "async def f(a = 5, b=1, /, c, d=2): pass") ++ check_syntax_error(self, "async def f(a = 5, b, /): pass") ++ + check_syntax_error(self, "async def f(*args, /): pass") + check_syntax_error(self, "async def f(*args, a, /): pass") + check_syntax_error(self, "async def f(**kwargs, /): pass") +@@ -231,9 +236,11 @@ def test_lambdas(self): + self.assertEqual(x(1, 2), 3) + + def test_invalid_syntax_lambda(self): +- check_syntax_error(self, "lambda a, b = 5, /, c: None", "non-default argument follows default argument") +- check_syntax_error(self, "lambda a = 5, b, /, c: None", "non-default argument follows default argument") +- check_syntax_error(self, "lambda a = 5, b, /: None", "non-default argument follows default argument") ++ if not sys.flags.use_peg: ++ check_syntax_error(self, "lambda a, b = 5, /, c: None") ++ check_syntax_error(self, "lambda a = 5, b, /, c: None") ++ check_syntax_error(self, "lambda a = 5, b, /: None") ++ + check_syntax_error(self, "lambda *args, /: None") + check_syntax_error(self, "lambda *args, a, /: None") + check_syntax_error(self, "lambda **kwargs, /: None") +diff --git a/Lib/test/test_string_literals.py b/Lib/test/test_string_literals.py +--- a/Lib/test/test_string_literals.py ++++ b/Lib/test/test_string_literals.py +@@ -119,7 +119,8 @@ def test_eval_str_invalid_escape(self): + eval("'''\n\\z'''") + self.assertEqual(len(w), 1) + self.assertEqual(w[0].filename, '') +- self.assertEqual(w[0].lineno, 1) ++ if not sys.flags.use_peg: ++ self.assertEqual(w[0].lineno, 1) + + with warnings.catch_warnings(record=True) as w: + warnings.simplefilter('error', category=DeprecationWarning) +@@ -128,7 +129,8 @@ def test_eval_str_invalid_escape(self): + exc = cm.exception + self.assertEqual(w, []) + self.assertEqual(exc.filename, '') +- self.assertEqual(exc.lineno, 1) ++ if not sys.flags.use_peg: ++ self.assertEqual(exc.lineno, 1) + + def test_eval_str_raw(self): + self.assertEqual(eval(""" r'x' """), 'x') +@@ -168,7 +170,8 @@ def test_eval_bytes_invalid_escape(self): + eval("b'''\n\\z'''") + self.assertEqual(len(w), 1) + self.assertEqual(w[0].filename, '') +- self.assertEqual(w[0].lineno, 1) ++ if not sys.flags.use_peg: ++ self.assertEqual(w[0].lineno, 1) + + with warnings.catch_warnings(record=True) as w: + warnings.simplefilter('error', category=DeprecationWarning) +@@ -177,7 +180,8 @@ def test_eval_bytes_invalid_escape(self): + exc = cm.exception + self.assertEqual(w, []) + self.assertEqual(exc.filename, '') +- self.assertEqual(exc.lineno, 1) ++ if not sys.flags.use_peg: ++ self.assertEqual(exc.lineno, 1) + + def test_eval_bytes_raw(self): + self.assertEqual(eval(""" br'x' """), b'x') +diff --git a/Lib/test/test_syntax.py b/Lib/test/test_syntax.py +--- a/Lib/test/test_syntax.py ++++ b/Lib/test/test_syntax.py +@@ -63,9 +63,10 @@ + Traceback (most recent call last): + SyntaxError: cannot assign to function call + +->>> del f() +-Traceback (most recent call last): +-SyntaxError: cannot delete function call ++# Pegen does not support this yet ++# >>> del f() ++# Traceback (most recent call last): ++# SyntaxError: cannot delete function call + + >>> a + 1 = 2 + Traceback (most recent call last): +@@ -100,29 +101,30 @@ + This test just checks a couple of cases rather than enumerating all of + them. + +->>> (a, "b", c) = (1, 2, 3) +-Traceback (most recent call last): +-SyntaxError: cannot assign to literal ++# All of the following also produce different error messages with pegen ++# >>> (a, "b", c) = (1, 2, 3) ++# Traceback (most recent call last): ++# SyntaxError: cannot assign to literal + +->>> (a, True, c) = (1, 2, 3) +-Traceback (most recent call last): +-SyntaxError: cannot assign to True ++# >>> (a, True, c) = (1, 2, 3) ++# Traceback (most recent call last): ++# SyntaxError: cannot assign to True + + >>> (a, __debug__, c) = (1, 2, 3) + Traceback (most recent call last): + SyntaxError: cannot assign to __debug__ + +->>> (a, *True, c) = (1, 2, 3) +-Traceback (most recent call last): +-SyntaxError: cannot assign to True ++# >>> (a, *True, c) = (1, 2, 3) ++# Traceback (most recent call last): ++# SyntaxError: cannot assign to True + + >>> (a, *__debug__, c) = (1, 2, 3) + Traceback (most recent call last): + SyntaxError: cannot assign to __debug__ + +->>> [a, b, c + 1] = [1, 2, 3] +-Traceback (most recent call last): +-SyntaxError: cannot assign to operator ++# >>> [a, b, c + 1] = [1, 2, 3] ++# Traceback (most recent call last): ++# SyntaxError: cannot assign to operator + + >>> a if 1 else b = 1 + Traceback (most recent call last): +@@ -186,9 +188,11 @@ + >>> f(x for x in L, **{}) + Traceback (most recent call last): + SyntaxError: Generator expression must be parenthesized +->>> f(L, x for x in L) +-Traceback (most recent call last): +-SyntaxError: Generator expression must be parenthesized ++ ++# >>> f(L, x for x in L) ++# Traceback (most recent call last): ++# SyntaxError: Generator expression must be parenthesized ++ + >>> f(x for x in L, y for y in L) + Traceback (most recent call last): + SyntaxError: Generator expression must be parenthesized +@@ -297,31 +301,34 @@ + ... 290, 291, 292, 293, 294, 295, 296, 297, 298, 299) # doctest: +ELLIPSIS + (0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, ..., 297, 298, 299) + +->>> f(lambda x: x[0] = 3) +-Traceback (most recent call last): +-SyntaxError: expression cannot contain assignment, perhaps you meant "=="? ++# >>> f(lambda x: x[0] = 3) ++# Traceback (most recent call last): ++# SyntaxError: expression cannot contain assignment, perhaps you meant "=="? + + The grammar accepts any test (basically, any expression) in the + keyword slot of a call site. Test a few different options. + +->>> f(x()=2) +-Traceback (most recent call last): +-SyntaxError: expression cannot contain assignment, perhaps you meant "=="? +->>> f(a or b=1) +-Traceback (most recent call last): +-SyntaxError: expression cannot contain assignment, perhaps you meant "=="? +->>> f(x.y=1) +-Traceback (most recent call last): +-SyntaxError: expression cannot contain assignment, perhaps you meant "=="? +->>> f((x)=2) +-Traceback (most recent call last): +-SyntaxError: expression cannot contain assignment, perhaps you meant "=="? +->>> f(True=2) +-Traceback (most recent call last): +-SyntaxError: cannot assign to True ++# >>> f(x()=2) ++# Traceback (most recent call last): ++# SyntaxError: expression cannot contain assignment, perhaps you meant "=="? ++# >>> f(a or b=1) ++# Traceback (most recent call last): ++# SyntaxError: expression cannot contain assignment, perhaps you meant "=="? ++# >>> f(x.y=1) ++# Traceback (most recent call last): ++# SyntaxError: expression cannot contain assignment, perhaps you meant "=="? ++# >>> f((x)=2) ++# Traceback (most recent call last): ++# SyntaxError: expression cannot contain assignment, perhaps you meant "=="? ++# >>> f(True=2) ++# Traceback (most recent call last): ++# SyntaxError: cannot assign to True + >>> f(__debug__=1) + Traceback (most recent call last): + SyntaxError: cannot assign to __debug__ ++>>> __debug__: int ++Traceback (most recent call last): ++SyntaxError: cannot assign to __debug__ + + + More set_context(): +@@ -620,9 +627,9 @@ + Traceback (most recent call last): + SyntaxError: cannot assign to __debug__ + +- >>> with (lambda *:0): pass +- Traceback (most recent call last): +- SyntaxError: named arguments must follow bare * ++ # >>> with (lambda *:0): pass ++ # Traceback (most recent call last): ++ # SyntaxError: named arguments must follow bare * + + Corner-cases that used to crash: + +@@ -637,6 +644,7 @@ + """ + + import re ++import sys + import unittest + + from test import support +@@ -670,6 +678,8 @@ def _check_error(self, code, errtext, + def test_assign_call(self): + self._check_error("f() = 1", "assign") + ++ @unittest.skipIf(sys.flags.use_peg, "Pegen does not produce a specialized error " ++ "message yet") + def test_assign_del(self): + self._check_error("del f()", "delete") + +diff --git a/Lib/test/test_sys.py b/Lib/test/test_sys.py +--- a/Lib/test/test_sys.py ++++ b/Lib/test/test_sys.py +@@ -545,10 +545,10 @@ def __hash__(self): + def test_sys_flags(self): + self.assertTrue(sys.flags) + attrs = ("debug", +- "inspect", "interactive", "optimize", "dont_write_bytecode", +- "no_user_site", "no_site", "ignore_environment", "verbose", +- "bytes_warning", "quiet", "hash_randomization", "isolated", +- "dev_mode", "utf8_mode") ++ "inspect", "interactive", "optimize", "use_peg", ++ "dont_write_bytecode", "no_user_site", "no_site", ++ "ignore_environment", "verbose", "bytes_warning", "quiet", ++ "hash_randomization", "isolated", "dev_mode", "utf8_mode") + for attr in attrs: + self.assertTrue(hasattr(sys.flags, attr), attr) + attr_type = bool if attr == "dev_mode" else int +diff --git a/Lib/test/test_traceback.py b/Lib/test/test_traceback.py +--- a/Lib/test/test_traceback.py ++++ b/Lib/test/test_traceback.py +@@ -656,6 +656,8 @@ def outer_raise(): + self.assertIn('inner_raise() # Marker', blocks[2]) + self.check_zero_div(blocks[2]) + ++ @unittest.skipIf(sys.flags.use_peg, ++ "Pegen is arguably better here, so no need to fix this") + def test_syntax_error_offset_at_eol(self): + # See #10186. + def e(): +diff --git a/Lib/test/test_type_comments.py b/Lib/test/test_type_comments.py +--- a/Lib/test/test_type_comments.py ++++ b/Lib/test/test_type_comments.py +@@ -218,6 +218,7 @@ def favk( + """ + + ++@unittest.skipIf(sys.flags.use_peg, "Pegen does not support type comments yet") + class TypeCommentTests(unittest.TestCase): + + lowest = 4 # Lowest minor version supported +diff --git a/Lib/test/test_unpack_ex.py b/Lib/test/test_unpack_ex.py +--- a/Lib/test/test_unpack_ex.py ++++ b/Lib/test/test_unpack_ex.py +@@ -158,14 +158,15 @@ + ... + SyntaxError: iterable unpacking cannot be used in comprehension + +-Generator expression in function arguments +- +- >>> list(*x for x in (range(5) for i in range(3))) +- Traceback (most recent call last): +- ... +- list(*x for x in (range(5) for i in range(3))) +- ^ +- SyntaxError: invalid syntax ++# Pegen is better here. ++# Generator expression in function arguments ++ ++# >>> list(*x for x in (range(5) for i in range(3))) ++# Traceback (most recent call last): ++# ... ++# list(*x for x in (range(5) for i in range(3))) ++# ^ ++# SyntaxError: invalid syntax + + >>> dict(**x for x in [{1:2}]) + Traceback (most recent call last): +diff --git a/Lib/test/test_unparse.py b/Lib/test/test_unparse.py +--- a/Lib/test/test_unparse.py ++++ b/Lib/test/test_unparse.py +@@ -6,6 +6,7 @@ + import random + import tokenize + import ast ++import sys + + + def read_pyfile(filename): +@@ -327,6 +328,7 @@ def test_constant_tuples(self): + ast.Constant(value=(1, 2, 3), kind=None), "(1, 2, 3)" + ) + ++ @unittest.skipIf(sys.flags.use_peg, "Pegen does not support type annotation yet") + def test_function_type(self): + for function_type in ( + "() -> int", diff --git a/cpython_1/tests/private/eval_tests_aug.patch b/cpython_1/tests/private/eval_tests_aug.patch new file mode 100644 index 0000000000000000000000000000000000000000..56a08005c35b409635c7e8021e50bb4d417e7112 --- /dev/null +++ b/cpython_1/tests/private/eval_tests_aug.patch @@ -0,0 +1,723 @@ +diff --git a/Lib/test/test_peg_aug.py b/Lib/test/test_peg_aug.py +new file mode 100644 +--- /dev/null ++++ b/Lib/test/test_peg_aug.py +@@ -0,0 +1,657 @@ ++import ast ++import sys ++import tempfile ++import types ++import unittest ++from io import StringIO ++from pathlib import Path ++from tokenize import TokenInfo ++from tokenize import open as tokenize_open ++from typing import Any, Dict, Iterable, List ++ ++from test import test_tools ++ ++test_tools.skip_if_missing("peg_generator") ++with test_tools.imports_under_tool("peg_generator"): ++ from pegen.first_sets import FirstSetCalculator ++ from pegen.grammar import Grammar ++ from pegen.grammar_parser import GeneratedParser as GrammarParser ++ from pegen.testutil import ( ++ generate_parser, ++ generate_parser_c_extension, ++ make_parser, ++ parse_string, ++ ) ++ ++ ++def _require_active_peg_parser() -> None: ++ if not getattr(sys.flags, "use_peg", False): ++ raise AssertionError("PEG parser is not active") ++ ++ ++class _ActivePegParserAdapter: ++ @staticmethod ++ def parse_string(source: str, mode: str = "exec") -> ast.AST: ++ _require_active_peg_parser() ++ return ast.parse(source, mode=mode) ++ ++ @staticmethod ++ def parse_file(filename: str, mode: str = "exec") -> ast.AST: ++ _require_active_peg_parser() ++ with tokenize_open(filename) as handle: ++ source = handle.read() ++ return ast.parse(source, filename=filename, mode=mode) ++ ++ ++peg_parser = _ActivePegParserAdapter() ++ ++ ++class PegParserModeAugTest(unittest.TestCase): ++ def assertAstEqual(self, actual: ast.AST, expected: ast.AST) -> None: ++ self.assertEqual( ++ ast.dump(actual, include_attributes=True), ++ ast.dump(expected, include_attributes=True), ++ ) ++ ++ def test_parse_string_modes_and_cookie_handling(self) -> None: ++ module_source = "# coding: definitely-not-an-encoding\nx = 1\ny = x + 2\n" ++ self.assertAstEqual(peg_parser.parse_string(module_source), ast.parse(module_source)) ++ ++ expr_source = "1 + 2 * 3" ++ actual_expr = peg_parser.parse_string(expr_source, mode="eval") ++ self.assertIsInstance(actual_expr, ast.Expression) ++ self.assertAstEqual(actual_expr, ast.parse(expr_source, mode="eval")) ++ ++ single_source = "answer = 42\n" ++ actual_single = peg_parser.parse_string(single_source, mode="single") ++ self.assertIsInstance(actual_single, ast.Interactive) ++ self.assertAstEqual(actual_single, ast.parse(single_source, mode="single")) ++ ++ def test_parse_file_modes(self) -> None: ++ with tempfile.TemporaryDirectory() as tmp: ++ exec_path = Path(tmp) / "program.py" ++ exec_path.write_text("a = 1\nb = a + 2\n", encoding="utf-8") ++ self.assertAstEqual( ++ peg_parser.parse_file(str(exec_path)), ++ ast.parse(exec_path.read_text(encoding="utf-8")), ++ ) ++ ++ single_path = Path(tmp) / "single.py" ++ single_path.write_text("value = 5\n", encoding="utf-8") ++ actual_single = peg_parser.parse_file(str(single_path), mode="single") ++ self.assertIsInstance(actual_single, ast.Interactive) ++ self.assertAstEqual( ++ actual_single, ++ ast.parse(single_path.read_text(encoding="utf-8"), mode="single"), ++ ) ++ ++ def test_generated_extension_parse_string_modes(self) -> None: ++ grammar_source = """ ++ start[mod_ty]: a=[statements] ENDMARKER { Module(a, NULL, p->arena) } ++ statements[asdl_seq*]: a=statement+ { a } ++ statement[stmt_ty]: pass_stmt ++ pass_stmt[stmt_ty]: 'pass' NEWLINE { _Py_Pass(EXTRA) } ++ """ ++ extension = build_c_extension(grammar_source) ++ ++ self.assertIsNone(extension.parse_string("pass\n", mode=0)) ++ ast_obj = extension.parse_string("pass\n", mode=1) ++ self.assertEqual(type(ast_obj).__name__, "Module") ++ self.assertEqual(len(ast_obj.body), 1) ++ self.assertEqual(type(ast_obj.body[0]).__name__, "Pass") ++ code_obj = extension.parse_string("pass\n", mode=2) ++ self.assertIsInstance(code_obj, types.CodeType) ++ exec(code_obj, {}) ++ ++ ++class PegParserGrammarCoverageAugTest(unittest.TestCase): ++ VALID_PROGRAMS = [ ++ "pass\n", ++ "a = 1; b = 2; c = a + b\n", ++ "a = b = c = (1, 2, 3)\n", ++ "name: int = 1\nbox.attr: str = 'value'\nitems[0]: object = None\n", ++ "(target): int = 3\n", ++ "total += 1\ntotal -= 1\ntotal *= 2\ntotal @= matrix\ntotal /= 2\n" ++ "total %= 2\ntotal &= mask\ntotal |= flag\ntotal ^= bit\n" ++ "total <<= 1\ntotal >>= 1\ntotal **= 2\ntotal //= 2\n", ++ "import os, sys as system\nfrom pkg.subpkg import name as alias, other\n" ++ "from . import local\nfrom ...pkg import thing\nfrom pkg import *\n", ++ "assert ready, 'not ready'\ndel obj.attr, items[0], (name), [left, right]\n", ++ "if first:\n value = 1\nelif second:\n value = 2\nelif third:\n value = 3\nelse:\n value = 4\n", ++ "while running:\n break\nelse:\n finished = True\n", ++ "for first, *middle, last in rows:\n continue\nelse:\n exhausted = True\n", ++ "with manager() as resource, other_manager():\n resource.use()\n", ++ "with (manager() as resource, other_manager() as other):\n result = other\n", ++ "try:\n risky()\nexcept ValueError as exc:\n handle(exc)\nexcept:\n recover()\nelse:\n success()\nfinally:\n cleanup()\n", ++ "try:\n cleanup_only()\nfinally:\n done()\n", ++ "raise RuntimeError('boom') from cause\nraise\n", ++ "def plain():\n return\n", ++ "def params(a, b, /, c, d=4, *args, e, f=6, **kw):\n return a, b, c, d, args, e, f, kw\n", ++ "def annotated(a: int, /, b: str = 'x', *, c: float, **kw: object) -> None:\n return None\n", ++ "def keyword_only(*, option, default=True):\n return option, default\n", ++ "def var_kwargs(**kw):\n return kw\n", ++ "@decorator\n@factory(arg=1)\ndef decorated(value):\n return value\n", ++ "@class_decorator\nclass Child(Base, mixin=True, **metadata):\n attr = 1\n", ++ "def outer():\n value = 0\n def inner():\n nonlocal value\n" ++ " value += 1\n return value\n return inner\n", ++ "def uses_global():\n global shared\n shared = 1\n", ++ "async def async_features(source, manager):\n await source.ready()\n" ++ " async for item in source:\n yield item\n" ++ " async with manager as handle:\n return handle\n", ++ "def generator():\n yield\n yield 1, 2\n yield from other\n", ++ "values = [x for x in data if x > 0 if x < 10]\n" ++ "pairs = {(k, v) for k, v in entries if k}\n" ++ "mapping = {k: v for k, v in entries if v}\n" ++ "gen = (item async for item in stream if item)\n", ++ "starred = [first, *middle, last]\n" ++ "tupled = (*items, tail)\n" ++ "called = func(1, *args, key=value, other=2, **kw)\n" ++ "called2 = func(*(x for x in data), **kw)\n", ++ "slices = data[1:10:2, :, ...]\n" ++ "chained = root.child[index](arg).leaf\n" ++ "target.attr[index] = value\n", ++ "literals = (True, False, None, ..., 0xFF, 0b1010, 3.14, 1j, b'bytes')\n" ++ "strings = 'a' 'b' f'{name!r:>10}' rf'{path}'\n", ++ "exprs = (a or b and not c, a if b else c, lambda x, y=2: x + y)\n" ++ "more = (lambda a, b, /, c=3, *args, d, **kw: (a, b, c, args, d, kw))\n", ++ "comparisons = a == b != c <= d < e >= f > g not in h in i is not j is k\n", ++ "numbers = (+a, -b, ~c, a ** b, a * b, a @ b, a / b, a // b, a % b,\n" ++ " a + b, a - b, a << b, a >> b, a & b, a ^ b, a | b)\n", ++ "named = (result := compute())\n" ++ "list_target, (nested_target), [another_target] = data\n", ++ ] ++ ++ VALID_EVAL_EXPRESSIONS = [ ++ "1, 2, 3", ++ "lambda a, b, /, c=3, *, d=4, **kw: (a, b, c, d, kw)", ++ "{**base, 'x': value, **override}", ++ "func(1, *(x for x in seq), key=value, **kw)", ++ "(await coro())", ++ "f'{value!s:^10} {other!r}'", ++ ] ++ ++ INVALID_PROGRAMS = [ ++ "__new_parser__\n", ++ "call(**kw, *items)\n", ++ "call(x for x in seq, 1)\n", ++ "1 := 2\n", ++ "[target]: int = value\n", ++ "(left, right): int = value\n", ++ "1: int = value\n", ++ "call() = value\n", ++ "a + b = value\n", ++ "if condition:\npass\n", ++ "[*item for item in seq]\n", ++ "(*item for item in seq)\n", ++ "{*item for item in seq}\n", ++ "def bad(a=1, b):\n pass\n", ++ "f'{}'\n", ++ "f'{value'\n", ++ "f'{1 # comment}'\n", ++ "f'{(1 + 2}'\n", ++ ] ++ ++ INVALID_EVAL_EXPRESSIONS = [ ++ "lambda a=1, b: a", ++ "func(keyword=1, positional)", ++ "(x := y) := z", ++ ] ++ ++ EDGE_EXEC_STEMS = [ ++ "", ++ "if condition", ++ "if condition:", ++ "if condition:\n", ++ "if condition:\n value = 1\nelif other", ++ "while condition", ++ "while condition:", ++ "for item in items", ++ "for item in", ++ "async for item in items", ++ "with manager", ++ "with manager as", ++ "with (manager() as resource", ++ "async with manager", ++ "try", ++ "try:", ++ "try:\n risky()\nexcept ValueError as", ++ "try:\n risky()\nelse", ++ "except ValueError:", ++ "finally:", ++ "def f", ++ "def f(", ++ "def f(a, /, b=1, c", ++ "def f(*, a, b=1", ++ "def f(**", ++ "async def f", ++ "class C", ++ "class C(", ++ "@decorator", ++ "@decorator\nclass C", ++ "return", ++ "yield from", ++ "raise ValueError from", ++ "assert value,", ++ "del", ++ "global", ++ "nonlocal", ++ "import", ++ "import pkg as", ++ "from", ++ "from . import", ++ "from pkg import (", ++ "a:", ++ "a: int =", ++ "(a, b): int = value", ++ "[a]: int = value", ++ "a =", ++ "a + b =", ++ "target.", ++ "target[", ++ "target[1:", ++ "target.attr[0] =", ++ "call(", ++ "call(a,", ++ "call(a=1,", ++ "call(**kw,", ++ "lambda_value = lambda", ++ "lambda_value = lambda a=1, b", ++ "comp = [x for", ++ "comp = [*x for x in y]", ++ "comp = {x: for x in y}", ++ "text = f'{", ++ "text = f'{}'", ++ ] ++ ++ EDGE_EXEC_TAILS = [ ++ "", ++ "\n", ++ ":\n pass\n", ++ ":\n pass\nelse:\n pass\n", ++ ":\n yield value\n", ++ " as name:\n pass\n", ++ " import name\n", ++ " = value\n", ++ " += value\n", ++ ")\n", ++ ] ++ ++ EDGE_EVAL_STEMS = [ ++ "", ++ "lambda", ++ "lambda a", ++ "lambda a=1, b", ++ "a if b", ++ "a if b else", ++ "a or", ++ "a and", ++ "not", ++ "a ==", ++ "a !=", ++ "a <", ++ "a not", ++ "a is", ++ "a +", ++ "a -", ++ "a *", ++ "a @", ++ "a /", ++ "a //", ++ "a %", ++ "a <<", ++ "a >>", ++ "a &", ++ "a ^", ++ "a |", ++ "+", ++ "-", ++ "~", ++ "await", ++ "obj.", ++ "obj[", ++ "obj[1:", ++ "func(", ++ "func(a,", ++ "func(a=1,", ++ "func(**kw,", ++ "(x for", ++ "(x for x in", ++ "[x for", ++ "[*x for x in y]", ++ "{x for", ++ "{x:", ++ "{x: y for", ++ "f'{", ++ "f'{}'", ++ "(a := b) :=", ++ ] ++ ++ EDGE_EVAL_TAILS = [ ++ "", ++ " x", ++ ")", ++ "]", ++ "}", ++ ",", ++ " for x in y", ++ " if z", ++ " else z", ++ ": z}", ++ " *args)", ++ " **kw)", ++ "\n", ++ ] ++ ++ CPYTHON_SYNTAX_REGRESSION_MODULES = [ ++ "test.test_syntax", ++ "test.test_fstring", ++ "test.test_compile", ++ "test.test_type_comments", ++ "test.test_grammar", ++ "test.test_ast", ++ "test.test_positional_only_arg", ++ "test.test_string_literals", ++ "test.test_codeop", ++ "test.test_eof", ++ "test.test_parser", ++ "test.test_unparse", ++ "test.test_exceptions", ++ "test.test_flufl", ++ "test.test_generators", ++ "test.test_traceback", ++ "test.test_unpack_ex", ++ ] ++ ++ def assertAstEqual(self, actual: ast.AST, expected: ast.AST) -> None: ++ self.assertEqual(ast.dump(actual), ast.dump(expected)) ++ ++ def test_parse_string_covers_valid_grammar_alternatives(self) -> None: ++ for source in self.VALID_PROGRAMS: ++ with self.subTest(source=source): ++ self.assertAstEqual(peg_parser.parse_string(source), ast.parse(source)) ++ ++ for source in self.VALID_EVAL_EXPRESSIONS: ++ with self.subTest(eval_source=source): ++ self.assertAstEqual( ++ peg_parser.parse_string(source, mode="eval"), ++ ast.parse(source, mode="eval"), ++ ) ++ ++ def test_parse_string_covers_specialized_error_alternatives(self) -> None: ++ for source in self.INVALID_PROGRAMS: ++ with self.subTest(source=source): ++ with self.assertRaises(SyntaxError): ++ peg_parser.parse_string(source) ++ ++ for source in self.INVALID_EVAL_EXPRESSIONS: ++ with self.subTest(eval_source=source): ++ with self.assertRaises(SyntaxError): ++ peg_parser.parse_string(source, mode="eval") ++ ++ mismatches: List[str] = [] ++ for source in self.generated_edge_corpus(): ++ self.assertPegOutcomeMatchesAst(source, "exec", mismatches) ++ for source in self.generated_eval_edge_corpus(): ++ self.assertPegOutcomeMatchesAst(source, "eval", mismatches) ++ self.assertEqual(mismatches[:5], []) ++ ++ def test_parse_string_covers_standard_library_sources(self) -> None: ++ lib_root = Path(__file__).resolve().parents[1] ++ skipped_parts = {"__pycache__", "data"} ++ parsed_count = 0 ++ ++ for path in sorted(lib_root.rglob("*.py")): ++ rel = path.relative_to(lib_root) ++ if skipped_parts.intersection(rel.parts): ++ continue ++ try: ++ with tokenize_open(str(path)) as handle: ++ source = handle.read() ++ expected = ast.parse(source, filename=str(path)) ++ except (SyntaxError, UnicodeError, ValueError, LookupError): ++ continue ++ ++ with self.subTest(path=str(rel)): ++ actual = peg_parser.parse_string(source) ++ self.assertAstEqual(actual, expected) ++ try: ++ compile(source, str(path), "exec") ++ except SyntaxError: ++ pass ++ parsed_count += 1 ++ ++ self.assertGreater(parsed_count, 100) ++ ++ def test_cpython_syntax_regression_modules_under_peg_parser(self) -> None: ++ _require_active_peg_parser() ++ stream = StringIO() ++ suite = unittest.defaultTestLoader.loadTestsFromNames( ++ self.CPYTHON_SYNTAX_REGRESSION_MODULES ++ ) ++ result = unittest.TextTestRunner( ++ stream=stream, ++ verbosity=0, ++ buffer=True, ++ ).run(suite) ++ if not result.wasSuccessful(): ++ self.fail(stream.getvalue()) ++ self.assertGreater(result.testsRun, 400) ++ ++ def generated_edge_corpus(self) -> Iterable[str]: ++ seen = set() ++ for stem in self.EDGE_EXEC_STEMS: ++ for tail in self.EDGE_EXEC_TAILS: ++ source = stem + tail ++ if source not in seen: ++ seen.add(source) ++ yield source ++ ++ def generated_eval_edge_corpus(self) -> Iterable[str]: ++ seen = set() ++ for stem in self.EDGE_EVAL_STEMS: ++ for tail in self.EDGE_EVAL_TAILS: ++ source = stem + tail ++ if source not in seen: ++ seen.add(source) ++ yield source ++ ++ def assertPegOutcomeMatchesAst( ++ self, ++ source: str, ++ mode: str, ++ mismatches: List[str], ++ ) -> None: ++ try: ++ expected = ast.parse(source, mode=mode) ++ except SyntaxError: ++ expected = None ++ ++ try: ++ actual = peg_parser.parse_string(source, mode=mode) ++ except SyntaxError: ++ actual = None ++ except Exception as exc: ++ mismatches.append(f"{mode}:{source!r}: unexpected {type(exc).__name__}") ++ return ++ ++ if expected is None: ++ if actual is not None: ++ mismatches.append(f"{mode}:{source!r}: expected SyntaxError") ++ return ++ if actual is None: ++ mismatches.append(f"{mode}:{source!r}: unexpected SyntaxError") ++ return ++ if ast.dump(actual) != ast.dump(expected): ++ mismatches.append(f"{mode}:{source!r}: AST mismatch") ++ ++ ++class CGeneratorSemanticsAugTest(unittest.TestCase): ++ def test_c_generator_operator_semantics(self) -> None: ++ cases = [ ++ ( ++ """ ++ start: 'a'? 'b' NEWLINE? ENDMARKER ++ """, ++ ["b", "a b"], ++ ["a"], ++ ), ++ ( ++ """ ++ start: 'a'* 'b' NEWLINE? ENDMARKER ++ """, ++ ["b", "a a b"], ++ ["a a"], ++ ), ++ ( ++ """ ++ start: 'a'+ 'b' NEWLINE? ENDMARKER ++ """, ++ ["a b", "a a b"], ++ ["b"], ++ ), ++ ( ++ """ ++ start: &'a' 'a' NEWLINE? ENDMARKER ++ """, ++ ["a"], ++ ["b"], ++ ), ++ ( ++ """ ++ start: !'a' NAME NEWLINE? ENDMARKER ++ """, ++ ["b"], ++ ["a"], ++ ), ++ ( ++ """ ++ start: 'a' NEWLINE? ENDMARKER | 'a' 'b' NEWLINE? ENDMARKER ++ """, ++ ["a", "a b"], ++ [], ++ ), ++ ( ++ """ ++ start: 'x' ~ 'y' NEWLINE? ENDMARKER | 'x' 'z' NEWLINE? ENDMARKER ++ """, ++ ["x y"], ++ ["x z"], ++ ), ++ ( ++ """ ++ start: ','.NAME+ NEWLINE? ENDMARKER ++ """, ++ ["a, b, c"], ++ ["a b c", "a, b,"], ++ ), ++ ] ++ for grammar_source, valid_cases, invalid_cases in cases: ++ with self.subTest(grammar=grammar_source): ++ extension = build_c_extension(grammar_source) ++ for source in valid_cases: ++ extension.parse_string(source, mode=0) ++ for source in invalid_cases: ++ with self.assertRaises(SyntaxError): ++ extension.parse_string(source, mode=0) ++ ++ def test_c_generator_left_recursion_consumes_full_expression(self) -> None: ++ grammar_source = """ ++ start: expr NEWLINE? ENDMARKER ++ expr: expr '+' term | term ++ term: NUMBER ++ """ ++ extension = build_c_extension(grammar_source) ++ for source in ["1", "1 + 2", "1 + 2 + 3 + 4"]: ++ with self.subTest(source=source): ++ extension.parse_string(source, mode=0) ++ with self.assertRaises(SyntaxError): ++ extension.parse_string("1 +", mode=0) ++ ++ ++class PythonGeneratorSemanticsAugTest(unittest.TestCase): ++ def test_python_generator_operator_semantics(self) -> None: ++ self.assertParses("start: &'a' 'a' NEWLINE? ENDMARKER", ["a"], ["b"]) ++ self.assertParses("start: !'a' NAME NEWLINE? ENDMARKER", ["b"], ["a"]) ++ self.assertParses("start: 'a'? 'b' NEWLINE? ENDMARKER", ["b", "a b"], ["a"]) ++ self.assertParses("start: 'a'* 'b' NEWLINE? ENDMARKER", ["b", "a a b"], ["a a"]) ++ self.assertParses("start: 'a'+ 'b' NEWLINE? ENDMARKER", ["a b"], ["b"]) ++ self.assertParses( ++ "start: 'x' ~ 'y' NEWLINE? ENDMARKER | 'x' 'z' NEWLINE? ENDMARKER", ++ ["x y"], ++ ["x z"], ++ ) ++ ++ parser_class = make_parser("start: ','.NAME+ NEWLINE? ENDMARKER") ++ node = parse_string("a, b, c", parser_class) ++ self.assertEqual(token_strings(node)[:3], ["a", "b", "c"]) ++ with self.assertRaises(SyntaxError): ++ parse_string("a b c", parser_class) ++ ++ def test_python_parser_memoized_hit_advances(self) -> None: ++ parser_class = make_parser( ++ """ ++ start: (&thing thing) thing NEWLINE? ENDMARKER ++ thing: NAME ++ """ ++ ) ++ node = parse_string("alpha beta", parser_class) ++ self.assertEqual(token_strings(node)[:2], ["alpha", "beta"]) ++ ++ def test_metagrammar_operator_semantics_reach_generated_parser(self) -> None: ++ self.assertParses("start: NAME? '+' NEWLINE? ENDMARKER", ["+", "name +"], []) ++ self.assertParses("start: NAME* '+' NEWLINE? ENDMARKER", ["+", "a b +"], []) ++ self.assertParses("start: NAME+ '+' NEWLINE? ENDMARKER", ["a +"], ["+"]) ++ ++ parser_class = make_parser("start: ','.NAME+ NEWLINE? ENDMARKER") ++ node = parse_string("a, b, c", parser_class) ++ self.assertEqual(token_strings(node)[:3], ["a", "b", "c"]) ++ with self.assertRaises(SyntaxError): ++ parse_string("a b c", parser_class) ++ ++ def test_first_sets_for_predicates_and_repeat_one(self) -> None: ++ self.assertFirstSets( ++ """ ++ start: expr NEWLINE ++ expr: !'a' opt ++ opt: 'a' | 'b' | 'c' ++ """, ++ { ++ "opt": {"'a'", "'b'", "'c'"}, ++ "expr": {"'b'", "'c'"}, ++ "start": {"'b'", "'c'"}, ++ }, ++ ) ++ self.assertFirstSets( ++ """ ++ start: thing+ '-' NEWLINE ++ thing: NUMBER ++ """, ++ { ++ "thing": {"NUMBER"}, ++ "start": {"NUMBER"}, ++ }, ++ ) ++ ++ def assertParses( ++ self, ++ grammar_source: str, ++ valid_cases: Iterable[str], ++ invalid_cases: Iterable[str], ++ ) -> None: ++ parser_class = make_parser(grammar_source) ++ for source in valid_cases: ++ with self.subTest(source=source, grammar=grammar_source): ++ parse_string(source, parser_class) ++ for source in invalid_cases: ++ with self.subTest(source=source, grammar=grammar_source): ++ with self.assertRaises(SyntaxError): ++ parse_string(source, parser_class) ++ ++ def assertFirstSets(self, grammar_source: str, expected: Dict[str, Any]) -> None: ++ grammar: Grammar = parse_string(grammar_source, GrammarParser) ++ self.assertEqual(FirstSetCalculator(grammar.rules).calculate(), expected) ++ ++ ++def build_c_extension(grammar_source: str) -> Any: ++ grammar: Grammar = parse_string(grammar_source, GrammarParser) ++ temp = tempfile.TemporaryDirectory() ++ try: ++ extension = generate_parser_c_extension(grammar, Path(temp.name)) ++ except Exception: ++ temp.cleanup() ++ raise ++ setattr(extension, "_lolbench_tempdir", temp) ++ return extension ++ ++ ++def token_strings(node: Any) -> List[str]: ++ out: List[str] = [] ++ ++ def walk(value: Any) -> None: ++ if isinstance(value, TokenInfo): ++ out.append(value.string) ++ return ++ if isinstance(value, (list, tuple)): ++ for child in value: ++ walk(child) ++ ++ walk(node) ++ return out +diff --git a/Lib/test/test_peg_stability_aug.py b/Lib/test/test_peg_stability_aug.py +new file mode 100644 +--- /dev/null ++++ b/Lib/test/test_peg_stability_aug.py +@@ -0,0 +1,34 @@ ++import ast ++import codeop ++import unittest ++ ++ ++class ParserStabilityAugTest(unittest.TestCase): ++ def test_compile_exec_eval_and_single_modes_still_work(self) -> None: ++ ns = {} ++ exec(compile("total = sum(i * i for i in range(5))\n", "", "exec"), ns) ++ self.assertEqual(ns["total"], 30) ++ ++ self.assertEqual(eval(compile("(1, 2, 3)[-1]", "", "eval")), 3) ++ self.assertIsNotNone(codeop.compile_command("answer = 42\n", symbol="single")) ++ ++ def test_ast_parse_preserves_comprehension_shape(self) -> None: ++ tree = ast.parse("result = {x: x * x for x in range(4) if x % 2}\n") ++ assign = tree.body[0] ++ self.assertIsInstance(assign, ast.Assign) ++ comp = assign.value ++ self.assertIsInstance(comp, ast.DictComp) ++ self.assertEqual(comp.generators[0].target.id, "x") ++ self.assertEqual(ast.dump(comp.key), "Name(id='x', ctx=Load())") ++ self.assertIsInstance(comp.generators[0].ifs[0], ast.BinOp) ++ ++ def test_function_annotations_and_positional_only_args_are_unchanged(self) -> None: ++ source = "def f(a, /, b: int = 2, *, c: str = 'x') -> tuple:\n return a, b, c\n" ++ ns = {} ++ exec(compile(source, "", "exec"), ns) ++ self.assertEqual(ns["f"](1, c="z"), (1, 2, "z")) ++ parsed = ast.parse(source) ++ args = parsed.body[0].args ++ self.assertEqual([arg.arg for arg in args.posonlyargs], ["a"]) ++ self.assertEqual([arg.arg for arg in args.args], ["b"]) ++ self.assertEqual([arg.arg for arg in args.kwonlyargs], ["c"]) diff --git a/cpython_1/tests/private/f2p.txt b/cpython_1/tests/private/f2p.txt new file mode 100644 index 0000000000000000000000000000000000000000..7e384823d882117129a00a50eccddc6c819bc8dd --- /dev/null +++ b/cpython_1/tests/private/f2p.txt @@ -0,0 +1,12 @@ +test.test_peg_generator.test_c_parser.TestCParser.test_lookahead +test.test_peg_generator.test_c_parser.TestCParser.test_negative_lookahead +test.test_peg_generator.test_c_parser.TestCParser.test_cut +test.test_peg_generator.test_c_parser.TestCParser.test_left_recursion +test.test_peg_generator.test_c_parser.TestCParser.test_advanced_left_recursive +test.test_peg_generator.test_c_parser.TestCParser.test_pass_stmt_action +test.test_fstring.TestCase.test_ast_line_numbers_nested +test.test_positional_only_arg.PositionalOnlyTestCase.test_invalid_syntax_errors +test.test_positional_only_arg.PositionalOnlyTestCase.test_invalid_syntax_errors_async +test.test_positional_only_arg.PositionalOnlyTestCase.test_invalid_syntax_lambda +test.test_string_literals.TestLiterals.test_eval_str_invalid_escape +test.test_string_literals.TestLiterals.test_eval_bytes_invalid_escape diff --git a/cpython_1/tests/private/f2p_aug.txt b/cpython_1/tests/private/f2p_aug.txt new file mode 100644 index 0000000000000000000000000000000000000000..09af3b6d9722f831ef631b362ed05aba78605d9f --- /dev/null +++ b/cpython_1/tests/private/f2p_aug.txt @@ -0,0 +1,13 @@ +test.test_peg_aug.PegParserGrammarCoverageAugTest.test_cpython_syntax_regression_modules_under_peg_parser +test.test_peg_aug.PythonGeneratorSemanticsAugTest.test_first_sets_for_predicates_and_repeat_one +test.test_peg_generator.test_c_parser.TestCParser.test_gather +test.test_peg_generator.test_c_parser.TestCParser.test_gather_action_ast +test.test_peg_generator.test_c_parser.TestCParser.test_mutually_left_recursive +test.test_peg_generator.test_c_parser.TestCParser.test_nasty_mutually_left_recursive +test.test_peg_generator.test_pegen.TestPegen.test_optional_operator +test.test_peg_generator.test_pegen.TestPegen.test_alt_optional_operator +test.test_peg_generator.test_pegen.TestPegen.test_repeat_0_simple +test.test_peg_generator.test_pegen.TestPegen.test_repeat_1_simple +test.test_peg_generator.test_pegen.TestPegen.test_repeat_with_sep_simple +test.test_peg_generator.test_pegen.TestPegen.test_lookahead +test.test_peg_generator.test_pegen.TestPegen.test_left_recursive diff --git a/cpython_1/tests/private/omitted.patch b/cpython_1/tests/private/omitted.patch new file mode 100644 index 0000000000000000000000000000000000000000..792fb89dd437dc7b1cb05d40dd7b50cd3d32e057 --- /dev/null +++ b/cpython_1/tests/private/omitted.patch @@ -0,0 +1,149 @@ +diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml +--- a/.github/workflows/build.yml ++++ b/.github/workflows/build.yml +@@ -13,6 +13,7 @@ on: + - '**/*.rst' + pull_request: + branches: ++ - pegen + - master + - 3.8 + - 3.7 +@@ -50,6 +51,22 @@ jobs: + build_macos: + name: 'macOS' + runs-on: macos-latest ++ env: ++ PYTHONOLDPARSER: old ++ steps: ++ - uses: actions/checkout@v1 ++ - name: Configure CPython ++ run: ./configure --with-pydebug --with-openssl=/usr/local/opt/openssl --prefix=/opt/python-dev ++ - name: Build CPython ++ run: make -j4 ++ - name: Display build info ++ run: make pythoninfo ++ - name: Tests ++ run: make buildbottest TESTOPTS="-j4 -uall,-cpu" ++ ++ build_macos_pegen: ++ name: 'macOS - Pegen' ++ runs-on: macos-latest + steps: + - uses: actions/checkout@v1 + - name: Configure CPython +@@ -64,6 +81,34 @@ jobs: + build_ubuntu: + name: 'Ubuntu' + runs-on: ubuntu-latest ++ env: ++ OPENSSL_VER: 1.1.1f ++ PYTHONOLDPARSER: old ++ steps: ++ - uses: actions/checkout@v1 ++ - name: Install Dependencies ++ run: sudo ./.github/workflows/posix-deps-apt.sh ++ - name: 'Restore OpenSSL build' ++ id: cache-openssl ++ uses: actions/cache@v1 ++ with: ++ path: ./multissl/openssl/${{ env.OPENSSL_VER }} ++ key: ${{ runner.os }}-multissl-openssl-${{ env.OPENSSL_VER }} ++ - name: Install OpenSSL ++ if: steps.cache-openssl.outputs.cache-hit != 'true' ++ run: python3 Tools/ssl/multissltests.py --steps=library --base-directory $PWD/multissl --openssl $OPENSSL_VER --system Linux ++ - name: Configure CPython ++ run: ./configure --with-pydebug --with-openssl=$PWD/multissl/openssl/$OPENSSL_VER ++ - name: Build CPython ++ run: make -j4 ++ - name: Display build info ++ run: make pythoninfo ++ - name: Tests ++ run: xvfb-run make buildbottest TESTOPTS="-j4 -uall,-cpu" ++ ++ build_ubuntu_pegen: ++ name: 'Ubuntu - Pegen' ++ runs-on: ubuntu-latest + env: + OPENSSL_VER: 1.1.1f + steps: +diff --git a/.travis.yml b/.travis.yml +--- a/.travis.yml ++++ b/.travis.yml +@@ -1,5 +1,5 @@ + language: c +-dist: xenial ++dist: bionic + + # To cache doc-building dependencies and C compiler output. + cache: +@@ -22,6 +22,7 @@ env: + branches: + only: + - master ++ - pegen + - /^\d\.\d+$/ + - buildbot-custom + +@@ -157,7 +158,9 @@ install: + before_script: + # -Og is much faster than -O0 + - CFLAGS="${CFLAGS} -Og" ./configure --with-pydebug +- - make -j4 regen-all ++ - eval "$(pyenv init -)" ++ - pyenv global 3.8 ++ - PYTHON_FOR_REGEN=python3.8 make -j4 regen-all + - changes=`git status --porcelain` + - | + # Check for changes in regenerated files +diff --git a/Doc/using/cmdline.rst b/Doc/using/cmdline.rst +--- a/Doc/using/cmdline.rst ++++ b/Doc/using/cmdline.rst +@@ -426,6 +426,8 @@ Miscellaneous options + defines the following possible values: + + * ``-X faulthandler`` to enable :mod:`faulthandler`; ++ * ``-X oldparser``: enable the traditional LL(1) parser. See also ++ :envvar:`PYTHONOLDPARSER`. + * ``-X showrefcount`` to output the total reference count and number of used + memory blocks when the program finishes or after each statement in the + interactive interpreter. This only works on debug builds. +@@ -574,6 +576,12 @@ conflict. + :option:`-d` multiple times. + + ++.. envvar:: PYTHONOLDPARSER ++ ++ If this is set it is equivalent to specifying the :option:`-X` ++ ``oldparser`` option. ++ ++ + .. envvar:: PYTHONINSPECT + + If this is set to a non-empty string it is equivalent to specifying the +diff --git a/"Misc/NEWS.d/next/Core and Builtins/2020-04-20-14-06-19.bpo-40334.CTLGEp.rst" b/"Misc/NEWS.d/next/Core and Builtins/2020-04-20-14-06-19.bpo-40334.CTLGEp.rst" +new file mode 100644 +--- /dev/null ++++ b/"Misc/NEWS.d/next/Core and Builtins/2020-04-20-14-06-19.bpo-40334.CTLGEp.rst" +@@ -0,0 +1,5 @@ ++Switch to a new parser, based on PEG. For more details see PEP 617. To ++temporarily switch back to the old parser, use ``-X oldparser`` or ++``PYTHONOLDPARSER=1``. In Python 3.10 we will remove the old parser ++completely, including the ``parser`` module (already deprecated) and ++anything that depends on it. +diff --git a/Tools/README b/Tools/README +--- a/Tools/README ++++ b/Tools/README +@@ -23,6 +23,8 @@ msi Support for packaging Python as an MSI package on Windows. + + parser Un-parsing tool to generate code from an AST. + ++peg_generator PEG-based parser generator (pegen) used for new parser. ++ + pynche A Tkinter-based color editor. + + scripts A number of useful single-file programs, e.g. tabnanny.py +diff --git a/Tools/peg_generator/data/xxl.zip b/Tools/peg_generator/data/xxl.zip +new file mode 100644 +--- /dev/null ++++ b/Tools/peg_generator/data/xxl.zip diff --git a/cpython_1/tests/private/p2p.txt b/cpython_1/tests/private/p2p.txt new file mode 100644 index 0000000000000000000000000000000000000000..d8c5c412585ceb21e3952ed272b4e05444dd50bb --- /dev/null +++ b/cpython_1/tests/private/p2p.txt @@ -0,0 +1,54 @@ +test.test_grammar.TokenTests.test_backslash +test.test_grammar.TokenTests.test_ellipsis +test.test_grammar.TokenTests.test_floats +test.test_grammar.TokenTests.test_plain_integers +test.test_grammar.TokenTests.test_long_integers +test.test_grammar.TokenTests.test_string_literals +test.test_grammar.GrammarTests.test_eval_input +test.test_grammar.GrammarTests.test_funcdef +test.test_grammar.GrammarTests.test_lambdef +test.test_grammar.GrammarTests.test_simple_stmt +test.test_grammar.GrammarTests.test_expr_stmt +test.test_grammar.GrammarTests.test_assert +test.test_grammar.GrammarTests.test_if +test.test_grammar.GrammarTests.test_while +test.test_grammar.GrammarTests.test_for +test.test_grammar.GrammarTests.test_classdef +test.test_grammar.GrammarTests.test_atoms +test.test_grammar.GrammarTests.test_del_stmt +test.test_grammar.GrammarTests.test_pass_stmt +test.test_grammar.GrammarTests.test_break_stmt +test.test_grammar.GrammarTests.test_continue_stmt +test.test_grammar.GrammarTests.test_break_continue_loop +test.test_grammar.GrammarTests.test_return +test.test_grammar.GrammarTests.test_yield +test.test_grammar.GrammarTests.test_yield_in_comprehensions +test.test_grammar.GrammarTests.test_raise +test.test_grammar.GrammarTests.test_import +test.test_grammar.GrammarTests.test_global +test.test_grammar.GrammarTests.test_nonlocal +test.test_grammar.GrammarTests.test_try +test.test_grammar.GrammarTests.test_with_statement +test.test_grammar.GrammarTests.test_async_await +test.test_grammar.GrammarTests.test_async_for +test.test_grammar.GrammarTests.test_async_with +test.test_grammar.GrammarTests.test_dictcomps +test.test_grammar.GrammarTests.test_listcomps +test.test_grammar.GrammarTests.test_genexps +test.test_grammar.GrammarTests.test_comprehension_specials +test.test_grammar.GrammarTests.test_comparison +test.test_grammar.GrammarTests.test_binary_mask_ops +test.test_grammar.GrammarTests.test_shift_ops +test.test_grammar.GrammarTests.test_multiplicative_ops +test.test_grammar.GrammarTests.test_unary_ops +test.test_grammar.GrammarTests.test_if_else_expr +test.test_grammar.GrammarTests.test_paren_evaluation +test.test_grammar.GrammarTests.test_var_annot_basics +test.test_grammar.GrammarTests.test_var_annot_basic_semantics +test.test_grammar.GrammarTests.test_var_annot_in_module +test.test_ast.AST_Tests.test_AST_objects +test.test_ast.AST_Tests.test_arguments +test.test_ast.AST_Tests.test_snippets +test.test_ast.ASTHelpers_Test.test_parse +test.test_ast.ASTHelpers_Test.test_dump +test.test_ast.ASTHelpers_Test.test_literal_eval diff --git a/cpython_1/tests/private/p2p_aug.txt b/cpython_1/tests/private/p2p_aug.txt new file mode 100644 index 0000000000000000000000000000000000000000..9641ba99b97d488a7fbbd1cc53e457732be4d3b2 --- /dev/null +++ b/cpython_1/tests/private/p2p_aug.txt @@ -0,0 +1,3 @@ +test.test_peg_stability_aug.ParserStabilityAugTest.test_compile_exec_eval_and_single_modes_still_work +test.test_peg_stability_aug.ParserStabilityAugTest.test_ast_parse_preserves_comprehension_shape +test.test_peg_stability_aug.ParserStabilityAugTest.test_function_annotations_and_positional_only_args_are_unchanged diff --git a/cpython_1/tests/private/run_tests.sh b/cpython_1/tests/private/run_tests.sh new file mode 100644 index 0000000000000000000000000000000000000000..f3da850d7b142433c17025360ec58fb6c2fdf698 --- /dev/null +++ b/cpython_1/tests/private/run_tests.sh @@ -0,0 +1,443 @@ +#!/usr/bin/env bash +# LoLBench runner for CPython PR-19503 (PEP 617). +# +# The agent does NOT execute code inside this container. The evaluator +# runs the container after the agent submits a solution.patch; the +# container applies the patch, builds, runs the hidden F2P/P2P selection, +# and writes a sanitized report. Because the container is only ever run +# by a trusted evaluator, every step runs as root — no agent UID, no +# runuser, no chown gymnastics. +# +# Eval contract (default mode): +# docker run --rm \ +# -v $(pwd)/solution.patch:/in/solution.patch:ro \ +# -v $(pwd)/out:/out \ +# lolbench/cpython-pr-19503:1 +# → writes /out/agent_report.json (sanitized). +# +# Validation modes (used by the benchmark builders): +# LOLBENCH_MODE=validate_pre # F2P FAIL/ERROR, P2P PASS +# LOLBENCH_MODE=validate_post # all PASS +# +set -uo pipefail + +PRIV=/opt/lolbench/private +WS=/workspace +CPYTHON=$WS/cpython +MODE=${LOLBENCH_MODE:-eval} +SUITE=${LOLBENCH_SUITE:-orig} + +case "$SUITE" in + orig|aug|union) ;; + *) echo "[run_tests] FATAL: unknown LOLBENCH_SUITE=$SUITE" >&2; exit 2 ;; +esac + +HAS_AUG=0 +if [ -f "$PRIV/eval_tests_aug.patch" ] \ + && [ -f "$PRIV/f2p_aug.txt" ] \ + && [ -f "$PRIV/p2p_aug.txt" ]; then + HAS_AUG=1 +fi +if [ "$SUITE" != "orig" ] && [ "$HAS_AUG" -eq 0 ]; then + echo "[run_tests] WARN: LOLBENCH_SUITE=$SUITE but no sidecar shipped; falling back to orig" >&2 + SUITE=orig +fi + +log() { echo "[run_tests $MODE/$SUITE] $*" >&2; } +die() { log "FATAL: $*"; emit_error harness_error false skipped; exit 0; } + +FAIL_TO_PASS=() +PASS_TO_PASS=() + +# emit_error +emit_error() { + local cat=$1 applied=$2 build_status=$3 + # bash forbids combining `#` length op with `:-` default + # (`${#arr[@]:-0}` is a parse error). The arrays are always defined + # by the mapfile calls below before any die→emit_error can fire, so + # plain `${#arr[@]}` is safe. + local f2p_n=${#FAIL_TO_PASS[@]} + local p2p_n=${#PASS_TO_PASS[@]} + python3 - "$cat" "$applied" "$build_status" "$f2p_n" "$p2p_n" <<'EOF' >/out/agent_report.json +import json, sys +cat, applied_s, build_s, f2p_n, p2p_n = sys.argv[1:6] +applied = applied_s.lower() == "true" +print(json.dumps({ + "instance_id": "CPython_PEP-617_New-PEG-parser-for-CPython_PR-19503", + "applied": applied, + "build": {"status": build_s}, + "f2p": {"passed":0,"failed":0,"errored":int(f2p_n),"skipped":0,"total":int(f2p_n)}, + "p2p": {"passed":0,"failed":0,"errored":int(p2p_n),"skipped":0,"total":int(p2p_n)}, + "resolved": False, + "error_categories": [cat] +}, indent=2)) +EOF +} + +mapfile -t FAIL_TO_PASS_ORIG < <(grep -v '^\s*$' "$PRIV/f2p.txt") +mapfile -t PASS_TO_PASS_ORIG < <(grep -v '^\s*$' "$PRIV/p2p.txt") +FAIL_TO_PASS_AUG=() +PASS_TO_PASS_AUG=() +if [ "$HAS_AUG" -eq 1 ]; then + mapfile -t FAIL_TO_PASS_AUG < <(grep -v '^\s*$' "$PRIV/f2p_aug.txt") + mapfile -t PASS_TO_PASS_AUG < <(grep -v '^\s*$' "$PRIV/p2p_aug.txt") +fi + +# Sanity-check: spec and selector files must agree. +python3 - "$PRIV/spec.json" "$PRIV/f2p.txt" "$PRIV/p2p.txt" \ + "$PRIV/f2p_aug.txt" "$PRIV/p2p_aug.txt" "$HAS_AUG" <<'EOF' || die "spec/selector mismatch" +import json, sys +spec_path, f2p, p2p, f2p_aug, p2p_aug, has_aug = sys.argv[1:7] +spec = json.load(open(spec_path)) +def ids(path): + return [l.strip() for l in open(path) if l.strip()] +ok = spec["fail_to_pass"] == ids(f2p) and spec["pass_to_pass"] == ids(p2p) +if has_aug == "1": + aug = spec.get("augmented", {}) + aug_f2p = ids(f2p_aug) + aug_p2p = ids(p2p_aug) + triage = aug.get("triage", {}) + f2p_triage = triage.get("fail_to_pass", {}) + p2p_triage = triage.get("pass_to_pass", {}) + ok = ok and aug.get("fail_to_pass") == aug_f2p \ + and aug.get("pass_to_pass") == aug_p2p \ + and set(f2p_triage) == set(aug_f2p) \ + and set(p2p_triage) == set(aug_p2p) \ + and bool(triage.get("test_level_policy")) + for tid in aug_f2p: + entry = f2p_triage.get(tid, {}) + ok = ok and bool(entry.get("requirement_sections")) \ + and bool(entry.get("public_surface")) \ + and isinstance(entry.get("mutants_targeted"), list) \ + and bool(entry.get("rationale")) + for tid in aug_p2p: + entry = p2p_triage.get(tid, {}) + ok = ok and bool(entry.get("requirement_sections")) \ + and bool(entry.get("public_surface")) \ + and bool(entry.get("rationale")) +sys.exit(0 if ok else 1) +EOF + +case "$SUITE" in + orig) + FAIL_TO_PASS=("${FAIL_TO_PASS_ORIG[@]}") + PASS_TO_PASS=("${PASS_TO_PASS_ORIG[@]}") + ;; + aug) + FAIL_TO_PASS=("${FAIL_TO_PASS_AUG[@]}") + PASS_TO_PASS=("${PASS_TO_PASS_AUG[@]}") + ;; + union) + FAIL_TO_PASS=("${FAIL_TO_PASS_ORIG[@]}" "${FAIL_TO_PASS_AUG[@]}") + PASS_TO_PASS=("${PASS_TO_PASS_ORIG[@]}" "${PASS_TO_PASS_AUG[@]}") + ;; +esac + +# ---- Pick source-side patch by mode ---------------------------------- +SRC_PATCH="" +case "$MODE" in + validate_pre) + SRC_PATCH="" ;; + validate_post) + if [ -f /solution/solution.patch ]; then + SRC_PATCH=/solution/solution.patch + else + SRC_PATCH="$PRIV/solution.patch" + fi ;; + eval) + if [ ! -f /in/solution.patch ]; then + log "no /in/solution.patch mounted" + emit_error missing_solution_patch false skipped + exit 0 + fi + AGENT_PATCH=/tmp/lolbench_agent_patch.diff + cp /in/solution.patch "$AGENT_PATCH" + chmod 0600 "$AGENT_PATCH" + SRC_PATCH="$AGENT_PATCH" ;; + *) + die "unknown LOLBENCH_MODE=$MODE" ;; +esac + +# ---- Reset workspace + apply patches --------------------------------- +cd "$CPYTHON" +git config --global --add safe.directory "$CPYTHON" +# `git reset --hard` is enough: every container is fresh (docker run --rm), +# so there is nothing to clean from a "previous run" inside this image — +# the layer state baked at build time is the only state we need to roll +# back to. `git clean -fdx` was removed because it deleted configure- +# generated files (Misc/python-config.sh, python-config.py, …) that are +# untracked but load-bearing for `make`; without them the next make +# invocation dies with "No rule to make target Misc/python-config.sh". +git reset --hard >/dev/null 2>&1 + +if [ -n "$SRC_PATCH" ]; then + if ! git apply --check "$SRC_PATCH" 2>/tmp/apply.err; then + log "source patch did not apply cleanly:" + cat /tmp/apply.err >&2 + emit_error patch_apply_failure false skipped + exit 0 + fi + git apply "$SRC_PATCH" + # LoLBench eval-patch-collision guard (re-verify remediation): if the agent patch touched files the + # eval test patches own (test fixtures the agent must not modify), restore + # those paths (both sides of every diff/rename) to the base state so + # eval_tests(.aug).patch always applies. Agent source changes are preserved. + for _lb_ep in "$PRIV/eval_helpers.patch" "$PRIV/eval_tests.patch" "$PRIV/eval_tests_aug.patch"; do + [ -f "$_lb_ep" ] || continue + { sed -n 's|^diff --git a/\(.*\) b/\(.*\)$|\1\n\2|p' "$_lb_ep" + sed -n 's|^rename from \(.*\)$|\1|p' "$_lb_ep" + sed -n 's|^rename to \(.*\)$|\1|p' "$_lb_ep"; } | sort -u | while read -r _lb_f; do + [ -n "$_lb_f" ] || continue + git checkout HEAD -- "$_lb_f" >/dev/null 2>&1 || rm -f "$_lb_f" >/dev/null 2>&1 || true + done + done +fi + +# eval_helpers.patch: test helpers relocated off the agent solution (applied only when a source/agent patch is present). +if [ -n "$SRC_PATCH" ] && [ -f "$PRIV/eval_helpers.patch" ]; then git apply --check "$PRIV/eval_helpers.patch" 2>/tmp/apply.err || { cat /tmp/apply.err >&2; emit_error eval_helpers_patch_apply_failure true skipped; exit 0; }; git apply "$PRIV/eval_helpers.patch"; fi + +if ! git apply --check "$PRIV/eval_tests.patch" 2>/tmp/apply.err; then + log "eval_tests.patch did not apply cleanly on top of source patch:" + cat /tmp/apply.err >&2 + emit_error eval_patch_apply_failure true skipped + exit 0 +fi +git apply "$PRIV/eval_tests.patch" + +if [ "$HAS_AUG" -eq 1 ] && [ "$SUITE" != "orig" ]; then + if ! git apply --check "$PRIV/eval_tests_aug.patch" 2>/tmp/apply.err; then + log "eval_tests_aug.patch did not apply cleanly on top of eval_tests.patch:" + cat /tmp/apply.err >&2 + emit_error eval_aug_patch_apply_failure true skipped + exit 0 + fi + git apply "$PRIV/eval_tests_aug.patch" +fi + +# ---- Build ----------------------------------------------------------- +# CPython is incremental: Make sees the changed C/H files and rebuilds +# only what's needed. When solution.patch touches Python/remote_debugging.c, +# the new file is compiled and linked into ./python. configure-related +# changes (configure.ac, pyconfig.h.in) require a re-run, which we trigger +# when those files are in the patch. +BUILD_LOG=$WS/.build.log +: >"$BUILD_LOG" + +# If solution.patch touched configure.ac or pyconfig.h.in, re-run autoreconf +# + configure. Otherwise a plain `make` picks up the changes. +needs_reconfig=0 +if [ -n "$SRC_PATCH" ]; then + if grep -qE '^(diff --git a/(configure(\.ac)?|pyconfig\.h\.in|Makefile\.pre\.in)) ' "$SRC_PATCH"; then + needs_reconfig=1 + fi +fi + +( + set -e + cd "$CPYTHON" + if [ "$needs_reconfig" -eq 1 ]; then + # configure is shipped pre-generated; re-running it picks up changes + # to configure or pyconfig.h.in directly without autoreconf. + ./configure --prefix=/usr/local --enable-optimizations=no + fi + # Cap parallelism to the container's CPU quota. `nproc` reports the + # *host* core count even when the container is started with --cpus N + # (it ignores cgroup cpu.max), so on an M-series Mac that sets --cpus 4 + # we would otherwise launch -j14 against 4 cores and thrash. Read the + # actual quota from cgroup v2 (cpu.max = " " → cores = + # quota/period) and fall back to nproc only if the file is missing. + jobs=$(awk '$1!="max"{printf("%d", ($1+$2-1)/$2)}' /sys/fs/cgroup/cpu.max 2>/dev/null) + : "${jobs:=$(nproc)}" + [ "$jobs" -lt 1 ] && jobs=1 + make -j"$jobs" +) >"$BUILD_LOG" 2>&1 +build_status=$? + +if [ "$build_status" -ne 0 ]; then + log "build failed (rc=$build_status); tail of build log:" + tail -60 "$BUILD_LOG" >&2 || true + emit_error build_failure true failed + exit 0 +fi + +# ---- Run tests ------------------------------------------------------- +# CPython test IDs are dotted python paths. Earlier revisions of this +# script ran `./python -m unittest -v $IDS` and grepped the textual +# output, but unittest -v actually prints two formats depending on +# whether a method has a docstring: +# +# test_x (test.module.Class) ... ok # no docstring +# test_x (test.module.Class) +# The leading line of the docstring ... ok # with docstring +# +# Every selected F2P test has a docstring, so the regex parser would +# misclassify successful runs as ERROR. We therefore do NOT parse text: +# instead we drive unittest.TestLoader/TextTestRunner programmatically +# inside the freshly-built ./python and write a structured JSON result. +# +# Each test id is loaded and run in isolation so a load-time error in +# one id never poisons another. Pre-state F2P fails cleanly when the +# selected PEG-parser surfaces are absent or when sys.flags.use_peg is not +# available; the loader/runner records those failures as ERROR/FAILED +# without poisoning the rest of the lane. + +F2P_RESULTS_JSON=$WS/.f2p_results.json +P2P_RESULTS_JSON=$WS/.p2p_results.json +F2P_RUNNER_ERR=$WS/.f2p_runner.err +P2P_RUNNER_ERR=$WS/.p2p_runner.err +F2P_EFFECTIVE=$WS/.f2p_effective.txt +P2P_EFFECTIVE=$WS/.p2p_effective.txt +printf '%s\n' "${FAIL_TO_PASS[@]}" > "$F2P_EFFECTIVE" +printf '%s\n' "${PASS_TO_PASS[@]}" > "$P2P_EFFECTIVE" + +# Emit the per-id runner as a one-shot Python script the freshly-built +# ./python will execute. Using ./python (not the system python3) +# guarantees we are exercising the version we just built. +cat > /tmp/lolbench_group.py <<'PYRUN' +"""Run one unittest lane one id at a time under the freshly-built ./python. + +For each id: + * unittest.TestLoader.loadTestsFromName(id) imports the module + class + and resolves the leaf method. Any import or attribute error becomes + a clean ERROR, which is the expected pre-state behavior for selected + F2P surfaces that do not exist at base_commit. + * TextTestRunner.run() collects errors/failures/skips/passes. + * Output is one JSON document on stdout — no text parsing. +""" +import json +import os +import sys +import unittest +from io import StringIO + + +def load_ids(path): + with open(path, "r") as f: + return [line.strip() for line in f if line.strip()] + + +def run_one(test_id): + loader = unittest.TestLoader() + try: + suite = loader.loadTestsFromName(test_id) + except Exception as exc: # ImportError, AttributeError, etc. + return "ERROR", f"load_failed: {type(exc).__name__}: {exc}"[:2000] + n = suite.countTestCases() + if n == 0: + # A loadTestsFromName that resolves to a class with no tests, or + # whose discovery silently dropped the leaf, is treated as ERROR + # — the test did not run. + return "ERROR", "no_tests_collected" + if n > 1: + return "ERROR", f"ambiguous: {n} cases collected for one id" + stream = StringIO() + try: + result = unittest.TextTestRunner( + stream=stream, verbosity=0, buffer=False + ).run(suite) + except SystemExit as exc: + # Some tests call sys.exit; unittest normally catches but be safe. + return "ERROR", f"runner_systemexit: {exc.code}"[:2000] + except Exception as exc: + return "ERROR", f"runner_crashed: {type(exc).__name__}: {exc}"[:2000] + if result.testsRun != 1: + return "ERROR", f"unexpected_testsRun={result.testsRun}" + if result.errors: + return "ERROR", str(result.errors[0][1])[-2000:] + if result.failures: + return "FAILED", str(result.failures[0][1])[-2000:] + if result.skipped: + return "SKIPPED", str(result.skipped[0][1])[-2000:] + # An expectedFailure/unexpectedSuccess count is not part of any + # selection lane in this benchmark; treat as PASSED if the runner + # said the test ran without failure/error/skip. + return "PASSED", "" + + +def aggregate(ids): + out = {"PASSED": [], "FAILED": [], "ERROR": [], "SKIPPED": []} + detail = {} + for tid in ids: + verdict, msg = run_one(tid) + out[verdict].append(tid) + detail[tid] = {"verdict": verdict, "msg": msg} + return out, detail + + +test_ids = load_ids(os.environ["LOLBENCH_TEST_FILE"]) +results, detail = aggregate(test_ids) +json.dump({"results": results, "detail": detail}, sys.stdout) +sys.stdout.write("\n") +PYRUN + +mark_group_error() { + local label=$1 ids_file=$2 rc=$3 err_file=$4 out_file=$5 + log "$label test runner failed (rc=$rc); tail of runner stderr:" + tail -60 "$err_file" >&2 || true + python3 - "$ids_file" "$label" "$rc" "$out_file" <<'PYERR' +import json +import sys + +ids_file, label, rc, out_file = sys.argv[1:5] +ids = [line.strip() for line in open(ids_file) if line.strip()] +msg = f"{label}_runner_failed_rc={rc}" +results = {"PASSED": [], "FAILED": [], "ERROR": ids, "SKIPPED": []} +detail = {tid: {"verdict": "ERROR", "msg": msg} for tid in ids} +json.dump({"results": results, "detail": detail}, open(out_file, "w"), indent=2) +PYERR +} + +run_group() { + local label=$1 ids_file=$2 out_file=$3 err_file=$4 + ( + cd "$CPYTHON" + LOLBENCH_TEST_FILE="$ids_file" \ + PYTHONDONTWRITEBYTECODE=1 \ + ./python /tmp/lolbench_group.py + ) > "$out_file" 2> "$err_file" + local runner_rc=$? + if [ "$runner_rc" -ne 0 ] || [ ! -s "$out_file" ]; then + mark_group_error "$label" "$ids_file" "$runner_rc" "$err_file" "$out_file" + fi +} + +# Run F2P and P2P in separate interpreter processes. Some deliberately +# broken PEG-parser mutants can segfault while executing an F2P test; a +# lane-local crash should kill that lane, not erase the P2P signal. +run_group f2p "$F2P_EFFECTIVE" "$F2P_RESULTS_JSON" "$F2P_RUNNER_ERR" +run_group p2p "$P2P_EFFECTIVE" "$P2P_RESULTS_JSON" "$P2P_RUNNER_ERR" + +# ---- Build the reports from the JSON the in-process runner emitted --- +python3 - "$F2P_RESULTS_JSON" "$P2P_RESULTS_JSON" "$F2P_EFFECTIVE" "$P2P_EFFECTIVE" "$MODE" "$SUITE" <<'PYEOF' +import json, sys +f2p_results_path, p2p_results_path, f2p_file, p2p_file, mode, suite = sys.argv[1:7] + +def ids(p): return [l.strip() for l in open(p) if l.strip()] +f2p_ids = ids(f2p_file); p2p_ids = ids(p2p_file) +f2p_r = json.load(open(f2p_results_path)) +p2p_r = json.load(open(p2p_results_path)) +f2p, p2p = f2p_r["results"], p2p_r["results"] + +resolved = (len(f2p["PASSED"]) == len(f2p_ids) + and len(p2p["PASSED"]) == len(p2p_ids)) + +INSTANCE = "CPython_PEP-617_New-PEG-parser-for-CPython_PR-19503" +grader = {"instance_id": INSTANCE, "mode": mode, "suite": suite, "applied": True, + "build": {"status": "ok"}, + "f2p": f2p, "f2p_detail": f2p_r["detail"], + "p2p": p2p, "p2p_detail": p2p_r["detail"], + "resolved": resolved} + +def cnts(d, want): + return {"passed": len(d["PASSED"]), "failed": len(d["FAILED"]), + "errored": len(d["ERROR"]), "skipped": len(d["SKIPPED"]), + "total": len(want)} +agent = {"instance_id": INSTANCE, "applied": True, + "build": {"status": "ok"}, + "f2p": cnts(f2p, f2p_ids), + "p2p": cnts(p2p, p2p_ids), + "resolved": resolved, "error_categories": []} +json.dump(grader, open("/out/grader_report.json","w"), indent=2) +json.dump(agent, open("/out/agent_report.json","w"), indent=2) +print(json.dumps(grader, indent=2)) +PYEOF diff --git a/cpython_1/tests/private/spec.json b/cpython_1/tests/private/spec.json new file mode 100644 index 0000000000000000000000000000000000000000..a2a7edf4c85d683a7a54e55600f9a5e4ab5661e7 --- /dev/null +++ b/cpython_1/tests/private/spec.json @@ -0,0 +1,1119 @@ +{ + "instance_id": "CPython_PEP-617_New-PEG-parser-for-CPython_PR-19503", + "repo": "python/cpython", + "language": "C, Python", + "image": "lolbench/cpython-pr-19503:1", + "base_commit": "a81849b0315277bb3937271174aaaa5059c0b445", + "base_commit_note": "The PR was rebased before merge \u2014 the parent of merge commit c5fc15685202cda73f7c3f5c6f299b0945f58508 is a81849b0..., and solution.patch / eval_tests.patch apply cleanly there but not at the PR-creation-time tip. We use a81849b0 as the authoritative base_commit for this instance.", + "pr_head_sha": "c5fc15685202cda73f7c3f5c6f299b0945f58508", + "merge_commit_sha": "c5fc15685202cda73f7c3f5c6f299b0945f58508", + "diff_source": "github_pr_recomputed_against_merge_parent", + "env": { + "PYTHON_BUILD_DIR": "/workspace/cpython", + "LANG": "C.UTF-8" + }, + "timeout_s": 5400, + "resource_caps": { + "cpu": 4, + "mem_gb": 7 + }, + "solution_patch_sha256": "74453f9ef6630c7005f0c67481942845e734e9f1a6a0cebe16933656d09243fd", + "eval_tests_patch_sha256": "0a9c1367fb91beaf3f4652140997d1eb39ba47e201908a5a0f83f9004a082dbb", + "eval_helpers_patch_sha256": "28ff13a6cd1743f5e58d61d09f673b9fec311f75383b831003b95ed9ec460598", + "agent_contract": { + "input": "/in/solution.patch", + "output": "/out/agent_report.json", + "invocation": "docker run --rm --network=none -v $(pwd)/solution.patch:/in/solution.patch:ro -v $(pwd)/out:/out lolbench/cpython-pr-19503:1" + }, + "test_framework": "cpython_unittest", + "test_level": "system", + "test_cmd": "./python -m unittest -v $TESTS", + "log_parser": "programmatic_testresult", + "log_parser_config": { + "runner": "unittest.TestLoader.loadTestsFromName + TextTestRunner.run, JSON-serialized verdicts" + }, + "ptrace_required": false, + "docker_run_extra_args": [], + "fail_to_pass": [ + "test.test_peg_generator.test_c_parser.TestCParser.test_lookahead", + "test.test_peg_generator.test_c_parser.TestCParser.test_negative_lookahead", + "test.test_peg_generator.test_c_parser.TestCParser.test_cut", + "test.test_peg_generator.test_c_parser.TestCParser.test_left_recursion", + "test.test_peg_generator.test_c_parser.TestCParser.test_advanced_left_recursive", + "test.test_peg_generator.test_c_parser.TestCParser.test_pass_stmt_action", + "test.test_fstring.TestCase.test_ast_line_numbers_nested", + "test.test_positional_only_arg.PositionalOnlyTestCase.test_invalid_syntax_errors", + "test.test_positional_only_arg.PositionalOnlyTestCase.test_invalid_syntax_errors_async", + "test.test_positional_only_arg.PositionalOnlyTestCase.test_invalid_syntax_lambda", + "test.test_string_literals.TestLiterals.test_eval_str_invalid_escape", + "test.test_string_literals.TestLiterals.test_eval_bytes_invalid_escape" + ], + "pass_to_pass": [ + "test.test_grammar.TokenTests.test_backslash", + "test.test_grammar.TokenTests.test_ellipsis", + "test.test_grammar.TokenTests.test_floats", + "test.test_grammar.TokenTests.test_plain_integers", + "test.test_grammar.TokenTests.test_long_integers", + "test.test_grammar.TokenTests.test_string_literals", + "test.test_grammar.GrammarTests.test_eval_input", + "test.test_grammar.GrammarTests.test_funcdef", + "test.test_grammar.GrammarTests.test_lambdef", + "test.test_grammar.GrammarTests.test_simple_stmt", + "test.test_grammar.GrammarTests.test_expr_stmt", + "test.test_grammar.GrammarTests.test_assert", + "test.test_grammar.GrammarTests.test_if", + "test.test_grammar.GrammarTests.test_while", + "test.test_grammar.GrammarTests.test_for", + "test.test_grammar.GrammarTests.test_classdef", + "test.test_grammar.GrammarTests.test_atoms", + "test.test_grammar.GrammarTests.test_del_stmt", + "test.test_grammar.GrammarTests.test_pass_stmt", + "test.test_grammar.GrammarTests.test_break_stmt", + "test.test_grammar.GrammarTests.test_continue_stmt", + "test.test_grammar.GrammarTests.test_break_continue_loop", + "test.test_grammar.GrammarTests.test_return", + "test.test_grammar.GrammarTests.test_yield", + "test.test_grammar.GrammarTests.test_yield_in_comprehensions", + "test.test_grammar.GrammarTests.test_raise", + "test.test_grammar.GrammarTests.test_import", + "test.test_grammar.GrammarTests.test_global", + "test.test_grammar.GrammarTests.test_nonlocal", + "test.test_grammar.GrammarTests.test_try", + "test.test_grammar.GrammarTests.test_with_statement", + "test.test_grammar.GrammarTests.test_async_await", + "test.test_grammar.GrammarTests.test_async_for", + "test.test_grammar.GrammarTests.test_async_with", + "test.test_grammar.GrammarTests.test_dictcomps", + "test.test_grammar.GrammarTests.test_listcomps", + "test.test_grammar.GrammarTests.test_genexps", + "test.test_grammar.GrammarTests.test_comprehension_specials", + "test.test_grammar.GrammarTests.test_comparison", + "test.test_grammar.GrammarTests.test_binary_mask_ops", + "test.test_grammar.GrammarTests.test_shift_ops", + "test.test_grammar.GrammarTests.test_multiplicative_ops", + "test.test_grammar.GrammarTests.test_unary_ops", + "test.test_grammar.GrammarTests.test_if_else_expr", + "test.test_grammar.GrammarTests.test_paren_evaluation", + "test.test_grammar.GrammarTests.test_var_annot_basics", + "test.test_grammar.GrammarTests.test_var_annot_basic_semantics", + "test.test_grammar.GrammarTests.test_var_annot_in_module", + "test.test_ast.AST_Tests.test_AST_objects", + "test.test_ast.AST_Tests.test_arguments", + "test.test_ast.AST_Tests.test_snippets", + "test.test_ast.ASTHelpers_Test.test_parse", + "test.test_ast.ASTHelpers_Test.test_dump", + "test.test_ast.ASTHelpers_Test.test_literal_eval" + ], + "synthetic_tests": [], + "out_of_scope_surfaces": [ + { + "surface": "test_peg_generator.test_pegen.TestPegen + test_peg_generator.test_first_sets.TestFirstSets (~35 methods)", + "reason": "After source-symbol cleanup, the selected TestCParser F2P methods are the six parser-generator behavior tests whose selected bodies do not directly name PR-added source symbols absent from the requirement doc. The other two test_peg_generator classes \u2014 TestPegen tests the pegen Python module's grammar-parsing internals, TestFirstSets tests the first-sets static analysis \u2014 are pure-Python unit tests of the build-time tool with no runtime parsing component. Including them would inflate F2P without adding orthogonal system-level coverage." + }, + { + "surface": "test.test_peg_parser.ASTGenerationTest.test_correct_but_known_to_fail_ast_generation_on_source_files (1 method)", + "reason": "This upstream test is decorated `@unittest.skipIf(sys.flags.use_peg, 'This tests nothing for now, since compile uses pegen as well')`. Since solution.patch makes PEG the default (config->use_peg=1), the test SKIPs at post-state. Per the LoLBench no-skipped-tests rule, SKIPPED cannot count as PASSED, so the test cannot be in F2P; the runner does not pass -X oldparser. The other ASTGenerationTest methods were removed from the selected F2P set during source-symbol cleanup because their selected bodies directly invoke parse_string, which is absent from the requirement doc." + }, + { + "surface": "Six pre-existing test methods adjacent to PR hunks but not themselves modified: test_codeop.CodeopTests.test_valid, test_compile.TestSpecifics.test_single_statement, test_eof.EOFTestCase.test_EOFS, test_parser.ParserStackLimitTestCase.test_deeply_nested_list, test_positional_only_arg.PositionalOnlyTestCase.test_lambdas, test_unparse.UnparseTestCase.test_constant_tuples", + "reason": "These methods sit immediately before the actually-modified methods in their files, so git's diff hunk-context shows their function header in the `@@ \u2026 def test_X(self):` line \u2014 but the changes are to the NEXT method, not to these. Their bodies are byte-identical between base_commit and merge_commit. Confirmed by AST-walk: the methods themselves contain no `sys.flags.use_peg` reference, so their pre-state behavior would be identical to post-state \u2014 disqualifying them as F2P (no transition). The actually-modified peers in the same files (test_codeop.test_incomplete, test_compile.test_bad_single_statement, test_eof.test_line_continuation_EOF, test_parser.test_trigger_memory_error, test_positional_only_arg.test_invalid_syntax_*, test_unparse.test_function_type) use the `@unittest.skipIf(sys.flags.use_peg, \u2026)` decorator pattern; at post-state PEG is the default \u2192 those methods SKIP \u2192 SKIPPED \u2260 PASSED, also disqualifying them from F2P under the no-skipped-tests rule." + } + ], + "eval_tests_patch_notes": "eval_tests.patch is based on the PR's test hunks for the 7 added Lib/test/test_peg_parser*/test_peg_generator* files plus 18 modified Lib/test/test_*.py files. The benchmark patch moves test_pegen imports of grammar_visualizer/python_generator behind the non-selected tests that use them, so selected F2P test loading no longer depends on those PR-added module paths. The added file Tools/peg_generator/data/xxl.zip is binary fixture data referenced only by Tools/peg_generator/scripts/test_pypi_packages.py (a benchmark utility, not in F2P/P2P) and cannot be reconstructed from the github API's text-only patch field; it is recorded in omitted.patch with reason 'binary fixture, not referenced by selected tests'.", + "fixture_taint_summary": "After the 2026-06-08 source-symbol cleanup, original F2P keeps 12 selected tests whose bodies do not directly invoke _peg_parser.parse_string, pegen.testutil.parse_string, GeneratedParser, or PR-added _PyPegen_* helper names absent from the requirement doc. The retained set includes 6 TestCParser parser-generator behavior tests that call local helpers without directly naming the source symbols, plus 6 pre-existing parser-regression methods in modified Lib/test/*.py files gated on sys.flags.use_peg. The 54 P2P selectors remain from Lib/test/test_grammar.py and Lib/test/test_ast.py.", + "triage": { + "fail_to_pass": { + "TestCParser.test_lookahead": { + "system_reason": "Builds a C parser whose grammar uses positive-lookahead operators (&rule) and asserts the parser accepts/rejects strings correctly.", + "public_surface": "pegen.build + dlopen-compiled C parser", + "internal_symbol_check": [ + "_PyPegen_Parser", + "PyPegen_*" + ], + "runner_surface": "./python -m unittest -v test.test_peg_generator.test_c_parser.TestCParser.test_lookahead", + "fixture_taint_checked": true, + "requires_gcc_at_runtime": true + }, + "TestCParser.test_negative_lookahead": { + "system_reason": "Builds a C parser whose grammar uses negative-lookahead operators (!rule) and asserts correct accept/reject behavior.", + "public_surface": "pegen.build + dlopen-compiled C parser", + "internal_symbol_check": [ + "_PyPegen_Parser", + "PyPegen_*" + ], + "runner_surface": "./python -m unittest -v test.test_peg_generator.test_c_parser.TestCParser.test_negative_lookahead", + "fixture_taint_checked": true, + "requires_gcc_at_runtime": true + }, + "TestCParser.test_cut": { + "system_reason": "Builds a C parser using the PEG 'cut' operator (~) and asserts correct backtracking behavior.", + "public_surface": "pegen.build + dlopen-compiled C parser", + "internal_symbol_check": [ + "_PyPegen_Parser", + "PyPegen_*" + ], + "runner_surface": "./python -m unittest -v test.test_peg_generator.test_c_parser.TestCParser.test_cut", + "fixture_taint_checked": true, + "requires_gcc_at_runtime": true + }, + "TestCParser.test_left_recursion": { + "system_reason": "Builds a C parser for a left-recursive grammar (e.g. expr: expr '+' atom | atom) and asserts correct parsing.", + "public_surface": "pegen.build + dlopen-compiled C parser", + "internal_symbol_check": [ + "_PyPegen_Parser", + "PyPegen_*" + ], + "runner_surface": "./python -m unittest -v test.test_peg_generator.test_c_parser.TestCParser.test_left_recursion", + "fixture_taint_checked": true, + "requires_gcc_at_runtime": true + }, + "TestCParser.test_advanced_left_recursive": { + "system_reason": "Builds a C parser for an advanced left-recursion case (multiple LR alternatives) and asserts correctness.", + "public_surface": "pegen.build + dlopen-compiled C parser", + "internal_symbol_check": [ + "_PyPegen_Parser", + "PyPegen_*" + ], + "runner_surface": "./python -m unittest -v test.test_peg_generator.test_c_parser.TestCParser.test_advanced_left_recursive", + "fixture_taint_checked": true, + "requires_gcc_at_runtime": true + }, + "TestCParser.test_pass_stmt_action": { + "system_reason": "Builds a C parser whose grammar action returns a pass statement AST node; asserts correct AST emission from the action.", + "public_surface": "pegen.build + dlopen-compiled C parser", + "internal_symbol_check": [ + "_PyPegen_Parser", + "PyPegen_*" + ], + "runner_surface": "./python -m unittest -v test.test_peg_generator.test_c_parser.TestCParser.test_pass_stmt_action", + "fixture_taint_checked": true, + "requires_gcc_at_runtime": true + }, + "TestCase.test_ast_line_numbers_nested": { + "system_reason": "Pre-existing f-string AST line-number test gated on sys.flags.use_peg. Same semantics.", + "public_surface": "compile() / codeop / ast.parse + sys.flags.use_peg", + "internal_symbol_check": [ + "_peg_parser", + "_PyPegen_*", + "PyPegen_*" + ], + "runner_surface": "./python -m unittest -v test.test_fstring.TestCase.test_ast_line_numbers_nested", + "fixture_taint_checked": true, + "f2p_signal_strength": "weak \u2014 pre\u2192post transition is partly driven by sys.flags.use_peg presence; the body's unconditional assertions still exercise the new parser via compile()" + }, + "PositionalOnlyTestCase.test_invalid_syntax_errors": { + "system_reason": "Pre-existing PEP-570 positional-only error test. The 4 default-args assertions are guarded by `if not sys.flags.use_peg:` (new parser accepts those cases). The 8+ remaining unconditional check_syntax_error assertions still run and exercise the new parser's invalid-syntax handling.", + "public_surface": "compile() / codeop / ast.parse + sys.flags.use_peg", + "internal_symbol_check": [ + "_peg_parser", + "_PyPegen_*", + "PyPegen_*" + ], + "runner_surface": "./python -m unittest -v test.test_positional_only_arg.PositionalOnlyTestCase.test_invalid_syntax_errors", + "fixture_taint_checked": true, + "f2p_signal_strength": "weak \u2014 pre\u2192post transition is partly driven by sys.flags.use_peg presence; the body's unconditional assertions still exercise the new parser via compile()" + }, + "PositionalOnlyTestCase.test_invalid_syntax_errors_async": { + "system_reason": "async-def variant of the above.", + "public_surface": "compile() / codeop / ast.parse + sys.flags.use_peg", + "internal_symbol_check": [ + "_peg_parser", + "_PyPegen_*", + "PyPegen_*" + ], + "runner_surface": "./python -m unittest -v test.test_positional_only_arg.PositionalOnlyTestCase.test_invalid_syntax_errors_async", + "fixture_taint_checked": true, + "f2p_signal_strength": "weak \u2014 pre\u2192post transition is partly driven by sys.flags.use_peg presence; the body's unconditional assertions still exercise the new parser via compile()" + }, + "PositionalOnlyTestCase.test_invalid_syntax_lambda": { + "system_reason": "lambda variant of the above.", + "public_surface": "compile() / codeop / ast.parse + sys.flags.use_peg", + "internal_symbol_check": [ + "_peg_parser", + "_PyPegen_*", + "PyPegen_*" + ], + "runner_surface": "./python -m unittest -v test.test_positional_only_arg.PositionalOnlyTestCase.test_invalid_syntax_lambda", + "fixture_taint_checked": true, + "f2p_signal_strength": "weak \u2014 pre\u2192post transition is partly driven by sys.flags.use_peg presence; the body's unconditional assertions still exercise the new parser via compile()" + }, + "TestLiterals.test_eval_str_invalid_escape": { + "system_reason": "Pre-existing string-literal invalid-escape test gated on sys.flags.use_peg for warning-vs-error nuance.", + "public_surface": "compile() / codeop / ast.parse + sys.flags.use_peg", + "internal_symbol_check": [ + "_peg_parser", + "_PyPegen_*", + "PyPegen_*" + ], + "runner_surface": "./python -m unittest -v test.test_string_literals.TestLiterals.test_eval_str_invalid_escape", + "fixture_taint_checked": true, + "f2p_signal_strength": "weak \u2014 pre\u2192post transition is partly driven by sys.flags.use_peg presence; the body's unconditional assertions still exercise the new parser via compile()" + }, + "TestLiterals.test_eval_bytes_invalid_escape": { + "system_reason": "Bytes-literal variant.", + "public_surface": "compile() / codeop / ast.parse + sys.flags.use_peg", + "internal_symbol_check": [ + "_peg_parser", + "_PyPegen_*", + "PyPegen_*" + ], + "runner_surface": "./python -m unittest -v test.test_string_literals.TestLiterals.test_eval_bytes_invalid_escape", + "fixture_taint_checked": true, + "f2p_signal_strength": "weak \u2014 pre\u2192post transition is partly driven by sys.flags.use_peg presence; the body's unconditional assertions still exercise the new parser via compile()" + } + }, + "pass_to_pass": { + "TokenTests.test_backslash": { + "system_reason": "Pre-existing grammar token-level test for line continuations; exercised through compile() \u2014 orthogonal to PEP 617's new parser path.", + "public_surface": "compile() / tokenize line-continuation handling", + "internal_symbol_check": [ + "_peg_parser", + "_PyPegen_*", + "PyPegen_*" + ], + "runner_surface": "./python -m unittest -v test.test_grammar.TokenTests.test_backslash", + "fixture_taint_checked": true + }, + "TokenTests.test_ellipsis": { + "system_reason": "Pre-existing test for ellipsis token (`...`) recognition through compile(); orthogonal to PEP 617.", + "public_surface": "compile()", + "internal_symbol_check": [ + "_peg_parser", + "_PyPegen_*", + "PyPegen_*" + ], + "runner_surface": "./python -m unittest -v test.test_grammar.TokenTests.test_ellipsis", + "fixture_taint_checked": true + }, + "TokenTests.test_floats": { + "system_reason": "Pre-existing test for floating-point literal parsing through compile(); orthogonal to PEP 617.", + "public_surface": "compile() + numeric tokenization", + "internal_symbol_check": [ + "_peg_parser", + "_PyPegen_*", + "PyPegen_*" + ], + "runner_surface": "./python -m unittest -v test.test_grammar.TokenTests.test_floats", + "fixture_taint_checked": true + }, + "TokenTests.test_plain_integers": { + "system_reason": "Pre-existing grammar token-level test exercised through compile() and tokenize; orthogonal to PEP 617's new parser.", + "public_surface": "compile() / ast.* / sys.* depending on the test", + "internal_symbol_check": [ + "_peg_parser", + "_PyPegen_*", + "PyPegen_*" + ], + "runner_surface": "./python -m unittest -v test.test_grammar.TokenTests.test_plain_integers", + "fixture_taint_checked": true + }, + "TokenTests.test_long_integers": { + "system_reason": "Pre-existing grammar token-level test exercised through compile() and tokenize; orthogonal to PEP 617's new parser.", + "public_surface": "compile() / ast.* / sys.* depending on the test", + "internal_symbol_check": [ + "_peg_parser", + "_PyPegen_*", + "PyPegen_*" + ], + "runner_surface": "./python -m unittest -v test.test_grammar.TokenTests.test_long_integers", + "fixture_taint_checked": true + }, + "TokenTests.test_string_literals": { + "system_reason": "Pre-existing grammar token-level test exercised through compile() and tokenize; orthogonal to PEP 617's new parser.", + "public_surface": "compile() / ast.* / sys.* depending on the test", + "internal_symbol_check": [ + "_peg_parser", + "_PyPegen_*", + "PyPegen_*" + ], + "runner_surface": "./python -m unittest -v test.test_grammar.TokenTests.test_string_literals", + "fixture_taint_checked": true + }, + "GrammarTests.test_eval_input": { + "system_reason": "Pre-existing grammar-rule test exercised through compile()/exec. At post-state PEG is the default parser, so the assertions now flow through the new parser and act as additional new-parser regression coverage on top of F2P.", + "public_surface": "compile() / ast.* / sys.* depending on the test", + "internal_symbol_check": [ + "_peg_parser", + "_PyPegen_*", + "PyPegen_*" + ], + "runner_surface": "./python -m unittest -v test.test_grammar.GrammarTests.test_eval_input", + "fixture_taint_checked": true + }, + "GrammarTests.test_funcdef": { + "system_reason": "Pre-existing comprehensive grammar test for function-definition statements; exercises def, parameters, return, decorators through compile()/exec \u2014 orthogonal to PEP 617.", + "public_surface": "compile() + exec()", + "internal_symbol_check": [ + "_peg_parser", + "_PyPegen_*" + ], + "runner_surface": "./python -m unittest -v test.test_grammar.GrammarTests.test_funcdef", + "fixture_taint_checked": true + }, + "GrammarTests.test_lambdef": { + "system_reason": "Pre-existing grammar test for lambda expressions through compile(); orthogonal to PEP 617.", + "public_surface": "compile() + lambda", + "internal_symbol_check": [ + "_peg_parser", + "_PyPegen_*" + ], + "runner_surface": "./python -m unittest -v test.test_grammar.GrammarTests.test_lambdef", + "fixture_taint_checked": true + }, + "GrammarTests.test_simple_stmt": { + "system_reason": "Pre-existing grammar test for simple-statement parsing through compile(); orthogonal to PEP 617.", + "public_surface": "compile()", + "internal_symbol_check": [ + "_peg_parser", + "_PyPegen_*" + ], + "runner_surface": "./python -m unittest -v test.test_grammar.GrammarTests.test_simple_stmt", + "fixture_taint_checked": true + }, + "GrammarTests.test_expr_stmt": { + "system_reason": "Pre-existing grammar-rule test exercised through compile()/exec. At post-state PEG is the default parser, so the assertions now flow through the new parser and act as additional new-parser regression coverage on top of F2P.", + "public_surface": "compile() / ast.* / sys.* depending on the test", + "internal_symbol_check": [ + "_peg_parser", + "_PyPegen_*", + "PyPegen_*" + ], + "runner_surface": "./python -m unittest -v test.test_grammar.GrammarTests.test_expr_stmt", + "fixture_taint_checked": true + }, + "GrammarTests.test_assert": { + "system_reason": "Pre-existing grammar test for assert statements through compile(); orthogonal to PEP 617.", + "public_surface": "compile() + assert", + "internal_symbol_check": [ + "_peg_parser", + "_PyPegen_*" + ], + "runner_surface": "./python -m unittest -v test.test_grammar.GrammarTests.test_assert", + "fixture_taint_checked": true + }, + "GrammarTests.test_if": { + "system_reason": "Pre-existing grammar test for if/elif/else statements through compile(); orthogonal to PEP 617.", + "public_surface": "compile() + if", + "internal_symbol_check": [ + "_peg_parser", + "_PyPegen_*" + ], + "runner_surface": "./python -m unittest -v test.test_grammar.GrammarTests.test_if", + "fixture_taint_checked": true + }, + "GrammarTests.test_while": { + "system_reason": "Pre-existing grammar test for while loops through compile(); orthogonal to PEP 617.", + "public_surface": "compile() + while", + "internal_symbol_check": [ + "_peg_parser", + "_PyPegen_*" + ], + "runner_surface": "./python -m unittest -v test.test_grammar.GrammarTests.test_while", + "fixture_taint_checked": true + }, + "GrammarTests.test_for": { + "system_reason": "Pre-existing grammar test for for loops through compile(); orthogonal to PEP 617.", + "public_surface": "compile() + for", + "internal_symbol_check": [ + "_peg_parser", + "_PyPegen_*" + ], + "runner_surface": "./python -m unittest -v test.test_grammar.GrammarTests.test_for", + "fixture_taint_checked": true + }, + "GrammarTests.test_classdef": { + "system_reason": "Pre-existing grammar test for class definitions through compile()/exec; orthogonal to PEP 617.", + "public_surface": "compile() + class", + "internal_symbol_check": [ + "_peg_parser", + "_PyPegen_*" + ], + "runner_surface": "./python -m unittest -v test.test_grammar.GrammarTests.test_classdef", + "fixture_taint_checked": true + }, + "GrammarTests.test_atoms": { + "system_reason": "Pre-existing grammar test for atomic expression forms (literals, identifiers, parens) through compile(); orthogonal to PEP 617.", + "public_surface": "compile()", + "internal_symbol_check": [ + "_peg_parser", + "_PyPegen_*" + ], + "runner_surface": "./python -m unittest -v test.test_grammar.GrammarTests.test_atoms", + "fixture_taint_checked": true + }, + "GrammarTests.test_del_stmt": { + "system_reason": "Pre-existing grammar-rule test exercised through compile()/exec; orthogonal to PEP 617's new parser path.", + "public_surface": "compile() / ast.* / sys.* depending on the test", + "internal_symbol_check": [ + "_peg_parser", + "_PyPegen_*", + "PyPegen_*" + ], + "runner_surface": "./python -m unittest -v test.test_grammar.GrammarTests.test_del_stmt", + "fixture_taint_checked": true + }, + "GrammarTests.test_pass_stmt": { + "system_reason": "Pre-existing grammar-rule test exercised through compile()/exec; orthogonal to PEP 617's new parser path.", + "public_surface": "compile() / ast.* / sys.* depending on the test", + "internal_symbol_check": [ + "_peg_parser", + "_PyPegen_*", + "PyPegen_*" + ], + "runner_surface": "./python -m unittest -v test.test_grammar.GrammarTests.test_pass_stmt", + "fixture_taint_checked": true + }, + "GrammarTests.test_break_stmt": { + "system_reason": "Pre-existing grammar-rule test exercised through compile()/exec; orthogonal to PEP 617's new parser path.", + "public_surface": "compile() / ast.* / sys.* depending on the test", + "internal_symbol_check": [ + "_peg_parser", + "_PyPegen_*", + "PyPegen_*" + ], + "runner_surface": "./python -m unittest -v test.test_grammar.GrammarTests.test_break_stmt", + "fixture_taint_checked": true + }, + "GrammarTests.test_continue_stmt": { + "system_reason": "Pre-existing grammar-rule test exercised through compile()/exec; orthogonal to PEP 617's new parser path.", + "public_surface": "compile() / ast.* / sys.* depending on the test", + "internal_symbol_check": [ + "_peg_parser", + "_PyPegen_*", + "PyPegen_*" + ], + "runner_surface": "./python -m unittest -v test.test_grammar.GrammarTests.test_continue_stmt", + "fixture_taint_checked": true + }, + "GrammarTests.test_break_continue_loop": { + "system_reason": "Pre-existing grammar-rule test exercised through compile()/exec. At post-state PEG is the default parser, so the assertions now flow through the new parser and act as additional new-parser regression coverage on top of F2P.", + "public_surface": "compile() / ast.* / sys.* depending on the test", + "internal_symbol_check": [ + "_peg_parser", + "_PyPegen_*", + "PyPegen_*" + ], + "runner_surface": "./python -m unittest -v test.test_grammar.GrammarTests.test_break_continue_loop", + "fixture_taint_checked": true + }, + "GrammarTests.test_return": { + "system_reason": "Pre-existing grammar-rule test exercised through compile()/exec; orthogonal to PEP 617's new parser path.", + "public_surface": "compile() / ast.* / sys.* depending on the test", + "internal_symbol_check": [ + "_peg_parser", + "_PyPegen_*", + "PyPegen_*" + ], + "runner_surface": "./python -m unittest -v test.test_grammar.GrammarTests.test_return", + "fixture_taint_checked": true + }, + "GrammarTests.test_yield": { + "system_reason": "Pre-existing grammar-rule test exercised through compile()/exec; orthogonal to PEP 617's new parser path.", + "public_surface": "compile() / ast.* / sys.* depending on the test", + "internal_symbol_check": [ + "_peg_parser", + "_PyPegen_*", + "PyPegen_*" + ], + "runner_surface": "./python -m unittest -v test.test_grammar.GrammarTests.test_yield", + "fixture_taint_checked": true + }, + "GrammarTests.test_yield_in_comprehensions": { + "system_reason": "Pre-existing grammar-rule test exercised through compile()/exec. At post-state PEG is the default parser, so the assertions now flow through the new parser and act as additional new-parser regression coverage on top of F2P.", + "public_surface": "compile() / ast.* / sys.* depending on the test", + "internal_symbol_check": [ + "_peg_parser", + "_PyPegen_*", + "PyPegen_*" + ], + "runner_surface": "./python -m unittest -v test.test_grammar.GrammarTests.test_yield_in_comprehensions", + "fixture_taint_checked": true + }, + "GrammarTests.test_raise": { + "system_reason": "Pre-existing grammar-rule test exercised through compile()/exec; orthogonal to PEP 617's new parser path.", + "public_surface": "compile() / ast.* / sys.* depending on the test", + "internal_symbol_check": [ + "_peg_parser", + "_PyPegen_*", + "PyPegen_*" + ], + "runner_surface": "./python -m unittest -v test.test_grammar.GrammarTests.test_raise", + "fixture_taint_checked": true + }, + "GrammarTests.test_import": { + "system_reason": "Pre-existing grammar-rule test exercised through compile()/exec; orthogonal to PEP 617's new parser path.", + "public_surface": "compile() / ast.* / sys.* depending on the test", + "internal_symbol_check": [ + "_peg_parser", + "_PyPegen_*", + "PyPegen_*" + ], + "runner_surface": "./python -m unittest -v test.test_grammar.GrammarTests.test_import", + "fixture_taint_checked": true + }, + "GrammarTests.test_global": { + "system_reason": "Pre-existing grammar-rule test exercised through compile()/exec; orthogonal to PEP 617's new parser path.", + "public_surface": "compile() / ast.* / sys.* depending on the test", + "internal_symbol_check": [ + "_peg_parser", + "_PyPegen_*", + "PyPegen_*" + ], + "runner_surface": "./python -m unittest -v test.test_grammar.GrammarTests.test_global", + "fixture_taint_checked": true + }, + "GrammarTests.test_nonlocal": { + "system_reason": "Pre-existing grammar-rule test exercised through compile()/exec; orthogonal to PEP 617's new parser path.", + "public_surface": "compile() / ast.* / sys.* depending on the test", + "internal_symbol_check": [ + "_peg_parser", + "_PyPegen_*", + "PyPegen_*" + ], + "runner_surface": "./python -m unittest -v test.test_grammar.GrammarTests.test_nonlocal", + "fixture_taint_checked": true + }, + "GrammarTests.test_try": { + "system_reason": "Pre-existing grammar-rule test exercised through compile()/exec; orthogonal to PEP 617's new parser path.", + "public_surface": "compile() / ast.* / sys.* depending on the test", + "internal_symbol_check": [ + "_peg_parser", + "_PyPegen_*", + "PyPegen_*" + ], + "runner_surface": "./python -m unittest -v test.test_grammar.GrammarTests.test_try", + "fixture_taint_checked": true + }, + "GrammarTests.test_with_statement": { + "system_reason": "Pre-existing grammar-rule test exercised through compile()/exec; orthogonal to PEP 617's new parser path.", + "public_surface": "compile() / ast.* / sys.* depending on the test", + "internal_symbol_check": [ + "_peg_parser", + "_PyPegen_*", + "PyPegen_*" + ], + "runner_surface": "./python -m unittest -v test.test_grammar.GrammarTests.test_with_statement", + "fixture_taint_checked": true + }, + "GrammarTests.test_async_await": { + "system_reason": "Pre-existing grammar-rule test exercised through compile()/exec; orthogonal to PEP 617's new parser path.", + "public_surface": "compile() / ast.* / sys.* depending on the test", + "internal_symbol_check": [ + "_peg_parser", + "_PyPegen_*", + "PyPegen_*" + ], + "runner_surface": "./python -m unittest -v test.test_grammar.GrammarTests.test_async_await", + "fixture_taint_checked": true + }, + "GrammarTests.test_async_for": { + "system_reason": "Pre-existing grammar-rule test exercised through compile()/exec; orthogonal to PEP 617's new parser path.", + "public_surface": "compile() / ast.* / sys.* depending on the test", + "internal_symbol_check": [ + "_peg_parser", + "_PyPegen_*", + "PyPegen_*" + ], + "runner_surface": "./python -m unittest -v test.test_grammar.GrammarTests.test_async_for", + "fixture_taint_checked": true + }, + "GrammarTests.test_async_with": { + "system_reason": "Pre-existing grammar-rule test exercised through compile()/exec; orthogonal to PEP 617's new parser path.", + "public_surface": "compile() / ast.* / sys.* depending on the test", + "internal_symbol_check": [ + "_peg_parser", + "_PyPegen_*", + "PyPegen_*" + ], + "runner_surface": "./python -m unittest -v test.test_grammar.GrammarTests.test_async_with", + "fixture_taint_checked": true + }, + "GrammarTests.test_dictcomps": { + "system_reason": "Pre-existing grammar-rule test exercised through compile()/exec; orthogonal to PEP 617's new parser path.", + "public_surface": "compile() / ast.* / sys.* depending on the test", + "internal_symbol_check": [ + "_peg_parser", + "_PyPegen_*", + "PyPegen_*" + ], + "runner_surface": "./python -m unittest -v test.test_grammar.GrammarTests.test_dictcomps", + "fixture_taint_checked": true + }, + "GrammarTests.test_listcomps": { + "system_reason": "Pre-existing grammar-rule test exercised through compile()/exec; orthogonal to PEP 617's new parser path.", + "public_surface": "compile() / ast.* / sys.* depending on the test", + "internal_symbol_check": [ + "_peg_parser", + "_PyPegen_*", + "PyPegen_*" + ], + "runner_surface": "./python -m unittest -v test.test_grammar.GrammarTests.test_listcomps", + "fixture_taint_checked": true + }, + "GrammarTests.test_genexps": { + "system_reason": "Pre-existing grammar-rule test exercised through compile()/exec; orthogonal to PEP 617's new parser path.", + "public_surface": "compile() / ast.* / sys.* depending on the test", + "internal_symbol_check": [ + "_peg_parser", + "_PyPegen_*", + "PyPegen_*" + ], + "runner_surface": "./python -m unittest -v test.test_grammar.GrammarTests.test_genexps", + "fixture_taint_checked": true + }, + "GrammarTests.test_comprehension_specials": { + "system_reason": "Pre-existing grammar-rule test exercised through compile()/exec. At post-state PEG is the default parser, so the assertions now flow through the new parser and act as additional new-parser regression coverage on top of F2P.", + "public_surface": "compile() / ast.* / sys.* depending on the test", + "internal_symbol_check": [ + "_peg_parser", + "_PyPegen_*", + "PyPegen_*" + ], + "runner_surface": "./python -m unittest -v test.test_grammar.GrammarTests.test_comprehension_specials", + "fixture_taint_checked": true + }, + "GrammarTests.test_comparison": { + "system_reason": "Pre-existing grammar-rule test exercised through compile()/exec; orthogonal to PEP 617's new parser path.", + "public_surface": "compile() / ast.* / sys.* depending on the test", + "internal_symbol_check": [ + "_peg_parser", + "_PyPegen_*", + "PyPegen_*" + ], + "runner_surface": "./python -m unittest -v test.test_grammar.GrammarTests.test_comparison", + "fixture_taint_checked": true + }, + "GrammarTests.test_binary_mask_ops": { + "system_reason": "Pre-existing grammar-rule test exercised through compile()/exec. At post-state PEG is the default parser, so the assertions now flow through the new parser and act as additional new-parser regression coverage on top of F2P.", + "public_surface": "compile() / ast.* / sys.* depending on the test", + "internal_symbol_check": [ + "_peg_parser", + "_PyPegen_*", + "PyPegen_*" + ], + "runner_surface": "./python -m unittest -v test.test_grammar.GrammarTests.test_binary_mask_ops", + "fixture_taint_checked": true + }, + "GrammarTests.test_shift_ops": { + "system_reason": "Pre-existing grammar-rule test exercised through compile()/exec; orthogonal to PEP 617's new parser path.", + "public_surface": "compile() / ast.* / sys.* depending on the test", + "internal_symbol_check": [ + "_peg_parser", + "_PyPegen_*", + "PyPegen_*" + ], + "runner_surface": "./python -m unittest -v test.test_grammar.GrammarTests.test_shift_ops", + "fixture_taint_checked": true + }, + "GrammarTests.test_multiplicative_ops": { + "system_reason": "Pre-existing grammar-rule test exercised through compile()/exec; orthogonal to PEP 617's new parser path.", + "public_surface": "compile() / ast.* / sys.* depending on the test", + "internal_symbol_check": [ + "_peg_parser", + "_PyPegen_*", + "PyPegen_*" + ], + "runner_surface": "./python -m unittest -v test.test_grammar.GrammarTests.test_multiplicative_ops", + "fixture_taint_checked": true + }, + "GrammarTests.test_unary_ops": { + "system_reason": "Pre-existing grammar-rule test exercised through compile()/exec. At post-state PEG is the default parser, so the assertions now flow through the new parser and act as additional new-parser regression coverage on top of F2P.", + "public_surface": "compile() / ast.* / sys.* depending on the test", + "internal_symbol_check": [ + "_peg_parser", + "_PyPegen_*", + "PyPegen_*" + ], + "runner_surface": "./python -m unittest -v test.test_grammar.GrammarTests.test_unary_ops", + "fixture_taint_checked": true + }, + "GrammarTests.test_if_else_expr": { + "system_reason": "Pre-existing grammar-rule test exercised through compile()/exec. At post-state PEG is the default parser, so the assertions now flow through the new parser and act as additional new-parser regression coverage on top of F2P.", + "public_surface": "compile() / ast.* / sys.* depending on the test", + "internal_symbol_check": [ + "_peg_parser", + "_PyPegen_*", + "PyPegen_*" + ], + "runner_surface": "./python -m unittest -v test.test_grammar.GrammarTests.test_if_else_expr", + "fixture_taint_checked": true + }, + "GrammarTests.test_paren_evaluation": { + "system_reason": "Pre-existing grammar-rule test exercised through compile()/exec. At post-state PEG is the default parser, so the assertions now flow through the new parser and act as additional new-parser regression coverage on top of F2P.", + "public_surface": "compile() / ast.* / sys.* depending on the test", + "internal_symbol_check": [ + "_peg_parser", + "_PyPegen_*", + "PyPegen_*" + ], + "runner_surface": "./python -m unittest -v test.test_grammar.GrammarTests.test_paren_evaluation", + "fixture_taint_checked": true + }, + "GrammarTests.test_var_annot_basics": { + "system_reason": "Pre-existing grammar-rule test exercised through compile()/exec; orthogonal to PEP 617's new parser path.", + "public_surface": "compile() / ast.* / sys.* depending on the test", + "internal_symbol_check": [ + "_peg_parser", + "_PyPegen_*", + "PyPegen_*" + ], + "runner_surface": "./python -m unittest -v test.test_grammar.GrammarTests.test_var_annot_basics", + "fixture_taint_checked": true + }, + "GrammarTests.test_var_annot_basic_semantics": { + "system_reason": "Pre-existing grammar-rule test exercised through compile()/exec. At post-state PEG is the default parser, so the assertions now flow through the new parser and act as additional new-parser regression coverage on top of F2P.", + "public_surface": "compile() / ast.* / sys.* depending on the test", + "internal_symbol_check": [ + "_peg_parser", + "_PyPegen_*", + "PyPegen_*" + ], + "runner_surface": "./python -m unittest -v test.test_grammar.GrammarTests.test_var_annot_basic_semantics", + "fixture_taint_checked": true + }, + "GrammarTests.test_var_annot_in_module": { + "system_reason": "Pre-existing grammar-rule test exercised through compile()/exec. At post-state PEG is the default parser, so the assertions now flow through the new parser and act as additional new-parser regression coverage on top of F2P.", + "public_surface": "compile() / ast.* / sys.* depending on the test", + "internal_symbol_check": [ + "_peg_parser", + "_PyPegen_*", + "PyPegen_*" + ], + "runner_surface": "./python -m unittest -v test.test_grammar.GrammarTests.test_var_annot_in_module", + "fixture_taint_checked": true + }, + "AST_Tests.test_AST_objects": { + "system_reason": "Pre-existing test for AST node construction and attribute access via the public `ast` module; doesn't invoke the parser at all.", + "public_surface": "ast.AST + ast subclass construction", + "internal_symbol_check": [ + "_peg_parser", + "_PyPegen_*" + ], + "runner_surface": "./python -m unittest -v test.test_ast.AST_Tests.test_AST_objects", + "fixture_taint_checked": true + }, + "AST_Tests.test_arguments": { + "system_reason": "Pre-existing test for ast.arguments node shape; uses ast.parse on canonical Python forms.", + "public_surface": "ast.parse + ast.arguments", + "internal_symbol_check": [ + "_peg_parser", + "_PyPegen_*" + ], + "runner_surface": "./python -m unittest -v test.test_ast.AST_Tests.test_arguments", + "fixture_taint_checked": true + }, + "AST_Tests.test_snippets": { + "system_reason": "Pre-existing parametric test that parses a battery of Python source snippets via ast.parse and asserts dump equivalence with a known-good AST string.", + "public_surface": "ast.parse + ast.dump", + "internal_symbol_check": [ + "_peg_parser", + "_PyPegen_*" + ], + "runner_surface": "./python -m unittest -v test.test_ast.AST_Tests.test_snippets", + "fixture_taint_checked": true + }, + "ASTHelpers_Test.test_parse": { + "system_reason": "Pre-existing test for the public ast.parse function; basic source\u2192AST round-trip.", + "public_surface": "ast.parse", + "internal_symbol_check": [ + "_peg_parser", + "_PyPegen_*" + ], + "runner_surface": "./python -m unittest -v test.test_ast.ASTHelpers_Test.test_parse", + "fixture_taint_checked": true + }, + "ASTHelpers_Test.test_dump": { + "system_reason": "Pre-existing test for ast.dump rendering; orthogonal to the parser implementation.", + "public_surface": "ast.dump", + "internal_symbol_check": [ + "_peg_parser", + "_PyPegen_*" + ], + "runner_surface": "./python -m unittest -v test.test_ast.ASTHelpers_Test.test_dump", + "fixture_taint_checked": true + }, + "ASTHelpers_Test.test_literal_eval": { + "system_reason": "Pre-existing test for ast.literal_eval; uses ast.parse internally but the test asserts on the resulting Python value, not the AST nodes themselves.", + "public_surface": "ast.literal_eval", + "internal_symbol_check": [ + "_peg_parser", + "_PyPegen_*" + ], + "runner_surface": "./python -m unittest -v test.test_ast.ASTHelpers_Test.test_literal_eval", + "fixture_taint_checked": true + } + } + }, + "augmented": { + "suite_support": [ + "orig", + "aug", + "union" + ], + "eval_tests_patch": "eval_tests_aug.patch", + "eval_tests_aug_patch_sha256": "6025d51d486c16444295f55525d5d2c5f86b51677dba62e46536ef6e1f95480f", + "fail_to_pass": [ + "test.test_peg_aug.PegParserGrammarCoverageAugTest.test_cpython_syntax_regression_modules_under_peg_parser", + "test.test_peg_aug.PythonGeneratorSemanticsAugTest.test_first_sets_for_predicates_and_repeat_one", + "test.test_peg_generator.test_c_parser.TestCParser.test_gather", + "test.test_peg_generator.test_c_parser.TestCParser.test_gather_action_ast", + "test.test_peg_generator.test_c_parser.TestCParser.test_mutually_left_recursive", + "test.test_peg_generator.test_c_parser.TestCParser.test_nasty_mutually_left_recursive", + "test.test_peg_generator.test_pegen.TestPegen.test_optional_operator", + "test.test_peg_generator.test_pegen.TestPegen.test_alt_optional_operator", + "test.test_peg_generator.test_pegen.TestPegen.test_repeat_0_simple", + "test.test_peg_generator.test_pegen.TestPegen.test_repeat_1_simple", + "test.test_peg_generator.test_pegen.TestPegen.test_repeat_with_sep_simple", + "test.test_peg_generator.test_pegen.TestPegen.test_lookahead", + "test.test_peg_generator.test_pegen.TestPegen.test_left_recursive" + ], + "pass_to_pass": [ + "test.test_peg_stability_aug.ParserStabilityAugTest.test_compile_exec_eval_and_single_modes_still_work", + "test.test_peg_stability_aug.ParserStabilityAugTest.test_ast_parse_preserves_comprehension_shape", + "test.test_peg_stability_aug.ParserStabilityAugTest.test_function_annotations_and_positional_only_args_are_unchanged" + ], + "targets_mutants": [ + "mutant_002_c_generator_negative_lookahead_is_positive", + "mutant_003_c_generator_cut_disabled", + "mutant_004_python_parser_negative_lookahead_not_inverted", + "mutant_009_peg_extension_parse_string_uses_eval_start", + "mutant_011_c_generator_positive_lookahead_is_negative", + "mutant_014_c_generator_gather_ignores_separators", + "mutant_015_c_generator_alt_success_backtracks", + "mutant_016_c_generator_gather_swaps_element_and_sequence", + "mutant_017_python_generator_positive_lookahead_is_negative", + "mutant_019_metagrammar_question_becomes_repeat1", + "mutant_020_metagrammar_star_becomes_repeat1", + "mutant_021_metagrammar_plus_becomes_repeat0", + "mutant_022_metagrammar_gather_drops_separator", + "mutant_023_python_parser_positive_lookahead_inverted", + "mutant_024_python_parser_memoized_hit_does_not_advance", + "mutant_025_c_generator_left_recursion_stops_before_growth", + "mutant_026_c_generator_left_recursion_discards_raw_result", + "mutant_030_parser_generator_gather_repeats_separator", + "mutant_031_first_sets_negative_lookahead_has_no_terminals", + "mutant_032_first_sets_repeat1_nullable", + "mutant_033_python_generator_optional_is_mandatory", + "mutant_035_python_generator_repeat1_allows_empty", + "mutant_036_python_generator_gather_ignores_separators", + "mutant_037_python_generator_gather_reverses_sequence" + ], + "mutant_set_revision": { + "date": "2026-06-17", + "removed": [ + "mutant_001_parse_string_eval_uses_exec_mode", + "mutant_006_parse_string_single_uses_exec_mode", + "mutant_007_parse_file_single_uses_exec_mode", + "mutant_008_parse_string_honors_encoding_cookie", + "mutant_010_peg_extension_compile_mode_returns_none", + "mutant_038_parse_string_default_mode_is_eval", + "mutant_039_parse_file_default_mode_is_single", + "mutant_005_c_generator_repeat1_allows_empty", + "mutant_012_c_generator_optional_is_mandatory", + "mutant_013_c_generator_repeat0_requires_one", + "mutant_018_python_generator_cut_disabled", + "mutant_027_c_generator_memoizes_left_recursive_rules", + "mutant_029_parser_generator_loop0_named_loop1", + "mutant_034_python_generator_repeat0_requires_one" + ], + "reason": "unreachable", + "note": "Seven parse-mode mutants were removed as \u00a76-unreachable. mutant_001 (eval-start-vs-exec-start flip in Modules/_peg_parser.c, _Py_parse_string) plus mutant_006/007/008/010/038/039 all mutate the mode/encoding/default-start behavior of the test-facing _peg_parser extension module (Modules/_peg_parser.c and Tools/peg_generator/peg_extension/peg_extension.c). That behavior is observable only through _peg_parser.parse_string / parse_file (PR-added symbols whose mode semantics are absent from requirement_docs/CPython_PEP-617_New-PEG-parser-for-CPython_PR-19503.md, and which the bundle's own out_of_scope_surfaces / triage policy excludes). Public compile()/eval()/exec()/ast.parse() route through PyPegen_ASTFromStringObject with the caller-supplied start mode and never reach the mutated lines, so no \u00a76-compliant committed test can distinguish them from golden. They were deleted from mutations/ and from this spec's targets_mutants; 31 mutants remain. Additionally, 7 PEG-generator-internal mutants (m005/m012/m013/m027 c_generator, m018 python_generator cut, m029/m034 loop0/repeat0) were removed: per-test container runs on 2026-06-17 confirmed none is killable through any \u00a76-eligible committed test that runs cleanly in this harness \u2014 TestCParser has no targeted optional/repeat unit and its only full-codegen test (test_correct_ast_generation_on_source_files) errors on golden; the only Python cut test (TestPegen.test_cut) prints a verbose parse trace to stdout that corrupts run_tests.sh's results JSON; and no committed pegen test parses an empty repetition, so loop0/repeat0 codegen flips are unobservable. 24 mutants remain, all killed by union (golden green F2P 25/25, P2P 57/57).", + "new_total": 24, + "remaining_mutants_targeted": 24, + "union_kills_all_remaining": true + }, + "coverage_gate": { + "minimum_line_coverage_percent": 50, + "status": "passed", + "coverage_report": "coverage_out/coverage_report_union.json", + "union_line_coverage_percent": 79.4, + "executable_lines_in_patch": 9989, + "union_covered_lines": 7927, + "coverage_complete": true, + "measurement_note": "source-bearing gcov C lines; blank, comment, label, and brace-only gcov entries are excluded from the denominator" + }, + "triage": { + "test_level_policy": "Augmented F2P selectors exercise broad parser behavior through selected test bodies that do not directly invoke newly added source functions/classes absent from the requirement doc. Augmented P2P selectors use only pre-existing public ast/compile/codeop behavior and avoid importing _peg_parser or pegen so they pass in base, golden, and mutant states.", + "fail_to_pass": { + "test.test_peg_aug.PegParserGrammarCoverageAugTest.test_cpython_syntax_regression_modules_under_peg_parser": { + "requirement_sections": [ + "The new proposed PEG parser > Syntax > Grammar Expressions", + "Performance and validation > Validation" + ], + "public_surface": "CPython public unittest syntax modules running through compile(), ast.parse, and parser-facing standard-library tests after sys.flags.use_peg confirms the PEG parser is active", + "mutants_targeted": [], + "rationale": "Runs CPython syntax, f-string, compile, grammar, AST, type-comment, unparse, and related parser regression modules under the PEG-enabled interpreter to exercise broad public parser behavior and invalid-syntax handling while keeping the selected LoLBench test as a single wrapper method." + }, + "test.test_peg_aug.PythonGeneratorSemanticsAugTest.test_first_sets_for_predicates_and_repeat_one": { + "requirement_sections": [ + "The new proposed PEG parser > Grammar actions" + ], + "public_surface": "pegen FirstSetCalculator over parsed grammar rules", + "mutants_targeted": [ + "mutant_031_first_sets_negative_lookahead_has_no_terminals", + "mutant_032_first_sets_repeat1_nullable" + ], + "rationale": "Verifies first-set analysis for negative lookahead exclusions and non-nullable one-or-more repetitions, which feeds generated parser decisions." + }, + "test.test_peg_generator.test_c_parser.TestCParser.test_gather": { + "requirement_sections": [ + "The new proposed PEG parser > Syntax > Grammar Expressions" + ], + "public_surface": "pegen.build C-extension parser generated from a gather (sep.elem+) grammar, driven via the same check_input_strings_for_grammar helper as the original TestCParser F2P methods", + "mutants_targeted": [ + "mutant_014_c_generator_gather_ignores_separators", + "mutant_016_c_generator_gather_swaps_element_and_sequence" + ], + "rationale": "Selection expansion of a committed-original TestCParser method (already present in eval_tests.patch) whose selected body calls only the local check_input_strings_for_grammar helper, the same surface precedent as the six original TestCParser F2P selectors. The C generator's gather emission requires the separator between every pair and at least one element, so a gather grammar with separator/empty assertions distinguishes the golden C generator from the gather and one-or-more mutants." + }, + "test.test_peg_generator.test_c_parser.TestCParser.test_gather_action_ast": { + "requirement_sections": [ + "The new proposed PEG parser > Syntax > Grammar Expressions", + "The new proposed PEG parser > Grammar actions" + ], + "public_surface": "pegen.build C-extension parser generated from a gather grammar with an AST-producing action, driven via the verify_ast_generation helper as in the original TestCParser F2P methods", + "mutants_targeted": [ + "mutant_014_c_generator_gather_ignores_separators", + "mutant_016_c_generator_gather_swaps_element_and_sequence" + ], + "rationale": "Committed-original TestCParser method selected by precedent; its body calls only the local verify_ast_generation helper. The expected AST for a gathered sequence pins both the element/separator ordering and the action result, killing C generator gather mutants that swap element and sequence or drop separators." + }, + "test.test_peg_generator.test_c_parser.TestCParser.test_mutually_left_recursive": { + "requirement_sections": [ + "The new proposed PEG parser > Grammar actions" + ], + "public_surface": "pegen.build C-extension parser generated from a mutually left-recursive grammar, driven via check_input_strings_for_grammar as in the original TestCParser F2P methods", + "mutants_targeted": [ + "mutant_025_c_generator_left_recursion_stops_before_growth", + "mutant_026_c_generator_left_recursion_discards_raw_result" + ], + "rationale": "Committed-original TestCParser method selected by precedent; body calls only the local helper. Indirect (mutual) left recursion only parses when the C generator memoizes left-recursive rules and grows the seed correctly, so this distinguishes the golden generator from the left-recursion memoization mutants." + }, + "test.test_peg_generator.test_c_parser.TestCParser.test_nasty_mutually_left_recursive": { + "requirement_sections": [ + "The new proposed PEG parser > Grammar actions" + ], + "public_surface": "pegen.build C-extension parser generated from a hidden/indirect left-recursive grammar, driven via check_input_strings_for_grammar as in the original TestCParser F2P methods", + "mutants_targeted": [ + "mutant_025_c_generator_left_recursion_stops_before_growth", + "mutant_026_c_generator_left_recursion_discards_raw_result" + ], + "rationale": "Committed-original TestCParser method selected by precedent; body calls only the local helper. Hidden left recursion with both valid and invalid cases stresses the C generator's left-recursion memoization, killing mutants that stop before growth, discard the raw result, or memoize left-recursive rules incorrectly." + }, + "test.test_peg_generator.test_pegen.TestPegen.test_optional_operator": { + "requirement_sections": [ + "The new proposed PEG parser > Syntax > Grammar Expressions" + ], + "public_surface": "pegen make_parser + parse_string over a grammar using the optional operator (...)?", + "mutants_targeted": [ + "mutant_019_metagrammar_question_becomes_repeat1", + "mutant_033_python_generator_optional_is_mandatory" + ], + "rationale": "Selection expansion of a committed-original TestPegen method (present in eval_tests.patch), the same pegen module surface the bundle's committed first-sets aug test already uses. Asserting the parse tree both when the optional group is present and when it is absent (yields None) distinguishes the golden Python generator from the optional-is-mandatory mutant, and parsing the '?'-bearing grammar exercises the metagrammar that the question-becomes-repeat1 mutant alters." + }, + "test.test_peg_generator.test_pegen.TestPegen.test_alt_optional_operator": { + "requirement_sections": [ + "The new proposed PEG parser > Syntax > Grammar Expressions" + ], + "public_surface": "pegen make_parser + parse_string over a grammar using the bracketed optional form [ ... ]", + "mutants_targeted": [ + "mutant_033_python_generator_optional_is_mandatory" + ], + "rationale": "Committed-original TestPegen method selected by precedent. The bracketed optional [ '+' term ] must accept input both with and without the optional group (absent yields None), pinning the golden Python generator against the optional-is-mandatory mutant and exercising the bracketed-optional metagrammar form." + }, + "test.test_peg_generator.test_pegen.TestPegen.test_repeat_0_simple": { + "requirement_sections": [ + "The new proposed PEG parser > Syntax > Grammar Expressions" + ], + "public_surface": "pegen make_parser + parse_string over a grammar using the zero-or-more operator thing*", + "mutants_targeted": [ + "mutant_020_metagrammar_star_becomes_repeat1" + ], + "rationale": "Committed-original TestPegen method selected by precedent. Parsing a single 'thing' (empty repetition yields []) requires the zero-or-more operator to accept zero matches, distinguishing the golden generator from the repeat0-requires-one and loop0-named-loop1 mutants, while parsing the '*'-bearing grammar exercises the metagrammar the star-becomes-repeat1 mutant alters." + }, + "test.test_peg_generator.test_pegen.TestPegen.test_repeat_1_simple": { + "requirement_sections": [ + "The new proposed PEG parser > Syntax > Grammar Expressions" + ], + "public_surface": "pegen make_parser + parse_string over a grammar using the one-or-more operator thing+", + "mutants_targeted": [ + "mutant_035_python_generator_repeat1_allows_empty" + ], + "rationale": "Committed-original TestPegen method selected by precedent. The body asserts both a successful multi-element parse and a SyntaxError on a single-element input that violates the one-or-more requirement, distinguishing the golden Python generator from the repeat1-allows-empty mutant." + }, + "test.test_peg_generator.test_pegen.TestPegen.test_repeat_with_sep_simple": { + "requirement_sections": [ + "The new proposed PEG parser > Syntax > Grammar Expressions" + ], + "public_surface": "pegen make_parser + parse_string over a grammar using the gather operator sep.elem+", + "mutants_targeted": [ + "mutant_022_metagrammar_gather_drops_separator", + "mutant_030_parser_generator_gather_repeats_separator", + "mutant_036_python_generator_gather_ignores_separators", + "mutant_037_python_generator_gather_reverses_sequence" + ], + "rationale": "Committed-original TestPegen method selected by precedent. The exact parse tree for a comma-separated list pins the element/separator structure and ordering, distinguishing the golden Python generator from gather mutants that ignore or repeat the separator or reverse the sequence, and parsing the gather grammar exercises the metagrammar the gather-drops-separator mutant alters." + }, + "test.test_peg_generator.test_pegen.TestPegen.test_lookahead": { + "requirement_sections": [ + "The new proposed PEG parser > Syntax > Grammar Expressions" + ], + "public_surface": "pegen make_parser + parse_string over a grammar using positive (&) and negative (!) lookahead operators", + "mutants_targeted": [ + "mutant_004_python_parser_negative_lookahead_not_inverted", + "mutant_017_python_generator_positive_lookahead_is_negative", + "mutant_023_python_parser_positive_lookahead_inverted" + ], + "rationale": "Committed-original TestPegen method selected by precedent. The grammar uses both a positive lookahead (&'.') and a negative lookahead (!(target '=')); the asserted parse tree only holds when both predicates behave correctly, distinguishing the golden Python generator/parser from the lookahead-inversion mutants." + }, + "test.test_peg_generator.test_pegen.TestPegen.test_left_recursive": { + "requirement_sections": [ + "The new proposed PEG parser > Grammar actions" + ], + "public_surface": "pegen parse_string + generate_parser over a left-recursive grammar, asserting both left_recursive flags and the resulting parse tree", + "mutants_targeted": [ + "mutant_024_python_parser_memoized_hit_does_not_advance" + ], + "rationale": "Committed-original TestPegen method selected by precedent. The asserted left-recursive parse tree for '1 + 2 + 3' only forms when memoized results advance the input position correctly, distinguishing the golden Python parser from the memoized-hit-does-not-advance mutant." + } + }, + "pass_to_pass": { + "test.test_peg_stability_aug.ParserStabilityAugTest.test_compile_exec_eval_and_single_modes_still_work": { + "requirement_sections": [ + "Migration plan", + "Performance and validation > Validation" + ], + "public_surface": "compile(), eval(), exec(), and codeop.compile_command", + "rationale": "Pins unchanged public compile/eval/single-input behavior outside the new helper modules while still flowing through the active default parser." + }, + "test.test_peg_stability_aug.ParserStabilityAugTest.test_ast_parse_preserves_comprehension_shape": { + "requirement_sections": [ + "Performance and validation > Validation" + ], + "public_surface": "ast.parse and ast node classes", + "rationale": "Checks that an existing dictionary-comprehension AST shape remains stable under the new parser migration." + }, + "test.test_peg_stability_aug.ParserStabilityAugTest.test_function_annotations_and_positional_only_args_are_unchanged": { + "requirement_sections": [ + "Migration plan", + "Performance and validation > Validation" + ], + "public_surface": "compile(), exec(), ast.parse, and function-call semantics", + "rationale": "Guards unrelated function signature semantics, including positional-only arguments and annotations, which PEP-617 must preserve." + } + } + } + }, + "validated_at": "2026-06-08", + "omitted_patch_sha256": "b01429de2ae581bedcd8bbe3a3d5d13b66221e9a146ec4e64490e446fb398fe4", + "omitted_patch_note": "Informational artifact only \u2014 recording what was excluded from solution.patch + eval_tests.patch. It is NOT a fully applyable diff: Tools/peg_generator/data/xxl.zip is a binary fixture whose content the github API patch field omits, and the NEWS path 'Misc/NEWS.d/next/Core and Builtins/\u2026' contains a literal space which makes git's standard diff quoting non-roundtrippable through na\u00efve text concatenation.", + "solution_patch_note": "Parser/pegen/parse.c (15391 lines, auto-generated by Tools/peg_generator/pegen) is included verbatim from the merge commit c5fc15685202cda73f7c3f5c6f299b0945f58508. The pr_files_cache JSON's patch field for that file is empty because the GitHub API truncates very large diffs; the canonical content was extracted via `git show c5fc1568:Parser/pegen/parse.c` on the local clone.", + "validated_at_note": "\u00a77 invariant confirmed end-to-end on 2026-06-08 after source-symbol cleanup. orig pre-state (base_commit + eval_tests.patch): F2P 0/12 PASSED (12 ERROR \u2014 missing pegen directory for retained TestCParser methods and missing sys.flags.use_peg for inline-gated methods), P2P 54/54 PASSED; orig post-state (base_commit + solution.patch + eval_tests.patch): F2P 12/12 PASSED, P2P 54/54 PASSED, resolved=true. aug pre-state: F2P 0/2 PASSED, P2P 3/3 PASSED; aug post-state: F2P 2/2 PASSED, P2P 3/3 PASSED, resolved=true. union pre-state: F2P 0/14 PASSED (14 ERROR), P2P 57/57 PASSED; union post-state: F2P 14/14 PASSED, P2P 57/57 PASSED, resolved=true. coverage_out/coverage_report_union.json reports complete union coverage 79.4% (7,927 / 9,989 executable source-bearing C lines), above the executable-environment-plan 50% floor. All 54 original P2P method names were AST-walk verified to exist in Lib/test/test_grammar.py + Lib/test/test_ast.py at the merge-parent base_commit a81849b0 before validation. REFRESH 2026-06-17 (selection expansion): f2p_aug.txt grew from 2 to 13 (added 11 pre-existing committed test_peg_generator selectors \u2014 TestCParser test_gather/test_gather_action_ast/test_mutually_left_recursive/test_nasty_mutually_left_recursive and TestPegen test_optional_operator/test_alt_optional_operator/test_repeat_0_simple/test_repeat_1_simple/test_repeat_with_sep_simple/test_lookahead/test_left_recursive) to kill the generator-family survivors. New union counts: aug post F2P 13/13 + P2P 3/3; union post F2P 25/25 + P2P 57/57 (golden green). The mutant set was reduced 37->31 (removed 7 \u00a76-unreachable parse-mode mutants 001/006/007/008/010/038/039). After the \u00a76-clean test_peg_generator selection expansion (golden green: union F2P 25/25, P2P 57/57) and removing 7 PEG-generator-internal mutants unkillable via any cleanly-running \u00a76-eligible committed test in this harness (see augmented.mutant_set_revision), the 24 remaining mutants are all killed by union (12 originally killed + 12 newly killed by the selection expansion). Mutant set reduced 38->24 across the two removals. AUDIT CLEANUP 2026-07-09: eval_tests.patch now localizes non-selected test_pegen implementation imports, and eval_tests_aug.patch uses sys.flags.use_peg plus public ast.parse behavior instead of importing _peg_parser for the selected wrapper; the full docker validation matrix has not been rerun after this metadata-only benchmark cleanup.", + "pr_link": "https://github.com/python/cpython/pull/19503", + "coverage": { + "orig": 74.45, + "aug": 79.36, + "union": 79.36, + "denominator": "union_executable_lines" + } +} diff --git a/cpython_1/tests/report_to_reward.py b/cpython_1/tests/report_to_reward.py new file mode 100644 index 0000000000000000000000000000000000000000..53455a6935ccf17ee2634b5052f0d4d03c8894ea --- /dev/null +++ b/cpython_1/tests/report_to_reward.py @@ -0,0 +1,73 @@ +#!/usr/bin/env python3 +import argparse +import json +from pathlib import Path + + +def rate(bucket): + total = float(bucket.get("total", 0) or 0) + if total <= 0: + return 0.0 + return float(bucket.get("passed", 0) or 0) / total + + +def write_json(path, payload): + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(json.dumps(payload, indent=2, sort_keys=True) + "\n") + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument("--suite", default="union") + parser.add_argument("--missing-patch") + parser.add_argument("--invalid-suite", action="store_true") + parser.add_argument("--runner-rc", type=int, default=0) + parser.add_argument("agent_report") + parser.add_argument("reward_file") + args = parser.parse_args() + + report_path = Path(args.agent_report) + reward_path = Path(args.reward_file) + + if args.invalid_suite: + reward = {"reward": 0.0, "resolved": 0.0, "applied": 0.0, "build_ok": 0.0, "f2p_pass_rate": 0.0, "p2p_pass_rate": 0.0, "harness_ok": 1.0} + sanitized = {"instance_id": "cpython_1", "suite": args.suite, "applied": False, "resolved": False, "error_categories": ["invalid_lolbench_suite"]} + write_json(report_path, sanitized) + write_json(reward_path, reward) + print(f"LoLBench reward=0 invalid suite {args.suite!r}") + return 0 + + if args.missing_patch: + reward = {"reward": 0.0, "resolved": 0.0, "applied": 0.0, "build_ok": 0.0, "f2p_pass_rate": 0.0, "p2p_pass_rate": 0.0, "harness_ok": 1.0} + sanitized = {"instance_id": "cpython_1", "suite": args.suite, "applied": False, "resolved": False, "error_categories": ["missing_solution_patch"]} + write_json(report_path, sanitized) + write_json(reward_path, reward) + print("LoLBench reward=0 missing solution patch") + return 0 + + if not report_path.exists(): + reward = {"reward": 0.0, "resolved": 0.0, "applied": 0.0, "build_ok": 0.0, "f2p_pass_rate": 0.0, "p2p_pass_rate": 0.0, "harness_ok": 0.0} + write_json(reward_path, reward) + print(f"LoLBench reward=0 no agent_report.json runner_rc={args.runner_rc}") + return 0 + + report = json.loads(report_path.read_text()) + build_status = report.get("build", {}).get("status") + resolved = bool(report.get("resolved")) + applied = bool(report.get("applied")) + reward = { + "reward": 1.0 if resolved else 0.0, + "resolved": 1.0 if resolved else 0.0, + "applied": 1.0 if applied else 0.0, + "build_ok": 1.0 if build_status == "ok" else 0.0, + "f2p_pass_rate": rate(report.get("f2p", {})), + "p2p_pass_rate": rate(report.get("p2p", {})), + "harness_ok": 1.0 if args.runner_rc == 0 else 0.0, + } + write_json(reward_path, reward) + print("LoLBench reward={reward} resolved={resolved} f2p={f2p_pass_rate:.3f} p2p={p2p_pass_rate:.3f}".format(**reward)) + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/cpython_1/tests/test.sh b/cpython_1/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..45ba2abd4f682d021752e6966a772a0ee2edb9f5 --- /dev/null +++ b/cpython_1/tests/test.sh @@ -0,0 +1,43 @@ +#!/usr/bin/env bash +set -euo pipefail + +suite=${LOLBENCH_SUITE:-union} +mode=${LOLBENCH_MODE:-eval} +patch=${LOLBENCH_SOLUTION_PATCH:-/logs/artifacts/solution.patch} +private_log=/tmp/lolbench-private-run.log + +mkdir -p /logs/verifier /logs/artifacts /in /out + +case "$suite" in + orig|aug|union) ;; + *) + python3 /tests/report_to_reward.py --suite "$suite" --invalid-suite /out/agent_report.json /logs/verifier/reward.json + exit 0 + ;; +esac + +if [ "$mode" = "eval" ] && [ ! -s "$patch" ]; then + python3 /tests/report_to_reward.py --suite "$suite" --missing-patch "$patch" /out/agent_report.json /logs/verifier/reward.json + exit 0 +fi + +if [ "$mode" = "eval" ]; then + cp "$patch" /in/solution.patch + chmod 0400 /in/solution.patch +fi + +set +e +LOLBENCH_MODE="$mode" LOLBENCH_SUITE="$suite" /opt/lolbench/private/run_tests.sh >"$private_log" 2>&1 +runner_rc=$? +set -e + +cp "$private_log" /logs/verifier/private_run.log +if [ -f /out/grader_report.json ]; then + cp /out/grader_report.json /logs/verifier/grader_report.json +fi + +python3 /tests/report_to_reward.py --suite "$suite" --runner-rc "$runner_rc" /out/agent_report.json /logs/verifier/reward.json + +if [ -f /out/agent_report.json ]; then + cp /out/agent_report.json /logs/verifier/agent_report.json +fi diff --git a/cpython_10/README.md b/cpython_10/README.md new file mode 100644 index 0000000000000000000000000000000000000000..5d35244b8f9044623d17f4064057ba2937026d65 --- /dev/null +++ b/cpython_10/README.md @@ -0,0 +1,87 @@ +# LoLBench Harbor Task: cpython_10 + +This is a Harbor-format LoLBench task generated from `CPython_PEP-695_Type-Parameter-Syntax_PR-103764`. + +Selected source instance: + +- Harbor ID: `cpython_10` +- PR: `python/cpython#103764` +- Base commit: `fdafdc235e74f2f4fedc1f745bf8b90141daa162` +- Test modes: `orig, aug, union` +- Default/canonical mode: `union` +- Harbor image: `smartdub26/lolbench-linux:cpython_10-1.0.0` +- Docker Hub image: `smartdub26/lolbench-linux:cpython_10-1.0.0` + +## Image Setup + +Prefer the published Docker Hub image when it is available. Harbor refers to +the image as `smartdub26/lolbench-linux:cpython_10-1.0.0`, so Docker can pull it +directly when it is not present locally: + +```bash +docker pull smartdub26/lolbench-linux:cpython_10-1.0.0 +``` + +Only if the Docker Hub image is unavailable, build the single task image +locally: + +```bash +docker build -t lolbench/cpython_10:1.0.0 harbor_tasks/cpython_10/environment +docker tag lolbench/cpython_10:1.0.0 smartdub26/lolbench-linux:cpython_10-1.0.0 +``` + +The image contains the processed source tree at the base commit under +`/workspace/cpython`. Harbor must not mount a host source checkout +for the agent. + +## Run an Agent + +```bash +.harbor-venv/bin/harbor run \ + -p harbor_tasks/cpython_10 \ + -a codex \ + -m "" \ + --job-name cpython_10_agent_union \ + --jobs-dir harbor_runs/cpython_10 \ + --no-delete \ + --n-concurrent 1 \ + --ve LOLBENCH_SUITE=union +``` + +After implementing the requirement, the agent must clean any test-file edits +and run: + +```bash +lolbench-submit +``` + +## Evaluate a Patch + +Choose one mode with `LOLBENCH_SUITE=orig`, `aug`, or `union`; if unset, the +task defaults to `union`. + +```bash +PATCH="$(pwd)/path/to/solution.patch" + +.harbor-venv/bin/harbor run \ + -p harbor_tasks/cpython_10 \ + -a oracle \ + --job-name cpython_10_eval_union \ + --jobs-dir harbor_runs/cpython_10 \ + --no-delete \ + --n-concurrent 1 \ + --mounts '[{"type":"bind","source":"'"$PATCH"'","target":"/candidate/solution.patch","read_only":true}]' \ + --ae LOLBENCH_ORACLE_PATCH=/candidate/solution.patch \ + --ve LOLBENCH_SUITE=union +``` + +Outputs: + +```bash +find harbor_runs/cpython_10/cpython_10_eval_union -path '*/verifier/agent_report.json' -print +find harbor_runs/cpython_10/cpython_10_eval_union -path '*/verifier/reward.json' -print +``` + +`tests/docker-compose.yaml` is a verifier-only Harbor overlay. It mounts +`tests/`, `tests/private/`, and `solution/` into the separate verifier +container; none of those paths are mounted into the agent container. diff --git a/cpython_10/environment/Dockerfile b/cpython_10/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..ff51acfbb8157ea08a9b88c49905335b97fbb368 --- /dev/null +++ b/cpython_10/environment/Dockerfile @@ -0,0 +1,135 @@ +# LoLBench eval image: CPython PR-103764 (PEP 695: Type Parameter Syntax) +# Requirement: https://peps.python.org/pep-0695/ +# base_commit: fdafdc235e74f2f4fedc1f745bf8b90141daa162 (parent of squash- +# merge commit 24d8b88420b81fc60aeb0cbcacef1e72d633824a — +# see spec.json base_commit_note) +# +# Agent-facing contract (the agent does NOT run anything inside this image; +# the evaluator runs the container after the agent submits a solution.patch): +# +# docker run --rm \ +# --network=none \ +# -v $(pwd)/solution.patch:/in/solution.patch:ro \ +# -v $(pwd)/out:/out \ +# lolbench/cpython-pr-103764:1 +# +# PEP 695 is the foundational type-parameter syntax PR (the PEP-696 +# `T = default` extension builds on it). It adds three new pieces of +# syntax: `class C[T, *Ts, **P]:`, `def f[T, *Ts, **P]():`, and the +# new `type Alias[T] = ...` type-alias statement. The change is broad: +# - parser: Grammar/python.gram, Parser/Python.asdl, Parser/parser.c, +# Parser/action_helpers.c +# - AST: Python/ast.c, Python-ast.c, ast_opt.c + pycore_ast*.h +# - compile/symtable: Python/compile.c, symtable.c, intrinsics.c +# - opcodes: Python/bytecodes.c + opcode_*.h +# - typing C accelerator: Objects/typevarobject.c (NEW, 1500+ lines), +# Objects/clinic/typevarobject.c.h, Modules/_typingmodule.c +# - object support: Objects/funcobject.c, typeobject.c, object.c, +# unionobject.c +# - lifecycle: Python/pylifecycle.c + assorted pycore_*.h headers +# - Python stdlib: Lib/typing.py, Lib/ast.py, Lib/keyword.py, +# Lib/opcode.py, Lib/importlib/_bootstrap_external.py +# +# No special capabilities are needed. The container stays --network=none +# with the default seccomp profile. +# +# Because the agent's code never executes here, the container runs every +# step as root — no agent UID, no chown of /usr/local, no runuser dance. +# +# Layered build per docs/executable_environment_plan.md §4: +# layer 1: ubuntu:22.04 +# layer 2: lolbench/cpython-base:1 (toolchain + stdlib build deps) +# layer 3: THIS image (cpython @ base_commit + built python + private bundle) + +ARG BASE_IMAGE=lolbench/cpython-base:1 +FROM ${BASE_IMAGE} + +ARG BASE_COMMIT=fdafdc235e74f2f4fedc1f745bf8b90141daa162 + +RUN mkdir -p /opt/lolbench/private /in /out /workspace + +WORKDIR /workspace +RUN git init cpython && \ + cd cpython && \ + git remote add origin https://github.com/python/cpython.git && \ + git fetch --no-tags origin ${BASE_COMMIT} && \ + git checkout ${BASE_COMMIT} && \ + git config user.email lolbench@local && \ + git config user.name lolbench && \ + if ! git diff --quiet || ! git diff --cached --quiet || [ -n "$(git ls-files --others --exclude-standard)" ]; then \ + git add -A && git -c commit.gpgsign=false commit -q -m "LoLBench environment overlay"; \ + fi && \ + git tag -f base && git tag -f lolbench-base && \ + git for-each-ref --format='%(refname)' refs/heads refs/remotes refs/tags | \ + while read ref; do \ + case "$ref" in refs/tags/base|refs/tags/lolbench-base) ;; *) git update-ref -d "$ref" ;; esac; \ + done && \ + ( git remote remove origin 2>/dev/null || true ) && \ + rm -f .git/FETCH_HEAD && \ + git reflog expire --expire=now --all && \ + git repack -Ad && \ + git prune --expire=now && \ + git config --global --add safe.directory /workspace/cpython + +# Pre-build CPython at base_commit. solution.patch touches Grammar/python.gram +# + Parser/Python.asdl, but `make` regenerates the parser tables and Python-ast.c +# from those sources via the standard build rules. No configure.ac / +# Makefile.pre.in / pyconfig.h.in changes — no reconfigure is needed at eval time. +SHELL ["/bin/bash", "-o", "pipefail", "-c"] +RUN cd /workspace/cpython && \ + ./configure --prefix=/usr/local --enable-optimizations=no && \ + jobs=$(awk '$1!="max"{printf("%d", ($1+$2-1)/$2)}' /sys/fs/cgroup/cpu.max 2>/dev/null); \ + : "${jobs:=$(nproc)}"; \ + [ "$jobs" -lt 1 ] && jobs=1; \ + make -j"$jobs" 2>&1 | tee /tmp/cpython-build.log | tail -400 + +# Harbor runtime adapter: keep the image public/agent-safe. +RUN mkdir -p /opt/lolbench /logs/artifacts /logs/agent /logs/verifier /in /out && \ + if ! id -u agent >/dev/null 2>&1; then useradd -m -s /bin/bash agent; fi +COPY metadata.json /opt/lolbench/metadata.json +COPY lolbench-submit /usr/local/bin/lolbench-submit +RUN chmod +x /usr/local/bin/lolbench-submit && \ + git config --global --add safe.directory /workspace/cpython && \ + if [ -d /workspace/cpython/.git ]; then \ + cd /workspace/cpython && git ls-files --others --exclude-standard | sort > /opt/lolbench/base_untracked.txt; \ + else \ + : > /opt/lolbench/base_untracked.txt; \ + fi && \ + chown -R agent:agent /workspace/cpython /logs +# Local-reference hardening: retain only the approved base history. +RUN cd /workspace/cpython && \ + git for-each-ref --format='%(refname)' refs/heads refs/remotes refs/tags | \ + while read ref; do \ + case "$ref" in refs/tags/base|refs/tags/lolbench-base) ;; *) git update-ref -d "$ref" ;; esac; \ + done && \ + ( git remote remove origin 2>/dev/null || true ) && \ + rm -f .git/FETCH_HEAD && \ + git reflog expire --expire=now --all && \ + git repack -Ad && \ + git prune --expire=now && \ + unreachable=$(git fsck --unreachable --no-reflogs) && \ + test -z "$unreachable" && \ + chown -R agent:agent .git +# Remove installed Python source copies/backports and package caches. +RUN for root in /usr/local/lib /usr/lib; do \ + [ ! -d "$root" ] || find "$root" -type d \ + \( -path '*/site-packages/pip' -o -path '*/dist-packages/pip' -o \ + -name ensurepip -o -name tomllib -o -name zoneinfo -o \ + -path '*/site-packages/tomli*' -o -path '*/dist-packages/tomli*' -o \ + -path '*/site-packages/typing_extensions*' -o -path '*/dist-packages/typing_extensions*' -o \ + -path '*/site-packages/exceptiongroup*' -o -path '*/dist-packages/exceptiongroup*' \) \ + -prune -exec rm -rf '{}' +; \ + [ ! -d "$root" ] || find "$root" -type f \ + \( -name 'tomli*.py' -o -name 'typing_extensions*.py' -o -name 'exceptiongroup*.py' \) -delete; \ + done && \ + rm -rf /usr/share/python-wheels /usr/share/python3-wheels \ + /root/.cache/pip /root/.cache/uv /home/agent/.cache/pip /home/agent/.cache/uv && \ + rm -f /usr/local/bin/pip /usr/local/bin/pip3 /usr/local/bin/pip3.* \ + /usr/bin/pip /usr/bin/pip3 /usr/bin/pip3.* && \ + for p in /usr/local/lib/python*/site-packages /usr/lib/python*/dist-packages; do \ + [ ! -d "$p" ] || { chown -R root:root "$p"; chmod -R go-w "$p"; chmod 0711 "$p"; }; \ + done +USER agent +WORKDIR /workspace/cpython +ENV LOLBENCH_INSTANCE_ID=cpython_10 +ENV LOLBENCH_SOURCE_SLUG=CPython_PEP-695_Type-Parameter-Syntax_PR-103764 diff --git a/cpython_10/environment/docker-compose.yaml b/cpython_10/environment/docker-compose.yaml new file mode 100644 index 0000000000000000000000000000000000000000..7ed45f87dc9faf9df284f5b10d6d2289781ff254 --- /dev/null +++ b/cpython_10/environment/docker-compose.yaml @@ -0,0 +1,3 @@ +services: + main: + pull_policy: missing diff --git a/cpython_10/environment/lolbench-submit b/cpython_10/environment/lolbench-submit new file mode 100644 index 0000000000000000000000000000000000000000..0f89163f3f975ed8856ef411059c188c40e2eabc --- /dev/null +++ b/cpython_10/environment/lolbench-submit @@ -0,0 +1,32 @@ +#!/usr/bin/env bash +set -euo pipefail + +repo=${1:-$PWD} +out=${LOLBENCH_PATCH_OUT:-/logs/artifacts/solution.patch} + +mkdir -p "$(dirname "$out")" +cd "$repo" + +baseline=/opt/lolbench/base_untracked.txt +current=$(mktemp) +new_files=$(mktemp) +trap 'rm -f "$current" "$new_files"' EXIT + +git ls-files --others --exclude-standard | sort > "$current" +if [ -f "$baseline" ]; then + comm -13 "$baseline" "$current" > "$new_files" +else + cp "$current" "$new_files" +fi + +if [ -s "$new_files" ]; then + xargs -r git add -N -- < "$new_files" +fi + +git diff --binary > "$out" + +if [ ! -s "$out" ]; then + echo "warning: wrote an empty solution patch to $out" >&2 +else + echo "wrote solution patch to $out" +fi diff --git a/cpython_10/environment/metadata.json b/cpython_10/environment/metadata.json new file mode 100644 index 0000000000000000000000000000000000000000..4661c87feefaddd89e0210072313ec2ce9971e4f --- /dev/null +++ b/cpython_10/environment/metadata.json @@ -0,0 +1,22 @@ +{ + "instance_id": "cpython_10", + "source_instance_id": "CPython_PEP-695_Type-Parameter-Syntax_PR-103764", + "source_slug": "CPython_PEP-695_Type-Parameter-Syntax_PR-103764", + "docker_slug": "CPython_PEP-695_Type-Parameter-Syntax_PR-103764", + "dockerhub_image": "smartdub26/lolbench-linux:cpython_10-1.0.0", + "project": "cpython", + "repo": "python/cpython", + "requirement_doc": "https://peps.python.org/pep-0695/", + "pr_link": "https://github.com/python/cpython/pull/103764", + "base_commit": "fdafdc235e74f2f4fedc1f745bf8b90141daa162", + "merge_commit": "24d8b88420b81fc60aeb0cbcacef1e72d633824a", + "source_history_policy": "ancestors-only", + "lolbench_test_modes": [ + "orig", + "aug", + "union" + ], + "default_lolbench_suite": "union", + "canonical_lolbench_suite": "union", + "augmentation_available": true +} diff --git a/cpython_10/environment/source_audit.json b/cpython_10/environment/source_audit.json new file mode 100644 index 0000000000000000000000000000000000000000..e1e9017050d7bda685ead5070190c30a53dd5e9d --- /dev/null +++ b/cpython_10/environment/source_audit.json @@ -0,0 +1,7 @@ +{ + "source_policy": "dockerfile_fetch_pruned_ancestor_history", + "local_reference_policy": "auxiliary_sources_removed_execute_only", + "base_commit": "fdafdc235e74f2f4fedc1f745bf8b90141daa162", + "repo": "python/cpython", + "note": "The Dockerfile fetches only the declared base history, removes refs/remotes/reflogs, repacks and prunes unreachable objects, asserts that git fsck finds no unreachable object, removes auxiliary reference sources, and makes remaining auxiliary toolchains root-owned and non-enumerable to the agent." +} diff --git a/cpython_10/instruction.md b/cpython_10/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..20b28d27717dd7a4669a443e88ffd50b06c6ce6d --- /dev/null +++ b/cpython_10/instruction.md @@ -0,0 +1,1150 @@ +You are working in `/workspace/cpython`, a source tree checked out at +the base commit for this task. Implement the requested behavior in the source +tree, then run: + +```bash +lolbench-submit +``` + +Do not stop after editing files, running tests, or describing the solution. The +task is complete only when `lolbench-submit` has created +`/logs/artifacts/solution.patch`. If that file does not exist, continue +working and run `lolbench-submit` again. + +That command writes your implementation diff to +`/logs/artifacts/solution.patch`, which is the artifact the Harbor verifier +will grade. Before running `lolbench-submit`, clean or revert any test files +you created or modified; test files must not be included in the final +`solution.patch`. + +This environment has no outbound internet access — `curl`/`wget`, `git fetch`/`clone`, package installs, and web fetch/search will all fail. Implement the requirements using only the code already in the workspace and your own knowledge; do not attempt to fetch or search external resources. + +Now please implement the following requirements in the source tree: + +--- + +## Abstract +This PEP specifies an improved syntax for specifying type parameters within +a generic class, function, or type alias. It also introduces a new statement +for declaring type aliases. + +## Motivation +PEP 484 introduced type variables into the language. PEP 612 built +upon this concept by introducing parameter specifications, and +PEP 646 added variadic type variables. + +While generic types and type parameters have grown in popularity, the +syntax for specifying type parameters still feels "bolted on" to Python. +This is a source of confusion among Python developers. + +There is consensus within the Python static typing community that it is time +to provide a formal syntax that is similar to other modern programming +languages that support generic types. + +An analysis of 25 popular typed Python libraries revealed that type +variables (in particular, the `typing.TypeVar` symbol) were used in +14% of modules. + +### Points of Confusion +While the use of type variables has become widespread, the manner in which +they are specified within code is the source of confusion among many +Python developers. There are a couple of factors that contribute to this +confusion. + +The scoping rules for type variables are difficult to understand. Type +variables are typically allocated within the global scope, but their semantic +meaning is valid only when used within the context of a generic class, +function, or type alias. A single runtime instance of a type variable may be +reused in multiple generic contexts, and it has a different semantic meaning +in each of these contexts. This PEP proposes to eliminate this source of +confusion by declaring type parameters at a natural place within a class, +function, or type alias declaration statement. + +Generic type aliases are often misused because it is not clear to developers +that a type argument must be supplied when the type alias is used. This leads +to an implied type argument of `Any`, which is rarely the intent. This PEP +proposes to add new syntax that makes generic type alias declarations +clear. + +PEP 483 and PEP 484 introduced the concept of "variance" for a type +variable used within a generic class. Type variables can be invariant, +covariant, or contravariant. The concept of variance is an advanced detail +of type theory that is not well understood by most Python developers, yet +they must confront this concept today when defining their first generic +class. This PEP largely eliminates the need for most developers +to understand the concept of variance when defining generic classes. + +When more than one type parameter is used with a generic class or type alias, +the rules for type parameter ordering can be confusing. It is normally based on +the order in which they first appear within a class or type alias declaration +statement. However, this can be overridden in a class definition by +including a "Generic" or "Protocol" base class. For example, in the class +declaration `class ClassA(Mapping[K, V])`, the type parameters are +ordered as `K` and then `V`. However, in the class declaration +`class ClassB(Mapping[K, V], Generic[V, K])`, the type parameters are +ordered as `V` and then `K`. This PEP proposes to make type parameter +ordering explicit in all cases. + +The practice of sharing a type variable across multiple generic contexts +creates other problems today. Modern editors provide features like "find +all references" and "rename all references" that operate on symbols at the +semantic level. When a type parameter is shared among multiple generic +classes, functions, and type aliases, all references are semantically +equivalent. + +Type variables defined within the global scope also need to be given a name +that starts with an underscore to indicate that the variable is private to +the module. Globally-defined type variables are also often given names to +indicate their variance, leading to cumbersome names like "_T_contra" and +"_KT_co". The current mechanisms for allocating type variables also requires +the developer to supply a redundant name in quotes (e.g. `T = TypeVar("T")`). +This PEP eliminates the need for the redundant name and cumbersome +variable names. + +Defining type parameters today requires importing the `TypeVar` and +`Generic` symbols from the `typing` module. Over the past several releases +of Python, efforts have been made to eliminate the need to import `typing` +symbols for common use cases, and the PEP furthers this goal. + +## Summary Examples +Defining a generic class prior to this PEP looks something like this. + +``` +from typing import Generic, TypeVar + +_T_co = TypeVar("_T_co", covariant=True, bound=str) + +class ClassA(Generic[_T_co]): + def method1(self) -> _T_co: + ... +``` +With the new syntax, it looks like this. + +``` +class ClassA[T: str]: + def method1(self) -> T: + ... +``` +Here is an example of a generic function today. + +``` +from typing import TypeVar + +_T = TypeVar("_T") + +def func(a: _T, b: _T) -> _T: + ... +``` +And the new syntax. + +``` +def func[T](a: T, b: T) -> T: + ... +``` +Here is an example of a generic type alias today. + +``` +from typing import TypeAlias + +_T = TypeVar("_T") + +ListOrSet: TypeAlias = list[_T] | set[_T] +``` +And with the new syntax. + +``` +type ListOrSet[T] = list[T] | set[T] +``` +## Specification +### Type Parameter Declarations +Here is a new syntax for declaring type parameters for generic +classes, functions, and type aliases. The syntax adds support for +a comma-delimited list of type parameters in square brackets after +the name of the class, function, or type alias. + +Simple (non-variadic) type variables are declared with an unadorned name. +Variadic type variables are preceded by `*` (see PEP 646 for details). +Parameter specifications are preceded by `**` (see PEP 612 for details). + +``` +## This generic class is parameterized by a TypeVar T, a +## TypeVarTuple Ts, and a ParamSpec P. +class ChildClass[T, *Ts, **P]: ... +``` +There is no need to include `Generic` as a base class. Its inclusion as +a base class is implied by the presence of type parameters, and it will +automatically be included in the `__mro__` and `__orig_bases__` attributes +for the class. The explicit use of a `Generic` base class will result in a +runtime error. + +``` +class ClassA[T](Generic[T]): ... # Runtime error +``` +A `Protocol` base class with type arguments may generate a runtime +error. Type checkers should generate an error in this case because +the use of type arguments is not needed, and the order of type parameters +for the class are no longer dictated by their order in the `Protocol` +base class. + +``` +class ClassA[S, T](Protocol): ... # OK + +class ClassB[S, T](Protocol[S, T]): ... # Recommended type checker error +``` +Type parameter names within a generic class, function, or type alias must be +unique within that same class, function, or type alias. A duplicate name +generates a syntax error at compile time. This is consistent with the +requirement that parameter names within a function signature must be unique. + +``` +class ClassA[T, *T]: ... # Syntax Error + +def func1[T, **T](): ... # Syntax Error +``` +Class type parameter names are mangled if they begin with a double +underscore, to avoid complicating the name lookup mechanism for names used +within the class. However, the `__name__` attribute of the type parameter +will hold the non-mangled name. + +### Upper Bound Specification +For a non-variadic type parameter, an "upper bound" type can be specified +through the use of a type annotation expression. If an upper bound is +not specified, the upper bound is assumed to be `object`. + +``` +class ClassA[T: str]: ... +``` +The specified upper bound type must use an expression form that is allowed in +type annotations. More complex expression forms should be flagged +as an error by a type checker. Quoted forward references are allowed. + +The specified upper bound type must be concrete. An attempt to use a generic +type should be flagged as an error by a type checker. This is consistent with +the existing rules enforced by type checkers for a `TypeVar` constructor call. + +``` +class ClassA[T: dict[str, int]]: ... # OK + +class ClassB[T: "ForwardReference"]: ... # OK + +class ClassC[V]: + class ClassD[T: dict[str, V]]: ... # Type checker error: generic type + +class ClassE[T: [str, int]]: ... # Type checker error: illegal expression form +``` +### Constrained Type Specification +PEP 484 introduced the concept of a "constrained type variable" which is +constrained to a set of two or more types. The new syntax supports this type +of constraint through the use of a literal tuple expression that contains +two or more types. + +``` +class ClassA[AnyStr: (str, bytes)]: ... # OK + +class ClassB[T: ("ForwardReference", bytes)]: ... # OK + +class ClassC[T: ()]: ... # Type checker error: two or more types required + +class ClassD[T: (str, )]: ... # Type checker error: two or more types required + +t1 = (bytes, str) +class ClassE[T: t1]: ... # Type checker error: literal tuple expression required +``` +If the specified type is not a tuple expression or the tuple expression includes +complex expression forms that are not allowed in a type annotation, a type +checker should generate an error. Quoted forward references are allowed. + +``` +class ClassF[T: (3, bytes)]: ... # Type checker error: invalid expression form +``` +The specified constrained types must be concrete. An attempt to use a generic +type should be flagged as an error by a type checker. This is consistent with +the existing rules enforced by type checkers for a `TypeVar` constructor call. + +``` +class ClassG[T: (list[S], str)]: ... # Type checker error: generic type +``` +### Runtime Representation of Bounds and Constraints +The upper bounds and constraints of `TypeVar` objects are accessible at +runtime through the `__bound__` and `__constraints__` attributes. +For `TypeVar` objects defined through the new syntax, these attributes +become lazily evaluated, as discussed under `Lazy Evaluation`_ below. + +### Generic Type Alias +We propose to introduce a new statement for declaring type aliases. Similar +to `class` and `def` statements, a `type` statement defines a scope +for type parameters. + +``` +## A non-generic type alias +type IntOrStr = int | str + +## A generic type alias +type ListOrSet[T] = list[T] | set[T] +``` +Type aliases can refer to themselves without the use of quotes. + +``` +## A type alias that includes a forward reference +type AnimalOrVegetable = Animal | "Vegetable" + +## A generic self-referential type alias +type RecursiveList[T] = T | list[RecursiveList[T]] +``` +The `type` keyword is a new soft keyword. It is interpreted as a keyword +only in this part of the grammar. In all other locations, it is assumed to +be an identifier name. + +Type parameters declared as part of a generic type alias are valid only +when evaluating the right-hand side of the type alias. + +As with `typing.TypeAlias`, type checkers should restrict the right-hand +expression to expression forms that are allowed within type annotations. +The use of more complex expression forms (call expressions, ternary operators, +arithmetic operators, comparison operators, etc.) should be flagged as an +error. + +Type alias expressions are not allowed to use traditional type variables (i.e. +those allocated with an explicit `TypeVar` constructor call). Type checkers +should generate an error in this case. + +``` +T = TypeVar("T") +type MyList = list[T] # Type checker error: traditional type variable usage +``` +We propose to deprecate the existing `typing.TypeAlias` introduced in +PEP 613. The new syntax eliminates its need entirely. + +### Runtime Type Alias Class +At runtime, a `type` statement will generate an instance of +`typing.TypeAliasType`. This class represents the type. Its attributes +include: + +* `__name__` is a str representing the name of the type alias +* `__type_params__` is a tuple of `TypeVar`, `TypeVarTuple`, or + `ParamSpec` objects that parameterize the type alias if it is generic +* `__value__` is the evaluated value of the type alias + +All of these attributes are read-only. + +The value of the type alias is evaluated lazily (see `Lazy Evaluation`_ below). + +### Type Parameter Scopes +When the new syntax is used, a new lexical scope is introduced, and this scope +includes the type parameters. Type parameters can be accessed by name +within inner scopes. As with other symbols in Python, an inner scope can +define its own symbol that overrides an outer-scope symbol of the same name. +This section provides a verbal description of the new scoping rules. +The `Scoping Behavior`_ section below specifies the behavior in terms +of a translation to near-equivalent existing Python code. + +Type parameters are visible to other +type parameters declared elsewhere in the list. This allows type parameters +to use other type parameters within their definition. While there is currently +no use for this capability, it preserves the ability in the future to support +upper bound expressions or type argument defaults that depend on earlier +type parameters. + +A compiler error or runtime exception is generated if the definition of an +earlier type parameter references a later type parameter even if the name is +defined in an outer scope. + +``` +## The following generates no compiler error, but a type checker +## should generate an error because an upper bound type must be concrete, +## and `Sequence[S]` is generic. Future extensions to the type system may +## eliminate this limitation. +class ClassA[S, T: Sequence[S]]: ... + +## The following generates no compiler error, because the bound for `S` +## is lazily evaluated. However, type checkers should generate an error. +class ClassB[S: Sequence[T], T]: ... +``` +A type parameter declared as part of a generic class is valid within the +class body and inner scopes contained therein. Type parameters are also +accessible when evaluating the argument list (base classes and any keyword +arguments) that comprise the class definition. This allows base classes +to be parameterized by these type parameters. Type parameters are not +accessible outside of the class body, including class decorators. + +``` +class ClassA[T](BaseClass[T], param = Foo[T]): ... # OK + +print(T) # Runtime error: 'T' is not defined + +@dec(Foo[T]) # Runtime error: 'T' is not defined +class ClassA[T]: ... +``` +A type parameter declared as part of a generic function is valid within +the function body and any scopes contained therein. It is also valid within +parameter and return type annotations. Default argument values for function +parameters are evaluated outside of this scope, so type parameters are +not accessible in default value expressions. Likewise, type parameters are not +in scope for function decorators. + +``` +def func1[T](a: T) -> T: ... # OK + +print(T) # Runtime error: 'T' is not defined + +def func2[T](a = list[T]): ... # Runtime error: 'T' is not defined + +@dec(list[T]) # Runtime error: 'T' is not defined +def func3[T](): ... +``` +A type parameter declared as part of a generic type alias is valid within +the type alias expression. + +``` +type Alias1[K, V] = Mapping[K, V] | Sequence[K] +``` +Type parameter symbols defined in outer scopes cannot be bound with +`nonlocal` statements in inner scopes. + +``` +S = 0 + +def outer1[S](): + S = 1 + T = 1 + + def outer2[T](): + + def inner1(): + nonlocal S # OK because it binds variable S from outer1 + nonlocal T # Syntax error: nonlocal binding not allowed for type parameter + + def inner2(): + global S # OK because it binds variable S from global scope +``` +The lexical scope introduced by the new type parameter syntax is unlike +traditional scopes introduced by a `def` or `class` statement. A type +parameter scope acts more like a temporary "overlay" to the containing scope. +The only new symbols contained +within its symbol table are the type parameters defined using the new syntax. +References to all other symbols are treated as though they were found within +the containing scope. This allows base class lists (in class definitions) and +type annotation expressions (in function definitions) to reference symbols +defined in the containing scope. + +``` +class Outer: + class Private: + pass + + # If the type parameter scope was like a traditional scope, + # the base class 'Private' would not be accessible here. + class Inner[T](Private, Sequence[T]): + pass + + # Likewise, 'Inner' would not be available in these type annotations. + def method1[T](self, a: Inner[T]) -> Inner[T]: + return a +``` +The compiler allows inner scopes to define a local symbol that overrides an +outer-scoped type parameter. + +Consistent with the scoping rules defined in PEP 484, type checkers should +generate an error if inner-scoped generic classes, functions, or type aliases +reuse the same type parameter name as an outer scope. + +``` +T = 0 + +@decorator(T) # Argument expression `T` evaluates to 0 +class ClassA[T](Sequence[T]): + T = 1 + + # All methods below should result in a type checker error + # "type parameter 'T' already in use" because they are using the + # type parameter 'T', which is already in use by the outer scope + # 'ClassA'. + def method1[T](self): + ... + + def method2[T](self, x = T): # Parameter 'x' gets default value of 1 + ... + + def method3[T](self, x: T): # Parameter 'x' has type T (scoped to method3) + ... +``` +Symbols referenced in inner scopes are resolved using existing rules except +that type parameter scopes are also considered during name resolution. + +``` +T = 0 + +## T refers to the global variable +print(T) # Prints 0 + +class Outer[T]: + T = 1 + + # T refers to the local variable scoped to class 'Outer' + print(T) # Prints 1 + + class Inner1: + T = 2 + + # T refers to the local type variable within 'Inner1' + print(T) # Prints 2 + + def inner_method(self): + # T refers to the type parameter scoped to class 'Outer'; + # If 'Outer' did not use the new type parameter syntax, + # this would instead refer to the global variable 'T' + print(T) # Prints 'T' + + def outer_method(self): + T = 3 + + # T refers to the local variable within 'outer_method' + print(T) # Prints 3 + + def inner_func(): + # T refers to the variable captured from 'outer_method' + print(T) # Prints 3 +``` +When the new type parameter syntax is used for a generic class, assignment +expressions are not allowed within the argument list for the class definition. +Likewise, with functions that use the new type parameter syntax, assignment +expressions are not allowed within parameter or return type annotations, nor +are they allowed within the expression that defines a type alias, or within +the bounds and constraints of a `TypeVar`. Similarly, `yield`, `yield from`, +and `await` expressions are disallowed in these contexts. + +This restriction is necessary because expressions evaluated within the +new lexical scope should not introduce symbols within that scope other than +the defined type parameters, and should not affect whether the enclosing function +is a generator or coroutine. + +``` +class ClassA[T]((x := Sequence[T])): ... # Syntax error: assignment expression not allowed + +def func1[T](val: (x := int)): ... # Syntax error: assignment expression not allowed + +def func2[T]() -> (x := Sequence[T]): ... # Syntax error: assignment expression not allowed + +type Alias1[T] = (x := list[T]) # Syntax error: assignment expression not allowed +``` +### Accessing Type Parameters at Runtime +A new attribute called `__type_params__` is available on generic classes, +functions, and type aliases. This attribute is a tuple of the +type parameters that parameterize the class, function, or alias. +The tuple contains `TypeVar`, `ParamSpec`, and `TypeVarTuple` instances. + +Type parameters declared using the new syntax will not appear within the +dictionary returned by `globals()` or `locals()`. + +### Variance Inference +This PEP eliminates the need for variance to be specified for type +parameters. Instead, type checkers will infer the variance of type parameters +based on their usage within a class. Type parameters are inferred to be +invariant, covariant, or contravariant depending on how they are used. + +Python type checkers already include the ability to determine the variance of +type parameters for the purpose of validating variance within a generic +protocol class. This capability can be used for all classes (whether or not +they are protocols) to calculate the variance of each type parameter. + +The algorithm for computing the variance of a type parameter is as follows. + +For each type parameter in a generic class: + +1. If the type parameter is variadic (`TypeVarTuple`) or a parameter +specification (`ParamSpec`), it is always considered invariant. No further +inference is needed. + +2. If the type parameter comes from a traditional `TypeVar` declaration and +is not specified as `infer_variance` (see below), its variance is specified +by the `TypeVar` constructor call. No further inference is needed. + +3. Create two specialized versions of the class. We'll refer to these as +`upper` and `lower` specializations. In both of these specializations, +replace all type parameters other than the one being inferred by a dummy type +instance (a concrete anonymous class that is type compatible with itself and +assumed to meet the bounds or constraints of the type parameter). In +the `upper` specialized class, specialize the target type parameter with +an `object` instance. This specialization ignores the type parameter's +upper bound or constraints. In the `lower` specialized class, specialize +the target type parameter with itself (i.e. the corresponding type argument +is the type parameter itself). + +4. Determine whether `lower` can be assigned to `upper` using normal type +compatibility rules. If so, the target type parameter is covariant. If not, +determine whether `upper` can be assigned to `lower`. If so, the target +type parameter is contravariant. If neither of these combinations are +assignable, the target type parameter is invariant. + +Here is an example. + +``` +class ClassA[T1, T2, T3](list[T1]): + def method1(self, a: T2) -> None: + ... + + def method2(self) -> T3: + ... +``` +To determine the variance of `T1`, we specialize `ClassA` as follows: + +``` +upper = ClassA[object, Dummy, Dummy] +lower = ClassA[T1, Dummy, Dummy] +``` +We find that `upper` is not assignable to `lower` using normal type +compatibility rules defined in PEP 484. Likewise, `lower` is not assignable +to `upper`, so we conclude that `T1` is invariant. + +To determine the variance of `T2`, we specialize `ClassA` as follows: + +``` +upper = ClassA[Dummy, object, Dummy] +lower = ClassA[Dummy, T2, Dummy] +``` +Since `upper` is assignable to `lower`, `T2` is contravariant. + +To determine the variance of `T3`, we specialize `ClassA` as follows: + +``` +upper = ClassA[Dummy, Dummy, object] +lower = ClassA[Dummy, Dummy, T3] +``` +Since `lower` is assignable to `upper`, `T3` is covariant. + +### Auto Variance For TypeVar +The existing `TypeVar` class constructor accepts keyword parameters named +`covariant` and `contravariant`. If both of these are `False`, the +type variable is assumed to be invariant. We propose to add another keyword +parameter named `infer_variance` indicating that a type checker should use +inference to determine whether the type variable is invariant, covariant or +contravariant. A corresponding instance variable `__infer_variance__` can be +accessed at runtime to determine whether the variance is inferred. Type +variables that are implicitly allocated using the new syntax will always +have `__infer_variance__` set to `True`. + +A generic class that uses the traditional syntax may include combinations of +type variables with explicit and inferred variance. + +``` +T1 = TypeVar("T1", infer_variance=True) # Inferred variance +T2 = TypeVar("T2") # Invariant +T3 = TypeVar("T3", covariant=True) # Covariant + +## A type checker should infer the variance for T1 but use the +## specified variance for T2 and T3. +class ClassA(Generic[T1, T2, T3]): ... +``` +### Compatibility with Traditional TypeVars +The existing mechanism for allocating `TypeVar`, `TypeVarTuple`, and +`ParamSpec` is retained for backward compatibility. However, these +"traditional" type variables should not be combined with type parameters +allocated using the new syntax. Such a combination should be flagged as +an error by type checkers. This is necessary because the type parameter +order is ambiguous. + +It is OK to combine traditional type variables with new-style type parameters +if the class, function, or type alias does not use the new syntax. The +new-style type parameters must come from an outer scope in this case. + +``` +K = TypeVar("K") + +class ClassA[V](dict[K, V]): ... # Type checker error + +class ClassB[K, V](dict[K, V]): ... # OK + +class ClassC[V]: + # The use of K and V for "method1" is OK because it uses the + # "traditional" generic function mechanism where type parameters + # are implicit. In this case V comes from an outer scope (ClassC) + # and K is introduced implicitly as a type parameter for "method1". + def method1(self, a: V, b: K) -> V | K: ... + + # The use of M and K are not allowed for "method2". A type checker + # should generate an error in this case because this method uses the + # new syntax for type parameters, and all type parameters associated + # with the method must be explicitly declared. In this case, `K` + # is not declared by "method2", nor is it supplied by a new-style + # type parameter defined in an outer scope. + def method2[M](self, a: M, b: K) -> M | K: ... +``` +## Runtime Implementation +### Grammar Changes +This PEP introduces a new soft keyword `type`. It modifies the grammar +in the following ways: + +1. Addition of optional type parameter clause in `class` and `def` statements. + +``` +type_params[asdl_typeparam_seq*]: '[' t=type_param_seq ']' + +type_param_seq: a[asdl_typeparam_seq*]=','.type_param+ [','] + +type_param: + | a=NAME b=[type_param_bound] + | '*' a=NAME + | '**' a=NAME + +type_param_bound: ":" e=expression + +## Grammar definitions for class_def_raw and function_def_raw are modified +## to reference type_params as an optional syntax element. The definitions +## of class_def_raw and function_def_raw are simplified here for brevity. + +class_def_raw: 'class' n=NAME t=[type_params] ... + +function_def_raw: a=[ASYNC] 'def' n=NAME t=[type_params] ... +``` +2. Addition of new `type` statement for defining type aliases. + +``` +type_alias: "type" n=NAME t=[type_params] '=' b=expression +``` +### AST Changes +This PEP introduces a new AST node type called `TypeAlias`. + +``` +TypeAlias(expr name, typeparam* typeparams, expr value) +``` +It also adds an AST node type that represents a type parameter. + +``` +typeparam = TypeVar(identifier name, expr? bound) + | ParamSpec(identifier name) + | TypeVarTuple(identifier name) +``` +Bounds and constraints are represented identically in the AST. In the implementation, +any expression that is a `Tuple` AST node is treated as a constraint, and any other +expression is treated as a bound. + +It also modifies existing AST node types `FunctionDef`, `AsyncFunctionDef` +and `ClassDef` to include an additional optional attribute called +`typeparams` that includes a list of type parameters associated with the +function or class. + +### Lazy Evaluation +This PEP introduces three new contexts where expressions may occur that represent +static types: `TypeVar` bounds, `TypeVar` constraints, and the value of type +aliases. These expressions may contain references to names +that are not yet defined. For example, type aliases may be recursive, or even mutually +recursive, and type variable bounds may refer back to the current class. If these +expressions were evaluated eagerly, users would need to enclose such expressions in +quotes to prevent runtime errors. PEP 563 and PEP 649 detail the problems with +this situation for type annotations. + +To prevent a similar situation with the new syntax proposed in this PEP, we propose +to use lazy evaluation for these expressions, similar to the approach in PEP 649. +Specifically, each expression will be saved in a code object, and the code object +is evaluated only when the corresponding attribute is accessed (`TypeVar.__bound__`, +`TypeVar.__constraints__`, or `TypeAlias.__value__`). After the value is +successfully evaluated, the value is saved and later calls will return the same value +without re-evaluating the code object. + +If PEP 649 is implemented, additional evaluation mechanisms should be added to +mirror the options that PEP provides for annotations. In the current version of the +PEP, that might include adding an `__evaluate_bound__` method to `TypeVar` taking +a `format` parameter with the same meaning as in PEP 649's `__annotate__` method +(and a similar `__evaluate_constraints__` method, as well as an `__evaluate_value__` +method on `TypeAliasType`). +However, until PEP 649 is accepted and implemented, only the default evaluation format +(PEP 649's "VALUE" format) will be supported. + +As a consequence of lazy evaluation, the value observed for an attribute may +depend on the time the attribute is accessed. + +``` +X = int + +class Foo[T: X, U: X]: + t, u = T, U + +print(Foo.t.__bound__) # prints "int" +X = str +print(Foo.u.__bound__) # prints "str" +``` +Similar examples affecting type annotations can be constructed using the +semantics of PEP 563 or PEP 649. + +A naive implementation of lazy evaluation would handle class namespaces +incorrectly, because functions within a class do not normally have access to +the enclosing class namespace. The implementation will retain a reference to +the class namespace so that class-scoped names are resolved correctly. + +### Scoping Behavior +The new syntax requires a new kind of scope that behaves differently +from existing scopes in Python. Thus, the new syntax cannot be described exactly in terms of +existing Python scoping behavior. This section specifies these scopes +further by reference to existing scoping behavior: the new scopes behave +like function scopes, except for a number of minor differences listed below. + +All examples include functions introduced with the pseudo-keyword `def695`. +This keyword will not exist in the actual language; it is used to +clarify that the new scopes are for the most part like function scopes. + +`def695` scopes differ from regular function scopes in the following ways: + +- If a `def695` scope is immediately within a class scope, or within another + `def695` scope that is immediately within a class scope, then names defined + in that class scope can be accessed within the `def695` scope. (Regular functions, + by contrast, cannot access names defined within an enclosing class scope.) +- The following constructs are disallowed directly within a `def695` scope, though + they may be used within other scopes nested inside a `def695` scope: + + - `yield` + - `yield from` + - `await` + - `:=` (walrus operator) + +- The qualified name (`__qualname__`) of objects (classes and functions) defined within `def695` scopes + is as if the objects were defined within the closest enclosing scope. +- Names bound within `def695` scopes cannot be rebound with a `nonlocal` statement in nested scopes. + +`def695` scopes are used for the evaluation of several new syntactic constructs proposed +in this PEP. Some are evaluated eagerly (when a type alias, function, or class is defined); others are +evaluated lazily (only when evaluation is specifically requested). In all cases, the scoping semantics are identical: + +- Eagerly evaluated values: + + - The type parameters of generic type aliases + - The type parameters and annotations of generic functions + - The type parameters and base class expressions of generic classes +- Lazily evaluated values: + + - The value of generic type aliases + - The bounds of type variables + - The constraints of type variables + +In the below translations, names that start with two underscores are internal to the implementation +and not visible to actual Python code. We use the following intrinsic functions, which in the real +implementation are defined directly in the interpreter: + +- `__make_typealias(*, name, type_params=(), evaluate_value)`: Creates a new `typing.TypeAlias` object with the given + name, type parameters, and lazily evaluated value. The value is not evaluated until the `__value__` attribute + is accessed. +- `__make_typevar_with_bound(*, name, evaluate_bound)`: Creates a new `typing.TypeVar` object with the given + name and lazily evaluated bound. The bound is not evaluated until the `__bound__` attribute is accessed. +- `__make_typevar_with_constraints(*, name, evaluate_constraints)`: Creates a new `typing.TypeVar` object with the given + name and lazily evaluated constraints. The constraints are not evaluated until the `__constraints__` attribute + is accessed. + +Non-generic type aliases are translated as follows: + +``` +type Alias = int +``` +Equivalent to: + +``` +def695 __evaluate_Alias(): + return int + +Alias = __make_typealias(name='Alias', evaluate_value=__evaluate_Alias) +``` +Generic type aliases: + +``` +type Alias[T: int] = list[T] +``` +Equivalent to: + +``` +def695 __generic_parameters_of_Alias(): + def695 __evaluate_T_bound(): + return int + T = __make_typevar_with_bound(name='T', evaluate_bound=__evaluate_T_bound) + + def695 __evaluate_Alias(): + return list[T] + return __make_typealias(name='Alias', type_params=(T,), evaluate_value=__evaluate_Alias) + +Alias = __generic_parameters_of_Alias() +``` +Generic functions: + +``` +def f[T](x: T) -> T: + return x +``` +Equivalent to: + +``` +def695 __generic_parameters_of_f(): + T = typing.TypeVar(name='T') + + def f(x: T) -> T: + return x + f.__type_params__ = (T,) + return f + +f = __generic_parameters_of_f() +``` +A fuller example of generic functions, illustrating the scoping behavior of defaults, decorators, and bounds. +Note that this example does not use `ParamSpec` correctly, so it should be rejected by a static type checker. +It is however valid at runtime, and it us used here to illustrate the runtime semantics. + +``` +@decorator +def f[T: int, U: (int, str), *Ts, **P]( + x: T = SOME_CONSTANT, + y: U, + *args: *Ts, + **kwargs: P.kwargs, +) -> T: + return x +``` +Equivalent to: + +``` +__default_of_x = SOME_CONSTANT # evaluated outside the def695 scope +def695 __generic_parameters_of_f(): + def695 __evaluate_T_bound(): + return int + T = __make_typevar_with_bound(name='T', evaluate_bound=__evaluate_T_bound) + + def695 __evaluate_U_constraints(): + return (int, str) + U = __make_typevar_with_constraints(name='U', evaluate_constraints=__evaluate_U_constraints) + + Ts = typing.TypeVarTuple("Ts") + P = typing.ParamSpec("P") + + def f(x: T = __default_of_x, y: U, *args: *Ts, **kwargs: P.kwargs) -> T: + return x + f.__type_params__ = (T, U, Ts, P) + return f + +f = decorator(__generic_parameters_of_f()) +``` +Generic classes: + +``` +class C[T](Base): + def __init__(self, x: T): + self.x = x +``` +Equivalent to: + +``` +def695 __generic_parameters_of_C(): + T = typing.TypeVar('T') + class C(Base): + __type_params__ = (T,) + def __init__(self, x: T): + self.x = x + return C + +C = __generic_parameters_of_C() +``` +The biggest divergence from existing behavior for `def695` scopes +is the behavior within class scopes. This divergence is necessary +so that generics defined within classes behave in an intuitive way: + +``` +class C: + class Nested: ... + def generic_method[T](self, x: T, y: Nested) -> T: ... +``` +Equivalent to: + +``` +class C: + class Nested: ... + + def695 __generic_parameters_of_generic_method(): + T = typing.TypeVar('T') + + def generic_method(self, x: T, y: Nested) -> T: ... + return generic_method + + generic_method = __generic_parameters_of_generic_method() +``` +In this example, the annotations for `x` and `y` are evaluated within +a `def695` scope, because they need access to the type parameter `T` +for the generic method. However, they also need access to the `Nested` +name defined within the class namespace. If `def695` scopes behaved +like regular function scopes, `Nested` would not be visible within the +function scope. Therefore, `def695` scopes that are immediately within +class scopes have access to that class scope, as described above. + +### Library Changes +Several classes in the `typing` module that are currently implemented in +Python must be partially implemented in C. This includes `TypeVar`, +`TypeVarTuple`, `ParamSpec`, and `Generic`, and the new class +`TypeAliasType` (described above). The implementation may delegate to the +Python version of `typing.py` for some behaviors that interact heavily with +the rest of the module. The +documented behaviors of these classes should not change. + +## Rejected Ideas +### Prefix Clause +We explored various syntactic options for specifying type parameters that +preceded `def` and `class` statements. One such variant we considered +used a `using` clause as follows: + +``` +using S, T +class ClassA: ... +``` +This option was rejected because the scoping rules for the type parameters +were less clear. Also, this syntax did not interact well with class and +function decorators, which are common in Python. Only one other popular +programming language, C++, uses this approach. + +We likewise considered prefix forms that looked like decorators (e.g., +`@using(S, T)`). This idea was rejected because such forms would be confused +with regular decorators, and they would not compose well with existing +decorators. Furthermore, decorators are logically executed after the statement +they are decorating, so it would be confusing for them to introduce symbols +(type parameters) that are visible within the "decorated" statement, which is +logically executed before the decorator itself. + +### Angle Brackets +Many languages that support generics make use of angle brackets. (Refer to +the table at the end of Appendix A for a summary.) We explored the use of +angle brackets for type parameter declarations in Python, but we ultimately +rejected it for two reasons. First, angle brackets are not considered +"paired" by the Python scanner, so end-of-line characters between a `<` +and `>` token are retained. That means any line breaks within a list of +type parameters would require the use of unsightly and cumbersome `\` escape +sequences. Second, Python has already established the use of square brackets +for explicit specialization of a generic type (e.g., `list[int]`). We +concluded that it would be inconsistent and confusing to use angle brackets +for generic declarations but square brackets for explicit specialization. All +other languages that we surveyed were consistent in this regard. + +### Bounds Syntax +We explored various syntactic options for specifying the bounds and constraints +for a type variable. We considered, but ultimately rejected, the use +of a `<:` token like in Scala, the use of an `extends` or `with` +keyword like in various other languages, and the use of a function call +syntax similar to today's `typing.TypeVar` constructor. The simple colon +syntax is consistent with many other programming languages (see Appendix A), +and it was heavily preferred by a cross section of Python developers who +were surveyed. + +### Explicit Variance +We considered adding syntax for specifying whether a type parameter is intended +to be invariant, covariant, or contravariant. The `typing.TypeVar` mechanism +in Python requires this. A few other languages including Scala and C# +also require developers to specify the variance. We rejected this idea because +variance can generally be inferred, and most modern programming languages +do infer variance based on usage. Variance is an advanced topic that +many developers find confusing, so we want to eliminate the need to +understand this concept for most Python developers. + +### Name Mangling +When considering implementation options, we considered a "name mangling" +approach where each type parameter was given a unique "mangled" name by the +compiler. This mangled name would be based on the qualified name of the +generic class, function or type alias it was associated with. This approach +was rejected because qualified names are not necessarily unique, which means +the mangled name would need to be based on some other randomized value. +Furthermore, this approach is not compatible with techniques used for +evaluating quoted (forward referenced) type annotations. + +## Generic struct; type parameter with upper and lower bounds +## Valid for T in (Int64, Signed, Integer, Real, Number) +struct Container{Int <: T <: Number} + x::T +end + +## Generic function +function func1(v::Container{T}) where T <: Real end + +## Alternate forms of generic function +function func2(v::Container{T} where T <: Real) end +function func3(v::Container{<: Real}) end + +## Tuple types are covariant +## Valid for func4((2//3, 3.5)) +function func4(t::Tuple{Real,Real}) end +``` +### Dart +Dart uses angle brackets to declare type parameters and for specialization. +The upper bound of a type is specified using the `extends` keyword. +By default, type parameters are covariant. + +Dart supports declaration-site variance, where variance of type parameters is +explicitly declared using `in`, `out` and `inout` keywords. +It does not support use-site variance. + +Dart provides no way to specify a default type argument. + +```dart +// Generic class +class ClassA { } + +// Type parameter with upper bound +class ClassB { } + +// Contravariant and covariant type parameters +class ClassC { } + +// Generic function +T func1() { } + +// Generic type alias +typedef TypeDefFoo = ClassA; +``` +-- + +Go uses square brackets to declare type parameters and for specialization. +The upper bound of a type is specified after the name of the parameter, and +must always be specified. The keyword `any` is used for an unbound type parameter. + +Go doesn't support variance; all type parameters are invariant. + +Go provides no way to specify a default type argument. + +Go does not support generic type aliases. + +```go +// Generic type without a bound +type TypeA[T any] struct { + t T +} + +// Type parameter with upper bound +type TypeB[T SomeType1] struct { } + +// Generic function +func func1[T any]() { } +``` +### Summary ++------------+----------+---------+--------+----------+-----------+-----------+ +| | Decl | Upper | Lower | Default | Variance | Variance | +| | Syntax | Bound | Bound | Value | Site | | ++============+==========+=========+========+==========+===========+===========+ +| C++ | template | n/a | n/a | = | n/a | n/a | +| | <> | | | | | | ++------------+----------+---------+--------+----------+-----------+-----------+ +| Java | <> | extends | | | use | super, | +| | | | | | | extends | ++------------+----------+---------+--------+----------+-----------+-----------+ +| C# | <> | where | | | decl | in, out | ++------------+----------+---------+--------+----------+-----------+-----------+ +| TypeScript | <> | extends | | = | decl | inferred, | +| | | | | | | in, out | ++------------+----------+---------+--------+----------+-----------+-----------+ +| Scala | [] | T <: X | T >: X | | use, decl | +, - | ++------------+----------+---------+--------+----------+-----------+-----------+ +| Swift | <> | T: X | | | n/a | n/a | ++------------+----------+---------+--------+----------+-----------+-----------+ +| Rust | <> | T: X, | | = | n/a | n/a | +| | | where | | | | | ++------------+----------+---------+--------+----------+-----------+-----------+ +| Kotlin | <> | T: X, | | | use, decl | in, out | +| | | where | | | | | ++------------+----------+---------+--------+----------+-----------+-----------+ +| Julia | {} | T <: X | X <: T | | n/a | n/a | ++------------+----------+---------+--------+----------+-----------+-----------+ +| Dart | <> | extends | | | decl | in, out, | +| | | | | | | inout | ++------------+----------+---------+--------+----------+-----------+-----------+ +| Go | [] | T X | | | n/a | n/a | ++------------+----------+---------+--------+----------+-----------+-----------+ +| Python | [] | T: X | | | decl | inferred | +| (proposed) | | | | | | | ++------------+----------+---------+--------+----------+-----------+-----------+ + diff --git a/cpython_10/solution/solution.patch b/cpython_10/solution/solution.patch new file mode 100644 index 0000000000000000000000000000000000000000..b86fb84952f5b9068cdaf201e7139efb4990995f --- /dev/null +++ b/cpython_10/solution/solution.patch @@ -0,0 +1,23081 @@ +diff --git a/Grammar/python.gram b/Grammar/python.gram +index 6361dcd098..c79207b9cb 100644 +--- a/Grammar/python.gram ++++ b/Grammar/python.gram +@@ -112,6 +112,7 @@ simple_stmts[asdl_stmt_seq*]: + # will throw a SyntaxError. + simple_stmt[stmt_ty] (memo): + | assignment ++ | &"type" type_alias + | e=star_expressions { _PyAST_Expr(e, EXTRA) } + | &'return' return_stmt + | &('import' | 'from') import_stmt +@@ -252,8 +253,8 @@ class_def[stmt_ty]: + + class_def_raw[stmt_ty]: + | invalid_class_def_raw +- | 'class' a=NAME b=['(' z=[arguments] ')' { z }] ':' c=block { +- _PyAST_ClassDef(a->v.Name.id, ++ | 'class' a=NAME t=[type_params] b=['(' z=[arguments] ')' { z }] ':' c=block { ++ _PyAST_ClassDef(a->v.Name.id, t, + (b) ? ((expr_ty) b)->v.Call.args : NULL, + (b) ? ((expr_ty) b)->v.Call.keywords : NULL, + c, NULL, EXTRA) } +@@ -267,16 +268,16 @@ function_def[stmt_ty]: + + function_def_raw[stmt_ty]: + | invalid_def_raw +- | 'def' n=NAME &&'(' params=[params] ')' a=['->' z=expression { z }] &&':' tc=[func_type_comment] b=block { +- _PyAST_FunctionDef(n->v.Name.id, ++ | 'def' n=NAME t=[type_params] &&'(' params=[params] ')' a=['->' z=expression { z }] &&':' tc=[func_type_comment] b=block { ++ _PyAST_FunctionDef(n->v.Name.id, t, + (params) ? params : CHECK(arguments_ty, _PyPegen_empty_arguments(p)), + b, NULL, a, NEW_TYPE_COMMENT(p, tc), EXTRA) } +- | ASYNC 'def' n=NAME &&'(' params=[params] ')' a=['->' z=expression { z }] &&':' tc=[func_type_comment] b=block { ++ | ASYNC 'def' n=NAME t=[type_params] &&'(' params=[params] ')' a=['->' z=expression { z }] &&':' tc=[func_type_comment] b=block { + CHECK_VERSION( + stmt_ty, + 5, + "Async functions are", +- _PyAST_AsyncFunctionDef(n->v.Name.id, ++ _PyAST_AsyncFunctionDef(n->v.Name.id, t, + (params) ? params : CHECK(arguments_ty, _PyPegen_empty_arguments(p)), + b, NULL, a, NEW_TYPE_COMMENT(p, tc), EXTRA) + ) } +@@ -628,6 +629,39 @@ keyword_patterns[asdl_seq*]: + keyword_pattern[KeyPatternPair*]: + | arg=NAME '=' value=pattern { _PyPegen_key_pattern_pair(p, arg, value) } + ++# Type statement ++# --------------- ++ ++type_alias[stmt_ty]: ++ | "type" n=NAME t=[type_params] '=' b=expression { ++ CHECK_VERSION(stmt_ty, 12, "Type statement is", ++ _PyAST_TypeAlias(CHECK(expr_ty, _PyPegen_set_expr_context(p, n, Store)), t, b, EXTRA)) } ++ ++# Type parameter declaration ++# -------------------------- ++ ++type_params[asdl_typeparam_seq*]: '[' t=type_param_seq ']' { ++ CHECK_VERSION(asdl_typeparam_seq *, 12, "Type parameter lists are", t) } ++ ++type_param_seq[asdl_typeparam_seq*]: a[asdl_typeparam_seq*]=','.type_param+ [','] { a } ++ ++type_param[typeparam_ty] (memo): ++ | a=NAME b=[type_param_bound] { _PyAST_TypeVar(a->v.Name.id, b, EXTRA) } ++ | '*' a=NAME colon=":" e=expression { ++ RAISE_SYNTAX_ERROR_STARTING_FROM(colon, e->kind == Tuple_kind ++ ? "cannot use constraints with TypeVarTuple" ++ : "cannot use bound with TypeVarTuple") ++ } ++ | '*' a=NAME { _PyAST_TypeVarTuple(a->v.Name.id, EXTRA) } ++ | '**' a=NAME colon=":" e=expression { ++ RAISE_SYNTAX_ERROR_STARTING_FROM(colon, e->kind == Tuple_kind ++ ? "cannot use constraints with ParamSpec" ++ : "cannot use bound with ParamSpec") ++ } ++ | '**' a=NAME { _PyAST_ParamSpec(a->v.Name.id, EXTRA) } ++ ++type_param_bound[expr_ty]: ":" e=expression { e } ++ + # EXPRESSIONS + # ----------- + +diff --git a/Include/cpython/funcobject.h b/Include/cpython/funcobject.h +index c716330cc3..6f78f5868d 100644 +--- a/Include/cpython/funcobject.h ++++ b/Include/cpython/funcobject.h +@@ -41,6 +41,7 @@ typedef struct { + PyObject *func_weakreflist; /* List of weak references */ + PyObject *func_module; /* The __module__ attribute, can be anything */ + PyObject *func_annotations; /* Annotations, a dict or NULL */ ++ PyObject *func_typeparams; /* Tuple of active type variables or NULL */ + vectorcallfunc vectorcall; + /* Version number for use by specializer. + * Can set to non-zero when we want to specialize. +diff --git a/Include/internal/pycore_ast.h b/Include/internal/pycore_ast.h +index 36277efe9c..9f1cef0541 100644 +--- a/Include/internal/pycore_ast.h ++++ b/Include/internal/pycore_ast.h +@@ -51,6 +51,8 @@ typedef struct _pattern *pattern_ty; + + typedef struct _type_ignore *type_ignore_ty; + ++typedef struct _typeparam *typeparam_ty; ++ + + typedef struct { + _ASDL_SEQ_HEAD +@@ -147,6 +149,13 @@ typedef struct { + asdl_type_ignore_seq *_Py_asdl_type_ignore_seq_new(Py_ssize_t size, PyArena + *arena); + ++typedef struct { ++ _ASDL_SEQ_HEAD ++ typeparam_ty typed_elements[1]; ++} asdl_typeparam_seq; ++ ++asdl_typeparam_seq *_Py_asdl_typeparam_seq_new(Py_ssize_t size, PyArena *arena); ++ + + enum _mod_kind {Module_kind=1, Interactive_kind=2, Expression_kind=3, + FunctionType_kind=4}; +@@ -176,17 +185,19 @@ struct _mod { + + enum _stmt_kind {FunctionDef_kind=1, AsyncFunctionDef_kind=2, ClassDef_kind=3, + Return_kind=4, Delete_kind=5, Assign_kind=6, +- AugAssign_kind=7, AnnAssign_kind=8, For_kind=9, +- AsyncFor_kind=10, While_kind=11, If_kind=12, With_kind=13, +- AsyncWith_kind=14, Match_kind=15, Raise_kind=16, Try_kind=17, +- TryStar_kind=18, Assert_kind=19, Import_kind=20, +- ImportFrom_kind=21, Global_kind=22, Nonlocal_kind=23, +- Expr_kind=24, Pass_kind=25, Break_kind=26, Continue_kind=27}; ++ TypeAlias_kind=7, AugAssign_kind=8, AnnAssign_kind=9, ++ For_kind=10, AsyncFor_kind=11, While_kind=12, If_kind=13, ++ With_kind=14, AsyncWith_kind=15, Match_kind=16, ++ Raise_kind=17, Try_kind=18, TryStar_kind=19, Assert_kind=20, ++ Import_kind=21, ImportFrom_kind=22, Global_kind=23, ++ Nonlocal_kind=24, Expr_kind=25, Pass_kind=26, Break_kind=27, ++ Continue_kind=28}; + struct _stmt { + enum _stmt_kind kind; + union { + struct { + identifier name; ++ asdl_typeparam_seq *typeparams; + arguments_ty args; + asdl_stmt_seq *body; + asdl_expr_seq *decorator_list; +@@ -196,6 +207,7 @@ struct _stmt { + + struct { + identifier name; ++ asdl_typeparam_seq *typeparams; + arguments_ty args; + asdl_stmt_seq *body; + asdl_expr_seq *decorator_list; +@@ -205,6 +217,7 @@ struct _stmt { + + struct { + identifier name; ++ asdl_typeparam_seq *typeparams; + asdl_expr_seq *bases; + asdl_keyword_seq *keywords; + asdl_stmt_seq *body; +@@ -225,6 +238,12 @@ struct _stmt { + string type_comment; + } Assign; + ++ struct { ++ expr_ty name; ++ asdl_typeparam_seq *typeparams; ++ expr_ty value; ++ } TypeAlias; ++ + struct { + expr_ty target; + operator_ty op; +@@ -630,6 +649,30 @@ struct _type_ignore { + } v; + }; + ++enum _typeparam_kind {TypeVar_kind=1, ParamSpec_kind=2, TypeVarTuple_kind=3}; ++struct _typeparam { ++ enum _typeparam_kind kind; ++ union { ++ struct { ++ identifier name; ++ expr_ty bound; ++ } TypeVar; ++ ++ struct { ++ identifier name; ++ } ParamSpec; ++ ++ struct { ++ identifier name; ++ } TypeVarTuple; ++ ++ } v; ++ int lineno; ++ int col_offset; ++ int end_lineno; ++ int end_col_offset; ++}; ++ + + // Note: these macros affect function definitions, not only call sites. + mod_ty _PyAST_Module(asdl_stmt_seq * body, asdl_type_ignore_seq * type_ignores, +@@ -638,21 +681,22 @@ mod_ty _PyAST_Interactive(asdl_stmt_seq * body, PyArena *arena); + mod_ty _PyAST_Expression(expr_ty body, PyArena *arena); + mod_ty _PyAST_FunctionType(asdl_expr_seq * argtypes, expr_ty returns, PyArena + *arena); +-stmt_ty _PyAST_FunctionDef(identifier name, arguments_ty args, asdl_stmt_seq * +- body, asdl_expr_seq * decorator_list, expr_ty +- returns, string type_comment, int lineno, int +- col_offset, int end_lineno, int end_col_offset, +- PyArena *arena); +-stmt_ty _PyAST_AsyncFunctionDef(identifier name, arguments_ty args, +- asdl_stmt_seq * body, asdl_expr_seq * +- decorator_list, expr_ty returns, string +- type_comment, int lineno, int col_offset, int +- end_lineno, int end_col_offset, PyArena *arena); +-stmt_ty _PyAST_ClassDef(identifier name, asdl_expr_seq * bases, +- asdl_keyword_seq * keywords, asdl_stmt_seq * body, +- asdl_expr_seq * decorator_list, int lineno, int +- col_offset, int end_lineno, int end_col_offset, PyArena +- *arena); ++stmt_ty _PyAST_FunctionDef(identifier name, asdl_typeparam_seq * typeparams, ++ arguments_ty args, asdl_stmt_seq * body, ++ asdl_expr_seq * decorator_list, expr_ty returns, ++ string type_comment, int lineno, int col_offset, int ++ end_lineno, int end_col_offset, PyArena *arena); ++stmt_ty _PyAST_AsyncFunctionDef(identifier name, asdl_typeparam_seq * ++ typeparams, arguments_ty args, asdl_stmt_seq * ++ body, asdl_expr_seq * decorator_list, expr_ty ++ returns, string type_comment, int lineno, int ++ col_offset, int end_lineno, int end_col_offset, ++ PyArena *arena); ++stmt_ty _PyAST_ClassDef(identifier name, asdl_typeparam_seq * typeparams, ++ asdl_expr_seq * bases, asdl_keyword_seq * keywords, ++ asdl_stmt_seq * body, asdl_expr_seq * decorator_list, ++ int lineno, int col_offset, int end_lineno, int ++ end_col_offset, PyArena *arena); + stmt_ty _PyAST_Return(expr_ty value, int lineno, int col_offset, int + end_lineno, int end_col_offset, PyArena *arena); + stmt_ty _PyAST_Delete(asdl_expr_seq * targets, int lineno, int col_offset, int +@@ -660,6 +704,9 @@ stmt_ty _PyAST_Delete(asdl_expr_seq * targets, int lineno, int col_offset, int + stmt_ty _PyAST_Assign(asdl_expr_seq * targets, expr_ty value, string + type_comment, int lineno, int col_offset, int end_lineno, + int end_col_offset, PyArena *arena); ++stmt_ty _PyAST_TypeAlias(expr_ty name, asdl_typeparam_seq * typeparams, expr_ty ++ value, int lineno, int col_offset, int end_lineno, int ++ end_col_offset, PyArena *arena); + stmt_ty _PyAST_AugAssign(expr_ty target, operator_ty op, expr_ty value, int + lineno, int col_offset, int end_lineno, int + end_col_offset, PyArena *arena); +@@ -844,6 +891,14 @@ pattern_ty _PyAST_MatchOr(asdl_pattern_seq * patterns, int lineno, int + col_offset, int end_lineno, int end_col_offset, + PyArena *arena); + type_ignore_ty _PyAST_TypeIgnore(int lineno, string tag, PyArena *arena); ++typeparam_ty _PyAST_TypeVar(identifier name, expr_ty bound, int lineno, int ++ col_offset, int end_lineno, int end_col_offset, ++ PyArena *arena); ++typeparam_ty _PyAST_ParamSpec(identifier name, int lineno, int col_offset, int ++ end_lineno, int end_col_offset, PyArena *arena); ++typeparam_ty _PyAST_TypeVarTuple(identifier name, int lineno, int col_offset, ++ int end_lineno, int end_col_offset, PyArena ++ *arena); + + + PyObject* PyAST_mod2obj(mod_ty t); +diff --git a/Include/internal/pycore_ast_state.h b/Include/internal/pycore_ast_state.h +index f15b4905ee..e723ead577 100644 +--- a/Include/internal/pycore_ast_state.h ++++ b/Include/internal/pycore_ast_state.h +@@ -118,6 +118,7 @@ struct ast_state { + PyObject *Not_type; + PyObject *Or_singleton; + PyObject *Or_type; ++ PyObject *ParamSpec_type; + PyObject *Pass_type; + PyObject *Pow_singleton; + PyObject *Pow_type; +@@ -137,7 +138,10 @@ struct ast_state { + PyObject *TryStar_type; + PyObject *Try_type; + PyObject *Tuple_type; ++ PyObject *TypeAlias_type; + PyObject *TypeIgnore_type; ++ PyObject *TypeVarTuple_type; ++ PyObject *TypeVar_type; + PyObject *UAdd_singleton; + PyObject *UAdd_type; + PyObject *USub_singleton; +@@ -166,6 +170,7 @@ struct ast_state { + PyObject *bases; + PyObject *body; + PyObject *boolop_type; ++ PyObject *bound; + PyObject *cases; + PyObject *cause; + PyObject *cls; +@@ -243,6 +248,8 @@ struct ast_state { + PyObject *type_comment; + PyObject *type_ignore_type; + PyObject *type_ignores; ++ PyObject *typeparam_type; ++ PyObject *typeparams; + PyObject *unaryop_type; + PyObject *upper; + PyObject *value; +diff --git a/Include/internal/pycore_function.h b/Include/internal/pycore_function.h +index 1198814984..ecbb7001e7 100644 +--- a/Include/internal/pycore_function.h ++++ b/Include/internal/pycore_function.h +@@ -17,6 +17,8 @@ struct _py_func_state { + extern PyFunctionObject* _PyFunction_FromConstructor(PyFrameConstructor *constr); + + extern uint32_t _PyFunction_GetVersionForCurrentState(PyFunctionObject *func); ++extern PyObject *_Py_set_function_type_params( ++ PyThreadState* unused, PyObject *func, PyObject *type_params); + + #ifdef __cplusplus + } +diff --git a/Include/internal/pycore_global_objects.h b/Include/internal/pycore_global_objects.h +index 64d9384df9..40cc04d5d1 100644 +--- a/Include/internal/pycore_global_objects.h ++++ b/Include/internal/pycore_global_objects.h +@@ -68,6 +68,14 @@ struct _Py_interp_cached_objects { + PyObject *type_slots_pname; + pytype_slotdef *type_slots_ptrs[MAX_EQUIV]; + ++ /* TypeVar and related types */ ++ PyTypeObject *generic_type; ++ PyTypeObject *typevar_type; ++ PyTypeObject *typevartuple_type; ++ PyTypeObject *paramspec_type; ++ PyTypeObject *paramspecargs_type; ++ PyTypeObject *paramspeckwargs_type; ++ PyTypeObject *typealias_type; + }; + + #define _Py_INTERP_STATIC_OBJECT(interp, NAME) \ +diff --git a/Include/internal/pycore_global_objects_fini_generated.h b/Include/internal/pycore_global_objects_fini_generated.h +index 7e49581798..24a268ac8c 100644 +--- a/Include/internal/pycore_global_objects_fini_generated.h ++++ b/Include/internal/pycore_global_objects_fini_generated.h +@@ -555,15 +555,19 @@ _PyStaticObjects_CheckRefcnt(PyInterpreterState *interp) { + _PyStaticObject_CheckRefcnt((PyObject *)&_Py_STR(dbl_close_br)); + _PyStaticObject_CheckRefcnt((PyObject *)&_Py_STR(dbl_open_br)); + _PyStaticObject_CheckRefcnt((PyObject *)&_Py_STR(dbl_percent)); ++ _PyStaticObject_CheckRefcnt((PyObject *)&_Py_STR(defaults)); + _PyStaticObject_CheckRefcnt((PyObject *)&_Py_STR(dot)); + _PyStaticObject_CheckRefcnt((PyObject *)&_Py_STR(dot_locals)); + _PyStaticObject_CheckRefcnt((PyObject *)&_Py_STR(empty)); ++ _PyStaticObject_CheckRefcnt((PyObject *)&_Py_STR(generic_base)); + _PyStaticObject_CheckRefcnt((PyObject *)&_Py_STR(json_decoder)); ++ _PyStaticObject_CheckRefcnt((PyObject *)&_Py_STR(kwdefaults)); + _PyStaticObject_CheckRefcnt((PyObject *)&_Py_STR(list_err)); + _PyStaticObject_CheckRefcnt((PyObject *)&_Py_STR(newline)); + _PyStaticObject_CheckRefcnt((PyObject *)&_Py_STR(open_br)); + _PyStaticObject_CheckRefcnt((PyObject *)&_Py_STR(percent)); + _PyStaticObject_CheckRefcnt((PyObject *)&_Py_STR(shim_name)); ++ _PyStaticObject_CheckRefcnt((PyObject *)&_Py_STR(type_params)); + _PyStaticObject_CheckRefcnt((PyObject *)&_Py_STR(utf_8)); + _PyStaticObject_CheckRefcnt((PyObject *)&_Py_ID(CANCELLED)); + _PyStaticObject_CheckRefcnt((PyObject *)&_Py_ID(FINISHED)); +@@ -602,6 +606,8 @@ _PyStaticObjects_CheckRefcnt(PyInterpreterState *interp) { + _PyStaticObject_CheckRefcnt((PyObject *)&_Py_ID(__class__)); + _PyStaticObject_CheckRefcnt((PyObject *)&_Py_ID(__class_getitem__)); + _PyStaticObject_CheckRefcnt((PyObject *)&_Py_ID(__classcell__)); ++ _PyStaticObject_CheckRefcnt((PyObject *)&_Py_ID(__classdict__)); ++ _PyStaticObject_CheckRefcnt((PyObject *)&_Py_ID(__classdictcell__)); + _PyStaticObject_CheckRefcnt((PyObject *)&_Py_ID(__complex__)); + _PyStaticObject_CheckRefcnt((PyObject *)&_Py_ID(__contains__)); + _PyStaticObject_CheckRefcnt((PyObject *)&_Py_ID(__copy__)); +@@ -724,6 +730,7 @@ _PyStaticObjects_CheckRefcnt(PyInterpreterState *interp) { + _PyStaticObject_CheckRefcnt((PyObject *)&_Py_ID(__subclasshook__)); + _PyStaticObject_CheckRefcnt((PyObject *)&_Py_ID(__truediv__)); + _PyStaticObject_CheckRefcnt((PyObject *)&_Py_ID(__trunc__)); ++ _PyStaticObject_CheckRefcnt((PyObject *)&_Py_ID(__type_params__)); + _PyStaticObject_CheckRefcnt((PyObject *)&_Py_ID(__typing_is_unpacked_typevartuple__)); + _PyStaticObject_CheckRefcnt((PyObject *)&_Py_ID(__typing_prepare_subst__)); + _PyStaticObject_CheckRefcnt((PyObject *)&_Py_ID(__typing_subst__)); +@@ -779,8 +786,11 @@ _PyStaticObjects_CheckRefcnt(PyInterpreterState *interp) { + _PyStaticObject_CheckRefcnt((PyObject *)&_Py_ID(after_in_child)); + _PyStaticObject_CheckRefcnt((PyObject *)&_Py_ID(after_in_parent)); + _PyStaticObject_CheckRefcnt((PyObject *)&_Py_ID(aggregate_class)); ++ _PyStaticObject_CheckRefcnt((PyObject *)&_Py_ID(alias)); + _PyStaticObject_CheckRefcnt((PyObject *)&_Py_ID(append)); ++ _PyStaticObject_CheckRefcnt((PyObject *)&_Py_ID(arg)); + _PyStaticObject_CheckRefcnt((PyObject *)&_Py_ID(argdefs)); ++ _PyStaticObject_CheckRefcnt((PyObject *)&_Py_ID(args)); + _PyStaticObject_CheckRefcnt((PyObject *)&_Py_ID(arguments)); + _PyStaticObject_CheckRefcnt((PyObject *)&_Py_ID(argv)); + _PyStaticObject_CheckRefcnt((PyObject *)&_Py_ID(as_integer_ratio)); +@@ -795,6 +805,7 @@ _PyStaticObjects_CheckRefcnt(PyInterpreterState *interp) { + _PyStaticObject_CheckRefcnt((PyObject *)&_Py_ID(big)); + _PyStaticObject_CheckRefcnt((PyObject *)&_Py_ID(binary_form)); + _PyStaticObject_CheckRefcnt((PyObject *)&_Py_ID(block)); ++ _PyStaticObject_CheckRefcnt((PyObject *)&_Py_ID(bound)); + _PyStaticObject_CheckRefcnt((PyObject *)&_Py_ID(buffer)); + _PyStaticObject_CheckRefcnt((PyObject *)&_Py_ID(buffer_callback)); + _PyStaticObject_CheckRefcnt((PyObject *)&_Py_ID(buffer_size)); +@@ -850,11 +861,13 @@ _PyStaticObjects_CheckRefcnt(PyInterpreterState *interp) { + _PyStaticObject_CheckRefcnt((PyObject *)&_Py_ID(compile_mode)); + _PyStaticObject_CheckRefcnt((PyObject *)&_Py_ID(consts)); + _PyStaticObject_CheckRefcnt((PyObject *)&_Py_ID(context)); ++ _PyStaticObject_CheckRefcnt((PyObject *)&_Py_ID(contravariant)); + _PyStaticObject_CheckRefcnt((PyObject *)&_Py_ID(cookie)); + _PyStaticObject_CheckRefcnt((PyObject *)&_Py_ID(copy)); + _PyStaticObject_CheckRefcnt((PyObject *)&_Py_ID(copyreg)); + _PyStaticObject_CheckRefcnt((PyObject *)&_Py_ID(coro)); + _PyStaticObject_CheckRefcnt((PyObject *)&_Py_ID(count)); ++ _PyStaticObject_CheckRefcnt((PyObject *)&_Py_ID(covariant)); + _PyStaticObject_CheckRefcnt((PyObject *)&_Py_ID(cwd)); + _PyStaticObject_CheckRefcnt((PyObject *)&_Py_ID(d)); + _PyStaticObject_CheckRefcnt((PyObject *)&_Py_ID(data)); +@@ -964,6 +977,7 @@ _PyStaticObjects_CheckRefcnt(PyInterpreterState *interp) { + _PyStaticObject_CheckRefcnt((PyObject *)&_Py_ID(incoming)); + _PyStaticObject_CheckRefcnt((PyObject *)&_Py_ID(indexgroup)); + _PyStaticObject_CheckRefcnt((PyObject *)&_Py_ID(inf)); ++ _PyStaticObject_CheckRefcnt((PyObject *)&_Py_ID(infer_variance)); + _PyStaticObject_CheckRefcnt((PyObject *)&_Py_ID(inheritable)); + _PyStaticObject_CheckRefcnt((PyObject *)&_Py_ID(initial)); + _PyStaticObject_CheckRefcnt((PyObject *)&_Py_ID(initial_bytes)); +@@ -1080,6 +1094,7 @@ _PyStaticObjects_CheckRefcnt(PyInterpreterState *interp) { + _PyStaticObject_CheckRefcnt((PyObject *)&_Py_ID(optimize)); + _PyStaticObject_CheckRefcnt((PyObject *)&_Py_ID(options)); + _PyStaticObject_CheckRefcnt((PyObject *)&_Py_ID(order)); ++ _PyStaticObject_CheckRefcnt((PyObject *)&_Py_ID(origin)); + _PyStaticObject_CheckRefcnt((PyObject *)&_Py_ID(out_fd)); + _PyStaticObject_CheckRefcnt((PyObject *)&_Py_ID(outgoing)); + _PyStaticObject_CheckRefcnt((PyObject *)&_Py_ID(overlapped)); +@@ -1213,6 +1228,7 @@ _PyStaticObjects_CheckRefcnt(PyInterpreterState *interp) { + _PyStaticObject_CheckRefcnt((PyObject *)&_Py_ID(twice)); + _PyStaticObject_CheckRefcnt((PyObject *)&_Py_ID(txt)); + _PyStaticObject_CheckRefcnt((PyObject *)&_Py_ID(type)); ++ _PyStaticObject_CheckRefcnt((PyObject *)&_Py_ID(type_params)); + _PyStaticObject_CheckRefcnt((PyObject *)&_Py_ID(tz)); + _PyStaticObject_CheckRefcnt((PyObject *)&_Py_ID(tzname)); + _PyStaticObject_CheckRefcnt((PyObject *)&_Py_ID(uid)); +diff --git a/Include/internal/pycore_global_strings.h b/Include/internal/pycore_global_strings.h +index 8ebfee85c8..c1005d0515 100644 +--- a/Include/internal/pycore_global_strings.h ++++ b/Include/internal/pycore_global_strings.h +@@ -40,15 +40,19 @@ struct _Py_global_strings { + STRUCT_FOR_STR(dbl_close_br, "}}") + STRUCT_FOR_STR(dbl_open_br, "{{") + STRUCT_FOR_STR(dbl_percent, "%%") ++ STRUCT_FOR_STR(defaults, ".defaults") + STRUCT_FOR_STR(dot, ".") + STRUCT_FOR_STR(dot_locals, ".") + STRUCT_FOR_STR(empty, "") ++ STRUCT_FOR_STR(generic_base, ".generic_base") + STRUCT_FOR_STR(json_decoder, "json.decoder") ++ STRUCT_FOR_STR(kwdefaults, ".kwdefaults") + STRUCT_FOR_STR(list_err, "list index out of range") + STRUCT_FOR_STR(newline, "\n") + STRUCT_FOR_STR(open_br, "{") + STRUCT_FOR_STR(percent, "%") + STRUCT_FOR_STR(shim_name, "") ++ STRUCT_FOR_STR(type_params, ".type_params") + STRUCT_FOR_STR(utf_8, "utf-8") + } literals; + +@@ -90,6 +94,8 @@ struct _Py_global_strings { + STRUCT_FOR_ID(__class__) + STRUCT_FOR_ID(__class_getitem__) + STRUCT_FOR_ID(__classcell__) ++ STRUCT_FOR_ID(__classdict__) ++ STRUCT_FOR_ID(__classdictcell__) + STRUCT_FOR_ID(__complex__) + STRUCT_FOR_ID(__contains__) + STRUCT_FOR_ID(__copy__) +@@ -212,6 +218,7 @@ struct _Py_global_strings { + STRUCT_FOR_ID(__subclasshook__) + STRUCT_FOR_ID(__truediv__) + STRUCT_FOR_ID(__trunc__) ++ STRUCT_FOR_ID(__type_params__) + STRUCT_FOR_ID(__typing_is_unpacked_typevartuple__) + STRUCT_FOR_ID(__typing_prepare_subst__) + STRUCT_FOR_ID(__typing_subst__) +@@ -267,8 +274,11 @@ struct _Py_global_strings { + STRUCT_FOR_ID(after_in_child) + STRUCT_FOR_ID(after_in_parent) + STRUCT_FOR_ID(aggregate_class) ++ STRUCT_FOR_ID(alias) + STRUCT_FOR_ID(append) ++ STRUCT_FOR_ID(arg) + STRUCT_FOR_ID(argdefs) ++ STRUCT_FOR_ID(args) + STRUCT_FOR_ID(arguments) + STRUCT_FOR_ID(argv) + STRUCT_FOR_ID(as_integer_ratio) +@@ -283,6 +293,7 @@ struct _Py_global_strings { + STRUCT_FOR_ID(big) + STRUCT_FOR_ID(binary_form) + STRUCT_FOR_ID(block) ++ STRUCT_FOR_ID(bound) + STRUCT_FOR_ID(buffer) + STRUCT_FOR_ID(buffer_callback) + STRUCT_FOR_ID(buffer_size) +@@ -338,11 +349,13 @@ struct _Py_global_strings { + STRUCT_FOR_ID(compile_mode) + STRUCT_FOR_ID(consts) + STRUCT_FOR_ID(context) ++ STRUCT_FOR_ID(contravariant) + STRUCT_FOR_ID(cookie) + STRUCT_FOR_ID(copy) + STRUCT_FOR_ID(copyreg) + STRUCT_FOR_ID(coro) + STRUCT_FOR_ID(count) ++ STRUCT_FOR_ID(covariant) + STRUCT_FOR_ID(cwd) + STRUCT_FOR_ID(d) + STRUCT_FOR_ID(data) +@@ -452,6 +465,7 @@ struct _Py_global_strings { + STRUCT_FOR_ID(incoming) + STRUCT_FOR_ID(indexgroup) + STRUCT_FOR_ID(inf) ++ STRUCT_FOR_ID(infer_variance) + STRUCT_FOR_ID(inheritable) + STRUCT_FOR_ID(initial) + STRUCT_FOR_ID(initial_bytes) +@@ -568,6 +582,7 @@ struct _Py_global_strings { + STRUCT_FOR_ID(optimize) + STRUCT_FOR_ID(options) + STRUCT_FOR_ID(order) ++ STRUCT_FOR_ID(origin) + STRUCT_FOR_ID(out_fd) + STRUCT_FOR_ID(outgoing) + STRUCT_FOR_ID(overlapped) +@@ -701,6 +716,7 @@ struct _Py_global_strings { + STRUCT_FOR_ID(twice) + STRUCT_FOR_ID(txt) + STRUCT_FOR_ID(type) ++ STRUCT_FOR_ID(type_params) + STRUCT_FOR_ID(tz) + STRUCT_FOR_ID(tzname) + STRUCT_FOR_ID(uid) +diff --git a/Include/internal/pycore_intrinsics.h b/Include/internal/pycore_intrinsics.h +index 3902059a04..39f15681b7 100644 +--- a/Include/internal/pycore_intrinsics.h ++++ b/Include/internal/pycore_intrinsics.h +@@ -8,15 +8,23 @@ + #define INTRINSIC_ASYNC_GEN_WRAP 4 + #define INTRINSIC_UNARY_POSITIVE 5 + #define INTRINSIC_LIST_TO_TUPLE 6 ++#define INTRINSIC_TYPEVAR 7 ++#define INTRINSIC_PARAMSPEC 8 ++#define INTRINSIC_TYPEVARTUPLE 9 ++#define INTRINSIC_SUBSCRIPT_GENERIC 10 ++#define INTRINSIC_TYPEALIAS 11 + +-#define MAX_INTRINSIC_1 6 ++#define MAX_INTRINSIC_1 11 + + + /* Binary Functions: */ + #define INTRINSIC_2_INVALID 0 + #define INTRINSIC_PREP_RERAISE_STAR 1 ++#define INTRINSIC_TYPEVAR_WITH_BOUND 2 ++#define INTRINSIC_TYPEVAR_WITH_CONSTRAINTS 3 ++#define INTRINSIC_SET_FUNCTION_TYPE_PARAMS 4 + +-#define MAX_INTRINSIC_2 1 ++#define MAX_INTRINSIC_2 4 + + typedef PyObject *(*instrinsic_func1)(PyThreadState* tstate, PyObject *value); + typedef PyObject *(*instrinsic_func2)(PyThreadState* tstate, PyObject *value1, PyObject *value2); +diff --git a/Include/internal/pycore_opcode.h b/Include/internal/pycore_opcode.h +index e823e1bfb5..c2fa5692db 100644 +--- a/Include/internal/pycore_opcode.h ++++ b/Include/internal/pycore_opcode.h +@@ -167,7 +167,6 @@ const uint8_t _PyOpcode_Deopt[256] = { + [LOAD_ATTR_SLOT] = LOAD_ATTR, + [LOAD_ATTR_WITH_HINT] = LOAD_ATTR, + [LOAD_BUILD_CLASS] = LOAD_BUILD_CLASS, +- [LOAD_CLASSDEREF] = LOAD_CLASSDEREF, + [LOAD_CLOSURE] = LOAD_CLOSURE, + [LOAD_CONST] = LOAD_CONST, + [LOAD_CONST__LOAD_FAST] = LOAD_CONST, +@@ -177,9 +176,12 @@ const uint8_t _PyOpcode_Deopt[256] = { + [LOAD_FAST_CHECK] = LOAD_FAST_CHECK, + [LOAD_FAST__LOAD_CONST] = LOAD_FAST, + [LOAD_FAST__LOAD_FAST] = LOAD_FAST, ++ [LOAD_FROM_DICT_OR_DEREF] = LOAD_FROM_DICT_OR_DEREF, ++ [LOAD_FROM_DICT_OR_GLOBALS] = LOAD_FROM_DICT_OR_GLOBALS, + [LOAD_GLOBAL] = LOAD_GLOBAL, + [LOAD_GLOBAL_BUILTIN] = LOAD_GLOBAL, + [LOAD_GLOBAL_MODULE] = LOAD_GLOBAL, ++ [LOAD_LOCALS] = LOAD_LOCALS, + [LOAD_NAME] = LOAD_NAME, + [LOAD_SUPER_ATTR] = LOAD_SUPER_ATTR, + [LOAD_SUPER_ATTR_ATTR] = LOAD_SUPER_ATTR, +@@ -329,8 +331,8 @@ static const char *const _PyOpcode_OpName[267] = { + [LOAD_CONST__LOAD_FAST] = "LOAD_CONST__LOAD_FAST", + [SETUP_ANNOTATIONS] = "SETUP_ANNOTATIONS", + [LOAD_FAST__LOAD_CONST] = "LOAD_FAST__LOAD_CONST", ++ [LOAD_LOCALS] = "LOAD_LOCALS", + [LOAD_FAST__LOAD_FAST] = "LOAD_FAST__LOAD_FAST", +- [LOAD_GLOBAL_BUILTIN] = "LOAD_GLOBAL_BUILTIN", + [POP_EXCEPT] = "POP_EXCEPT", + [STORE_NAME] = "STORE_NAME", + [DELETE_NAME] = "DELETE_NAME", +@@ -353,9 +355,9 @@ static const char *const _PyOpcode_OpName[267] = { + [IMPORT_NAME] = "IMPORT_NAME", + [IMPORT_FROM] = "IMPORT_FROM", + [JUMP_FORWARD] = "JUMP_FORWARD", ++ [LOAD_GLOBAL_BUILTIN] = "LOAD_GLOBAL_BUILTIN", + [LOAD_GLOBAL_MODULE] = "LOAD_GLOBAL_MODULE", + [STORE_ATTR_INSTANCE_VALUE] = "STORE_ATTR_INSTANCE_VALUE", +- [STORE_ATTR_SLOT] = "STORE_ATTR_SLOT", + [POP_JUMP_IF_FALSE] = "POP_JUMP_IF_FALSE", + [POP_JUMP_IF_TRUE] = "POP_JUMP_IF_TRUE", + [LOAD_GLOBAL] = "LOAD_GLOBAL", +@@ -390,7 +392,7 @@ static const char *const _PyOpcode_OpName[267] = { + [LIST_APPEND] = "LIST_APPEND", + [SET_ADD] = "SET_ADD", + [MAP_ADD] = "MAP_ADD", +- [LOAD_CLASSDEREF] = "LOAD_CLASSDEREF", ++ [STORE_ATTR_SLOT] = "STORE_ATTR_SLOT", + [COPY_FREE_VARS] = "COPY_FREE_VARS", + [YIELD_VALUE] = "YIELD_VALUE", + [RESUME] = "RESUME", +@@ -417,8 +419,8 @@ static const char *const _PyOpcode_OpName[267] = { + [KW_NAMES] = "KW_NAMES", + [CALL_INTRINSIC_1] = "CALL_INTRINSIC_1", + [CALL_INTRINSIC_2] = "CALL_INTRINSIC_2", +- [175] = "<175>", +- [176] = "<176>", ++ [LOAD_FROM_DICT_OR_GLOBALS] = "LOAD_FROM_DICT_OR_GLOBALS", ++ [LOAD_FROM_DICT_OR_DEREF] = "LOAD_FROM_DICT_OR_DEREF", + [177] = "<177>", + [178] = "<178>", + [179] = "<179>", +@@ -515,8 +517,6 @@ static const char *const _PyOpcode_OpName[267] = { + #define EXTRA_CASES \ + case 169: \ + case 170: \ +- case 175: \ +- case 176: \ + case 177: \ + case 178: \ + case 179: \ +diff --git a/Include/internal/pycore_runtime_init_generated.h b/Include/internal/pycore_runtime_init_generated.h +index 7b9c73dd1e..ff1dee6eac 100644 +--- a/Include/internal/pycore_runtime_init_generated.h ++++ b/Include/internal/pycore_runtime_init_generated.h +@@ -546,15 +546,19 @@ extern "C" { + INIT_STR(dbl_close_br, "}}"), \ + INIT_STR(dbl_open_br, "{{"), \ + INIT_STR(dbl_percent, "%%"), \ ++ INIT_STR(defaults, ".defaults"), \ + INIT_STR(dot, "."), \ + INIT_STR(dot_locals, "."), \ + INIT_STR(empty, ""), \ ++ INIT_STR(generic_base, ".generic_base"), \ + INIT_STR(json_decoder, "json.decoder"), \ ++ INIT_STR(kwdefaults, ".kwdefaults"), \ + INIT_STR(list_err, "list index out of range"), \ + INIT_STR(newline, "\n"), \ + INIT_STR(open_br, "{"), \ + INIT_STR(percent, "%"), \ + INIT_STR(shim_name, ""), \ ++ INIT_STR(type_params, ".type_params"), \ + INIT_STR(utf_8, "utf-8"), \ + } + +@@ -596,6 +600,8 @@ extern "C" { + INIT_ID(__class__), \ + INIT_ID(__class_getitem__), \ + INIT_ID(__classcell__), \ ++ INIT_ID(__classdict__), \ ++ INIT_ID(__classdictcell__), \ + INIT_ID(__complex__), \ + INIT_ID(__contains__), \ + INIT_ID(__copy__), \ +@@ -718,6 +724,7 @@ extern "C" { + INIT_ID(__subclasshook__), \ + INIT_ID(__truediv__), \ + INIT_ID(__trunc__), \ ++ INIT_ID(__type_params__), \ + INIT_ID(__typing_is_unpacked_typevartuple__), \ + INIT_ID(__typing_prepare_subst__), \ + INIT_ID(__typing_subst__), \ +@@ -773,8 +780,11 @@ extern "C" { + INIT_ID(after_in_child), \ + INIT_ID(after_in_parent), \ + INIT_ID(aggregate_class), \ ++ INIT_ID(alias), \ + INIT_ID(append), \ ++ INIT_ID(arg), \ + INIT_ID(argdefs), \ ++ INIT_ID(args), \ + INIT_ID(arguments), \ + INIT_ID(argv), \ + INIT_ID(as_integer_ratio), \ +@@ -789,6 +799,7 @@ extern "C" { + INIT_ID(big), \ + INIT_ID(binary_form), \ + INIT_ID(block), \ ++ INIT_ID(bound), \ + INIT_ID(buffer), \ + INIT_ID(buffer_callback), \ + INIT_ID(buffer_size), \ +@@ -844,11 +855,13 @@ extern "C" { + INIT_ID(compile_mode), \ + INIT_ID(consts), \ + INIT_ID(context), \ ++ INIT_ID(contravariant), \ + INIT_ID(cookie), \ + INIT_ID(copy), \ + INIT_ID(copyreg), \ + INIT_ID(coro), \ + INIT_ID(count), \ ++ INIT_ID(covariant), \ + INIT_ID(cwd), \ + INIT_ID(d), \ + INIT_ID(data), \ +@@ -958,6 +971,7 @@ extern "C" { + INIT_ID(incoming), \ + INIT_ID(indexgroup), \ + INIT_ID(inf), \ ++ INIT_ID(infer_variance), \ + INIT_ID(inheritable), \ + INIT_ID(initial), \ + INIT_ID(initial_bytes), \ +@@ -1074,6 +1088,7 @@ extern "C" { + INIT_ID(optimize), \ + INIT_ID(options), \ + INIT_ID(order), \ ++ INIT_ID(origin), \ + INIT_ID(out_fd), \ + INIT_ID(outgoing), \ + INIT_ID(overlapped), \ +@@ -1207,6 +1222,7 @@ extern "C" { + INIT_ID(twice), \ + INIT_ID(txt), \ + INIT_ID(type), \ ++ INIT_ID(type_params), \ + INIT_ID(tz), \ + INIT_ID(tzname), \ + INIT_ID(uid), \ +diff --git a/Include/internal/pycore_symtable.h b/Include/internal/pycore_symtable.h +index 9a005be540..3fa825d0a8 100644 +--- a/Include/internal/pycore_symtable.h ++++ b/Include/internal/pycore_symtable.h +@@ -10,8 +10,17 @@ extern "C" { + + struct _mod; // Type defined in pycore_ast.h + +-typedef enum _block_type { FunctionBlock, ClassBlock, ModuleBlock, AnnotationBlock } +- _Py_block_ty; ++typedef enum _block_type { ++ FunctionBlock, ClassBlock, ModuleBlock, ++ // Used for annotations if 'from __future__ import annotations' is active. ++ // Annotation blocks cannot bind names and are not evaluated. ++ AnnotationBlock, ++ // Used for generics and type aliases. These work mostly like functions ++ // (see PEP 695 for details). The three different blocks function identically; ++ // they are different enum entries only so that error messages can be more ++ // precise. ++ TypeVarBoundBlock, TypeAliasBlock, TypeParamBlock ++} _Py_block_ty; + + typedef enum _comprehension_type { + NoComprehension = 0, +@@ -49,7 +58,7 @@ typedef struct _symtable_entry { + PyObject *ste_varnames; /* list of function parameters */ + PyObject *ste_children; /* list of child blocks */ + PyObject *ste_directives;/* locations of global and nonlocal statements */ +- _Py_block_ty ste_type; /* module, class, function or annotation */ ++ _Py_block_ty ste_type; + int ste_nested; /* true if block is nested */ + unsigned ste_free : 1; /* true if block has free variables */ + unsigned ste_child_free : 1; /* true if a child block has free vars, +@@ -64,8 +73,12 @@ typedef struct _symtable_entry { + unsigned ste_needs_class_closure : 1; /* for class scopes, true if a + closure over __class__ + should be created */ ++ unsigned ste_needs_classdict : 1; /* for class scopes, true if a closure ++ over the class dict should be created */ + unsigned ste_comp_inlined : 1; /* true if this comprehension is inlined */ + unsigned ste_comp_iter_target : 1; /* true if visiting comprehension target */ ++ unsigned ste_can_see_class_scope : 1; /* true if this block can see names bound in an ++ enclosing class scope */ + int ste_comp_iter_expr; /* non-zero if visiting a comprehension range expression */ + int ste_lineno; /* first line of block */ + int ste_col_offset; /* offset of first line of block */ +@@ -82,6 +95,7 @@ extern PyTypeObject PySTEntry_Type; + + extern long _PyST_GetSymbol(PySTEntryObject *, PyObject *); + extern int _PyST_GetScope(PySTEntryObject *, PyObject *); ++extern int _PyST_IsFunctionLike(PySTEntryObject *); + + extern struct symtable* _PySymtable_Build( + struct _mod *mod, +@@ -105,6 +119,7 @@ extern PyObject* _Py_Mangle(PyObject *p, PyObject *name); + #define DEF_IMPORT 2<<6 /* assignment occurred via import */ + #define DEF_ANNOT 2<<7 /* this name is annotated */ + #define DEF_COMP_ITER 2<<8 /* this name is a comprehension iteration variable */ ++#define DEF_TYPE_PARAM 2<<9 /* this name is a type parameter */ + + #define DEF_BOUND (DEF_LOCAL | DEF_PARAM | DEF_IMPORT) + +diff --git a/Include/internal/pycore_typevarobject.h b/Include/internal/pycore_typevarobject.h +new file mode 100644 +index 0000000000..2035e47e92 +--- /dev/null ++++ b/Include/internal/pycore_typevarobject.h +@@ -0,0 +1,22 @@ ++#ifndef Py_INTERNAL_TYPEVAROBJECT_H ++#define Py_INTERNAL_TYPEVAROBJECT_H ++#ifdef __cplusplus ++extern "C" { ++#endif ++ ++#ifndef Py_BUILD_CORE ++# error "this header requires Py_BUILD_CORE define" ++#endif ++ ++extern PyObject *_Py_make_typevar(PyObject *, PyObject *, PyObject *); ++extern PyObject *_Py_make_paramspec(PyThreadState *, PyObject *); ++extern PyObject *_Py_make_typevartuple(PyThreadState *, PyObject *); ++extern PyObject *_Py_make_typealias(PyThreadState *, PyObject *); ++extern PyObject *_Py_subscript_generic(PyThreadState *, PyObject *); ++extern int _Py_initialize_generic(PyInterpreterState *); ++extern void _Py_clear_generic_types(PyInterpreterState *); ++ ++#ifdef __cplusplus ++} ++#endif ++#endif /* !Py_INTERNAL_TYPEVAROBJECT_H */ +diff --git a/Include/internal/pycore_unicodeobject_generated.h b/Include/internal/pycore_unicodeobject_generated.h +index 8e086edbdf..ba6b37f1bf 100644 +--- a/Include/internal/pycore_unicodeobject_generated.h ++++ b/Include/internal/pycore_unicodeobject_generated.h +@@ -123,6 +123,12 @@ _PyUnicode_InitStaticStrings(PyInterpreterState *interp) { + string = &_Py_ID(__classcell__); + assert(_PyUnicode_CheckConsistency(string, 1)); + _PyUnicode_InternInPlace(interp, &string); ++ string = &_Py_ID(__classdict__); ++ assert(_PyUnicode_CheckConsistency(string, 1)); ++ _PyUnicode_InternInPlace(interp, &string); ++ string = &_Py_ID(__classdictcell__); ++ assert(_PyUnicode_CheckConsistency(string, 1)); ++ _PyUnicode_InternInPlace(interp, &string); + string = &_Py_ID(__complex__); + assert(_PyUnicode_CheckConsistency(string, 1)); + _PyUnicode_InternInPlace(interp, &string); +@@ -489,6 +495,9 @@ _PyUnicode_InitStaticStrings(PyInterpreterState *interp) { + string = &_Py_ID(__trunc__); + assert(_PyUnicode_CheckConsistency(string, 1)); + _PyUnicode_InternInPlace(interp, &string); ++ string = &_Py_ID(__type_params__); ++ assert(_PyUnicode_CheckConsistency(string, 1)); ++ _PyUnicode_InternInPlace(interp, &string); + string = &_Py_ID(__typing_is_unpacked_typevartuple__); + assert(_PyUnicode_CheckConsistency(string, 1)); + _PyUnicode_InternInPlace(interp, &string); +@@ -654,12 +663,21 @@ _PyUnicode_InitStaticStrings(PyInterpreterState *interp) { + string = &_Py_ID(aggregate_class); + assert(_PyUnicode_CheckConsistency(string, 1)); + _PyUnicode_InternInPlace(interp, &string); ++ string = &_Py_ID(alias); ++ assert(_PyUnicode_CheckConsistency(string, 1)); ++ _PyUnicode_InternInPlace(interp, &string); + string = &_Py_ID(append); + assert(_PyUnicode_CheckConsistency(string, 1)); + _PyUnicode_InternInPlace(interp, &string); ++ string = &_Py_ID(arg); ++ assert(_PyUnicode_CheckConsistency(string, 1)); ++ _PyUnicode_InternInPlace(interp, &string); + string = &_Py_ID(argdefs); + assert(_PyUnicode_CheckConsistency(string, 1)); + _PyUnicode_InternInPlace(interp, &string); ++ string = &_Py_ID(args); ++ assert(_PyUnicode_CheckConsistency(string, 1)); ++ _PyUnicode_InternInPlace(interp, &string); + string = &_Py_ID(arguments); + assert(_PyUnicode_CheckConsistency(string, 1)); + _PyUnicode_InternInPlace(interp, &string); +@@ -702,6 +720,9 @@ _PyUnicode_InitStaticStrings(PyInterpreterState *interp) { + string = &_Py_ID(block); + assert(_PyUnicode_CheckConsistency(string, 1)); + _PyUnicode_InternInPlace(interp, &string); ++ string = &_Py_ID(bound); ++ assert(_PyUnicode_CheckConsistency(string, 1)); ++ _PyUnicode_InternInPlace(interp, &string); + string = &_Py_ID(buffer); + assert(_PyUnicode_CheckConsistency(string, 1)); + _PyUnicode_InternInPlace(interp, &string); +@@ -867,6 +888,9 @@ _PyUnicode_InitStaticStrings(PyInterpreterState *interp) { + string = &_Py_ID(context); + assert(_PyUnicode_CheckConsistency(string, 1)); + _PyUnicode_InternInPlace(interp, &string); ++ string = &_Py_ID(contravariant); ++ assert(_PyUnicode_CheckConsistency(string, 1)); ++ _PyUnicode_InternInPlace(interp, &string); + string = &_Py_ID(cookie); + assert(_PyUnicode_CheckConsistency(string, 1)); + _PyUnicode_InternInPlace(interp, &string); +@@ -882,6 +906,9 @@ _PyUnicode_InitStaticStrings(PyInterpreterState *interp) { + string = &_Py_ID(count); + assert(_PyUnicode_CheckConsistency(string, 1)); + _PyUnicode_InternInPlace(interp, &string); ++ string = &_Py_ID(covariant); ++ assert(_PyUnicode_CheckConsistency(string, 1)); ++ _PyUnicode_InternInPlace(interp, &string); + string = &_Py_ID(cwd); + assert(_PyUnicode_CheckConsistency(string, 1)); + _PyUnicode_InternInPlace(interp, &string); +@@ -1209,6 +1236,9 @@ _PyUnicode_InitStaticStrings(PyInterpreterState *interp) { + string = &_Py_ID(inf); + assert(_PyUnicode_CheckConsistency(string, 1)); + _PyUnicode_InternInPlace(interp, &string); ++ string = &_Py_ID(infer_variance); ++ assert(_PyUnicode_CheckConsistency(string, 1)); ++ _PyUnicode_InternInPlace(interp, &string); + string = &_Py_ID(inheritable); + assert(_PyUnicode_CheckConsistency(string, 1)); + _PyUnicode_InternInPlace(interp, &string); +@@ -1557,6 +1587,9 @@ _PyUnicode_InitStaticStrings(PyInterpreterState *interp) { + string = &_Py_ID(order); + assert(_PyUnicode_CheckConsistency(string, 1)); + _PyUnicode_InternInPlace(interp, &string); ++ string = &_Py_ID(origin); ++ assert(_PyUnicode_CheckConsistency(string, 1)); ++ _PyUnicode_InternInPlace(interp, &string); + string = &_Py_ID(out_fd); + assert(_PyUnicode_CheckConsistency(string, 1)); + _PyUnicode_InternInPlace(interp, &string); +@@ -1956,6 +1989,9 @@ _PyUnicode_InitStaticStrings(PyInterpreterState *interp) { + string = &_Py_ID(type); + assert(_PyUnicode_CheckConsistency(string, 1)); + _PyUnicode_InternInPlace(interp, &string); ++ string = &_Py_ID(type_params); ++ assert(_PyUnicode_CheckConsistency(string, 1)); ++ _PyUnicode_InternInPlace(interp, &string); + string = &_Py_ID(tz); + assert(_PyUnicode_CheckConsistency(string, 1)); + _PyUnicode_InternInPlace(interp, &string); +diff --git a/Include/opcode.h b/Include/opcode.h +index c3b6e5dce4..dea7687c39 100644 +--- a/Include/opcode.h ++++ b/Include/opcode.h +@@ -45,6 +45,7 @@ extern "C" { + #define RETURN_GENERATOR 75 + #define RETURN_VALUE 83 + #define SETUP_ANNOTATIONS 85 ++#define LOAD_LOCALS 87 + #define POP_EXCEPT 89 + #define HAVE_ARGUMENT 90 + #define STORE_NAME 90 +@@ -102,7 +103,6 @@ extern "C" { + #define LIST_APPEND 145 + #define SET_ADD 146 + #define MAP_ADD 147 +-#define LOAD_CLASSDEREF 148 + #define COPY_FREE_VARS 149 + #define YIELD_VALUE 150 + #define RESUME 151 +@@ -118,6 +118,8 @@ extern "C" { + #define KW_NAMES 172 + #define CALL_INTRINSIC_1 173 + #define CALL_INTRINSIC_2 174 ++#define LOAD_FROM_DICT_OR_GLOBALS 175 ++#define LOAD_FROM_DICT_OR_DEREF 176 + #define MIN_INSTRUMENTED_OPCODE 238 + #define INSTRUMENTED_POP_JUMP_IF_NONE 238 + #define INSTRUMENTED_POP_JUMP_IF_NOT_NONE 239 +@@ -199,11 +201,11 @@ extern "C" { + #define LOAD_ATTR_METHOD_WITH_VALUES 82 + #define LOAD_CONST__LOAD_FAST 84 + #define LOAD_FAST__LOAD_CONST 86 +-#define LOAD_FAST__LOAD_FAST 87 +-#define LOAD_GLOBAL_BUILTIN 88 +-#define LOAD_GLOBAL_MODULE 111 +-#define STORE_ATTR_INSTANCE_VALUE 112 +-#define STORE_ATTR_SLOT 113 ++#define LOAD_FAST__LOAD_FAST 88 ++#define LOAD_GLOBAL_BUILTIN 111 ++#define LOAD_GLOBAL_MODULE 112 ++#define STORE_ATTR_INSTANCE_VALUE 113 ++#define STORE_ATTR_SLOT 148 + #define STORE_ATTR_WITH_HINT 153 + #define STORE_FAST__LOAD_FAST 154 + #define STORE_FAST__STORE_FAST 158 +diff --git a/Lib/ast.py b/Lib/ast.py +index 65152047a2..08904afb20 100644 +--- a/Lib/ast.py ++++ b/Lib/ast.py +@@ -1051,6 +1051,7 @@ def visit_ClassDef(self, node): + self.fill("@") + self.traverse(deco) + self.fill("class " + node.name) ++ self._typeparams_helper(node.typeparams) + with self.delimit_if("(", ")", condition = node.bases or node.keywords): + comma = False + for e in node.bases: +@@ -1082,6 +1083,7 @@ def _function_helper(self, node, fill_suffix): + self.traverse(deco) + def_str = fill_suffix + " " + node.name + self.fill(def_str) ++ self._typeparams_helper(node.typeparams) + with self.delimit("(", ")"): + self.traverse(node.args) + if node.returns: +@@ -1090,6 +1092,30 @@ def _function_helper(self, node, fill_suffix): + with self.block(extra=self.get_type_comment(node)): + self._write_docstring_and_traverse_body(node) + ++ def _typeparams_helper(self, typeparams): ++ if typeparams is not None and len(typeparams) > 0: ++ with self.delimit("[", "]"): ++ self.interleave(lambda: self.write(", "), self.traverse, typeparams) ++ ++ def visit_TypeVar(self, node): ++ self.write(node.name) ++ if node.bound: ++ self.write(": ") ++ self.traverse(node.bound) ++ ++ def visit_TypeVarTuple(self, node): ++ self.write("*" + node.name) ++ ++ def visit_ParamSpec(self, node): ++ self.write("**" + node.name) ++ ++ def visit_TypeAlias(self, node): ++ self.fill("type ") ++ self.traverse(node.name) ++ self._typeparams_helper(node.typeparams) ++ self.write(" = ") ++ self.traverse(node.value) ++ + def visit_For(self, node): + self._for_helper("for ", node) + +diff --git a/Lib/importlib/_bootstrap_external.py b/Lib/importlib/_bootstrap_external.py +index 3ca5a1aea2..73ac4405cb 100644 +--- a/Lib/importlib/_bootstrap_external.py ++++ b/Lib/importlib/_bootstrap_external.py +@@ -444,6 +444,7 @@ def _write_atomic(path, data, mode=0o666): + # Python 3.12b1 3528 (Add LOAD_SUPER_ATTR_METHOD specialization) + # Python 3.12b1 3529 (Inline list/dict/set comprehensions) + # Python 3.12b1 3530 (Shrink the LOAD_SUPER_ATTR caches) ++# Python 3.12b1 3531 (Add PEP 695 changes) + + # Python 3.13 will start with 3550 + +@@ -460,7 +461,7 @@ def _write_atomic(path, data, mode=0o666): + # Whenever MAGIC_NUMBER is changed, the ranges in the magic_values array + # in PC/launcher.c must also be updated. + +-MAGIC_NUMBER = (3530).to_bytes(2, 'little') + b'\r\n' ++MAGIC_NUMBER = (3531).to_bytes(2, 'little') + b'\r\n' + + _RAW_MAGIC_NUMBER = int.from_bytes(MAGIC_NUMBER, 'little') # For import.c + +diff --git a/Lib/keyword.py b/Lib/keyword.py +index cc2b46b722..e22c837835 100644 +--- a/Lib/keyword.py ++++ b/Lib/keyword.py +@@ -56,7 +56,8 @@ kwlist = [ + softkwlist = [ + '_', + 'case', +- 'match' ++ 'match', ++ 'type' + ] + + iskeyword = frozenset(kwlist).__contains__ +diff --git a/Lib/opcode.py b/Lib/opcode.py +index 155466b1ab..97d0a654a0 100644 +--- a/Lib/opcode.py ++++ b/Lib/opcode.py +@@ -131,6 +131,7 @@ def pseudo_op(name, op, real_ops): + def_op('RETURN_VALUE', 83) + + def_op('SETUP_ANNOTATIONS', 85) ++def_op('LOAD_LOCALS', 87) + + def_op('POP_EXCEPT', 89) + +@@ -206,7 +207,6 @@ def pseudo_op(name, op, real_ops): + def_op('LIST_APPEND', 145) + def_op('SET_ADD', 146) + def_op('MAP_ADD', 147) +-def_op('LOAD_CLASSDEREF', 148) + hasfree.append(148) + def_op('COPY_FREE_VARS', 149) + def_op('YIELD_VALUE', 150) +@@ -228,6 +228,10 @@ def pseudo_op(name, op, real_ops): + def_op('CALL_INTRINSIC_1', 173) + def_op('CALL_INTRINSIC_2', 174) + ++name_op('LOAD_FROM_DICT_OR_GLOBALS', 175) ++def_op('LOAD_FROM_DICT_OR_DEREF', 176) ++hasfree.append(176) ++ + # Instrumented instructions + MIN_INSTRUMENTED_OPCODE = 238 + +@@ -318,12 +322,20 @@ def pseudo_op(name, op, real_ops): + "INTRINSIC_ASYNC_GEN_WRAP", + "INTRINSIC_UNARY_POSITIVE", + "INTRINSIC_LIST_TO_TUPLE", ++ "INTRINSIC_TYPEVAR", ++ "INTRINSIC_PARAMSPEC", ++ "INTRINSIC_TYPEVARTUPLE", ++ "INTRINSIC_SUBSCRIPT_GENERIC", ++ "INTRINSIC_TYPEALIAS", + ] + + _intrinsic_2_descs = [ +- 'INTRINSIC_2_INVALID', +- 'INTRINSIC_PREP_RERAISE_STAR', +- ] ++ "INTRINSIC_2_INVALID", ++ "INTRINSIC_PREP_RERAISE_STAR", ++ "INTRINSIC_TYPEVAR_WITH_BOUND", ++ "INTRINSIC_TYPEVAR_WITH_CONSTRAINTS", ++ "INTRINSIC_SET_FUNCTION_TYPE_PARAMS", ++] + + _specializations = { + "BINARY_OP": [ +diff --git a/Lib/typing.py b/Lib/typing.py +index 61aed0980a..8d132e2cbf 100644 +--- a/Lib/typing.py ++++ b/Lib/typing.py +@@ -23,6 +23,7 @@ + import collections + from collections import defaultdict + import collections.abc ++import copyreg + import contextlib + import functools + import operator +@@ -32,12 +33,16 @@ + import warnings + from types import WrapperDescriptorType, MethodWrapperType, MethodDescriptorType, GenericAlias + +- +-try: +- from _typing import _idfunc +-except ImportError: +- def _idfunc(_, x): +- return x ++from _typing import ( ++ _idfunc, ++ TypeVar, ++ ParamSpec, ++ TypeVarTuple, ++ ParamSpecArgs, ++ ParamSpecKwargs, ++ TypeAliasType, ++ Generic, ++) + + # Please keep __all__ alphabetized within each category. + __all__ = [ +@@ -149,6 +154,7 @@ def _idfunc(_, x): + 'TYPE_CHECKING', + 'TypeAlias', + 'TypeGuard', ++ 'TypeAliasType', + 'Unpack', + ] + +@@ -695,6 +701,15 @@ def Union(self, parameters): + return _UnionGenericAlias(self, parameters, name="Optional") + return _UnionGenericAlias(self, parameters) + ++def _make_union(left, right): ++ """Used from the C implementation of TypeVar. ++ ++ TypeVar.__or__ calls this instead of returning types.UnionType ++ because we want to allow unions between TypeVars and strings ++ (forward references.) ++ """ ++ return Union[left, right] ++ + @_SpecialForm + def Optional(self, parameters): + """Optional type. +@@ -926,333 +941,162 @@ def __reduce__(self): + return self.__name__ + + +-class _BoundVarianceMixin: +- """Mixin giving __init__ bound and variance arguments. +- +- This is used by TypeVar and ParamSpec, which both employ the notions of +- a type 'bound' (restricting type arguments to be a subtype of some +- specified type) and type 'variance' (determining subtype relations between +- generic types). +- """ +- def __init__(self, bound, covariant, contravariant): +- """Used to setup TypeVars and ParamSpec's bound, covariant and +- contravariant attributes. +- """ +- if covariant and contravariant: +- raise ValueError("Bivariant types are not supported.") +- self.__covariant__ = bool(covariant) +- self.__contravariant__ = bool(contravariant) +- if bound: +- self.__bound__ = _type_check(bound, "Bound must be a type.") +- else: +- self.__bound__ = None +- +- def __or__(self, right): +- return Union[self, right] +- +- def __ror__(self, left): +- return Union[left, self] +- +- def __repr__(self): +- if self.__covariant__: +- prefix = '+' +- elif self.__contravariant__: +- prefix = '-' +- else: +- prefix = '~' +- return prefix + self.__name__ +- +- def __mro_entries__(self, bases): +- raise TypeError(f"Cannot subclass an instance of {type(self).__name__}") +- +- +-class TypeVar(_Final, _Immutable, _BoundVarianceMixin, _PickleUsingNameMixin, +- _root=True): +- """Type variable. +- +- Usage:: +- +- T = TypeVar('T') # Can be anything +- A = TypeVar('A', str, bytes) # Must be str or bytes +- +- Type variables exist primarily for the benefit of static type +- checkers. They serve as the parameters for generic types as well +- as for generic function definitions. See class Generic for more +- information on generic types. Generic functions work as follows: +- +- def repeat(x: T, n: int) -> List[T]: +- '''Return a list containing n references to x.''' +- return [x]*n +- +- def longest(x: A, y: A) -> A: +- '''Return the longest of two strings.''' +- return x if len(x) >= len(y) else y +- +- The latter example's signature is essentially the overloading +- of (str, str) -> str and (bytes, bytes) -> bytes. Also note +- that if the arguments are instances of some subclass of str, +- the return type is still plain str. +- +- At runtime, isinstance(x, T) and issubclass(C, T) will raise TypeError. +- +- Type variables defined with covariant=True or contravariant=True +- can be used to declare covariant or contravariant generic types. +- See PEP 484 for more details. By default generic types are invariant +- in all type variables. +- +- Type variables can be introspected. e.g.: +- +- T.__name__ == 'T' +- T.__constraints__ == () +- T.__covariant__ == False +- T.__contravariant__ = False +- A.__constraints__ == (str, bytes) +- +- Note that only type variables defined in global scope can be pickled. +- """ +- +- def __init__(self, name, *constraints, bound=None, +- covariant=False, contravariant=False): +- self.__name__ = name +- super().__init__(bound, covariant, contravariant) +- if constraints and bound is not None: +- raise TypeError("Constraints cannot be combined with bound=...") +- if constraints and len(constraints) == 1: +- raise TypeError("A single constraint is not allowed") +- msg = "TypeVar(name, constraint, ...): constraints must be types." +- self.__constraints__ = tuple(_type_check(t, msg) for t in constraints) +- def_mod = _caller() +- if def_mod != 'typing': +- self.__module__ = def_mod ++def _typevar_subst(self, arg): ++ msg = "Parameters to generic types must be types." ++ arg = _type_check(arg, msg, is_argument=True) ++ if ((isinstance(arg, _GenericAlias) and arg.__origin__ is Unpack) or ++ (isinstance(arg, GenericAlias) and getattr(arg, '__unpacked__', False))): ++ raise TypeError(f"{arg} is not valid as type argument") ++ return arg + +- def __typing_subst__(self, arg): +- msg = "Parameters to generic types must be types." +- arg = _type_check(arg, msg, is_argument=True) +- if ((isinstance(arg, _GenericAlias) and arg.__origin__ is Unpack) or +- (isinstance(arg, GenericAlias) and getattr(arg, '__unpacked__', False))): +- raise TypeError(f"{arg} is not valid as type argument") +- return arg + ++def _typevartuple_prepare_subst(self, alias, args): ++ params = alias.__parameters__ ++ typevartuple_index = params.index(self) ++ for param in params[typevartuple_index + 1:]: ++ if isinstance(param, TypeVarTuple): ++ raise TypeError(f"More than one TypeVarTuple parameter in {alias}") ++ ++ alen = len(args) ++ plen = len(params) ++ left = typevartuple_index ++ right = plen - typevartuple_index - 1 ++ var_tuple_index = None ++ fillarg = None ++ for k, arg in enumerate(args): ++ if not isinstance(arg, type): ++ subargs = getattr(arg, '__typing_unpacked_tuple_args__', None) ++ if subargs and len(subargs) == 2 and subargs[-1] is ...: ++ if var_tuple_index is not None: ++ raise TypeError("More than one unpacked arbitrary-length tuple argument") ++ var_tuple_index = k ++ fillarg = subargs[0] ++ if var_tuple_index is not None: ++ left = min(left, var_tuple_index) ++ right = min(right, alen - var_tuple_index - 1) ++ elif left + right > alen: ++ raise TypeError(f"Too few arguments for {alias};" ++ f" actual {alen}, expected at least {plen-1}") + +-class TypeVarTuple(_Final, _Immutable, _PickleUsingNameMixin, _root=True): +- """Type variable tuple. ++ return ( ++ *args[:left], ++ *([fillarg]*(typevartuple_index - left)), ++ tuple(args[left: alen - right]), ++ *([fillarg]*(plen - right - left - typevartuple_index - 1)), ++ *args[alen - right:], ++ ) + +- Usage: + +- Ts = TypeVarTuple('Ts') # Can be given any name ++def _paramspec_subst(self, arg): ++ if isinstance(arg, (list, tuple)): ++ arg = tuple(_type_check(a, "Expected a type.") for a in arg) ++ elif not _is_param_expr(arg): ++ raise TypeError(f"Expected a list of types, an ellipsis, " ++ f"ParamSpec, or Concatenate. Got {arg}") ++ return arg + +- Just as a TypeVar (type variable) is a placeholder for a single type, +- a TypeVarTuple is a placeholder for an *arbitrary* number of types. For +- example, if we define a generic class using a TypeVarTuple: + +- class C(Generic[*Ts]): ... ++def _paramspec_prepare_subst(self, alias, args): ++ params = alias.__parameters__ ++ i = params.index(self) ++ if i >= len(args): ++ raise TypeError(f"Too few arguments for {alias}") ++ # Special case where Z[[int, str, bool]] == Z[int, str, bool] in PEP 612. ++ if len(params) == 1 and not _is_param_expr(args[0]): ++ assert i == 0 ++ args = (args,) ++ # Convert lists to tuples to help other libraries cache the results. ++ elif isinstance(args[i], list): ++ args = (*args[:i], tuple(args[i]), *args[i+1:]) ++ return args + +- Then we can parameterize that class with an arbitrary number of type +- arguments: + +- C[int] # Fine +- C[int, str] # Also fine +- C[()] # Even this is fine ++@_tp_cache ++def _generic_class_getitem(cls, params): ++ """Parameterizes a generic class. + +- For more details, see PEP 646. ++ At least, parameterizing a generic class is the *main* thing this method ++ does. For example, for some generic class `Foo`, this is called when we ++ do `Foo[int]` - there, with `cls=Foo` and `params=int`. + +- Note that only TypeVarTuples defined in global scope can be pickled. ++ However, note that this method is also called when defining generic ++ classes in the first place with `class Foo(Generic[T]): ...`. + """ ++ if not isinstance(params, tuple): ++ params = (params,) + +- def __init__(self, name): +- self.__name__ = name +- +- # Used for pickling. +- def_mod = _caller() +- if def_mod != 'typing': +- self.__module__ = def_mod +- +- def __iter__(self): +- yield Unpack[self] +- +- def __repr__(self): +- return self.__name__ ++ params = tuple(_type_convert(p) for p in params) ++ is_generic_or_protocol = cls in (Generic, Protocol) + +- def __typing_subst__(self, arg): +- raise TypeError("Substitution of bare TypeVarTuple is not supported") ++ if is_generic_or_protocol: ++ # Generic and Protocol can only be subscripted with unique type variables. ++ if not params: ++ raise TypeError( ++ f"Parameter list to {cls.__qualname__}[...] cannot be empty" ++ ) ++ if not all(_is_typevar_like(p) for p in params): ++ raise TypeError( ++ f"Parameters to {cls.__name__}[...] must all be type variables " ++ f"or parameter specification variables.") ++ if len(set(params)) != len(params): ++ raise TypeError( ++ f"Parameters to {cls.__name__}[...] must all be unique") ++ else: ++ # Subscripting a regular Generic subclass. ++ for param in cls.__parameters__: ++ prepare = getattr(param, '__typing_prepare_subst__', None) ++ if prepare is not None: ++ params = prepare(cls, params) ++ _check_generic(cls, params, len(cls.__parameters__)) + +- def __typing_prepare_subst__(self, alias, args): +- params = alias.__parameters__ +- typevartuple_index = params.index(self) +- for param in params[typevartuple_index + 1:]: ++ new_args = [] ++ for param, new_arg in zip(cls.__parameters__, params): + if isinstance(param, TypeVarTuple): +- raise TypeError(f"More than one TypeVarTuple parameter in {alias}") +- +- alen = len(args) +- plen = len(params) +- left = typevartuple_index +- right = plen - typevartuple_index - 1 +- var_tuple_index = None +- fillarg = None +- for k, arg in enumerate(args): +- if not isinstance(arg, type): +- subargs = getattr(arg, '__typing_unpacked_tuple_args__', None) +- if subargs and len(subargs) == 2 and subargs[-1] is ...: +- if var_tuple_index is not None: +- raise TypeError("More than one unpacked arbitrary-length tuple argument") +- var_tuple_index = k +- fillarg = subargs[0] +- if var_tuple_index is not None: +- left = min(left, var_tuple_index) +- right = min(right, alen - var_tuple_index - 1) +- elif left + right > alen: +- raise TypeError(f"Too few arguments for {alias};" +- f" actual {alen}, expected at least {plen-1}") +- +- return ( +- *args[:left], +- *([fillarg]*(typevartuple_index - left)), +- tuple(args[left: alen - right]), +- *([fillarg]*(plen - right - left - typevartuple_index - 1)), +- *args[alen - right:], +- ) +- +- def __mro_entries__(self, bases): +- raise TypeError(f"Cannot subclass an instance of {type(self).__name__}") +- +- +-class ParamSpecArgs(_Final, _Immutable, _root=True): +- """The args for a ParamSpec object. +- +- Given a ParamSpec object P, P.args is an instance of ParamSpecArgs. +- +- ParamSpecArgs objects have a reference back to their ParamSpec: +- +- P.args.__origin__ is P +- +- This type is meant for runtime introspection and has no special meaning to +- static type checkers. +- """ +- def __init__(self, origin): +- self.__origin__ = origin +- +- def __repr__(self): +- return f"{self.__origin__.__name__}.args" +- +- def __eq__(self, other): +- if not isinstance(other, ParamSpecArgs): +- return NotImplemented +- return self.__origin__ == other.__origin__ +- +- def __mro_entries__(self, bases): +- raise TypeError(f"Cannot subclass an instance of {type(self).__name__}") +- +- +-class ParamSpecKwargs(_Final, _Immutable, _root=True): +- """The kwargs for a ParamSpec object. +- +- Given a ParamSpec object P, P.kwargs is an instance of ParamSpecKwargs. +- +- ParamSpecKwargs objects have a reference back to their ParamSpec: +- +- P.kwargs.__origin__ is P +- +- This type is meant for runtime introspection and has no special meaning to +- static type checkers. +- """ +- def __init__(self, origin): +- self.__origin__ = origin +- +- def __repr__(self): +- return f"{self.__origin__.__name__}.kwargs" +- +- def __eq__(self, other): +- if not isinstance(other, ParamSpecKwargs): +- return NotImplemented +- return self.__origin__ == other.__origin__ +- +- def __mro_entries__(self, bases): +- raise TypeError(f"Cannot subclass an instance of {type(self).__name__}") +- +- +-class ParamSpec(_Final, _Immutable, _BoundVarianceMixin, _PickleUsingNameMixin, +- _root=True): +- """Parameter specification variable. +- +- Usage:: +- +- P = ParamSpec('P') +- +- Parameter specification variables exist primarily for the benefit of static +- type checkers. They are used to forward the parameter types of one +- callable to another callable, a pattern commonly found in higher order +- functions and decorators. They are only valid when used in ``Concatenate``, +- or as the first argument to ``Callable``, or as parameters for user-defined +- Generics. See class Generic for more information on generic types. An +- example for annotating a decorator:: +- +- T = TypeVar('T') +- P = ParamSpec('P') +- +- def add_logging(f: Callable[P, T]) -> Callable[P, T]: +- '''A type-safe decorator to add logging to a function.''' +- def inner(*args: P.args, **kwargs: P.kwargs) -> T: +- logging.info(f'{f.__name__} was called') +- return f(*args, **kwargs) +- return inner +- +- @add_logging +- def add_two(x: float, y: float) -> float: +- '''Add two numbers together.''' +- return x + y +- +- Parameter specification variables defined with covariant=True or +- contravariant=True can be used to declare covariant or contravariant +- generic types. These keyword arguments are valid, but their actual semantics +- are yet to be decided. See PEP 612 for details. +- +- Parameter specification variables can be introspected. e.g.: +- +- P.__name__ == 'P' +- P.__bound__ == None +- P.__covariant__ == False +- P.__contravariant__ == False +- +- Note that only parameter specification variables defined in global scope can +- be pickled. +- """ ++ new_args.extend(new_arg) ++ else: ++ new_args.append(new_arg) ++ params = tuple(new_args) + +- @property +- def args(self): +- return ParamSpecArgs(self) ++ return _GenericAlias(cls, params) + +- @property +- def kwargs(self): +- return ParamSpecKwargs(self) +- +- def __init__(self, name, *, bound=None, covariant=False, contravariant=False): +- self.__name__ = name +- super().__init__(bound, covariant, contravariant) +- def_mod = _caller() +- if def_mod != 'typing': +- self.__module__ = def_mod + +- def __typing_subst__(self, arg): +- if isinstance(arg, (list, tuple)): +- arg = tuple(_type_check(a, "Expected a type.") for a in arg) +- elif not _is_param_expr(arg): +- raise TypeError(f"Expected a list of types, an ellipsis, " +- f"ParamSpec, or Concatenate. Got {arg}") +- return arg ++def _generic_init_subclass(cls, *args, **kwargs): ++ super(Generic, cls).__init_subclass__(*args, **kwargs) ++ tvars = [] ++ if '__orig_bases__' in cls.__dict__: ++ error = Generic in cls.__orig_bases__ ++ else: ++ error = (Generic in cls.__bases__ and ++ cls.__name__ != 'Protocol' and ++ type(cls) != _TypedDictMeta) ++ if error: ++ raise TypeError("Cannot inherit from plain Generic") ++ if '__orig_bases__' in cls.__dict__: ++ tvars = _collect_parameters(cls.__orig_bases__) ++ # Look for Generic[T1, ..., Tn]. ++ # If found, tvars must be a subset of it. ++ # If not found, tvars is it. ++ # Also check for and reject plain Generic, ++ # and reject multiple Generic[...]. ++ gvars = None ++ for base in cls.__orig_bases__: ++ if (isinstance(base, _GenericAlias) and ++ base.__origin__ is Generic): ++ if gvars is not None: ++ raise TypeError( ++ "Cannot inherit from Generic[...] multiple times.") ++ gvars = base.__parameters__ ++ if gvars is not None: ++ tvarset = set(tvars) ++ gvarset = set(gvars) ++ if not tvarset <= gvarset: ++ s_vars = ', '.join(str(t) for t in tvars if t not in gvarset) ++ s_args = ', '.join(str(g) for g in gvars) ++ raise TypeError(f"Some type variables ({s_vars}) are" ++ f" not listed in Generic[{s_args}]") ++ tvars = gvars ++ cls.__parameters__ = tuple(tvars) + +- def __typing_prepare_subst__(self, alias, args): +- params = alias.__parameters__ +- i = params.index(self) +- if i >= len(args): +- raise TypeError(f"Too few arguments for {alias}") +- # Special case where Z[[int, str, bool]] == Z[int, str, bool] in PEP 612. +- if len(params) == 1 and not _is_param_expr(args[0]): +- assert i == 0 +- args = (args,) +- # Convert lists to tuples to help other libraries cache the results. +- elif isinstance(args[i], list): +- args = (*args[:i], tuple(args[i]), *args[i+1:]) +- return args + + def _is_dunder(attr): + return attr.startswith('__') and attr.endswith('__') +@@ -1812,113 +1656,6 @@ def __typing_is_unpacked_typevartuple__(self): + return isinstance(self.__args__[0], TypeVarTuple) + + +-class Generic: +- """Abstract base class for generic types. +- +- A generic type is typically declared by inheriting from +- this class parameterized with one or more type variables. +- For example, a generic mapping type might be defined as:: +- +- class Mapping(Generic[KT, VT]): +- def __getitem__(self, key: KT) -> VT: +- ... +- # Etc. +- +- This class can then be used as follows:: +- +- def lookup_name(mapping: Mapping[KT, VT], key: KT, default: VT) -> VT: +- try: +- return mapping[key] +- except KeyError: +- return default +- """ +- __slots__ = () +- _is_protocol = False +- +- @_tp_cache +- def __class_getitem__(cls, params): +- """Parameterizes a generic class. +- +- At least, parameterizing a generic class is the *main* thing this method +- does. For example, for some generic class `Foo`, this is called when we +- do `Foo[int]` - there, with `cls=Foo` and `params=int`. +- +- However, note that this method is also called when defining generic +- classes in the first place with `class Foo(Generic[T]): ...`. +- """ +- if not isinstance(params, tuple): +- params = (params,) +- +- params = tuple(_type_convert(p) for p in params) +- if cls in (Generic, Protocol): +- # Generic and Protocol can only be subscripted with unique type variables. +- if not params: +- raise TypeError( +- f"Parameter list to {cls.__qualname__}[...] cannot be empty" +- ) +- if not all(_is_typevar_like(p) for p in params): +- raise TypeError( +- f"Parameters to {cls.__name__}[...] must all be type variables " +- f"or parameter specification variables.") +- if len(set(params)) != len(params): +- raise TypeError( +- f"Parameters to {cls.__name__}[...] must all be unique") +- else: +- # Subscripting a regular Generic subclass. +- for param in cls.__parameters__: +- prepare = getattr(param, '__typing_prepare_subst__', None) +- if prepare is not None: +- params = prepare(cls, params) +- _check_generic(cls, params, len(cls.__parameters__)) +- +- new_args = [] +- for param, new_arg in zip(cls.__parameters__, params): +- if isinstance(param, TypeVarTuple): +- new_args.extend(new_arg) +- else: +- new_args.append(new_arg) +- params = tuple(new_args) +- +- return _GenericAlias(cls, params) +- +- def __init_subclass__(cls, *args, **kwargs): +- super().__init_subclass__(*args, **kwargs) +- tvars = [] +- if '__orig_bases__' in cls.__dict__: +- error = Generic in cls.__orig_bases__ +- else: +- error = (Generic in cls.__bases__ and +- cls.__name__ != 'Protocol' and +- type(cls) != _TypedDictMeta) +- if error: +- raise TypeError("Cannot inherit from plain Generic") +- if '__orig_bases__' in cls.__dict__: +- tvars = _collect_parameters(cls.__orig_bases__) +- # Look for Generic[T1, ..., Tn]. +- # If found, tvars must be a subset of it. +- # If not found, tvars is it. +- # Also check for and reject plain Generic, +- # and reject multiple Generic[...]. +- gvars = None +- for base in cls.__orig_bases__: +- if (isinstance(base, _GenericAlias) and +- base.__origin__ is Generic): +- if gvars is not None: +- raise TypeError( +- "Cannot inherit from Generic[...] multiple times.") +- gvars = base.__parameters__ +- if gvars is not None: +- tvarset = set(tvars) +- gvarset = set(gvars) +- if not tvarset <= gvarset: +- s_vars = ', '.join(str(t) for t in tvars if t not in gvarset) +- s_args = ', '.join(str(g) for g in gvars) +- raise TypeError(f"Some type variables ({s_vars}) are" +- f" not listed in Generic[{s_args}]") +- tvars = gvars +- cls.__parameters__ = tuple(tvars) +- +- + class _TypingEllipsis: + """Internal placeholder for ... (ellipsis).""" + +@@ -2024,6 +1761,18 @@ def _lazy_load_getattr_static(): + + _cleanups.append(_lazy_load_getattr_static.cache_clear) + ++def _pickle_psargs(psargs): ++ return ParamSpecArgs, (psargs.__origin__,) ++ ++copyreg.pickle(ParamSpecArgs, _pickle_psargs) ++ ++def _pickle_pskwargs(pskwargs): ++ return ParamSpecKwargs, (pskwargs.__origin__,) ++ ++copyreg.pickle(ParamSpecKwargs, _pickle_pskwargs) ++ ++del _pickle_psargs, _pickle_pskwargs ++ + + class _ProtocolMeta(ABCMeta): + # This metaclass is really unfortunate and exists only because of +@@ -2943,7 +2692,7 @@ def __new__(cls, typename, bases, ns): + module=ns['__module__']) + nm_tpl.__bases__ = bases + if Generic in bases: +- class_getitem = Generic.__class_getitem__.__func__ ++ class_getitem = _generic_class_getitem + nm_tpl.__class_getitem__ = classmethod(class_getitem) + # update from user namespace without overriding special namedtuple attributes + for key in ns: +diff --git a/Makefile.pre.in b/Makefile.pre.in +index 7c44b7be5d..d665741432 100644 +--- a/Makefile.pre.in ++++ b/Makefile.pre.in +@@ -479,6 +479,7 @@ OBJECT_OBJS= \ + Objects/structseq.o \ + Objects/tupleobject.o \ + Objects/typeobject.o \ ++ Objects/typevarobject.o \ + Objects/unicodeobject.o \ + Objects/unicodectype.o \ + Objects/unionobject.o \ +@@ -1767,6 +1768,7 @@ PYTHON_HEADERS= \ + $(srcdir)/Include/internal/pycore_tracemalloc.h \ + $(srcdir)/Include/internal/pycore_tuple.h \ + $(srcdir)/Include/internal/pycore_typeobject.h \ ++ $(srcdir)/Include/internal/pycore_typevarobject.h \ + $(srcdir)/Include/internal/pycore_ucnhash.h \ + $(srcdir)/Include/internal/pycore_unionobject.h \ + $(srcdir)/Include/internal/pycore_unicodeobject.h \ +diff --git a/Modules/Setup.bootstrap.in b/Modules/Setup.bootstrap.in +index e3e9b96b06..8ef0f203a8 100644 +--- a/Modules/Setup.bootstrap.in ++++ b/Modules/Setup.bootstrap.in +@@ -21,6 +21,7 @@ itertools itertoolsmodule.c + _sre _sre/sre.c + _thread _threadmodule.c + time timemodule.c ++_typing _typingmodule.c + _weakref _weakref.c + + # commonly used core modules +diff --git a/Modules/Setup.stdlib.in b/Modules/Setup.stdlib.in +index 95409d48c0..6db567d713 100644 +--- a/Modules/Setup.stdlib.in ++++ b/Modules/Setup.stdlib.in +@@ -41,7 +41,6 @@ + @MODULE__QUEUE_TRUE@_queue _queuemodule.c + @MODULE__RANDOM_TRUE@_random _randommodule.c + @MODULE__STRUCT_TRUE@_struct _struct.c +-@MODULE__TYPING_TRUE@_typing _typingmodule.c + @MODULE__XXSUBINTERPRETERS_TRUE@_xxsubinterpreters _xxsubinterpretersmodule.c + @MODULE__XXINTERPCHANNELS_TRUE@_xxinterpchannels _xxinterpchannelsmodule.c + @MODULE__ZONEINFO_TRUE@_zoneinfo _zoneinfo.c +diff --git a/Modules/_typingmodule.c b/Modules/_typingmodule.c +index 6428637563..ed2999c0b6 100644 +--- a/Modules/_typingmodule.c ++++ b/Modules/_typingmodule.c +@@ -1,6 +1,11 @@ + /* typing accelerator C extension: _typing module. */ + ++#ifndef Py_BUILD_CORE ++#define Py_BUILD_CORE ++#endif ++ + #include "Python.h" ++#include "internal/pycore_interp.h" + #include "clinic/_typingmodule.c.h" + + /*[clinic input] +@@ -35,7 +40,30 @@ static PyMethodDef typing_methods[] = { + PyDoc_STRVAR(typing_doc, + "Accelerators for the typing module.\n"); + ++static int ++_typing_exec(PyObject *m) ++{ ++ PyInterpreterState *interp = PyInterpreterState_Get(); ++ ++#define EXPORT_TYPE(name, typename) \ ++ if (PyModule_AddObjectRef(m, name, \ ++ (PyObject *)interp->cached_objects.typename) < 0) { \ ++ return -1; \ ++ } ++ ++ EXPORT_TYPE("TypeVar", typevar_type); ++ EXPORT_TYPE("TypeVarTuple", typevartuple_type); ++ EXPORT_TYPE("ParamSpec", paramspec_type); ++ EXPORT_TYPE("ParamSpecArgs", paramspecargs_type); ++ EXPORT_TYPE("ParamSpecKwargs", paramspeckwargs_type); ++ EXPORT_TYPE("TypeAliasType", typealias_type); ++ EXPORT_TYPE("Generic", generic_type); ++#undef EXPORT_TYPE ++ return 0; ++} ++ + static struct PyModuleDef_Slot _typingmodule_slots[] = { ++ {Py_mod_exec, _typing_exec}, + {Py_mod_multiple_interpreters, Py_MOD_PER_INTERPRETER_GIL_SUPPORTED}, + {0, NULL} + }; +diff --git a/Objects/clinic/typevarobject.c.h b/Objects/clinic/typevarobject.c.h +new file mode 100644 +index 0000000000..54189b9844 +--- /dev/null ++++ b/Objects/clinic/typevarobject.c.h +@@ -0,0 +1,786 @@ ++/*[clinic input] ++preserve ++[clinic start generated code]*/ ++ ++#if defined(Py_BUILD_CORE) && !defined(Py_BUILD_CORE_MODULE) ++# include "pycore_gc.h" // PyGC_Head ++# include "pycore_runtime.h" // _Py_ID() ++#endif ++ ++ ++PyDoc_STRVAR(typevar_new__doc__, ++"typevar(name, *constraints, *, bound=None, covariant=False,\n" ++" contravariant=False, infer_variance=False)\n" ++"--\n" ++"\n" ++"Create a TypeVar."); ++ ++static PyObject * ++typevar_new_impl(PyTypeObject *type, PyObject *name, PyObject *constraints, ++ PyObject *bound, int covariant, int contravariant, ++ int infer_variance); ++ ++static PyObject * ++typevar_new(PyTypeObject *type, PyObject *args, PyObject *kwargs) ++{ ++ PyObject *return_value = NULL; ++ #if defined(Py_BUILD_CORE) && !defined(Py_BUILD_CORE_MODULE) ++ ++ #define NUM_KEYWORDS 5 ++ static struct { ++ PyGC_Head _this_is_not_used; ++ PyObject_VAR_HEAD ++ PyObject *ob_item[NUM_KEYWORDS]; ++ } _kwtuple = { ++ .ob_base = PyVarObject_HEAD_INIT(&PyTuple_Type, NUM_KEYWORDS) ++ .ob_item = { &_Py_ID(name), &_Py_ID(bound), &_Py_ID(covariant), &_Py_ID(contravariant), &_Py_ID(infer_variance), }, ++ }; ++ #undef NUM_KEYWORDS ++ #define KWTUPLE (&_kwtuple.ob_base.ob_base) ++ ++ #else // !Py_BUILD_CORE ++ # define KWTUPLE NULL ++ #endif // !Py_BUILD_CORE ++ ++ static const char * const _keywords[] = {"name", "bound", "covariant", "contravariant", "infer_variance", NULL}; ++ static _PyArg_Parser _parser = { ++ .keywords = _keywords, ++ .fname = "typevar", ++ .kwtuple = KWTUPLE, ++ }; ++ #undef KWTUPLE ++ PyObject *argsbuf[6]; ++ PyObject * const *fastargs; ++ Py_ssize_t nargs = PyTuple_GET_SIZE(args); ++ Py_ssize_t noptargs = Py_MIN(nargs, 1) + (kwargs ? PyDict_GET_SIZE(kwargs) : 0) - 1; ++ PyObject *name; ++ PyObject *constraints = NULL; ++ PyObject *bound = Py_None; ++ int covariant = 0; ++ int contravariant = 0; ++ int infer_variance = 0; ++ ++ fastargs = _PyArg_UnpackKeywordsWithVararg(_PyTuple_CAST(args)->ob_item, nargs, kwargs, NULL, &_parser, 1, 1, 0, 1, argsbuf); ++ if (!fastargs) { ++ goto exit; ++ } ++ if (!PyUnicode_Check(fastargs[0])) { ++ _PyArg_BadArgument("typevar", "argument 'name'", "str", fastargs[0]); ++ goto exit; ++ } ++ name = fastargs[0]; ++ constraints = fastargs[1]; ++ if (!noptargs) { ++ goto skip_optional_kwonly; ++ } ++ if (fastargs[2]) { ++ bound = fastargs[2]; ++ if (!--noptargs) { ++ goto skip_optional_kwonly; ++ } ++ } ++ if (fastargs[3]) { ++ covariant = PyObject_IsTrue(fastargs[3]); ++ if (covariant < 0) { ++ goto exit; ++ } ++ if (!--noptargs) { ++ goto skip_optional_kwonly; ++ } ++ } ++ if (fastargs[4]) { ++ contravariant = PyObject_IsTrue(fastargs[4]); ++ if (contravariant < 0) { ++ goto exit; ++ } ++ if (!--noptargs) { ++ goto skip_optional_kwonly; ++ } ++ } ++ infer_variance = PyObject_IsTrue(fastargs[5]); ++ if (infer_variance < 0) { ++ goto exit; ++ } ++skip_optional_kwonly: ++ return_value = typevar_new_impl(type, name, constraints, bound, covariant, contravariant, infer_variance); ++ ++exit: ++ Py_XDECREF(constraints); ++ return return_value; ++} ++ ++PyDoc_STRVAR(typevar_typing_subst__doc__, ++"__typing_subst__($self, /, arg)\n" ++"--\n" ++"\n"); ++ ++#define TYPEVAR_TYPING_SUBST_METHODDEF \ ++ {"__typing_subst__", _PyCFunction_CAST(typevar_typing_subst), METH_FASTCALL|METH_KEYWORDS, typevar_typing_subst__doc__}, ++ ++static PyObject * ++typevar_typing_subst_impl(typevarobject *self, PyObject *arg); ++ ++static PyObject * ++typevar_typing_subst(typevarobject *self, PyObject *const *args, Py_ssize_t nargs, PyObject *kwnames) ++{ ++ PyObject *return_value = NULL; ++ #if defined(Py_BUILD_CORE) && !defined(Py_BUILD_CORE_MODULE) ++ ++ #define NUM_KEYWORDS 1 ++ static struct { ++ PyGC_Head _this_is_not_used; ++ PyObject_VAR_HEAD ++ PyObject *ob_item[NUM_KEYWORDS]; ++ } _kwtuple = { ++ .ob_base = PyVarObject_HEAD_INIT(&PyTuple_Type, NUM_KEYWORDS) ++ .ob_item = { &_Py_ID(arg), }, ++ }; ++ #undef NUM_KEYWORDS ++ #define KWTUPLE (&_kwtuple.ob_base.ob_base) ++ ++ #else // !Py_BUILD_CORE ++ # define KWTUPLE NULL ++ #endif // !Py_BUILD_CORE ++ ++ static const char * const _keywords[] = {"arg", NULL}; ++ static _PyArg_Parser _parser = { ++ .keywords = _keywords, ++ .fname = "__typing_subst__", ++ .kwtuple = KWTUPLE, ++ }; ++ #undef KWTUPLE ++ PyObject *argsbuf[1]; ++ PyObject *arg; ++ ++ args = _PyArg_UnpackKeywords(args, nargs, NULL, kwnames, &_parser, 1, 1, 0, argsbuf); ++ if (!args) { ++ goto exit; ++ } ++ arg = args[0]; ++ return_value = typevar_typing_subst_impl(self, arg); ++ ++exit: ++ return return_value; ++} ++ ++PyDoc_STRVAR(typevar_reduce__doc__, ++"__reduce__($self, /)\n" ++"--\n" ++"\n"); ++ ++#define TYPEVAR_REDUCE_METHODDEF \ ++ {"__reduce__", (PyCFunction)typevar_reduce, METH_NOARGS, typevar_reduce__doc__}, ++ ++static PyObject * ++typevar_reduce_impl(typevarobject *self); ++ ++static PyObject * ++typevar_reduce(typevarobject *self, PyObject *Py_UNUSED(ignored)) ++{ ++ return typevar_reduce_impl(self); ++} ++ ++PyDoc_STRVAR(paramspecargs_new__doc__, ++"paramspecargs(origin)\n" ++"--\n" ++"\n" ++"Create a ParamSpecArgs object."); ++ ++static PyObject * ++paramspecargs_new_impl(PyTypeObject *type, PyObject *origin); ++ ++static PyObject * ++paramspecargs_new(PyTypeObject *type, PyObject *args, PyObject *kwargs) ++{ ++ PyObject *return_value = NULL; ++ #if defined(Py_BUILD_CORE) && !defined(Py_BUILD_CORE_MODULE) ++ ++ #define NUM_KEYWORDS 1 ++ static struct { ++ PyGC_Head _this_is_not_used; ++ PyObject_VAR_HEAD ++ PyObject *ob_item[NUM_KEYWORDS]; ++ } _kwtuple = { ++ .ob_base = PyVarObject_HEAD_INIT(&PyTuple_Type, NUM_KEYWORDS) ++ .ob_item = { &_Py_ID(origin), }, ++ }; ++ #undef NUM_KEYWORDS ++ #define KWTUPLE (&_kwtuple.ob_base.ob_base) ++ ++ #else // !Py_BUILD_CORE ++ # define KWTUPLE NULL ++ #endif // !Py_BUILD_CORE ++ ++ static const char * const _keywords[] = {"origin", NULL}; ++ static _PyArg_Parser _parser = { ++ .keywords = _keywords, ++ .fname = "paramspecargs", ++ .kwtuple = KWTUPLE, ++ }; ++ #undef KWTUPLE ++ PyObject *argsbuf[1]; ++ PyObject * const *fastargs; ++ Py_ssize_t nargs = PyTuple_GET_SIZE(args); ++ PyObject *origin; ++ ++ fastargs = _PyArg_UnpackKeywords(_PyTuple_CAST(args)->ob_item, nargs, kwargs, NULL, &_parser, 1, 1, 0, argsbuf); ++ if (!fastargs) { ++ goto exit; ++ } ++ origin = fastargs[0]; ++ return_value = paramspecargs_new_impl(type, origin); ++ ++exit: ++ return return_value; ++} ++ ++PyDoc_STRVAR(paramspeckwargs_new__doc__, ++"paramspeckwargs(origin)\n" ++"--\n" ++"\n" ++"Create a ParamSpecKwargs object."); ++ ++static PyObject * ++paramspeckwargs_new_impl(PyTypeObject *type, PyObject *origin); ++ ++static PyObject * ++paramspeckwargs_new(PyTypeObject *type, PyObject *args, PyObject *kwargs) ++{ ++ PyObject *return_value = NULL; ++ #if defined(Py_BUILD_CORE) && !defined(Py_BUILD_CORE_MODULE) ++ ++ #define NUM_KEYWORDS 1 ++ static struct { ++ PyGC_Head _this_is_not_used; ++ PyObject_VAR_HEAD ++ PyObject *ob_item[NUM_KEYWORDS]; ++ } _kwtuple = { ++ .ob_base = PyVarObject_HEAD_INIT(&PyTuple_Type, NUM_KEYWORDS) ++ .ob_item = { &_Py_ID(origin), }, ++ }; ++ #undef NUM_KEYWORDS ++ #define KWTUPLE (&_kwtuple.ob_base.ob_base) ++ ++ #else // !Py_BUILD_CORE ++ # define KWTUPLE NULL ++ #endif // !Py_BUILD_CORE ++ ++ static const char * const _keywords[] = {"origin", NULL}; ++ static _PyArg_Parser _parser = { ++ .keywords = _keywords, ++ .fname = "paramspeckwargs", ++ .kwtuple = KWTUPLE, ++ }; ++ #undef KWTUPLE ++ PyObject *argsbuf[1]; ++ PyObject * const *fastargs; ++ Py_ssize_t nargs = PyTuple_GET_SIZE(args); ++ PyObject *origin; ++ ++ fastargs = _PyArg_UnpackKeywords(_PyTuple_CAST(args)->ob_item, nargs, kwargs, NULL, &_parser, 1, 1, 0, argsbuf); ++ if (!fastargs) { ++ goto exit; ++ } ++ origin = fastargs[0]; ++ return_value = paramspeckwargs_new_impl(type, origin); ++ ++exit: ++ return return_value; ++} ++ ++PyDoc_STRVAR(paramspec_new__doc__, ++"paramspec(name, *, bound=None, covariant=False, contravariant=False,\n" ++" infer_variance=False)\n" ++"--\n" ++"\n" ++"Create a ParamSpec object."); ++ ++static PyObject * ++paramspec_new_impl(PyTypeObject *type, PyObject *name, PyObject *bound, ++ int covariant, int contravariant, int infer_variance); ++ ++static PyObject * ++paramspec_new(PyTypeObject *type, PyObject *args, PyObject *kwargs) ++{ ++ PyObject *return_value = NULL; ++ #if defined(Py_BUILD_CORE) && !defined(Py_BUILD_CORE_MODULE) ++ ++ #define NUM_KEYWORDS 5 ++ static struct { ++ PyGC_Head _this_is_not_used; ++ PyObject_VAR_HEAD ++ PyObject *ob_item[NUM_KEYWORDS]; ++ } _kwtuple = { ++ .ob_base = PyVarObject_HEAD_INIT(&PyTuple_Type, NUM_KEYWORDS) ++ .ob_item = { &_Py_ID(name), &_Py_ID(bound), &_Py_ID(covariant), &_Py_ID(contravariant), &_Py_ID(infer_variance), }, ++ }; ++ #undef NUM_KEYWORDS ++ #define KWTUPLE (&_kwtuple.ob_base.ob_base) ++ ++ #else // !Py_BUILD_CORE ++ # define KWTUPLE NULL ++ #endif // !Py_BUILD_CORE ++ ++ static const char * const _keywords[] = {"name", "bound", "covariant", "contravariant", "infer_variance", NULL}; ++ static _PyArg_Parser _parser = { ++ .keywords = _keywords, ++ .fname = "paramspec", ++ .kwtuple = KWTUPLE, ++ }; ++ #undef KWTUPLE ++ PyObject *argsbuf[5]; ++ PyObject * const *fastargs; ++ Py_ssize_t nargs = PyTuple_GET_SIZE(args); ++ Py_ssize_t noptargs = nargs + (kwargs ? PyDict_GET_SIZE(kwargs) : 0) - 1; ++ PyObject *name; ++ PyObject *bound = Py_None; ++ int covariant = 0; ++ int contravariant = 0; ++ int infer_variance = 0; ++ ++ fastargs = _PyArg_UnpackKeywords(_PyTuple_CAST(args)->ob_item, nargs, kwargs, NULL, &_parser, 1, 1, 0, argsbuf); ++ if (!fastargs) { ++ goto exit; ++ } ++ if (!PyUnicode_Check(fastargs[0])) { ++ _PyArg_BadArgument("paramspec", "argument 'name'", "str", fastargs[0]); ++ goto exit; ++ } ++ name = fastargs[0]; ++ if (!noptargs) { ++ goto skip_optional_kwonly; ++ } ++ if (fastargs[1]) { ++ bound = fastargs[1]; ++ if (!--noptargs) { ++ goto skip_optional_kwonly; ++ } ++ } ++ if (fastargs[2]) { ++ covariant = PyObject_IsTrue(fastargs[2]); ++ if (covariant < 0) { ++ goto exit; ++ } ++ if (!--noptargs) { ++ goto skip_optional_kwonly; ++ } ++ } ++ if (fastargs[3]) { ++ contravariant = PyObject_IsTrue(fastargs[3]); ++ if (contravariant < 0) { ++ goto exit; ++ } ++ if (!--noptargs) { ++ goto skip_optional_kwonly; ++ } ++ } ++ infer_variance = PyObject_IsTrue(fastargs[4]); ++ if (infer_variance < 0) { ++ goto exit; ++ } ++skip_optional_kwonly: ++ return_value = paramspec_new_impl(type, name, bound, covariant, contravariant, infer_variance); ++ ++exit: ++ return return_value; ++} ++ ++PyDoc_STRVAR(paramspec_typing_subst__doc__, ++"__typing_subst__($self, /, arg)\n" ++"--\n" ++"\n"); ++ ++#define PARAMSPEC_TYPING_SUBST_METHODDEF \ ++ {"__typing_subst__", _PyCFunction_CAST(paramspec_typing_subst), METH_FASTCALL|METH_KEYWORDS, paramspec_typing_subst__doc__}, ++ ++static PyObject * ++paramspec_typing_subst_impl(paramspecobject *self, PyObject *arg); ++ ++static PyObject * ++paramspec_typing_subst(paramspecobject *self, PyObject *const *args, Py_ssize_t nargs, PyObject *kwnames) ++{ ++ PyObject *return_value = NULL; ++ #if defined(Py_BUILD_CORE) && !defined(Py_BUILD_CORE_MODULE) ++ ++ #define NUM_KEYWORDS 1 ++ static struct { ++ PyGC_Head _this_is_not_used; ++ PyObject_VAR_HEAD ++ PyObject *ob_item[NUM_KEYWORDS]; ++ } _kwtuple = { ++ .ob_base = PyVarObject_HEAD_INIT(&PyTuple_Type, NUM_KEYWORDS) ++ .ob_item = { &_Py_ID(arg), }, ++ }; ++ #undef NUM_KEYWORDS ++ #define KWTUPLE (&_kwtuple.ob_base.ob_base) ++ ++ #else // !Py_BUILD_CORE ++ # define KWTUPLE NULL ++ #endif // !Py_BUILD_CORE ++ ++ static const char * const _keywords[] = {"arg", NULL}; ++ static _PyArg_Parser _parser = { ++ .keywords = _keywords, ++ .fname = "__typing_subst__", ++ .kwtuple = KWTUPLE, ++ }; ++ #undef KWTUPLE ++ PyObject *argsbuf[1]; ++ PyObject *arg; ++ ++ args = _PyArg_UnpackKeywords(args, nargs, NULL, kwnames, &_parser, 1, 1, 0, argsbuf); ++ if (!args) { ++ goto exit; ++ } ++ arg = args[0]; ++ return_value = paramspec_typing_subst_impl(self, arg); ++ ++exit: ++ return return_value; ++} ++ ++PyDoc_STRVAR(paramspec_typing_prepare_subst__doc__, ++"__typing_prepare_subst__($self, /, alias, args)\n" ++"--\n" ++"\n"); ++ ++#define PARAMSPEC_TYPING_PREPARE_SUBST_METHODDEF \ ++ {"__typing_prepare_subst__", _PyCFunction_CAST(paramspec_typing_prepare_subst), METH_FASTCALL|METH_KEYWORDS, paramspec_typing_prepare_subst__doc__}, ++ ++static PyObject * ++paramspec_typing_prepare_subst_impl(paramspecobject *self, PyObject *alias, ++ PyObject *args); ++ ++static PyObject * ++paramspec_typing_prepare_subst(paramspecobject *self, PyObject *const *args, Py_ssize_t nargs, PyObject *kwnames) ++{ ++ PyObject *return_value = NULL; ++ #if defined(Py_BUILD_CORE) && !defined(Py_BUILD_CORE_MODULE) ++ ++ #define NUM_KEYWORDS 2 ++ static struct { ++ PyGC_Head _this_is_not_used; ++ PyObject_VAR_HEAD ++ PyObject *ob_item[NUM_KEYWORDS]; ++ } _kwtuple = { ++ .ob_base = PyVarObject_HEAD_INIT(&PyTuple_Type, NUM_KEYWORDS) ++ .ob_item = { &_Py_ID(alias), &_Py_ID(args), }, ++ }; ++ #undef NUM_KEYWORDS ++ #define KWTUPLE (&_kwtuple.ob_base.ob_base) ++ ++ #else // !Py_BUILD_CORE ++ # define KWTUPLE NULL ++ #endif // !Py_BUILD_CORE ++ ++ static const char * const _keywords[] = {"alias", "args", NULL}; ++ static _PyArg_Parser _parser = { ++ .keywords = _keywords, ++ .fname = "__typing_prepare_subst__", ++ .kwtuple = KWTUPLE, ++ }; ++ #undef KWTUPLE ++ PyObject *argsbuf[2]; ++ PyObject *alias; ++ PyObject *__clinic_args; ++ ++ args = _PyArg_UnpackKeywords(args, nargs, NULL, kwnames, &_parser, 2, 2, 0, argsbuf); ++ if (!args) { ++ goto exit; ++ } ++ alias = args[0]; ++ __clinic_args = args[1]; ++ return_value = paramspec_typing_prepare_subst_impl(self, alias, __clinic_args); ++ ++exit: ++ return return_value; ++} ++ ++PyDoc_STRVAR(paramspec_reduce__doc__, ++"__reduce__($self, /)\n" ++"--\n" ++"\n"); ++ ++#define PARAMSPEC_REDUCE_METHODDEF \ ++ {"__reduce__", (PyCFunction)paramspec_reduce, METH_NOARGS, paramspec_reduce__doc__}, ++ ++static PyObject * ++paramspec_reduce_impl(paramspecobject *self); ++ ++static PyObject * ++paramspec_reduce(paramspecobject *self, PyObject *Py_UNUSED(ignored)) ++{ ++ return paramspec_reduce_impl(self); ++} ++ ++PyDoc_STRVAR(typevartuple__doc__, ++"typevartuple(name)\n" ++"--\n" ++"\n" ++"Create a new TypeVarTuple with the given name."); ++ ++static PyObject * ++typevartuple_impl(PyTypeObject *type, PyObject *name); ++ ++static PyObject * ++typevartuple(PyTypeObject *type, PyObject *args, PyObject *kwargs) ++{ ++ PyObject *return_value = NULL; ++ #if defined(Py_BUILD_CORE) && !defined(Py_BUILD_CORE_MODULE) ++ ++ #define NUM_KEYWORDS 1 ++ static struct { ++ PyGC_Head _this_is_not_used; ++ PyObject_VAR_HEAD ++ PyObject *ob_item[NUM_KEYWORDS]; ++ } _kwtuple = { ++ .ob_base = PyVarObject_HEAD_INIT(&PyTuple_Type, NUM_KEYWORDS) ++ .ob_item = { &_Py_ID(name), }, ++ }; ++ #undef NUM_KEYWORDS ++ #define KWTUPLE (&_kwtuple.ob_base.ob_base) ++ ++ #else // !Py_BUILD_CORE ++ # define KWTUPLE NULL ++ #endif // !Py_BUILD_CORE ++ ++ static const char * const _keywords[] = {"name", NULL}; ++ static _PyArg_Parser _parser = { ++ .keywords = _keywords, ++ .fname = "typevartuple", ++ .kwtuple = KWTUPLE, ++ }; ++ #undef KWTUPLE ++ PyObject *argsbuf[1]; ++ PyObject * const *fastargs; ++ Py_ssize_t nargs = PyTuple_GET_SIZE(args); ++ PyObject *name; ++ ++ fastargs = _PyArg_UnpackKeywords(_PyTuple_CAST(args)->ob_item, nargs, kwargs, NULL, &_parser, 1, 1, 0, argsbuf); ++ if (!fastargs) { ++ goto exit; ++ } ++ if (!PyUnicode_Check(fastargs[0])) { ++ _PyArg_BadArgument("typevartuple", "argument 'name'", "str", fastargs[0]); ++ goto exit; ++ } ++ name = fastargs[0]; ++ return_value = typevartuple_impl(type, name); ++ ++exit: ++ return return_value; ++} ++ ++PyDoc_STRVAR(typevartuple_typing_subst__doc__, ++"__typing_subst__($self, /, arg)\n" ++"--\n" ++"\n"); ++ ++#define TYPEVARTUPLE_TYPING_SUBST_METHODDEF \ ++ {"__typing_subst__", _PyCFunction_CAST(typevartuple_typing_subst), METH_FASTCALL|METH_KEYWORDS, typevartuple_typing_subst__doc__}, ++ ++static PyObject * ++typevartuple_typing_subst_impl(typevartupleobject *self, PyObject *arg); ++ ++static PyObject * ++typevartuple_typing_subst(typevartupleobject *self, PyObject *const *args, Py_ssize_t nargs, PyObject *kwnames) ++{ ++ PyObject *return_value = NULL; ++ #if defined(Py_BUILD_CORE) && !defined(Py_BUILD_CORE_MODULE) ++ ++ #define NUM_KEYWORDS 1 ++ static struct { ++ PyGC_Head _this_is_not_used; ++ PyObject_VAR_HEAD ++ PyObject *ob_item[NUM_KEYWORDS]; ++ } _kwtuple = { ++ .ob_base = PyVarObject_HEAD_INIT(&PyTuple_Type, NUM_KEYWORDS) ++ .ob_item = { &_Py_ID(arg), }, ++ }; ++ #undef NUM_KEYWORDS ++ #define KWTUPLE (&_kwtuple.ob_base.ob_base) ++ ++ #else // !Py_BUILD_CORE ++ # define KWTUPLE NULL ++ #endif // !Py_BUILD_CORE ++ ++ static const char * const _keywords[] = {"arg", NULL}; ++ static _PyArg_Parser _parser = { ++ .keywords = _keywords, ++ .fname = "__typing_subst__", ++ .kwtuple = KWTUPLE, ++ }; ++ #undef KWTUPLE ++ PyObject *argsbuf[1]; ++ PyObject *arg; ++ ++ args = _PyArg_UnpackKeywords(args, nargs, NULL, kwnames, &_parser, 1, 1, 0, argsbuf); ++ if (!args) { ++ goto exit; ++ } ++ arg = args[0]; ++ return_value = typevartuple_typing_subst_impl(self, arg); ++ ++exit: ++ return return_value; ++} ++ ++PyDoc_STRVAR(typevartuple_typing_prepare_subst__doc__, ++"__typing_prepare_subst__($self, /, alias, args)\n" ++"--\n" ++"\n"); ++ ++#define TYPEVARTUPLE_TYPING_PREPARE_SUBST_METHODDEF \ ++ {"__typing_prepare_subst__", _PyCFunction_CAST(typevartuple_typing_prepare_subst), METH_FASTCALL|METH_KEYWORDS, typevartuple_typing_prepare_subst__doc__}, ++ ++static PyObject * ++typevartuple_typing_prepare_subst_impl(typevartupleobject *self, ++ PyObject *alias, PyObject *args); ++ ++static PyObject * ++typevartuple_typing_prepare_subst(typevartupleobject *self, PyObject *const *args, Py_ssize_t nargs, PyObject *kwnames) ++{ ++ PyObject *return_value = NULL; ++ #if defined(Py_BUILD_CORE) && !defined(Py_BUILD_CORE_MODULE) ++ ++ #define NUM_KEYWORDS 2 ++ static struct { ++ PyGC_Head _this_is_not_used; ++ PyObject_VAR_HEAD ++ PyObject *ob_item[NUM_KEYWORDS]; ++ } _kwtuple = { ++ .ob_base = PyVarObject_HEAD_INIT(&PyTuple_Type, NUM_KEYWORDS) ++ .ob_item = { &_Py_ID(alias), &_Py_ID(args), }, ++ }; ++ #undef NUM_KEYWORDS ++ #define KWTUPLE (&_kwtuple.ob_base.ob_base) ++ ++ #else // !Py_BUILD_CORE ++ # define KWTUPLE NULL ++ #endif // !Py_BUILD_CORE ++ ++ static const char * const _keywords[] = {"alias", "args", NULL}; ++ static _PyArg_Parser _parser = { ++ .keywords = _keywords, ++ .fname = "__typing_prepare_subst__", ++ .kwtuple = KWTUPLE, ++ }; ++ #undef KWTUPLE ++ PyObject *argsbuf[2]; ++ PyObject *alias; ++ PyObject *__clinic_args; ++ ++ args = _PyArg_UnpackKeywords(args, nargs, NULL, kwnames, &_parser, 2, 2, 0, argsbuf); ++ if (!args) { ++ goto exit; ++ } ++ alias = args[0]; ++ __clinic_args = args[1]; ++ return_value = typevartuple_typing_prepare_subst_impl(self, alias, __clinic_args); ++ ++exit: ++ return return_value; ++} ++ ++PyDoc_STRVAR(typevartuple_reduce__doc__, ++"__reduce__($self, /)\n" ++"--\n" ++"\n"); ++ ++#define TYPEVARTUPLE_REDUCE_METHODDEF \ ++ {"__reduce__", (PyCFunction)typevartuple_reduce, METH_NOARGS, typevartuple_reduce__doc__}, ++ ++static PyObject * ++typevartuple_reduce_impl(typevartupleobject *self); ++ ++static PyObject * ++typevartuple_reduce(typevartupleobject *self, PyObject *Py_UNUSED(ignored)) ++{ ++ return typevartuple_reduce_impl(self); ++} ++ ++PyDoc_STRVAR(typealias_reduce__doc__, ++"__reduce__($self, /)\n" ++"--\n" ++"\n"); ++ ++#define TYPEALIAS_REDUCE_METHODDEF \ ++ {"__reduce__", (PyCFunction)typealias_reduce, METH_NOARGS, typealias_reduce__doc__}, ++ ++static PyObject * ++typealias_reduce_impl(typealiasobject *self); ++ ++static PyObject * ++typealias_reduce(typealiasobject *self, PyObject *Py_UNUSED(ignored)) ++{ ++ return typealias_reduce_impl(self); ++} ++ ++PyDoc_STRVAR(typealias_new__doc__, ++"typealias(name, value, *, type_params=)\n" ++"--\n" ++"\n" ++"Create a TypeAliasType."); ++ ++static PyObject * ++typealias_new_impl(PyTypeObject *type, PyObject *name, PyObject *value, ++ PyObject *type_params); ++ ++static PyObject * ++typealias_new(PyTypeObject *type, PyObject *args, PyObject *kwargs) ++{ ++ PyObject *return_value = NULL; ++ #if defined(Py_BUILD_CORE) && !defined(Py_BUILD_CORE_MODULE) ++ ++ #define NUM_KEYWORDS 3 ++ static struct { ++ PyGC_Head _this_is_not_used; ++ PyObject_VAR_HEAD ++ PyObject *ob_item[NUM_KEYWORDS]; ++ } _kwtuple = { ++ .ob_base = PyVarObject_HEAD_INIT(&PyTuple_Type, NUM_KEYWORDS) ++ .ob_item = { &_Py_ID(name), &_Py_ID(value), &_Py_ID(type_params), }, ++ }; ++ #undef NUM_KEYWORDS ++ #define KWTUPLE (&_kwtuple.ob_base.ob_base) ++ ++ #else // !Py_BUILD_CORE ++ # define KWTUPLE NULL ++ #endif // !Py_BUILD_CORE ++ ++ static const char * const _keywords[] = {"name", "value", "type_params", NULL}; ++ static _PyArg_Parser _parser = { ++ .keywords = _keywords, ++ .fname = "typealias", ++ .kwtuple = KWTUPLE, ++ }; ++ #undef KWTUPLE ++ PyObject *argsbuf[3]; ++ PyObject * const *fastargs; ++ Py_ssize_t nargs = PyTuple_GET_SIZE(args); ++ Py_ssize_t noptargs = nargs + (kwargs ? PyDict_GET_SIZE(kwargs) : 0) - 2; ++ PyObject *name; ++ PyObject *value; ++ PyObject *type_params = NULL; ++ ++ fastargs = _PyArg_UnpackKeywords(_PyTuple_CAST(args)->ob_item, nargs, kwargs, NULL, &_parser, 2, 2, 0, argsbuf); ++ if (!fastargs) { ++ goto exit; ++ } ++ if (!PyUnicode_Check(fastargs[0])) { ++ _PyArg_BadArgument("typealias", "argument 'name'", "str", fastargs[0]); ++ goto exit; ++ } ++ name = fastargs[0]; ++ value = fastargs[1]; ++ if (!noptargs) { ++ goto skip_optional_kwonly; ++ } ++ type_params = fastargs[2]; ++skip_optional_kwonly: ++ return_value = typealias_new_impl(type, name, value, type_params); ++ ++exit: ++ return return_value; ++} ++/*[clinic end generated code: output=807bcd30ebd10ac3 input=a9049054013a1b77]*/ +diff --git a/Objects/funcobject.c b/Objects/funcobject.c +index 78c1144afc..69898bf722 100644 +--- a/Objects/funcobject.c ++++ b/Objects/funcobject.c +@@ -127,6 +127,7 @@ _PyFunction_FromConstructor(PyFrameConstructor *constr) + PyErr_Clear(); + } + op->func_annotations = NULL; ++ op->func_typeparams = NULL; + op->vectorcall = _PyFunction_Vectorcall; + op->func_version = 0; + _PyObject_GC_TRACK(op); +@@ -202,6 +203,7 @@ PyFunction_NewWithQualName(PyObject *code, PyObject *globals, PyObject *qualname + op->func_weakreflist = NULL; + op->func_module = module; + op->func_annotations = NULL; ++ op->func_typeparams = NULL; + op->vectorcall = _PyFunction_Vectorcall; + op->func_version = 0; + _PyObject_GC_TRACK(op); +@@ -652,6 +654,28 @@ func_set_annotations(PyFunctionObject *op, PyObject *value, void *Py_UNUSED(igno + return 0; + } + ++static PyObject * ++func_get_type_params(PyFunctionObject *op, void *Py_UNUSED(ignored)) ++{ ++ if (op->func_typeparams == NULL) { ++ return PyTuple_New(0); ++ } ++ ++ assert(PyTuple_Check(op->func_typeparams)); ++ return Py_NewRef(op->func_typeparams); ++} ++ ++PyObject * ++_Py_set_function_type_params(PyThreadState *Py_UNUSED(ignored), PyObject *func, ++ PyObject *type_params) ++{ ++ assert(PyFunction_Check(func)); ++ assert(PyTuple_Check(type_params)); ++ PyFunctionObject *f = (PyFunctionObject *)func; ++ Py_XSETREF(f->func_typeparams, Py_NewRef(type_params)); ++ return Py_NewRef(func); ++} ++ + static PyGetSetDef func_getsetlist[] = { + {"__code__", (getter)func_get_code, (setter)func_set_code}, + {"__defaults__", (getter)func_get_defaults, +@@ -663,6 +687,7 @@ static PyGetSetDef func_getsetlist[] = { + {"__dict__", PyObject_GenericGetDict, PyObject_GenericSetDict}, + {"__name__", (getter)func_get_name, (setter)func_set_name}, + {"__qualname__", (getter)func_get_qualname, (setter)func_set_qualname}, ++ {"__type_params__", (getter)func_get_type_params, NULL}, + {NULL} /* Sentinel */ + }; + +@@ -783,6 +808,7 @@ func_clear(PyFunctionObject *op) + Py_CLEAR(op->func_dict); + Py_CLEAR(op->func_closure); + Py_CLEAR(op->func_annotations); ++ Py_CLEAR(op->func_typeparams); + // Don't Py_CLEAR(op->func_code), since code is always required + // to be non-NULL. Similarly, name and qualname shouldn't be NULL. + // However, name and qualname could be str subclasses, so they +@@ -837,6 +863,7 @@ func_traverse(PyFunctionObject *f, visitproc visit, void *arg) + Py_VISIT(f->func_dict); + Py_VISIT(f->func_closure); + Py_VISIT(f->func_annotations); ++ Py_VISIT(f->func_typeparams); + Py_VISIT(f->func_qualname); + return 0; + } +diff --git a/Objects/object.c b/Objects/object.c +index a7c79c673d..f311866543 100644 +--- a/Objects/object.c ++++ b/Objects/object.c +@@ -14,6 +14,7 @@ + #include "pycore_pymem.h" // _PyMem_IsPtrFreed() + #include "pycore_pystate.h" // _PyThreadState_GET() + #include "pycore_symtable.h" // PySTEntry_Type ++#include "pycore_typevarobject.h" // _PyTypeVar_Type etc., _Py_initialize_generic + #include "pycore_typeobject.h" // _PyBufferWrapper_Type + #include "pycore_unionobject.h" // _PyUnion_Type + #include "pycore_interpreteridobject.h" // _PyInterpreterID_Type +@@ -2139,6 +2140,11 @@ _PyTypes_InitTypes(PyInterpreterState *interp) + } + } + ++ // Must be after static types are initialized ++ if (_Py_initialize_generic(interp) < 0) { ++ return _PyStatus_ERR("Can't initialize generic types"); ++ } ++ + return _PyStatus_OK(); + } + +diff --git a/Objects/typeobject.c b/Objects/typeobject.c +index c1525320a7..624dc63ce8 100644 +--- a/Objects/typeobject.c ++++ b/Objects/typeobject.c +@@ -1460,6 +1460,18 @@ type_get_annotations(PyTypeObject *type, void *context) + return annotations; + } + ++static PyObject * ++type_get_type_params(PyTypeObject *type, void *context) ++{ ++ PyObject *params = PyDict_GetItem(lookup_tp_dict(type), &_Py_ID(__type_params__)); ++ ++ if (params) { ++ return Py_NewRef(params); ++ } ++ ++ return PyTuple_New(0); ++} ++ + static int + type_set_annotations(PyTypeObject *type, PyObject *value, void *context) + { +@@ -1536,6 +1548,7 @@ static PyGetSetDef type_getsets[] = { + {"__doc__", (getter)type_get_doc, (setter)type_set_doc, NULL}, + {"__text_signature__", (getter)type_get_text_signature, NULL, NULL}, + {"__annotations__", (getter)type_get_annotations, (setter)type_set_annotations, NULL}, ++ {"__type_params__", (getter)type_get_type_params, NULL, NULL}, + {0} + }; + +@@ -3130,11 +3143,12 @@ type_new_copy_slots(type_new_ctx *ctx, PyObject *dict) + goto error; + } + if (r > 0) { +- /* CPython inserts __qualname__ and __classcell__ (when needed) ++ /* CPython inserts these names (when needed) + into the namespace when creating a class. They will be deleted + below so won't act as class variables. */ + if (!_PyUnicode_Equal(slot, &_Py_ID(__qualname__)) && +- !_PyUnicode_Equal(slot, &_Py_ID(__classcell__))) ++ !_PyUnicode_Equal(slot, &_Py_ID(__classcell__)) && ++ !_PyUnicode_Equal(slot, &_Py_ID(__classdictcell__))) + { + PyErr_Format(PyExc_ValueError, + "%R in __slots__ conflicts with class variable", +@@ -3585,6 +3599,32 @@ type_new_set_classcell(PyTypeObject *type) + return 0; + } + ++static int ++type_new_set_classdictcell(PyTypeObject *type) ++{ ++ PyObject *dict = lookup_tp_dict(type); ++ PyObject *cell = PyDict_GetItemWithError(dict, &_Py_ID(__classdictcell__)); ++ if (cell == NULL) { ++ if (PyErr_Occurred()) { ++ return -1; ++ } ++ return 0; ++ } ++ ++ /* At least one method requires a reference to the dict of its defining class */ ++ if (!PyCell_Check(cell)) { ++ PyErr_Format(PyExc_TypeError, ++ "__classdictcell__ must be a nonlocal cell, not %.200R", ++ Py_TYPE(cell)); ++ return -1; ++ } ++ ++ (void)PyCell_Set(cell, (PyObject *)dict); ++ if (PyDict_DelItem(dict, &_Py_ID(__classdictcell__)) < 0) { ++ return -1; ++ } ++ return 0; ++} + + static int + type_new_set_attrs(const type_new_ctx *ctx, PyTypeObject *type) +@@ -3629,6 +3669,9 @@ type_new_set_attrs(const type_new_ctx *ctx, PyTypeObject *type) + if (type_new_set_classcell(type) < 0) { + return -1; + } ++ if (type_new_set_classdictcell(type) < 0) { ++ return -1; ++ } + return 0; + } + +diff --git a/Objects/typevarobject.c b/Objects/typevarobject.c +new file mode 100644 +index 0000000000..b0578756f7 +--- /dev/null ++++ b/Objects/typevarobject.c +@@ -0,0 +1,1620 @@ ++// TypeVar, TypeVarTuple, and ParamSpec ++#include "Python.h" ++#include "pycore_object.h" // _PyObject_GC_TRACK/UNTRACK ++#include "pycore_typevarobject.h" ++#include "pycore_unionobject.h" // _Py_union_type_or ++#include "structmember.h" ++ ++/*[clinic input] ++class typevar "typevarobject *" "&_PyTypeVar_Type" ++class paramspec "paramspecobject *" "&_PyParamSpec_Type" ++class paramspecargs "paramspecattrobject *" "&_PyParamSpecArgs_Type" ++class paramspeckwargs "paramspecattrobject *" "&_PyParamSpecKwargs_Type" ++class typevartuple "typevartupleobject *" "&_PyTypeVarTuple_Type" ++class typealias "typealiasobject *" "&_PyTypeAlias_Type" ++class Generic "PyObject *" "&PyGeneric_Type" ++[clinic start generated code]*/ ++/*[clinic end generated code: output=da39a3ee5e6b4b0d input=aa86741931a0f55c]*/ ++ ++typedef struct { ++ PyObject_HEAD ++ PyObject *name; ++ PyObject *bound; ++ PyObject *evaluate_bound; ++ PyObject *constraints; ++ PyObject *evaluate_constraints; ++ bool covariant; ++ bool contravariant; ++ bool infer_variance; ++} typevarobject; ++ ++typedef struct { ++ PyObject_HEAD ++ PyObject *name; ++} typevartupleobject; ++ ++typedef struct { ++ PyObject_HEAD ++ PyObject *name; ++ PyObject *bound; ++ bool covariant; ++ bool contravariant; ++ bool infer_variance; ++} paramspecobject; ++ ++typedef struct { ++ PyObject_HEAD ++ PyObject *name; ++ PyObject *type_params; ++ PyObject *compute_value; ++ PyObject *value; ++} typealiasobject; ++ ++#include "clinic/typevarobject.c.h" ++ ++static PyObject * ++call_typing_func_object(const char *name, PyObject **args, size_t nargs) ++{ ++ PyObject *typing = PyImport_ImportModule("typing"); ++ if (typing == NULL) { ++ return NULL; ++ } ++ PyObject *func = PyObject_GetAttrString(typing, name); ++ if (func == NULL) { ++ Py_DECREF(typing); ++ return NULL; ++ } ++ PyObject *result = PyObject_Vectorcall(func, args, nargs, NULL); ++ Py_DECREF(func); ++ Py_DECREF(typing); ++ return result; ++} ++ ++static PyObject * ++type_check(PyObject *arg, const char *msg) ++{ ++ // Calling typing.py here leads to bootstrapping problems ++ if (Py_IsNone(arg)) { ++ return Py_NewRef(Py_TYPE(arg)); ++ } ++ PyObject *message_str = PyUnicode_FromString(msg); ++ if (message_str == NULL) { ++ return NULL; ++ } ++ PyObject *args[2] = {arg, message_str}; ++ PyObject *result = call_typing_func_object("_type_check", args, 2); ++ Py_DECREF(message_str); ++ return result; ++} ++ ++/* ++ * Return a typing.Union. This is used as the nb_or (|) operator for ++ * TypeVar and ParamSpec. We use this rather than _Py_union_type_or ++ * (which would produce a types.Union) because historically TypeVar ++ * supported unions with string forward references, and we want to ++ * preserve that behavior. _Py_union_type_or only allows a small set ++ * of types. ++ */ ++static PyObject * ++make_union(PyObject *self, PyObject *other) ++{ ++ PyObject *args[2] = {self, other}; ++ PyObject *result = call_typing_func_object("_make_union", args, 2); ++ return result; ++} ++ ++static PyObject * ++caller(void) ++{ ++ _PyInterpreterFrame *f = _PyThreadState_GET()->cframe->current_frame; ++ if (f == NULL) { ++ Py_RETURN_NONE; ++ } ++ if (f == NULL || f->f_funcobj == NULL) { ++ Py_RETURN_NONE; ++ } ++ PyObject *r = PyFunction_GetModule(f->f_funcobj); ++ if (!r) { ++ PyErr_Clear(); ++ Py_RETURN_NONE; ++ } ++ return Py_NewRef(r); ++} ++ ++static PyObject * ++typevartuple_unpack(PyObject *tvt) ++{ ++ PyObject *typing = PyImport_ImportModule("typing"); ++ if (typing == NULL) { ++ return NULL; ++ } ++ PyObject *unpack = PyObject_GetAttrString(typing, "Unpack"); ++ if (unpack == NULL) { ++ Py_DECREF(typing); ++ return NULL; ++ } ++ PyObject *unpacked = PyObject_GetItem(unpack, tvt); ++ Py_DECREF(typing); ++ Py_DECREF(unpack); ++ return unpacked; ++} ++ ++static int ++contains_typevartuple(PyTupleObject *params) ++{ ++ Py_ssize_t n = PyTuple_GET_SIZE(params); ++ PyTypeObject *tp = PyInterpreterState_Get()->cached_objects.typevartuple_type; ++ for (Py_ssize_t i = 0; i < n; i++) { ++ PyObject *param = PyTuple_GET_ITEM(params, i); ++ if (Py_IS_TYPE(param, tp)) { ++ return 1; ++ } ++ } ++ return 0; ++} ++ ++static PyObject * ++unpack_typevartuples(PyObject *params) ++{ ++ assert(PyTuple_Check(params)); ++ // TypeVarTuple must be unpacked when passed to Generic, so we do that here. ++ if (contains_typevartuple((PyTupleObject *)params)) { ++ Py_ssize_t n = PyTuple_GET_SIZE(params); ++ PyObject *new_params = PyTuple_New(n); ++ if (new_params == NULL) { ++ return NULL; ++ } ++ PyTypeObject *tp = PyInterpreterState_Get()->cached_objects.typevartuple_type; ++ for (Py_ssize_t i = 0; i < n; i++) { ++ PyObject *param = PyTuple_GET_ITEM(params, i); ++ if (Py_IS_TYPE(param, tp)) { ++ PyObject *unpacked = typevartuple_unpack(param); ++ if (unpacked == NULL) { ++ Py_DECREF(new_params); ++ return NULL; ++ } ++ PyTuple_SET_ITEM(new_params, i, unpacked); ++ } ++ else { ++ PyTuple_SET_ITEM(new_params, i, Py_NewRef(param)); ++ } ++ } ++ return new_params; ++ } ++ else { ++ return Py_NewRef(params); ++ } ++} ++ ++static void ++typevar_dealloc(PyObject *self) ++{ ++ PyTypeObject *tp = Py_TYPE(self); ++ typevarobject *tv = (typevarobject *)self; ++ ++ _PyObject_GC_UNTRACK(self); ++ ++ Py_DECREF(tv->name); ++ Py_XDECREF(tv->bound); ++ Py_XDECREF(tv->evaluate_bound); ++ Py_XDECREF(tv->constraints); ++ Py_XDECREF(tv->evaluate_constraints); ++ _PyObject_ClearManagedDict(self); ++ ++ Py_TYPE(self)->tp_free(self); ++ Py_DECREF(tp); ++} ++ ++static int ++typevar_traverse(PyObject *self, visitproc visit, void *arg) ++{ ++ Py_VISIT(Py_TYPE(self)); ++ typevarobject *tv = (typevarobject *)self; ++ Py_VISIT(tv->bound); ++ Py_VISIT(tv->evaluate_bound); ++ Py_VISIT(tv->constraints); ++ Py_VISIT(tv->evaluate_constraints); ++ _PyObject_VisitManagedDict(self, visit, arg); ++ return 0; ++} ++ ++static int ++typevar_clear(typevarobject *self) ++{ ++ Py_CLEAR(self->bound); ++ Py_CLEAR(self->evaluate_bound); ++ Py_CLEAR(self->constraints); ++ Py_CLEAR(self->evaluate_constraints); ++ _PyObject_ClearManagedDict((PyObject *)self); ++ return 0; ++} ++ ++static PyObject * ++typevar_repr(PyObject *self) ++{ ++ typevarobject *tv = (typevarobject *)self; ++ ++ if (tv->infer_variance) { ++ return Py_NewRef(tv->name); ++ } ++ ++ char variance = tv->covariant ? '+' : tv->contravariant ? '-' : '~'; ++ return PyUnicode_FromFormat("%c%U", variance, tv->name); ++} ++ ++static PyMemberDef typevar_members[] = { ++ {"__name__", T_OBJECT, offsetof(typevarobject, name), READONLY}, ++ {"__covariant__", T_BOOL, offsetof(typevarobject, covariant), READONLY}, ++ {"__contravariant__", T_BOOL, offsetof(typevarobject, contravariant), READONLY}, ++ {"__infer_variance__", T_BOOL, offsetof(typevarobject, infer_variance), READONLY}, ++ {0} ++}; ++ ++static PyObject * ++typevar_bound(typevarobject *self, void *Py_UNUSED(ignored)) ++{ ++ if (self->bound != NULL) { ++ return Py_NewRef(self->bound); ++ } ++ if (self->evaluate_bound == NULL) { ++ Py_RETURN_NONE; ++ } ++ PyObject *bound = PyObject_CallNoArgs(self->evaluate_bound); ++ self->bound = Py_XNewRef(bound); ++ return bound; ++} ++ ++static PyObject * ++typevar_constraints(typevarobject *self, void *Py_UNUSED(ignored)) ++{ ++ if (self->constraints != NULL) { ++ return Py_NewRef(self->constraints); ++ } ++ if (self->evaluate_constraints == NULL) { ++ Py_RETURN_NONE; ++ } ++ PyObject *constraints = PyObject_CallNoArgs(self->evaluate_constraints); ++ self->constraints = Py_XNewRef(constraints); ++ return constraints; ++} ++ ++static PyGetSetDef typevar_getset[] = { ++ {"__bound__", (getter)typevar_bound, NULL, NULL, NULL}, ++ {"__constraints__", (getter)typevar_constraints, NULL, NULL, NULL}, ++ {0} ++}; ++ ++static typevarobject * ++typevar_alloc(PyObject *name, PyObject *bound, PyObject *evaluate_bound, ++ PyObject *constraints, PyObject *evaluate_constraints, ++ bool covariant, bool contravariant, bool infer_variance, ++ PyObject *module) ++{ ++ PyTypeObject *tp = PyInterpreterState_Get()->cached_objects.typevar_type; ++ assert(tp != NULL); ++ typevarobject *tv = PyObject_GC_New(typevarobject, tp); ++ if (tv == NULL) { ++ return NULL; ++ } ++ ++ tv->name = Py_NewRef(name); ++ ++ tv->bound = Py_XNewRef(bound); ++ tv->evaluate_bound = Py_XNewRef(evaluate_bound); ++ tv->constraints = Py_XNewRef(constraints); ++ tv->evaluate_constraints = Py_XNewRef(evaluate_constraints); ++ ++ tv->covariant = covariant; ++ tv->contravariant = contravariant; ++ tv->infer_variance = infer_variance; ++ _PyObject_GC_TRACK(tv); ++ ++ if (module != NULL) { ++ if (PyObject_SetAttrString((PyObject *)tv, "__module__", module) < 0) { ++ Py_DECREF(tv); ++ return NULL; ++ } ++ } ++ ++ return tv; ++} ++ ++/*[clinic input] ++@classmethod ++typevar.__new__ as typevar_new ++ ++ name: object(subclass_of="&PyUnicode_Type") ++ *constraints: object ++ * ++ bound: object = None ++ covariant: bool = False ++ contravariant: bool = False ++ infer_variance: bool = False ++ ++Create a TypeVar. ++[clinic start generated code]*/ ++ ++static PyObject * ++typevar_new_impl(PyTypeObject *type, PyObject *name, PyObject *constraints, ++ PyObject *bound, int covariant, int contravariant, ++ int infer_variance) ++/*[clinic end generated code: output=1d200450ee99226d input=2c07ab87c94f462b]*/ ++{ ++ if (covariant && contravariant) { ++ PyErr_SetString(PyExc_ValueError, ++ "Bivariant types are not supported."); ++ return NULL; ++ } ++ ++ if (infer_variance && (covariant || contravariant)) { ++ PyErr_SetString(PyExc_ValueError, ++ "Variance cannot be specified with infer_variance."); ++ return NULL; ++ } ++ ++ if (Py_IsNone(bound)) { ++ bound = NULL; ++ } ++ if (bound != NULL) { ++ bound = type_check(bound, "Bound must be a type."); ++ if (bound == NULL) { ++ return NULL; ++ } ++ } ++ ++ if (!PyTuple_CheckExact(constraints)) { ++ PyErr_SetString(PyExc_TypeError, ++ "constraints must be a tuple"); ++ return NULL; ++ } ++ Py_ssize_t n_constraints = PyTuple_GET_SIZE(constraints); ++ if (n_constraints == 1) { ++ PyErr_SetString(PyExc_TypeError, ++ "A single constraint is not allowed"); ++ Py_XDECREF(bound); ++ return NULL; ++ } else if (n_constraints == 0) { ++ constraints = NULL; ++ } else if (bound != NULL) { ++ PyErr_SetString(PyExc_TypeError, ++ "Constraints cannot be combined with bound=..."); ++ Py_XDECREF(bound); ++ return NULL; ++ } ++ PyObject *module = caller(); ++ if (module == NULL) { ++ Py_XDECREF(bound); ++ return NULL; ++ } ++ ++ PyObject *tv = (PyObject *)typevar_alloc(name, bound, NULL, ++ constraints, NULL, ++ covariant, contravariant, ++ infer_variance, module); ++ Py_XDECREF(bound); ++ Py_XDECREF(module); ++ return tv; ++} ++ ++/*[clinic input] ++typevar.__typing_subst__ as typevar_typing_subst ++ ++ arg: object ++ ++[clinic start generated code]*/ ++ ++static PyObject * ++typevar_typing_subst_impl(typevarobject *self, PyObject *arg) ++/*[clinic end generated code: output=c76ced134ed8f4e1 input=6b70a4bb2da838de]*/ ++{ ++ PyObject *args[2] = {(PyObject *)self, arg}; ++ PyObject *result = call_typing_func_object("_typevar_subst", args, 2); ++ return result; ++} ++ ++/*[clinic input] ++typevar.__reduce__ as typevar_reduce ++ ++[clinic start generated code]*/ ++ ++static PyObject * ++typevar_reduce_impl(typevarobject *self) ++/*[clinic end generated code: output=02e5c55d7cf8a08f input=de76bc95f04fb9ff]*/ ++{ ++ return Py_NewRef(self->name); ++} ++ ++static PyObject * ++typevar_mro_entries(PyObject *self, PyObject *args) ++{ ++ PyErr_SetString(PyExc_TypeError, ++ "Cannot subclass an instance of TypeVar"); ++ return NULL; ++} ++ ++static PyMethodDef typevar_methods[] = { ++ TYPEVAR_TYPING_SUBST_METHODDEF ++ TYPEVAR_REDUCE_METHODDEF ++ {"__mro_entries__", typevar_mro_entries, METH_O}, ++ {0} ++}; ++ ++PyDoc_STRVAR(typevar_doc, ++"Type variable.\n\ ++\n\ ++Usage::\n\ ++\n\ ++ T = TypeVar('T') # Can be anything\n\ ++ A = TypeVar('A', str, bytes) # Must be str or bytes\n\ ++\n\ ++Type variables exist primarily for the benefit of static type\n\ ++checkers. They serve as the parameters for generic types as well\n\ ++as for generic function definitions. See class Generic for more\n\ ++information on generic types. Generic functions work as follows:\n\ ++\n\ ++ def repeat(x: T, n: int) -> List[T]:\n\ ++ '''Return a list containing n references to x.'''\n\ ++ return [x]*n\n\ ++\n\ ++ def longest(x: A, y: A) -> A:\n\ ++ '''Return the longest of two strings.'''\n\ ++ return x if len(x) >= len(y) else y\n\ ++\n\ ++The latter example's signature is essentially the overloading\n\ ++of (str, str) -> str and (bytes, bytes) -> bytes. Also note\n\ ++that if the arguments are instances of some subclass of str,\n\ ++the return type is still plain str.\n\ ++\n\ ++At runtime, isinstance(x, T) and issubclass(C, T) will raise TypeError.\n\ ++\n\ ++Type variables defined with covariant=True or contravariant=True\n\ ++can be used to declare covariant or contravariant generic types.\n\ ++See PEP 484 for more details. By default generic types are invariant\n\ ++in all type variables.\n\ ++\n\ ++Type variables can be introspected. e.g.:\n\ ++\n\ ++ T.__name__ == 'T'\n\ ++ T.__constraints__ == ()\n\ ++ T.__covariant__ == False\n\ ++ T.__contravariant__ = False\n\ ++ A.__constraints__ == (str, bytes)\n\ ++\n\ ++Note that only type variables defined in global scope can be pickled.\n\ ++"); ++ ++static PyType_Slot typevar_slots[] = { ++ {Py_tp_doc, (void *)typevar_doc}, ++ {Py_tp_methods, typevar_methods}, ++ {Py_nb_or, make_union}, ++ {Py_tp_new, typevar_new}, ++ {Py_tp_dealloc, typevar_dealloc}, ++ {Py_tp_alloc, PyType_GenericAlloc}, ++ {Py_tp_free, PyObject_GC_Del}, ++ {Py_tp_traverse, typevar_traverse}, ++ {Py_tp_clear, typevar_clear}, ++ {Py_tp_repr, typevar_repr}, ++ {Py_tp_members, typevar_members}, ++ {Py_tp_getset, typevar_getset}, ++ {0, NULL}, ++}; ++ ++PyType_Spec typevar_spec = { ++ .name = "typing.TypeVar", ++ .basicsize = sizeof(typevarobject), ++ .flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC | Py_TPFLAGS_IMMUTABLETYPE ++ | Py_TPFLAGS_MANAGED_DICT, ++ .slots = typevar_slots, ++}; ++ ++typedef struct { ++ PyObject_HEAD ++ PyObject *__origin__; ++} paramspecattrobject; ++ ++static void ++paramspecattr_dealloc(PyObject *self) ++{ ++ PyTypeObject *tp = Py_TYPE(self); ++ paramspecattrobject *psa = (paramspecattrobject *)self; ++ ++ _PyObject_GC_UNTRACK(self); ++ ++ Py_XDECREF(psa->__origin__); ++ ++ Py_TYPE(self)->tp_free(self); ++ Py_DECREF(tp); ++} ++ ++static int ++paramspecattr_traverse(PyObject *self, visitproc visit, void *arg) ++{ ++ paramspecattrobject *psa = (paramspecattrobject *)self; ++ Py_VISIT(psa->__origin__); ++ return 0; ++} ++ ++static int ++paramspecattr_clear(paramspecattrobject *self) ++{ ++ Py_CLEAR(self->__origin__); ++ return 0; ++} ++ ++static PyObject * ++paramspecattr_richcompare(PyObject *a, PyObject *b, int op) ++{ ++ if (!Py_IS_TYPE(a, Py_TYPE(b))) { ++ Py_RETURN_NOTIMPLEMENTED; ++ } ++ if (op != Py_EQ && op != Py_NE) { ++ Py_RETURN_NOTIMPLEMENTED; ++ } ++ return PyObject_RichCompare( ++ ((paramspecattrobject *)a)->__origin__, ++ ((paramspecattrobject *)b)->__origin__, ++ op ++ ); ++} ++ ++static PyMemberDef paramspecattr_members[] = { ++ {"__origin__", T_OBJECT, offsetof(paramspecattrobject, __origin__), READONLY}, ++ {0} ++}; ++ ++static paramspecattrobject * ++paramspecattr_new(PyTypeObject *tp, PyObject *origin) ++{ ++ paramspecattrobject *psa = PyObject_GC_New(paramspecattrobject, tp); ++ if (psa == NULL) { ++ return NULL; ++ } ++ psa->__origin__ = Py_NewRef(origin); ++ _PyObject_GC_TRACK(psa); ++ return psa; ++} ++ ++static PyObject * ++paramspecargs_repr(PyObject *self) ++{ ++ paramspecattrobject *psa = (paramspecattrobject *)self; ++ ++ PyTypeObject *tp = PyInterpreterState_Get()->cached_objects.paramspec_type; ++ if (Py_IS_TYPE(psa->__origin__, tp)) { ++ return PyUnicode_FromFormat("%U.args", ++ ((paramspecobject *)psa->__origin__)->name); ++ } ++ return PyUnicode_FromFormat("%R.args", psa->__origin__); ++} ++ ++ ++/*[clinic input] ++@classmethod ++paramspecargs.__new__ as paramspecargs_new ++ ++ origin: object ++ ++Create a ParamSpecArgs object. ++[clinic start generated code]*/ ++ ++static PyObject * ++paramspecargs_new_impl(PyTypeObject *type, PyObject *origin) ++/*[clinic end generated code: output=9a1463dc8942fe4e input=3596a0bb6183c208]*/ ++{ ++ return (PyObject *)paramspecattr_new(type, origin); ++} ++ ++static PyObject * ++paramspecargs_mro_entries(PyObject *self, PyObject *args) ++{ ++ PyErr_SetString(PyExc_TypeError, ++ "Cannot subclass an instance of ParamSpecArgs"); ++ return NULL; ++} ++ ++static PyMethodDef paramspecargs_methods[] = { ++ {"__mro_entries__", paramspecargs_mro_entries, METH_O}, ++ {0} ++}; ++ ++PyDoc_STRVAR(paramspecargs_doc, ++"The args for a ParamSpec object.\n\ ++\n\ ++Given a ParamSpec object P, P.args is an instance of ParamSpecArgs.\n\ ++\n\ ++ParamSpecArgs objects have a reference back to their ParamSpec:\n\ ++\n\ ++ P.args.__origin__ is P\n\ ++\n\ ++This type is meant for runtime introspection and has no special meaning to\n\ ++static type checkers.\n\ ++"); ++ ++static PyType_Slot paramspecargs_slots[] = { ++ {Py_tp_doc, (void *)paramspecargs_doc}, ++ {Py_tp_methods, paramspecargs_methods}, ++ {Py_tp_new, paramspecargs_new}, ++ {Py_tp_dealloc, paramspecattr_dealloc}, ++ {Py_tp_alloc, PyType_GenericAlloc}, ++ {Py_tp_free, PyObject_GC_Del}, ++ {Py_tp_traverse, paramspecattr_traverse}, ++ {Py_tp_clear, (inquiry)paramspecattr_clear}, ++ {Py_tp_repr, paramspecargs_repr}, ++ {Py_tp_members, paramspecattr_members}, ++ {Py_tp_richcompare, paramspecattr_richcompare}, ++ {0, NULL}, ++}; ++ ++PyType_Spec paramspecargs_spec = { ++ .name = "typing.ParamSpecArgs", ++ .basicsize = sizeof(paramspecattrobject), ++ .flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC | Py_TPFLAGS_IMMUTABLETYPE, ++ .slots = paramspecargs_slots, ++}; ++ ++static PyObject * ++paramspeckwargs_repr(PyObject *self) ++{ ++ paramspecattrobject *psk = (paramspecattrobject *)self; ++ ++ PyTypeObject *tp = PyInterpreterState_Get()->cached_objects.paramspec_type; ++ if (Py_IS_TYPE(psk->__origin__, tp)) { ++ return PyUnicode_FromFormat("%U.kwargs", ++ ((paramspecobject *)psk->__origin__)->name); ++ } ++ return PyUnicode_FromFormat("%R.kwargs", psk->__origin__); ++} ++ ++/*[clinic input] ++@classmethod ++paramspeckwargs.__new__ as paramspeckwargs_new ++ ++ origin: object ++ ++Create a ParamSpecKwargs object. ++[clinic start generated code]*/ ++ ++static PyObject * ++paramspeckwargs_new_impl(PyTypeObject *type, PyObject *origin) ++/*[clinic end generated code: output=277b11967ebaf4ab input=981bca9b0cf9e40a]*/ ++{ ++ return (PyObject *)paramspecattr_new(type, origin); ++} ++ ++static PyObject * ++paramspeckwargs_mro_entries(PyObject *self, PyObject *args) ++{ ++ PyErr_SetString(PyExc_TypeError, ++ "Cannot subclass an instance of ParamSpecKwargs"); ++ return NULL; ++} ++ ++static PyMethodDef paramspeckwargs_methods[] = { ++ {"__mro_entries__", paramspeckwargs_mro_entries, METH_O}, ++ {0} ++}; ++ ++PyDoc_STRVAR(paramspeckwargs_doc, ++"The kwargs for a ParamSpec object.\n\ ++\n\ ++Given a ParamSpec object P, P.kwargs is an instance of ParamSpecKwargs.\n\ ++\n\ ++ParamSpecKwargs objects have a reference back to their ParamSpec:\n\ ++\n\ ++ P.kwargs.__origin__ is P\n\ ++\n\ ++This type is meant for runtime introspection and has no special meaning to\n\ ++static type checkers.\n\ ++"); ++ ++static PyType_Slot paramspeckwargs_slots[] = { ++ {Py_tp_doc, (void *)paramspeckwargs_doc}, ++ {Py_tp_methods, paramspeckwargs_methods}, ++ {Py_tp_new, paramspeckwargs_new}, ++ {Py_tp_dealloc, paramspecattr_dealloc}, ++ {Py_tp_alloc, PyType_GenericAlloc}, ++ {Py_tp_free, PyObject_GC_Del}, ++ {Py_tp_traverse, paramspecattr_traverse}, ++ {Py_tp_clear, (inquiry)paramspecattr_clear}, ++ {Py_tp_repr, paramspeckwargs_repr}, ++ {Py_tp_members, paramspecattr_members}, ++ {Py_tp_richcompare, paramspecattr_richcompare}, ++ {0, NULL}, ++}; ++ ++PyType_Spec paramspeckwargs_spec = { ++ .name = "typing.ParamSpecKwargs", ++ .basicsize = sizeof(paramspecattrobject), ++ .flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC | Py_TPFLAGS_IMMUTABLETYPE, ++ .slots = paramspeckwargs_slots, ++}; ++ ++static void ++paramspec_dealloc(PyObject *self) ++{ ++ PyTypeObject *tp = Py_TYPE(self); ++ paramspecobject *ps = (paramspecobject *)self; ++ ++ _PyObject_GC_UNTRACK(self); ++ ++ Py_DECREF(ps->name); ++ Py_XDECREF(ps->bound); ++ _PyObject_ClearManagedDict(self); ++ ++ Py_TYPE(self)->tp_free(self); ++ Py_DECREF(tp); ++} ++ ++static int ++paramspec_traverse(PyObject *self, visitproc visit, void *arg) ++{ ++ Py_VISIT(Py_TYPE(self)); ++ paramspecobject *ps = (paramspecobject *)self; ++ Py_VISIT(ps->bound); ++ _PyObject_VisitManagedDict(self, visit, arg); ++ return 0; ++} ++ ++static int ++paramspec_clear(paramspecobject *self) ++{ ++ Py_CLEAR(self->bound); ++ _PyObject_ClearManagedDict((PyObject *)self); ++ return 0; ++} ++ ++static PyObject * ++paramspec_repr(PyObject *self) ++{ ++ paramspecobject *ps = (paramspecobject *)self; ++ ++ if (ps->infer_variance) { ++ return Py_NewRef(ps->name); ++ } ++ ++ char variance = ps->covariant ? '+' : ps->contravariant ? '-' : '~'; ++ return PyUnicode_FromFormat("%c%U", variance, ps->name); ++} ++ ++static PyMemberDef paramspec_members[] = { ++ {"__name__", T_OBJECT, offsetof(paramspecobject, name), READONLY}, ++ {"__bound__", T_OBJECT, offsetof(paramspecobject, bound), READONLY}, ++ {"__covariant__", T_BOOL, offsetof(paramspecobject, covariant), READONLY}, ++ {"__contravariant__", T_BOOL, offsetof(paramspecobject, contravariant), READONLY}, ++ {"__infer_variance__", T_BOOL, offsetof(paramspecobject, infer_variance), READONLY}, ++ {0} ++}; ++ ++static PyObject * ++paramspec_args(PyObject *self, void *unused) ++{ ++ PyTypeObject *tp = PyInterpreterState_Get()->cached_objects.paramspecargs_type; ++ return (PyObject *)paramspecattr_new(tp, self); ++} ++ ++static PyObject * ++paramspec_kwargs(PyObject *self, void *unused) ++{ ++ PyTypeObject *tp = PyInterpreterState_Get()->cached_objects.paramspeckwargs_type; ++ return (PyObject *)paramspecattr_new(tp, self); ++} ++ ++static PyGetSetDef paramspec_getset[] = { ++ {"args", (getter)paramspec_args, NULL, "Represents positional arguments.", NULL}, ++ {"kwargs", (getter)paramspec_kwargs, NULL, "Represents keyword arguments.", NULL}, ++ {0}, ++}; ++ ++static paramspecobject * ++paramspec_alloc(PyObject *name, PyObject *bound, bool covariant, ++ bool contravariant, bool infer_variance, PyObject *module) ++{ ++ PyTypeObject *tp = PyInterpreterState_Get()->cached_objects.paramspec_type; ++ paramspecobject *ps = PyObject_GC_New(paramspecobject, tp); ++ if (ps == NULL) { ++ return NULL; ++ } ++ ps->name = Py_NewRef(name); ++ ps->bound = Py_XNewRef(bound); ++ ps->covariant = covariant; ++ ps->contravariant = contravariant; ++ ps->infer_variance = infer_variance; ++ _PyObject_GC_TRACK(ps); ++ if (module != NULL) { ++ if (PyObject_SetAttrString((PyObject *)ps, "__module__", module) < 0) { ++ Py_DECREF(ps); ++ return NULL; ++ } ++ } ++ return ps; ++} ++ ++/*[clinic input] ++@classmethod ++paramspec.__new__ as paramspec_new ++ ++ name: object(subclass_of="&PyUnicode_Type") ++ * ++ bound: object = None ++ covariant: bool = False ++ contravariant: bool = False ++ infer_variance: bool = False ++ ++Create a ParamSpec object. ++[clinic start generated code]*/ ++ ++static PyObject * ++paramspec_new_impl(PyTypeObject *type, PyObject *name, PyObject *bound, ++ int covariant, int contravariant, int infer_variance) ++/*[clinic end generated code: output=fd2daab79cba62da input=57c49c581979b952]*/ ++{ ++ if (covariant && contravariant) { ++ PyErr_SetString(PyExc_ValueError, "Bivariant types are not supported."); ++ return NULL; ++ } ++ if (infer_variance && (covariant || contravariant)) { ++ PyErr_SetString(PyExc_ValueError, "Variance cannot be specified with infer_variance."); ++ return NULL; ++ } ++ if (bound != NULL) { ++ bound = type_check(bound, "Bound must be a type."); ++ if (bound == NULL) { ++ return NULL; ++ } ++ } ++ PyObject *module = caller(); ++ if (module == NULL) { ++ Py_XDECREF(bound); ++ return NULL; ++ } ++ PyObject *ps = (PyObject *)paramspec_alloc( ++ name, bound, covariant, contravariant, infer_variance, module); ++ Py_XDECREF(bound); ++ Py_DECREF(module); ++ return ps; ++} ++ ++ ++/*[clinic input] ++paramspec.__typing_subst__ as paramspec_typing_subst ++ ++ arg: object ++ ++[clinic start generated code]*/ ++ ++static PyObject * ++paramspec_typing_subst_impl(paramspecobject *self, PyObject *arg) ++/*[clinic end generated code: output=803e1ade3f13b57d input=4e0005d24023e896]*/ ++{ ++ PyObject *args[2] = {(PyObject *)self, arg}; ++ PyObject *result = call_typing_func_object("_paramspec_subst", args, 2); ++ return result; ++} ++ ++/*[clinic input] ++paramspec.__typing_prepare_subst__ as paramspec_typing_prepare_subst ++ ++ alias: object ++ args: object ++ ++[clinic start generated code]*/ ++ ++static PyObject * ++paramspec_typing_prepare_subst_impl(paramspecobject *self, PyObject *alias, ++ PyObject *args) ++/*[clinic end generated code: output=95449d630a2adb9a input=4375e2ffcb2ad635]*/ ++{ ++ PyObject *args_array[3] = {(PyObject *)self, alias, args}; ++ PyObject *result = call_typing_func_object( ++ "_paramspec_prepare_subst", args_array, 3); ++ return result; ++} ++ ++/*[clinic input] ++paramspec.__reduce__ as paramspec_reduce ++ ++[clinic start generated code]*/ ++ ++static PyObject * ++paramspec_reduce_impl(paramspecobject *self) ++/*[clinic end generated code: output=b83398674416db27 input=5bf349f0d5dd426c]*/ ++{ ++ return Py_NewRef(self->name); ++} ++ ++static PyObject * ++paramspec_mro_entries(PyObject *self, PyObject *args) ++{ ++ PyErr_SetString(PyExc_TypeError, ++ "Cannot subclass an instance of ParamSpec"); ++ return NULL; ++} ++ ++static PyMethodDef paramspec_methods[] = { ++ PARAMSPEC_TYPING_SUBST_METHODDEF ++ PARAMSPEC_TYPING_PREPARE_SUBST_METHODDEF ++ PARAMSPEC_REDUCE_METHODDEF ++ {"__mro_entries__", paramspec_mro_entries, METH_O}, ++ {0} ++}; ++ ++PyDoc_STRVAR(paramspec_doc, ++"Parameter specification variable.\n\ ++\n\ ++Usage::\n\ ++\n\ ++ P = ParamSpec('P')\n\ ++\n\ ++Parameter specification variables exist primarily for the benefit of static\n\ ++type checkers. They are used to forward the parameter types of one\n\ ++callable to another callable, a pattern commonly found in higher order\n\ ++functions and decorators. They are only valid when used in ``Concatenate``,\n\ ++or as the first argument to ``Callable``, or as parameters for user-defined\n\ ++Generics. See class Generic for more information on generic types. An\n\ ++example for annotating a decorator::\n\ ++\n\ ++ T = TypeVar('T')\n\ ++ P = ParamSpec('P')\n\ ++\n\ ++ def add_logging(f: Callable[P, T]) -> Callable[P, T]:\n\ ++ '''A type-safe decorator to add logging to a function.'''\n\ ++ def inner(*args: P.args, **kwargs: P.kwargs) -> T:\n\ ++ logging.info(f'{f.__name__} was called')\n\ ++ return f(*args, **kwargs)\n\ ++ return inner\n\ ++\n\ ++ @add_logging\n\ ++ def add_two(x: float, y: float) -> float:\n\ ++ '''Add two numbers together.'''\n\ ++ return x + y\n\ ++\n\ ++Parameter specification variables defined with covariant=True or\n\ ++contravariant=True can be used to declare covariant or contravariant\n\ ++generic types. These keyword arguments are valid, but their actual semantics\n\ ++are yet to be decided. See PEP 612 for details.\n\ ++\n\ ++Parameter specification variables can be introspected. e.g.:\n\ ++\n\ ++ P.__name__ == 'P'\n\ ++ P.__bound__ == None\n\ ++ P.__covariant__ == False\n\ ++ P.__contravariant__ == False\n\ ++\n\ ++Note that only parameter specification variables defined in global scope can\n\ ++be pickled.\n\ ++"); ++ ++static PyType_Slot paramspec_slots[] = { ++ {Py_tp_doc, (void *)paramspec_doc}, ++ {Py_tp_members, paramspec_members}, ++ {Py_tp_methods, paramspec_methods}, ++ {Py_tp_getset, paramspec_getset}, ++ // Unions of ParamSpecs have no defined meaning, but they were allowed ++ // by the Python implementation, so we allow them here too. ++ {Py_nb_or, make_union}, ++ {Py_tp_new, paramspec_new}, ++ {Py_tp_dealloc, paramspec_dealloc}, ++ {Py_tp_alloc, PyType_GenericAlloc}, ++ {Py_tp_free, PyObject_GC_Del}, ++ {Py_tp_traverse, paramspec_traverse}, ++ {Py_tp_clear, paramspec_clear}, ++ {Py_tp_repr, paramspec_repr}, ++ {0, 0}, ++}; ++ ++PyType_Spec paramspec_spec = { ++ .name = "typing.ParamSpec", ++ .basicsize = sizeof(paramspecobject), ++ .flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC | Py_TPFLAGS_IMMUTABLETYPE ++ | Py_TPFLAGS_MANAGED_DICT, ++ .slots = paramspec_slots, ++}; ++ ++static void ++typevartuple_dealloc(PyObject *self) ++{ ++ PyTypeObject *tp = Py_TYPE(self); ++ _PyObject_GC_UNTRACK(self); ++ typevartupleobject *tvt = (typevartupleobject *)self; ++ ++ Py_DECREF(tvt->name); ++ _PyObject_ClearManagedDict(self); ++ ++ Py_TYPE(self)->tp_free(self); ++ Py_DECREF(tp); ++} ++ ++static PyObject * ++typevartuple_iter(PyObject *self) ++{ ++ PyObject *unpacked = typevartuple_unpack(self); ++ if (unpacked == NULL) { ++ return NULL; ++ } ++ PyObject *tuple = PyTuple_Pack(1, unpacked); ++ if (tuple == NULL) { ++ Py_DECREF(unpacked); ++ return NULL; ++ } ++ PyObject *result = PyObject_GetIter(tuple); ++ Py_DECREF(unpacked); ++ Py_DECREF(tuple); ++ return result; ++} ++ ++static PyObject * ++typevartuple_repr(PyObject *self) ++{ ++ typevartupleobject *tvt = (typevartupleobject *)self; ++ ++ return Py_NewRef(tvt->name); ++} ++ ++static PyMemberDef typevartuple_members[] = { ++ {"__name__", T_OBJECT, offsetof(typevartupleobject, name), READONLY}, ++ {0} ++}; ++ ++static typevartupleobject * ++typevartuple_alloc(PyObject *name, PyObject *module) ++{ ++ PyTypeObject *tp = PyInterpreterState_Get()->cached_objects.typevartuple_type; ++ typevartupleobject *tvt = PyObject_GC_New(typevartupleobject, tp); ++ if (tvt == NULL) { ++ return NULL; ++ } ++ tvt->name = Py_NewRef(name); ++ _PyObject_GC_TRACK(tvt); ++ if (module != NULL) { ++ if (PyObject_SetAttrString((PyObject *)tvt, "__module__", module) < 0) { ++ Py_DECREF(tvt); ++ return NULL; ++ } ++ } ++ return tvt; ++} ++ ++/*[clinic input] ++@classmethod ++typevartuple.__new__ ++ ++ name: object(subclass_of="&PyUnicode_Type") ++ ++Create a new TypeVarTuple with the given name. ++[clinic start generated code]*/ ++ ++static PyObject * ++typevartuple_impl(PyTypeObject *type, PyObject *name) ++/*[clinic end generated code: output=09d417a28f976202 input=00d28abcf1fc96bb]*/ ++{ ++ PyObject *module = caller(); ++ if (module == NULL) { ++ return NULL; ++ } ++ PyObject *result = (PyObject *)typevartuple_alloc(name, module); ++ Py_DECREF(module); ++ return result; ++} ++ ++/*[clinic input] ++typevartuple.__typing_subst__ as typevartuple_typing_subst ++ ++ arg: object ++ ++[clinic start generated code]*/ ++ ++static PyObject * ++typevartuple_typing_subst_impl(typevartupleobject *self, PyObject *arg) ++/*[clinic end generated code: output=814316519441cd76 input=670c4e0a36e5d8c0]*/ ++{ ++ PyErr_SetString(PyExc_TypeError, "Substitution of bare TypeVarTuple is not supported"); ++ return NULL; ++} ++ ++/*[clinic input] ++typevartuple.__typing_prepare_subst__ as typevartuple_typing_prepare_subst ++ ++ alias: object ++ args: object ++ ++[clinic start generated code]*/ ++ ++static PyObject * ++typevartuple_typing_prepare_subst_impl(typevartupleobject *self, ++ PyObject *alias, PyObject *args) ++/*[clinic end generated code: output=ff999bc5b02036c1 input=a211b05f2eeb4306]*/ ++{ ++ PyObject *args_array[3] = {(PyObject *)self, alias, args}; ++ PyObject *result = call_typing_func_object( ++ "_typevartuple_prepare_subst", args_array, 3); ++ return result; ++} ++ ++/*[clinic input] ++typevartuple.__reduce__ as typevartuple_reduce ++ ++[clinic start generated code]*/ ++ ++static PyObject * ++typevartuple_reduce_impl(typevartupleobject *self) ++/*[clinic end generated code: output=3215bc0477913d20 input=3018a4d66147e807]*/ ++{ ++ return Py_NewRef(self->name); ++} ++ ++static PyObject * ++typevartuple_mro_entries(PyObject *self, PyObject *args) ++{ ++ PyErr_SetString(PyExc_TypeError, ++ "Cannot subclass an instance of TypeVarTuple"); ++ return NULL; ++} ++ ++static int ++typevartuple_traverse(PyObject *self, visitproc visit, void *arg) ++{ ++ Py_VISIT(Py_TYPE(self)); ++ _PyObject_VisitManagedDict(self, visit, arg); ++ return 0; ++} ++ ++static int ++typevartuple_clear(PyObject *self) ++{ ++ _PyObject_ClearManagedDict(self); ++ return 0; ++} ++ ++static PyMethodDef typevartuple_methods[] = { ++ TYPEVARTUPLE_TYPING_SUBST_METHODDEF ++ TYPEVARTUPLE_TYPING_PREPARE_SUBST_METHODDEF ++ TYPEVARTUPLE_REDUCE_METHODDEF ++ {"__mro_entries__", typevartuple_mro_entries, METH_O}, ++ {0} ++}; ++ ++PyDoc_STRVAR(typevartuple_doc, ++"Type variable tuple.\n\ ++\n\ ++Usage:\n\ ++\n\ ++ Ts = TypeVarTuple('Ts') # Can be given any name\n\ ++\n\ ++Just as a TypeVar (type variable) is a placeholder for a single type,\n\ ++a TypeVarTuple is a placeholder for an *arbitrary* number of types. For\n\ ++example, if we define a generic class using a TypeVarTuple:\n\ ++\n\ ++ class C(Generic[*Ts]): ...\n\ ++\n\ ++Then we can parameterize that class with an arbitrary number of type\n\ ++arguments:\n\ ++\n\ ++ C[int] # Fine\n\ ++ C[int, str] # Also fine\n\ ++ C[()] # Even this is fine\n\ ++\n\ ++For more details, see PEP 646.\n\ ++\n\ ++Note that only TypeVarTuples defined in global scope can be pickled.\n\ ++"); ++ ++PyType_Slot typevartuple_slots[] = { ++ {Py_tp_doc, (void *)typevartuple_doc}, ++ {Py_tp_members, typevartuple_members}, ++ {Py_tp_methods, typevartuple_methods}, ++ {Py_tp_new, typevartuple}, ++ {Py_tp_iter, typevartuple_iter}, ++ {Py_tp_repr, typevartuple_repr}, ++ {Py_tp_dealloc, typevartuple_dealloc}, ++ {Py_tp_alloc, PyType_GenericAlloc}, ++ {Py_tp_free, PyObject_GC_Del}, ++ {Py_tp_traverse, typevartuple_traverse}, ++ {Py_tp_clear, typevartuple_clear}, ++ {0, 0}, ++}; ++ ++PyType_Spec typevartuple_spec = { ++ .name = "typing.TypeVarTuple", ++ .basicsize = sizeof(typevartupleobject), ++ .flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_IMMUTABLETYPE | Py_TPFLAGS_MANAGED_DICT ++ | Py_TPFLAGS_HAVE_GC, ++ .slots = typevartuple_slots, ++}; ++ ++PyObject * ++_Py_make_typevar(PyObject *name, PyObject *evaluate_bound, PyObject *evaluate_constraints) ++{ ++ return (PyObject *)typevar_alloc(name, NULL, evaluate_bound, NULL, evaluate_constraints, ++ false, false, true, NULL); ++} ++ ++PyObject * ++_Py_make_paramspec(PyThreadState *Py_UNUSED(ignored), PyObject *v) ++{ ++ assert(PyUnicode_Check(v)); ++ return (PyObject *)paramspec_alloc(v, NULL, false, false, true, NULL); ++} ++ ++PyObject * ++_Py_make_typevartuple(PyThreadState *Py_UNUSED(ignored), PyObject *v) ++{ ++ assert(PyUnicode_Check(v)); ++ return (PyObject *)typevartuple_alloc(v, NULL); ++} ++ ++static void ++typealias_dealloc(PyObject *self) ++{ ++ PyTypeObject *tp = Py_TYPE(self); ++ _PyObject_GC_UNTRACK(self); ++ typealiasobject *ta = (typealiasobject *)self; ++ Py_DECREF(ta->name); ++ Py_XDECREF(ta->type_params); ++ Py_XDECREF(ta->compute_value); ++ Py_XDECREF(ta->value); ++ Py_TYPE(self)->tp_free(self); ++ Py_DECREF(tp); ++} ++ ++static PyObject * ++typealias_get_value(typealiasobject *ta) ++{ ++ if (ta->value != NULL) { ++ return Py_NewRef(ta->value); ++ } ++ PyObject *result = PyObject_CallNoArgs(ta->compute_value); ++ if (result == NULL) { ++ return NULL; ++ } ++ ta->value = Py_NewRef(result); ++ return result; ++} ++ ++static PyObject * ++typealias_repr(PyObject *self) ++{ ++ typealiasobject *ta = (typealiasobject *)self; ++ return Py_NewRef(ta->name); ++} ++ ++static PyMemberDef typealias_members[] = { ++ {"__name__", T_OBJECT, offsetof(typealiasobject, name), READONLY}, ++ {0} ++}; ++ ++static PyObject * ++typealias_value(PyObject *self, void *unused) ++{ ++ typealiasobject *ta = (typealiasobject *)self; ++ return typealias_get_value(ta); ++} ++ ++static PyObject * ++typealias_parameters(PyObject *self, void *unused) ++{ ++ typealiasobject *ta = (typealiasobject *)self; ++ if (ta->type_params == NULL) { ++ return PyTuple_New(0); ++ } ++ return unpack_typevartuples(ta->type_params); ++} ++ ++static PyObject * ++typealias_type_params(PyObject *self, void *unused) ++{ ++ typealiasobject *ta = (typealiasobject *)self; ++ if (ta->type_params == NULL) { ++ return PyTuple_New(0); ++ } ++ return Py_NewRef(ta->type_params); ++} ++ ++static PyGetSetDef typealias_getset[] = { ++ {"__parameters__", typealias_parameters, (setter)NULL, NULL, NULL}, ++ {"__type_params__", typealias_type_params, (setter)NULL, NULL, NULL}, ++ {"__value__", typealias_value, (setter)NULL, NULL, NULL}, ++ {0} ++}; ++ ++static typealiasobject * ++typealias_alloc(PyObject *name, PyObject *type_params, PyObject *compute_value, ++ PyObject *value) ++{ ++ PyTypeObject *tp = PyInterpreterState_Get()->cached_objects.typealias_type; ++ typealiasobject *ta = PyObject_GC_New(typealiasobject, tp); ++ if (ta == NULL) { ++ return NULL; ++ } ++ ta->name = Py_NewRef(name); ++ ta->type_params = Py_IsNone(type_params) ? NULL : Py_XNewRef(type_params); ++ ta->compute_value = Py_XNewRef(compute_value); ++ ta->value = Py_XNewRef(value); ++ _PyObject_GC_TRACK(ta); ++ return ta; ++} ++ ++static int ++typealias_traverse(typealiasobject *self, visitproc visit, void *arg) ++{ ++ Py_VISIT(self->type_params); ++ Py_VISIT(self->compute_value); ++ Py_VISIT(self->value); ++ return 0; ++} ++ ++static int ++typealias_clear(typealiasobject *self) ++{ ++ Py_CLEAR(self->type_params); ++ Py_CLEAR(self->compute_value); ++ Py_CLEAR(self->value); ++ return 0; ++} ++ ++/*[clinic input] ++typealias.__reduce__ as typealias_reduce ++ ++[clinic start generated code]*/ ++ ++static PyObject * ++typealias_reduce_impl(typealiasobject *self) ++/*[clinic end generated code: output=913724f92ad3b39b input=4f06fbd9472ec0f1]*/ ++{ ++ return Py_NewRef(self->name); ++} ++ ++static PyObject * ++typealias_subscript(PyObject *self, PyObject *args) ++{ ++ if (((typealiasobject *)self)->type_params == NULL) { ++ PyErr_SetString(PyExc_TypeError, ++ "Only generic type aliases are subscriptable"); ++ return NULL; ++ } ++ return Py_GenericAlias(self, args); ++} ++ ++static PyMethodDef typealias_methods[] = { ++ TYPEALIAS_REDUCE_METHODDEF ++ {0} ++}; ++ ++ ++/*[clinic input] ++@classmethod ++typealias.__new__ as typealias_new ++ ++ name: object(subclass_of="&PyUnicode_Type") ++ value: object ++ * ++ type_params: object = NULL ++ ++Create a TypeAliasType. ++[clinic start generated code]*/ ++ ++static PyObject * ++typealias_new_impl(PyTypeObject *type, PyObject *name, PyObject *value, ++ PyObject *type_params) ++/*[clinic end generated code: output=8920ce6bdff86f00 input=df163c34e17e1a35]*/ ++{ ++ if (type_params != NULL && !PyTuple_Check(type_params)) { ++ PyErr_SetString(PyExc_TypeError, "type_params must be a tuple"); ++ return NULL; ++ } ++ return (PyObject *)typealias_alloc(name, type_params, NULL, value); ++} ++ ++PyDoc_STRVAR(typealias_doc, ++"Type alias.\n\ ++\n\ ++Type aliases are created through the type statement:\n\ ++\n\ ++ type Alias = int\n\ ++"); ++ ++static PyType_Slot typealias_slots[] = { ++ {Py_tp_doc, (void *)typealias_doc}, ++ {Py_tp_members, typealias_members}, ++ {Py_tp_methods, typealias_methods}, ++ {Py_tp_getset, typealias_getset}, ++ {Py_mp_subscript, typealias_subscript}, ++ {Py_tp_dealloc, typealias_dealloc}, ++ {Py_tp_alloc, PyType_GenericAlloc}, ++ {Py_tp_new, typealias_new}, ++ {Py_tp_free, PyObject_GC_Del}, ++ {Py_tp_traverse, (traverseproc)typealias_traverse}, ++ {Py_tp_clear, (inquiry)typealias_clear}, ++ {Py_tp_repr, typealias_repr}, ++ {Py_nb_or, _Py_union_type_or}, ++ {0, 0}, ++}; ++ ++PyType_Spec typealias_spec = { ++ .name = "typing.TypeAliasType", ++ .basicsize = sizeof(typealiasobject), ++ .flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_IMMUTABLETYPE | Py_TPFLAGS_HAVE_GC, ++ .slots = typealias_slots, ++}; ++ ++PyObject * ++_Py_make_typealias(PyThreadState* unused, PyObject *args) ++{ ++ assert(PyTuple_Check(args)); ++ assert(PyTuple_GET_SIZE(args) == 3); ++ PyObject *name = PyTuple_GET_ITEM(args, 0); ++ assert(PyUnicode_Check(name)); ++ PyObject *type_params = PyTuple_GET_ITEM(args, 1); ++ PyObject *compute_value = PyTuple_GET_ITEM(args, 2); ++ return (PyObject *)typealias_alloc(name, type_params, compute_value, NULL); ++} ++ ++PyDoc_STRVAR(generic_doc, ++"Abstract base class for generic types.\n\ ++\n\ ++A generic type is typically declared by inheriting from\n\ ++this class parameterized with one or more type variables.\n\ ++For example, a generic mapping type might be defined as::\n\ ++\n\ ++ class Mapping(Generic[KT, VT]):\n\ ++ def __getitem__(self, key: KT) -> VT:\n\ ++ ...\n\ ++ # Etc.\n\ ++\n\ ++This class can then be used as follows::\n\ ++\n\ ++ def lookup_name(mapping: Mapping[KT, VT], key: KT, default: VT) -> VT:\n\ ++ try:\n\ ++ return mapping[key]\n\ ++ except KeyError:\n\ ++ return default\n\ ++"); ++ ++PyDoc_STRVAR(generic_class_getitem_doc, ++"Parameterizes a generic class.\n\ ++\n\ ++At least, parameterizing a generic class is the *main* thing this method\n\ ++does. For example, for some generic class `Foo`, this is called when we\n\ ++do `Foo[int]` - there, with `cls=Foo` and `params=int`.\n\ ++\n\ ++However, note that this method is also called when defining generic\n\ ++classes in the first place with `class Foo(Generic[T]): ...`.\n\ ++"); ++ ++static PyObject * ++call_typing_args_kwargs(const char *name, PyTypeObject *cls, PyObject *args, PyObject *kwargs) ++{ ++ PyObject *typing = NULL, *func = NULL, *new_args = NULL; ++ typing = PyImport_ImportModule("typing"); ++ if (typing == NULL) { ++ goto error; ++ } ++ func = PyObject_GetAttrString(typing, name); ++ if (func == NULL) { ++ goto error; ++ } ++ assert(PyTuple_Check(args)); ++ Py_ssize_t nargs = PyTuple_GET_SIZE(args); ++ new_args = PyTuple_New(nargs + 1); ++ if (new_args == NULL) { ++ goto error; ++ } ++ PyTuple_SET_ITEM(new_args, 0, Py_NewRef((PyObject *)cls)); ++ for (Py_ssize_t i = 0; i < nargs; i++) { ++ PyObject *arg = PyTuple_GET_ITEM(args, i); ++ PyTuple_SET_ITEM(new_args, i + 1, Py_NewRef(arg)); ++ } ++ PyObject *result = PyObject_Call(func, new_args, kwargs); ++ Py_DECREF(typing); ++ Py_DECREF(func); ++ Py_DECREF(new_args); ++ return result; ++error: ++ Py_XDECREF(typing); ++ Py_XDECREF(func); ++ Py_XDECREF(new_args); ++ return NULL; ++} ++ ++static PyObject * ++generic_init_subclass(PyTypeObject *cls, PyObject *args, PyObject *kwargs) ++{ ++ return call_typing_args_kwargs("_generic_init_subclass", cls, args, kwargs); ++} ++ ++static PyObject * ++generic_class_getitem(PyTypeObject *cls, PyObject *args, PyObject *kwargs) ++{ ++ return call_typing_args_kwargs("_generic_class_getitem", cls, args, kwargs); ++} ++ ++PyObject * ++_Py_subscript_generic(PyThreadState* unused, PyObject *params) ++{ ++ params = unpack_typevartuples(params); ++ ++ PyInterpreterState *interp = PyInterpreterState_Get(); ++ if (interp->cached_objects.generic_type == NULL) { ++ PyErr_SetString(PyExc_SystemError, "Cannot find Generic type"); ++ return NULL; ++ } ++ PyObject *args[2] = {(PyObject *)interp->cached_objects.generic_type, params}; ++ PyObject *result = call_typing_func_object("_GenericAlias", args, 2); ++ Py_DECREF(params); ++ return result; ++} ++ ++static PyMethodDef generic_methods[] = { ++ {"__class_getitem__", (PyCFunction)(void (*)(void))generic_class_getitem, ++ METH_VARARGS | METH_KEYWORDS | METH_CLASS, ++ generic_class_getitem_doc}, ++ {"__init_subclass__", (PyCFunction)(void (*)(void))generic_init_subclass, ++ METH_VARARGS | METH_KEYWORDS | METH_CLASS, ++ PyDoc_STR("Function to initialize subclasses.")}, ++ {NULL} /* Sentinel */ ++}; ++ ++static void ++generic_dealloc(PyObject *self) ++{ ++ PyTypeObject *tp = Py_TYPE(self); ++ _PyObject_GC_UNTRACK(self); ++ Py_TYPE(self)->tp_free(self); ++ Py_DECREF(tp); ++} ++ ++static int ++generic_traverse(PyObject *self, visitproc visit, void *arg) ++{ ++ Py_VISIT(Py_TYPE(self)); ++ return 0; ++} ++ ++static PyType_Slot generic_slots[] = { ++ {Py_tp_doc, (void *)generic_doc}, ++ {Py_tp_methods, generic_methods}, ++ {Py_tp_dealloc, generic_dealloc}, ++ {Py_tp_alloc, PyType_GenericAlloc}, ++ {Py_tp_free, PyObject_GC_Del}, ++ {Py_tp_traverse, generic_traverse}, ++ {0, NULL}, ++}; ++ ++PyType_Spec generic_spec = { ++ .name = "typing.Generic", ++ .basicsize = sizeof(PyObject), ++ .flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC, ++ .slots = generic_slots, ++}; ++ ++int _Py_initialize_generic(PyInterpreterState *interp) ++{ ++#define MAKE_TYPE(name) \ ++ do { \ ++ PyTypeObject *name ## _type = (PyTypeObject *)PyType_FromSpec(&name ## _spec); \ ++ if (name ## _type == NULL) { \ ++ return -1; \ ++ } \ ++ interp->cached_objects.name ## _type = name ## _type; \ ++ } while(0) ++ ++ MAKE_TYPE(generic); ++ MAKE_TYPE(typevar); ++ MAKE_TYPE(typevartuple); ++ MAKE_TYPE(paramspec); ++ MAKE_TYPE(paramspecargs); ++ MAKE_TYPE(paramspeckwargs); ++ MAKE_TYPE(typealias); ++#undef MAKE_TYPE ++ return 0; ++} ++ ++void _Py_clear_generic_types(PyInterpreterState *interp) ++{ ++ Py_CLEAR(interp->cached_objects.generic_type); ++ Py_CLEAR(interp->cached_objects.typevar_type); ++ Py_CLEAR(interp->cached_objects.typevartuple_type); ++ Py_CLEAR(interp->cached_objects.paramspec_type); ++ Py_CLEAR(interp->cached_objects.paramspecargs_type); ++ Py_CLEAR(interp->cached_objects.paramspeckwargs_type); ++ Py_CLEAR(interp->cached_objects.typealias_type); ++} +diff --git a/Objects/unionobject.c b/Objects/unionobject.c +index f273f7d15e..9806678b80 100644 +--- a/Objects/unionobject.c ++++ b/Objects/unionobject.c +@@ -147,10 +147,14 @@ get_types(PyObject **obj, Py_ssize_t *size) + static int + is_unionable(PyObject *obj) + { +- return (obj == Py_None || ++ if (obj == Py_None || + PyType_Check(obj) || + _PyGenericAlias_Check(obj) || +- _PyUnion_Check(obj)); ++ _PyUnion_Check(obj)) { ++ return 1; ++ } ++ PyInterpreterState *interp = PyInterpreterState_Get(); ++ return Py_IS_TYPE(obj, interp->cached_objects.typealias_type); + } + + PyObject * +diff --git a/Parser/Python.asdl b/Parser/Python.asdl +index e9423a7c98..cfc41ef45b 100644 +--- a/Parser/Python.asdl ++++ b/Parser/Python.asdl +@@ -8,14 +8,15 @@ module Python + | Expression(expr body) + | FunctionType(expr* argtypes, expr returns) + +- stmt = FunctionDef(identifier name, arguments args, ++ stmt = FunctionDef(identifier name, typeparam* typeparams, arguments args, + stmt* body, expr* decorator_list, expr? returns, + string? type_comment) +- | AsyncFunctionDef(identifier name, arguments args, ++ | AsyncFunctionDef(identifier name, typeparam* typeparams, arguments args, + stmt* body, expr* decorator_list, expr? returns, + string? type_comment) + + | ClassDef(identifier name, ++ typeparam* typeparams, + expr* bases, + keyword* keywords, + stmt* body, +@@ -24,6 +25,7 @@ module Python + + | Delete(expr* targets) + | Assign(expr* targets, expr value, string? type_comment) ++ | TypeAlias(expr name, typeparam* typeparams, expr value) + | AugAssign(expr target, operator op, expr value) + -- 'simple' indicates that we annotate simple name without parens + | AnnAssign(expr target, expr annotation, expr? value, int simple) +@@ -142,4 +144,9 @@ module Python + attributes (int lineno, int col_offset, int end_lineno, int end_col_offset) + + type_ignore = TypeIgnore(int lineno, string tag) ++ ++ typeparam = TypeVar(identifier name, expr? bound) ++ | ParamSpec(identifier name) ++ | TypeVarTuple(identifier name) ++ attributes (int lineno, int col_offset, int? end_lineno, int? end_col_offset) + } +diff --git a/Parser/action_helpers.c b/Parser/action_helpers.c +index 0aaaed64c4..0134e6f16b 100644 +--- a/Parser/action_helpers.c ++++ b/Parser/action_helpers.c +@@ -752,7 +752,8 @@ _PyPegen_function_def_decorators(Parser *p, asdl_expr_seq *decorators, stmt_ty f + assert(function_def != NULL); + if (function_def->kind == AsyncFunctionDef_kind) { + return _PyAST_AsyncFunctionDef( +- function_def->v.FunctionDef.name, function_def->v.FunctionDef.args, ++ function_def->v.FunctionDef.name, function_def->v.FunctionDef.typeparams, ++ function_def->v.FunctionDef.args, + function_def->v.FunctionDef.body, decorators, function_def->v.FunctionDef.returns, + function_def->v.FunctionDef.type_comment, function_def->lineno, + function_def->col_offset, function_def->end_lineno, function_def->end_col_offset, +@@ -760,7 +761,8 @@ _PyPegen_function_def_decorators(Parser *p, asdl_expr_seq *decorators, stmt_ty f + } + + return _PyAST_FunctionDef( +- function_def->v.FunctionDef.name, function_def->v.FunctionDef.args, ++ function_def->v.FunctionDef.name, function_def->v.FunctionDef.typeparams, ++ function_def->v.FunctionDef.args, + function_def->v.FunctionDef.body, decorators, + function_def->v.FunctionDef.returns, + function_def->v.FunctionDef.type_comment, function_def->lineno, +@@ -774,8 +776,9 @@ _PyPegen_class_def_decorators(Parser *p, asdl_expr_seq *decorators, stmt_ty clas + { + assert(class_def != NULL); + return _PyAST_ClassDef( +- class_def->v.ClassDef.name, class_def->v.ClassDef.bases, +- class_def->v.ClassDef.keywords, class_def->v.ClassDef.body, decorators, ++ class_def->v.ClassDef.name, class_def->v.ClassDef.typeparams, ++ class_def->v.ClassDef.bases, class_def->v.ClassDef.keywords, ++ class_def->v.ClassDef.body, decorators, + class_def->lineno, class_def->col_offset, class_def->end_lineno, + class_def->end_col_offset, p->arena); + } +diff --git a/Parser/parser.c b/Parser/parser.c +index 6eb985a7d3..894846714e 100644 +--- a/Parser/parser.c ++++ b/Parser/parser.c +@@ -75,6 +75,7 @@ static char *soft_keywords[] = { + "_", + "case", + "match", ++ "type", + NULL, + }; + #define file_type 1000 +@@ -175,419 +176,426 @@ static char *soft_keywords[] = { + #define positional_patterns_type 1095 + #define keyword_patterns_type 1096 + #define keyword_pattern_type 1097 +-#define expressions_type 1098 +-#define expression_type 1099 +-#define yield_expr_type 1100 +-#define star_expressions_type 1101 +-#define star_expression_type 1102 +-#define star_named_expressions_type 1103 +-#define star_named_expression_type 1104 +-#define assignment_expression_type 1105 +-#define named_expression_type 1106 +-#define disjunction_type 1107 +-#define conjunction_type 1108 +-#define inversion_type 1109 +-#define comparison_type 1110 +-#define compare_op_bitwise_or_pair_type 1111 +-#define eq_bitwise_or_type 1112 +-#define noteq_bitwise_or_type 1113 +-#define lte_bitwise_or_type 1114 +-#define lt_bitwise_or_type 1115 +-#define gte_bitwise_or_type 1116 +-#define gt_bitwise_or_type 1117 +-#define notin_bitwise_or_type 1118 +-#define in_bitwise_or_type 1119 +-#define isnot_bitwise_or_type 1120 +-#define is_bitwise_or_type 1121 +-#define bitwise_or_type 1122 // Left-recursive +-#define bitwise_xor_type 1123 // Left-recursive +-#define bitwise_and_type 1124 // Left-recursive +-#define shift_expr_type 1125 // Left-recursive +-#define sum_type 1126 // Left-recursive +-#define term_type 1127 // Left-recursive +-#define factor_type 1128 +-#define power_type 1129 +-#define await_primary_type 1130 +-#define primary_type 1131 // Left-recursive +-#define slices_type 1132 +-#define slice_type 1133 +-#define atom_type 1134 +-#define group_type 1135 +-#define lambdef_type 1136 +-#define lambda_params_type 1137 +-#define lambda_parameters_type 1138 +-#define lambda_slash_no_default_type 1139 +-#define lambda_slash_with_default_type 1140 +-#define lambda_star_etc_type 1141 +-#define lambda_kwds_type 1142 +-#define lambda_param_no_default_type 1143 +-#define lambda_param_with_default_type 1144 +-#define lambda_param_maybe_default_type 1145 +-#define lambda_param_type 1146 +-#define fstring_middle_type 1147 +-#define fstring_replacement_field_type 1148 +-#define fstring_conversion_type 1149 +-#define fstring_full_format_spec_type 1150 +-#define fstring_format_spec_type 1151 +-#define string_type 1152 +-#define strings_type 1153 +-#define list_type 1154 +-#define tuple_type 1155 +-#define set_type 1156 +-#define dict_type 1157 +-#define double_starred_kvpairs_type 1158 +-#define double_starred_kvpair_type 1159 +-#define kvpair_type 1160 +-#define for_if_clauses_type 1161 +-#define for_if_clause_type 1162 +-#define listcomp_type 1163 +-#define setcomp_type 1164 +-#define genexp_type 1165 +-#define dictcomp_type 1166 +-#define arguments_type 1167 +-#define args_type 1168 +-#define kwargs_type 1169 +-#define starred_expression_type 1170 +-#define kwarg_or_starred_type 1171 +-#define kwarg_or_double_starred_type 1172 +-#define star_targets_type 1173 +-#define star_targets_list_seq_type 1174 +-#define star_targets_tuple_seq_type 1175 +-#define star_target_type 1176 +-#define target_with_star_atom_type 1177 +-#define star_atom_type 1178 +-#define single_target_type 1179 +-#define single_subscript_attribute_target_type 1180 +-#define t_primary_type 1181 // Left-recursive +-#define t_lookahead_type 1182 +-#define del_targets_type 1183 +-#define del_target_type 1184 +-#define del_t_atom_type 1185 +-#define type_expressions_type 1186 +-#define func_type_comment_type 1187 +-#define invalid_arguments_type 1188 +-#define invalid_kwarg_type 1189 +-#define expression_without_invalid_type 1190 +-#define invalid_legacy_expression_type 1191 +-#define invalid_expression_type 1192 +-#define invalid_named_expression_type 1193 +-#define invalid_assignment_type 1194 +-#define invalid_ann_assign_target_type 1195 +-#define invalid_del_stmt_type 1196 +-#define invalid_block_type 1197 +-#define invalid_comprehension_type 1198 +-#define invalid_dict_comprehension_type 1199 +-#define invalid_parameters_type 1200 +-#define invalid_default_type 1201 +-#define invalid_star_etc_type 1202 +-#define invalid_kwds_type 1203 +-#define invalid_parameters_helper_type 1204 +-#define invalid_lambda_parameters_type 1205 +-#define invalid_lambda_parameters_helper_type 1206 +-#define invalid_lambda_star_etc_type 1207 +-#define invalid_lambda_kwds_type 1208 +-#define invalid_double_type_comments_type 1209 +-#define invalid_with_item_type 1210 +-#define invalid_for_target_type 1211 +-#define invalid_group_type 1212 +-#define invalid_import_type 1213 +-#define invalid_import_from_targets_type 1214 +-#define invalid_with_stmt_type 1215 +-#define invalid_with_stmt_indent_type 1216 +-#define invalid_try_stmt_type 1217 +-#define invalid_except_stmt_type 1218 +-#define invalid_finally_stmt_type 1219 +-#define invalid_except_stmt_indent_type 1220 +-#define invalid_except_star_stmt_indent_type 1221 +-#define invalid_match_stmt_type 1222 +-#define invalid_case_block_type 1223 +-#define invalid_as_pattern_type 1224 +-#define invalid_class_pattern_type 1225 +-#define invalid_class_argument_pattern_type 1226 +-#define invalid_if_stmt_type 1227 +-#define invalid_elif_stmt_type 1228 +-#define invalid_else_stmt_type 1229 +-#define invalid_while_stmt_type 1230 +-#define invalid_for_stmt_type 1231 +-#define invalid_def_raw_type 1232 +-#define invalid_class_def_raw_type 1233 +-#define invalid_double_starred_kvpairs_type 1234 +-#define invalid_kvpair_type 1235 +-#define invalid_starred_expression_type 1236 +-#define invalid_replacement_field_type 1237 +-#define invalid_conversion_character_type 1238 +-#define _loop0_1_type 1239 +-#define _loop0_2_type 1240 +-#define _loop0_3_type 1241 +-#define _loop1_4_type 1242 +-#define _loop0_6_type 1243 +-#define _gather_5_type 1244 +-#define _tmp_7_type 1245 +-#define _tmp_8_type 1246 +-#define _tmp_9_type 1247 +-#define _tmp_10_type 1248 +-#define _tmp_11_type 1249 +-#define _tmp_12_type 1250 +-#define _tmp_13_type 1251 +-#define _tmp_14_type 1252 +-#define _loop1_15_type 1253 +-#define _tmp_16_type 1254 +-#define _tmp_17_type 1255 +-#define _tmp_18_type 1256 +-#define _loop0_20_type 1257 +-#define _gather_19_type 1258 +-#define _loop0_22_type 1259 +-#define _gather_21_type 1260 +-#define _tmp_23_type 1261 +-#define _tmp_24_type 1262 +-#define _loop0_25_type 1263 +-#define _loop1_26_type 1264 +-#define _loop0_28_type 1265 +-#define _gather_27_type 1266 +-#define _tmp_29_type 1267 +-#define _loop0_31_type 1268 +-#define _gather_30_type 1269 +-#define _tmp_32_type 1270 +-#define _loop1_33_type 1271 +-#define _tmp_34_type 1272 +-#define _tmp_35_type 1273 +-#define _tmp_36_type 1274 +-#define _loop0_37_type 1275 +-#define _loop0_38_type 1276 +-#define _loop0_39_type 1277 +-#define _loop1_40_type 1278 +-#define _loop0_41_type 1279 +-#define _loop1_42_type 1280 +-#define _loop1_43_type 1281 +-#define _loop1_44_type 1282 +-#define _loop0_45_type 1283 +-#define _loop1_46_type 1284 +-#define _loop0_47_type 1285 +-#define _loop1_48_type 1286 +-#define _loop0_49_type 1287 +-#define _loop0_50_type 1288 +-#define _loop1_51_type 1289 +-#define _loop0_53_type 1290 +-#define _gather_52_type 1291 +-#define _loop0_55_type 1292 +-#define _gather_54_type 1293 +-#define _loop0_57_type 1294 +-#define _gather_56_type 1295 +-#define _loop0_59_type 1296 +-#define _gather_58_type 1297 +-#define _tmp_60_type 1298 +-#define _loop1_61_type 1299 +-#define _loop1_62_type 1300 +-#define _tmp_63_type 1301 +-#define _tmp_64_type 1302 +-#define _loop1_65_type 1303 +-#define _loop0_67_type 1304 +-#define _gather_66_type 1305 +-#define _tmp_68_type 1306 +-#define _tmp_69_type 1307 +-#define _tmp_70_type 1308 +-#define _tmp_71_type 1309 +-#define _loop0_73_type 1310 +-#define _gather_72_type 1311 +-#define _loop0_75_type 1312 +-#define _gather_74_type 1313 +-#define _tmp_76_type 1314 +-#define _loop0_78_type 1315 +-#define _gather_77_type 1316 +-#define _loop0_80_type 1317 +-#define _gather_79_type 1318 +-#define _loop1_81_type 1319 +-#define _loop1_82_type 1320 +-#define _loop0_84_type 1321 +-#define _gather_83_type 1322 +-#define _loop1_85_type 1323 +-#define _loop1_86_type 1324 +-#define _loop1_87_type 1325 +-#define _tmp_88_type 1326 +-#define _loop0_90_type 1327 +-#define _gather_89_type 1328 +-#define _tmp_91_type 1329 +-#define _tmp_92_type 1330 +-#define _tmp_93_type 1331 +-#define _tmp_94_type 1332 +-#define _tmp_95_type 1333 +-#define _tmp_96_type 1334 +-#define _loop0_97_type 1335 +-#define _loop0_98_type 1336 +-#define _loop0_99_type 1337 +-#define _loop1_100_type 1338 +-#define _loop0_101_type 1339 +-#define _loop1_102_type 1340 +-#define _loop1_103_type 1341 +-#define _loop1_104_type 1342 +-#define _loop0_105_type 1343 +-#define _loop1_106_type 1344 +-#define _loop0_107_type 1345 +-#define _loop1_108_type 1346 +-#define _loop0_109_type 1347 +-#define _loop1_110_type 1348 +-#define _tmp_111_type 1349 +-#define _loop0_112_type 1350 +-#define _loop1_113_type 1351 +-#define _tmp_114_type 1352 +-#define _loop0_116_type 1353 +-#define _gather_115_type 1354 +-#define _loop1_117_type 1355 +-#define _loop0_118_type 1356 +-#define _loop0_119_type 1357 +-#define _tmp_120_type 1358 +-#define _loop0_122_type 1359 +-#define _gather_121_type 1360 +-#define _tmp_123_type 1361 +-#define _loop0_125_type 1362 +-#define _gather_124_type 1363 +-#define _loop0_127_type 1364 +-#define _gather_126_type 1365 +-#define _loop0_129_type 1366 +-#define _gather_128_type 1367 +-#define _loop0_131_type 1368 +-#define _gather_130_type 1369 +-#define _loop0_132_type 1370 +-#define _loop0_134_type 1371 +-#define _gather_133_type 1372 +-#define _loop1_135_type 1373 +-#define _tmp_136_type 1374 +-#define _loop0_138_type 1375 +-#define _gather_137_type 1376 +-#define _loop0_140_type 1377 +-#define _gather_139_type 1378 +-#define _loop0_142_type 1379 +-#define _gather_141_type 1380 +-#define _loop0_144_type 1381 +-#define _gather_143_type 1382 +-#define _loop0_146_type 1383 +-#define _gather_145_type 1384 +-#define _tmp_147_type 1385 +-#define _tmp_148_type 1386 +-#define _tmp_149_type 1387 +-#define _tmp_150_type 1388 +-#define _tmp_151_type 1389 +-#define _tmp_152_type 1390 +-#define _tmp_153_type 1391 +-#define _tmp_154_type 1392 +-#define _tmp_155_type 1393 +-#define _tmp_156_type 1394 +-#define _tmp_157_type 1395 +-#define _tmp_158_type 1396 +-#define _loop0_159_type 1397 +-#define _loop0_160_type 1398 +-#define _loop0_161_type 1399 +-#define _tmp_162_type 1400 +-#define _tmp_163_type 1401 +-#define _tmp_164_type 1402 +-#define _tmp_165_type 1403 +-#define _tmp_166_type 1404 +-#define _loop0_167_type 1405 +-#define _loop0_168_type 1406 +-#define _loop0_169_type 1407 +-#define _loop1_170_type 1408 +-#define _tmp_171_type 1409 +-#define _loop0_172_type 1410 +-#define _tmp_173_type 1411 +-#define _loop0_174_type 1412 +-#define _loop1_175_type 1413 +-#define _tmp_176_type 1414 +-#define _tmp_177_type 1415 +-#define _tmp_178_type 1416 +-#define _loop0_179_type 1417 +-#define _tmp_180_type 1418 +-#define _tmp_181_type 1419 +-#define _loop1_182_type 1420 +-#define _tmp_183_type 1421 +-#define _loop0_184_type 1422 +-#define _loop0_185_type 1423 +-#define _loop0_186_type 1424 +-#define _loop0_188_type 1425 +-#define _gather_187_type 1426 +-#define _tmp_189_type 1427 +-#define _loop0_190_type 1428 +-#define _tmp_191_type 1429 +-#define _loop0_192_type 1430 +-#define _loop1_193_type 1431 +-#define _loop1_194_type 1432 +-#define _tmp_195_type 1433 +-#define _tmp_196_type 1434 +-#define _loop0_197_type 1435 +-#define _tmp_198_type 1436 +-#define _tmp_199_type 1437 +-#define _tmp_200_type 1438 +-#define _loop0_202_type 1439 +-#define _gather_201_type 1440 +-#define _loop0_204_type 1441 +-#define _gather_203_type 1442 +-#define _loop0_206_type 1443 +-#define _gather_205_type 1444 +-#define _loop0_208_type 1445 +-#define _gather_207_type 1446 +-#define _tmp_209_type 1447 +-#define _loop0_210_type 1448 +-#define _loop1_211_type 1449 +-#define _tmp_212_type 1450 +-#define _loop0_213_type 1451 +-#define _loop1_214_type 1452 +-#define _tmp_215_type 1453 +-#define _tmp_216_type 1454 +-#define _tmp_217_type 1455 +-#define _tmp_218_type 1456 +-#define _tmp_219_type 1457 +-#define _tmp_220_type 1458 +-#define _tmp_221_type 1459 +-#define _tmp_222_type 1460 +-#define _tmp_223_type 1461 +-#define _tmp_224_type 1462 +-#define _loop0_226_type 1463 +-#define _gather_225_type 1464 +-#define _tmp_227_type 1465 +-#define _tmp_228_type 1466 +-#define _tmp_229_type 1467 +-#define _tmp_230_type 1468 +-#define _tmp_231_type 1469 +-#define _tmp_232_type 1470 +-#define _tmp_233_type 1471 +-#define _tmp_234_type 1472 +-#define _tmp_235_type 1473 +-#define _tmp_236_type 1474 +-#define _tmp_237_type 1475 +-#define _tmp_238_type 1476 +-#define _tmp_239_type 1477 +-#define _loop0_240_type 1478 +-#define _tmp_241_type 1479 +-#define _tmp_242_type 1480 +-#define _tmp_243_type 1481 +-#define _tmp_244_type 1482 +-#define _tmp_245_type 1483 +-#define _tmp_246_type 1484 +-#define _tmp_247_type 1485 +-#define _tmp_248_type 1486 +-#define _tmp_249_type 1487 +-#define _tmp_250_type 1488 +-#define _tmp_251_type 1489 +-#define _tmp_252_type 1490 +-#define _tmp_253_type 1491 +-#define _tmp_254_type 1492 +-#define _tmp_255_type 1493 +-#define _tmp_256_type 1494 +-#define _tmp_257_type 1495 +-#define _tmp_258_type 1496 +-#define _tmp_259_type 1497 +-#define _tmp_260_type 1498 +-#define _tmp_261_type 1499 +-#define _tmp_262_type 1500 +-#define _tmp_263_type 1501 +-#define _tmp_264_type 1502 +-#define _tmp_265_type 1503 +-#define _tmp_266_type 1504 +-#define _tmp_267_type 1505 +-#define _tmp_268_type 1506 +-#define _tmp_269_type 1507 +-#define _tmp_270_type 1508 +-#define _tmp_271_type 1509 +-#define _tmp_272_type 1510 ++#define type_alias_type 1098 ++#define type_params_type 1099 ++#define type_param_seq_type 1100 ++#define type_param_type 1101 ++#define type_param_bound_type 1102 ++#define expressions_type 1103 ++#define expression_type 1104 ++#define yield_expr_type 1105 ++#define star_expressions_type 1106 ++#define star_expression_type 1107 ++#define star_named_expressions_type 1108 ++#define star_named_expression_type 1109 ++#define assignment_expression_type 1110 ++#define named_expression_type 1111 ++#define disjunction_type 1112 ++#define conjunction_type 1113 ++#define inversion_type 1114 ++#define comparison_type 1115 ++#define compare_op_bitwise_or_pair_type 1116 ++#define eq_bitwise_or_type 1117 ++#define noteq_bitwise_or_type 1118 ++#define lte_bitwise_or_type 1119 ++#define lt_bitwise_or_type 1120 ++#define gte_bitwise_or_type 1121 ++#define gt_bitwise_or_type 1122 ++#define notin_bitwise_or_type 1123 ++#define in_bitwise_or_type 1124 ++#define isnot_bitwise_or_type 1125 ++#define is_bitwise_or_type 1126 ++#define bitwise_or_type 1127 // Left-recursive ++#define bitwise_xor_type 1128 // Left-recursive ++#define bitwise_and_type 1129 // Left-recursive ++#define shift_expr_type 1130 // Left-recursive ++#define sum_type 1131 // Left-recursive ++#define term_type 1132 // Left-recursive ++#define factor_type 1133 ++#define power_type 1134 ++#define await_primary_type 1135 ++#define primary_type 1136 // Left-recursive ++#define slices_type 1137 ++#define slice_type 1138 ++#define atom_type 1139 ++#define group_type 1140 ++#define lambdef_type 1141 ++#define lambda_params_type 1142 ++#define lambda_parameters_type 1143 ++#define lambda_slash_no_default_type 1144 ++#define lambda_slash_with_default_type 1145 ++#define lambda_star_etc_type 1146 ++#define lambda_kwds_type 1147 ++#define lambda_param_no_default_type 1148 ++#define lambda_param_with_default_type 1149 ++#define lambda_param_maybe_default_type 1150 ++#define lambda_param_type 1151 ++#define fstring_middle_type 1152 ++#define fstring_replacement_field_type 1153 ++#define fstring_conversion_type 1154 ++#define fstring_full_format_spec_type 1155 ++#define fstring_format_spec_type 1156 ++#define string_type 1157 ++#define strings_type 1158 ++#define list_type 1159 ++#define tuple_type 1160 ++#define set_type 1161 ++#define dict_type 1162 ++#define double_starred_kvpairs_type 1163 ++#define double_starred_kvpair_type 1164 ++#define kvpair_type 1165 ++#define for_if_clauses_type 1166 ++#define for_if_clause_type 1167 ++#define listcomp_type 1168 ++#define setcomp_type 1169 ++#define genexp_type 1170 ++#define dictcomp_type 1171 ++#define arguments_type 1172 ++#define args_type 1173 ++#define kwargs_type 1174 ++#define starred_expression_type 1175 ++#define kwarg_or_starred_type 1176 ++#define kwarg_or_double_starred_type 1177 ++#define star_targets_type 1178 ++#define star_targets_list_seq_type 1179 ++#define star_targets_tuple_seq_type 1180 ++#define star_target_type 1181 ++#define target_with_star_atom_type 1182 ++#define star_atom_type 1183 ++#define single_target_type 1184 ++#define single_subscript_attribute_target_type 1185 ++#define t_primary_type 1186 // Left-recursive ++#define t_lookahead_type 1187 ++#define del_targets_type 1188 ++#define del_target_type 1189 ++#define del_t_atom_type 1190 ++#define type_expressions_type 1191 ++#define func_type_comment_type 1192 ++#define invalid_arguments_type 1193 ++#define invalid_kwarg_type 1194 ++#define expression_without_invalid_type 1195 ++#define invalid_legacy_expression_type 1196 ++#define invalid_expression_type 1197 ++#define invalid_named_expression_type 1198 ++#define invalid_assignment_type 1199 ++#define invalid_ann_assign_target_type 1200 ++#define invalid_del_stmt_type 1201 ++#define invalid_block_type 1202 ++#define invalid_comprehension_type 1203 ++#define invalid_dict_comprehension_type 1204 ++#define invalid_parameters_type 1205 ++#define invalid_default_type 1206 ++#define invalid_star_etc_type 1207 ++#define invalid_kwds_type 1208 ++#define invalid_parameters_helper_type 1209 ++#define invalid_lambda_parameters_type 1210 ++#define invalid_lambda_parameters_helper_type 1211 ++#define invalid_lambda_star_etc_type 1212 ++#define invalid_lambda_kwds_type 1213 ++#define invalid_double_type_comments_type 1214 ++#define invalid_with_item_type 1215 ++#define invalid_for_target_type 1216 ++#define invalid_group_type 1217 ++#define invalid_import_type 1218 ++#define invalid_import_from_targets_type 1219 ++#define invalid_with_stmt_type 1220 ++#define invalid_with_stmt_indent_type 1221 ++#define invalid_try_stmt_type 1222 ++#define invalid_except_stmt_type 1223 ++#define invalid_finally_stmt_type 1224 ++#define invalid_except_stmt_indent_type 1225 ++#define invalid_except_star_stmt_indent_type 1226 ++#define invalid_match_stmt_type 1227 ++#define invalid_case_block_type 1228 ++#define invalid_as_pattern_type 1229 ++#define invalid_class_pattern_type 1230 ++#define invalid_class_argument_pattern_type 1231 ++#define invalid_if_stmt_type 1232 ++#define invalid_elif_stmt_type 1233 ++#define invalid_else_stmt_type 1234 ++#define invalid_while_stmt_type 1235 ++#define invalid_for_stmt_type 1236 ++#define invalid_def_raw_type 1237 ++#define invalid_class_def_raw_type 1238 ++#define invalid_double_starred_kvpairs_type 1239 ++#define invalid_kvpair_type 1240 ++#define invalid_starred_expression_type 1241 ++#define invalid_replacement_field_type 1242 ++#define invalid_conversion_character_type 1243 ++#define _loop0_1_type 1244 ++#define _loop0_2_type 1245 ++#define _loop0_3_type 1246 ++#define _loop1_4_type 1247 ++#define _loop0_6_type 1248 ++#define _gather_5_type 1249 ++#define _tmp_7_type 1250 ++#define _tmp_8_type 1251 ++#define _tmp_9_type 1252 ++#define _tmp_10_type 1253 ++#define _tmp_11_type 1254 ++#define _tmp_12_type 1255 ++#define _tmp_13_type 1256 ++#define _tmp_14_type 1257 ++#define _loop1_15_type 1258 ++#define _tmp_16_type 1259 ++#define _tmp_17_type 1260 ++#define _tmp_18_type 1261 ++#define _loop0_20_type 1262 ++#define _gather_19_type 1263 ++#define _loop0_22_type 1264 ++#define _gather_21_type 1265 ++#define _tmp_23_type 1266 ++#define _tmp_24_type 1267 ++#define _loop0_25_type 1268 ++#define _loop1_26_type 1269 ++#define _loop0_28_type 1270 ++#define _gather_27_type 1271 ++#define _tmp_29_type 1272 ++#define _loop0_31_type 1273 ++#define _gather_30_type 1274 ++#define _tmp_32_type 1275 ++#define _loop1_33_type 1276 ++#define _tmp_34_type 1277 ++#define _tmp_35_type 1278 ++#define _tmp_36_type 1279 ++#define _loop0_37_type 1280 ++#define _loop0_38_type 1281 ++#define _loop0_39_type 1282 ++#define _loop1_40_type 1283 ++#define _loop0_41_type 1284 ++#define _loop1_42_type 1285 ++#define _loop1_43_type 1286 ++#define _loop1_44_type 1287 ++#define _loop0_45_type 1288 ++#define _loop1_46_type 1289 ++#define _loop0_47_type 1290 ++#define _loop1_48_type 1291 ++#define _loop0_49_type 1292 ++#define _loop0_50_type 1293 ++#define _loop1_51_type 1294 ++#define _loop0_53_type 1295 ++#define _gather_52_type 1296 ++#define _loop0_55_type 1297 ++#define _gather_54_type 1298 ++#define _loop0_57_type 1299 ++#define _gather_56_type 1300 ++#define _loop0_59_type 1301 ++#define _gather_58_type 1302 ++#define _tmp_60_type 1303 ++#define _loop1_61_type 1304 ++#define _loop1_62_type 1305 ++#define _tmp_63_type 1306 ++#define _tmp_64_type 1307 ++#define _loop1_65_type 1308 ++#define _loop0_67_type 1309 ++#define _gather_66_type 1310 ++#define _tmp_68_type 1311 ++#define _tmp_69_type 1312 ++#define _tmp_70_type 1313 ++#define _tmp_71_type 1314 ++#define _loop0_73_type 1315 ++#define _gather_72_type 1316 ++#define _loop0_75_type 1317 ++#define _gather_74_type 1318 ++#define _tmp_76_type 1319 ++#define _loop0_78_type 1320 ++#define _gather_77_type 1321 ++#define _loop0_80_type 1322 ++#define _gather_79_type 1323 ++#define _loop0_82_type 1324 ++#define _gather_81_type 1325 ++#define _loop1_83_type 1326 ++#define _loop1_84_type 1327 ++#define _loop0_86_type 1328 ++#define _gather_85_type 1329 ++#define _loop1_87_type 1330 ++#define _loop1_88_type 1331 ++#define _loop1_89_type 1332 ++#define _tmp_90_type 1333 ++#define _loop0_92_type 1334 ++#define _gather_91_type 1335 ++#define _tmp_93_type 1336 ++#define _tmp_94_type 1337 ++#define _tmp_95_type 1338 ++#define _tmp_96_type 1339 ++#define _tmp_97_type 1340 ++#define _tmp_98_type 1341 ++#define _loop0_99_type 1342 ++#define _loop0_100_type 1343 ++#define _loop0_101_type 1344 ++#define _loop1_102_type 1345 ++#define _loop0_103_type 1346 ++#define _loop1_104_type 1347 ++#define _loop1_105_type 1348 ++#define _loop1_106_type 1349 ++#define _loop0_107_type 1350 ++#define _loop1_108_type 1351 ++#define _loop0_109_type 1352 ++#define _loop1_110_type 1353 ++#define _loop0_111_type 1354 ++#define _loop1_112_type 1355 ++#define _tmp_113_type 1356 ++#define _loop0_114_type 1357 ++#define _loop1_115_type 1358 ++#define _tmp_116_type 1359 ++#define _loop0_118_type 1360 ++#define _gather_117_type 1361 ++#define _loop1_119_type 1362 ++#define _loop0_120_type 1363 ++#define _loop0_121_type 1364 ++#define _tmp_122_type 1365 ++#define _loop0_124_type 1366 ++#define _gather_123_type 1367 ++#define _tmp_125_type 1368 ++#define _loop0_127_type 1369 ++#define _gather_126_type 1370 ++#define _loop0_129_type 1371 ++#define _gather_128_type 1372 ++#define _loop0_131_type 1373 ++#define _gather_130_type 1374 ++#define _loop0_133_type 1375 ++#define _gather_132_type 1376 ++#define _loop0_134_type 1377 ++#define _loop0_136_type 1378 ++#define _gather_135_type 1379 ++#define _loop1_137_type 1380 ++#define _tmp_138_type 1381 ++#define _loop0_140_type 1382 ++#define _gather_139_type 1383 ++#define _loop0_142_type 1384 ++#define _gather_141_type 1385 ++#define _loop0_144_type 1386 ++#define _gather_143_type 1387 ++#define _loop0_146_type 1388 ++#define _gather_145_type 1389 ++#define _loop0_148_type 1390 ++#define _gather_147_type 1391 ++#define _tmp_149_type 1392 ++#define _tmp_150_type 1393 ++#define _tmp_151_type 1394 ++#define _tmp_152_type 1395 ++#define _tmp_153_type 1396 ++#define _tmp_154_type 1397 ++#define _tmp_155_type 1398 ++#define _tmp_156_type 1399 ++#define _tmp_157_type 1400 ++#define _tmp_158_type 1401 ++#define _tmp_159_type 1402 ++#define _tmp_160_type 1403 ++#define _loop0_161_type 1404 ++#define _loop0_162_type 1405 ++#define _loop0_163_type 1406 ++#define _tmp_164_type 1407 ++#define _tmp_165_type 1408 ++#define _tmp_166_type 1409 ++#define _tmp_167_type 1410 ++#define _tmp_168_type 1411 ++#define _loop0_169_type 1412 ++#define _loop0_170_type 1413 ++#define _loop0_171_type 1414 ++#define _loop1_172_type 1415 ++#define _tmp_173_type 1416 ++#define _loop0_174_type 1417 ++#define _tmp_175_type 1418 ++#define _loop0_176_type 1419 ++#define _loop1_177_type 1420 ++#define _tmp_178_type 1421 ++#define _tmp_179_type 1422 ++#define _tmp_180_type 1423 ++#define _loop0_181_type 1424 ++#define _tmp_182_type 1425 ++#define _tmp_183_type 1426 ++#define _loop1_184_type 1427 ++#define _tmp_185_type 1428 ++#define _loop0_186_type 1429 ++#define _loop0_187_type 1430 ++#define _loop0_188_type 1431 ++#define _loop0_190_type 1432 ++#define _gather_189_type 1433 ++#define _tmp_191_type 1434 ++#define _loop0_192_type 1435 ++#define _tmp_193_type 1436 ++#define _loop0_194_type 1437 ++#define _loop1_195_type 1438 ++#define _loop1_196_type 1439 ++#define _tmp_197_type 1440 ++#define _tmp_198_type 1441 ++#define _loop0_199_type 1442 ++#define _tmp_200_type 1443 ++#define _tmp_201_type 1444 ++#define _tmp_202_type 1445 ++#define _loop0_204_type 1446 ++#define _gather_203_type 1447 ++#define _loop0_206_type 1448 ++#define _gather_205_type 1449 ++#define _loop0_208_type 1450 ++#define _gather_207_type 1451 ++#define _loop0_210_type 1452 ++#define _gather_209_type 1453 ++#define _tmp_211_type 1454 ++#define _loop0_212_type 1455 ++#define _loop1_213_type 1456 ++#define _tmp_214_type 1457 ++#define _loop0_215_type 1458 ++#define _loop1_216_type 1459 ++#define _tmp_217_type 1460 ++#define _tmp_218_type 1461 ++#define _tmp_219_type 1462 ++#define _tmp_220_type 1463 ++#define _tmp_221_type 1464 ++#define _tmp_222_type 1465 ++#define _tmp_223_type 1466 ++#define _tmp_224_type 1467 ++#define _tmp_225_type 1468 ++#define _tmp_226_type 1469 ++#define _loop0_228_type 1470 ++#define _gather_227_type 1471 ++#define _tmp_229_type 1472 ++#define _tmp_230_type 1473 ++#define _tmp_231_type 1474 ++#define _tmp_232_type 1475 ++#define _tmp_233_type 1476 ++#define _tmp_234_type 1477 ++#define _tmp_235_type 1478 ++#define _tmp_236_type 1479 ++#define _tmp_237_type 1480 ++#define _tmp_238_type 1481 ++#define _tmp_239_type 1482 ++#define _tmp_240_type 1483 ++#define _tmp_241_type 1484 ++#define _loop0_242_type 1485 ++#define _tmp_243_type 1486 ++#define _tmp_244_type 1487 ++#define _tmp_245_type 1488 ++#define _tmp_246_type 1489 ++#define _tmp_247_type 1490 ++#define _tmp_248_type 1491 ++#define _tmp_249_type 1492 ++#define _tmp_250_type 1493 ++#define _tmp_251_type 1494 ++#define _tmp_252_type 1495 ++#define _tmp_253_type 1496 ++#define _tmp_254_type 1497 ++#define _tmp_255_type 1498 ++#define _tmp_256_type 1499 ++#define _tmp_257_type 1500 ++#define _tmp_258_type 1501 ++#define _tmp_259_type 1502 ++#define _tmp_260_type 1503 ++#define _tmp_261_type 1504 ++#define _tmp_262_type 1505 ++#define _tmp_263_type 1506 ++#define _tmp_264_type 1507 ++#define _tmp_265_type 1508 ++#define _tmp_266_type 1509 ++#define _tmp_267_type 1510 ++#define _tmp_268_type 1511 ++#define _tmp_269_type 1512 ++#define _tmp_270_type 1513 ++#define _tmp_271_type 1514 ++#define _tmp_272_type 1515 ++#define _tmp_273_type 1516 ++#define _tmp_274_type 1517 + + static mod_ty file_rule(Parser *p); + static mod_ty interactive_rule(Parser *p); +@@ -687,6 +695,11 @@ static pattern_ty class_pattern_rule(Parser *p); + static asdl_pattern_seq* positional_patterns_rule(Parser *p); + static asdl_seq* keyword_patterns_rule(Parser *p); + static KeyPatternPair* keyword_pattern_rule(Parser *p); ++static stmt_ty type_alias_rule(Parser *p); ++static asdl_typeparam_seq* type_params_rule(Parser *p); ++static asdl_typeparam_seq* type_param_seq_rule(Parser *p); ++static typeparam_ty type_param_rule(Parser *p); ++static expr_ty type_param_bound_rule(Parser *p); + static expr_ty expressions_rule(Parser *p); + static expr_ty expression_rule(Parser *p); + static expr_ty yield_expr_rule(Parser *p); +@@ -908,64 +921,64 @@ static asdl_seq *_loop0_78_rule(Parser *p); + static asdl_seq *_gather_77_rule(Parser *p); + static asdl_seq *_loop0_80_rule(Parser *p); + static asdl_seq *_gather_79_rule(Parser *p); +-static asdl_seq *_loop1_81_rule(Parser *p); +-static asdl_seq *_loop1_82_rule(Parser *p); +-static asdl_seq *_loop0_84_rule(Parser *p); +-static asdl_seq *_gather_83_rule(Parser *p); +-static asdl_seq *_loop1_85_rule(Parser *p); +-static asdl_seq *_loop1_86_rule(Parser *p); ++static asdl_seq *_loop0_82_rule(Parser *p); ++static asdl_seq *_gather_81_rule(Parser *p); ++static asdl_seq *_loop1_83_rule(Parser *p); ++static asdl_seq *_loop1_84_rule(Parser *p); ++static asdl_seq *_loop0_86_rule(Parser *p); ++static asdl_seq *_gather_85_rule(Parser *p); + static asdl_seq *_loop1_87_rule(Parser *p); +-static void *_tmp_88_rule(Parser *p); +-static asdl_seq *_loop0_90_rule(Parser *p); +-static asdl_seq *_gather_89_rule(Parser *p); +-static void *_tmp_91_rule(Parser *p); +-static void *_tmp_92_rule(Parser *p); ++static asdl_seq *_loop1_88_rule(Parser *p); ++static asdl_seq *_loop1_89_rule(Parser *p); ++static void *_tmp_90_rule(Parser *p); ++static asdl_seq *_loop0_92_rule(Parser *p); ++static asdl_seq *_gather_91_rule(Parser *p); + static void *_tmp_93_rule(Parser *p); + static void *_tmp_94_rule(Parser *p); + static void *_tmp_95_rule(Parser *p); + static void *_tmp_96_rule(Parser *p); +-static asdl_seq *_loop0_97_rule(Parser *p); +-static asdl_seq *_loop0_98_rule(Parser *p); ++static void *_tmp_97_rule(Parser *p); ++static void *_tmp_98_rule(Parser *p); + static asdl_seq *_loop0_99_rule(Parser *p); +-static asdl_seq *_loop1_100_rule(Parser *p); ++static asdl_seq *_loop0_100_rule(Parser *p); + static asdl_seq *_loop0_101_rule(Parser *p); + static asdl_seq *_loop1_102_rule(Parser *p); +-static asdl_seq *_loop1_103_rule(Parser *p); ++static asdl_seq *_loop0_103_rule(Parser *p); + static asdl_seq *_loop1_104_rule(Parser *p); +-static asdl_seq *_loop0_105_rule(Parser *p); ++static asdl_seq *_loop1_105_rule(Parser *p); + static asdl_seq *_loop1_106_rule(Parser *p); + static asdl_seq *_loop0_107_rule(Parser *p); + static asdl_seq *_loop1_108_rule(Parser *p); + static asdl_seq *_loop0_109_rule(Parser *p); + static asdl_seq *_loop1_110_rule(Parser *p); +-static void *_tmp_111_rule(Parser *p); +-static asdl_seq *_loop0_112_rule(Parser *p); +-static asdl_seq *_loop1_113_rule(Parser *p); +-static void *_tmp_114_rule(Parser *p); +-static asdl_seq *_loop0_116_rule(Parser *p); +-static asdl_seq *_gather_115_rule(Parser *p); +-static asdl_seq *_loop1_117_rule(Parser *p); ++static asdl_seq *_loop0_111_rule(Parser *p); ++static asdl_seq *_loop1_112_rule(Parser *p); ++static void *_tmp_113_rule(Parser *p); ++static asdl_seq *_loop0_114_rule(Parser *p); ++static asdl_seq *_loop1_115_rule(Parser *p); ++static void *_tmp_116_rule(Parser *p); + static asdl_seq *_loop0_118_rule(Parser *p); +-static asdl_seq *_loop0_119_rule(Parser *p); +-static void *_tmp_120_rule(Parser *p); +-static asdl_seq *_loop0_122_rule(Parser *p); +-static asdl_seq *_gather_121_rule(Parser *p); +-static void *_tmp_123_rule(Parser *p); +-static asdl_seq *_loop0_125_rule(Parser *p); +-static asdl_seq *_gather_124_rule(Parser *p); ++static asdl_seq *_gather_117_rule(Parser *p); ++static asdl_seq *_loop1_119_rule(Parser *p); ++static asdl_seq *_loop0_120_rule(Parser *p); ++static asdl_seq *_loop0_121_rule(Parser *p); ++static void *_tmp_122_rule(Parser *p); ++static asdl_seq *_loop0_124_rule(Parser *p); ++static asdl_seq *_gather_123_rule(Parser *p); ++static void *_tmp_125_rule(Parser *p); + static asdl_seq *_loop0_127_rule(Parser *p); + static asdl_seq *_gather_126_rule(Parser *p); + static asdl_seq *_loop0_129_rule(Parser *p); + static asdl_seq *_gather_128_rule(Parser *p); + static asdl_seq *_loop0_131_rule(Parser *p); + static asdl_seq *_gather_130_rule(Parser *p); +-static asdl_seq *_loop0_132_rule(Parser *p); ++static asdl_seq *_loop0_133_rule(Parser *p); ++static asdl_seq *_gather_132_rule(Parser *p); + static asdl_seq *_loop0_134_rule(Parser *p); +-static asdl_seq *_gather_133_rule(Parser *p); +-static asdl_seq *_loop1_135_rule(Parser *p); +-static void *_tmp_136_rule(Parser *p); +-static asdl_seq *_loop0_138_rule(Parser *p); +-static asdl_seq *_gather_137_rule(Parser *p); ++static asdl_seq *_loop0_136_rule(Parser *p); ++static asdl_seq *_gather_135_rule(Parser *p); ++static asdl_seq *_loop1_137_rule(Parser *p); ++static void *_tmp_138_rule(Parser *p); + static asdl_seq *_loop0_140_rule(Parser *p); + static asdl_seq *_gather_139_rule(Parser *p); + static asdl_seq *_loop0_142_rule(Parser *p); +@@ -974,8 +987,8 @@ static asdl_seq *_loop0_144_rule(Parser *p); + static asdl_seq *_gather_143_rule(Parser *p); + static asdl_seq *_loop0_146_rule(Parser *p); + static asdl_seq *_gather_145_rule(Parser *p); +-static void *_tmp_147_rule(Parser *p); +-static void *_tmp_148_rule(Parser *p); ++static asdl_seq *_loop0_148_rule(Parser *p); ++static asdl_seq *_gather_147_rule(Parser *p); + static void *_tmp_149_rule(Parser *p); + static void *_tmp_150_rule(Parser *p); + static void *_tmp_151_rule(Parser *p); +@@ -986,64 +999,64 @@ static void *_tmp_155_rule(Parser *p); + static void *_tmp_156_rule(Parser *p); + static void *_tmp_157_rule(Parser *p); + static void *_tmp_158_rule(Parser *p); +-static asdl_seq *_loop0_159_rule(Parser *p); +-static asdl_seq *_loop0_160_rule(Parser *p); ++static void *_tmp_159_rule(Parser *p); ++static void *_tmp_160_rule(Parser *p); + static asdl_seq *_loop0_161_rule(Parser *p); +-static void *_tmp_162_rule(Parser *p); +-static void *_tmp_163_rule(Parser *p); ++static asdl_seq *_loop0_162_rule(Parser *p); ++static asdl_seq *_loop0_163_rule(Parser *p); + static void *_tmp_164_rule(Parser *p); + static void *_tmp_165_rule(Parser *p); + static void *_tmp_166_rule(Parser *p); +-static asdl_seq *_loop0_167_rule(Parser *p); +-static asdl_seq *_loop0_168_rule(Parser *p); ++static void *_tmp_167_rule(Parser *p); ++static void *_tmp_168_rule(Parser *p); + static asdl_seq *_loop0_169_rule(Parser *p); +-static asdl_seq *_loop1_170_rule(Parser *p); +-static void *_tmp_171_rule(Parser *p); +-static asdl_seq *_loop0_172_rule(Parser *p); ++static asdl_seq *_loop0_170_rule(Parser *p); ++static asdl_seq *_loop0_171_rule(Parser *p); ++static asdl_seq *_loop1_172_rule(Parser *p); + static void *_tmp_173_rule(Parser *p); + static asdl_seq *_loop0_174_rule(Parser *p); +-static asdl_seq *_loop1_175_rule(Parser *p); +-static void *_tmp_176_rule(Parser *p); +-static void *_tmp_177_rule(Parser *p); ++static void *_tmp_175_rule(Parser *p); ++static asdl_seq *_loop0_176_rule(Parser *p); ++static asdl_seq *_loop1_177_rule(Parser *p); + static void *_tmp_178_rule(Parser *p); +-static asdl_seq *_loop0_179_rule(Parser *p); ++static void *_tmp_179_rule(Parser *p); + static void *_tmp_180_rule(Parser *p); +-static void *_tmp_181_rule(Parser *p); +-static asdl_seq *_loop1_182_rule(Parser *p); ++static asdl_seq *_loop0_181_rule(Parser *p); ++static void *_tmp_182_rule(Parser *p); + static void *_tmp_183_rule(Parser *p); +-static asdl_seq *_loop0_184_rule(Parser *p); +-static asdl_seq *_loop0_185_rule(Parser *p); ++static asdl_seq *_loop1_184_rule(Parser *p); ++static void *_tmp_185_rule(Parser *p); + static asdl_seq *_loop0_186_rule(Parser *p); ++static asdl_seq *_loop0_187_rule(Parser *p); + static asdl_seq *_loop0_188_rule(Parser *p); +-static asdl_seq *_gather_187_rule(Parser *p); +-static void *_tmp_189_rule(Parser *p); + static asdl_seq *_loop0_190_rule(Parser *p); ++static asdl_seq *_gather_189_rule(Parser *p); + static void *_tmp_191_rule(Parser *p); + static asdl_seq *_loop0_192_rule(Parser *p); +-static asdl_seq *_loop1_193_rule(Parser *p); +-static asdl_seq *_loop1_194_rule(Parser *p); +-static void *_tmp_195_rule(Parser *p); +-static void *_tmp_196_rule(Parser *p); +-static asdl_seq *_loop0_197_rule(Parser *p); ++static void *_tmp_193_rule(Parser *p); ++static asdl_seq *_loop0_194_rule(Parser *p); ++static asdl_seq *_loop1_195_rule(Parser *p); ++static asdl_seq *_loop1_196_rule(Parser *p); ++static void *_tmp_197_rule(Parser *p); + static void *_tmp_198_rule(Parser *p); +-static void *_tmp_199_rule(Parser *p); ++static asdl_seq *_loop0_199_rule(Parser *p); + static void *_tmp_200_rule(Parser *p); +-static asdl_seq *_loop0_202_rule(Parser *p); +-static asdl_seq *_gather_201_rule(Parser *p); ++static void *_tmp_201_rule(Parser *p); ++static void *_tmp_202_rule(Parser *p); + static asdl_seq *_loop0_204_rule(Parser *p); + static asdl_seq *_gather_203_rule(Parser *p); + static asdl_seq *_loop0_206_rule(Parser *p); + static asdl_seq *_gather_205_rule(Parser *p); + static asdl_seq *_loop0_208_rule(Parser *p); + static asdl_seq *_gather_207_rule(Parser *p); +-static void *_tmp_209_rule(Parser *p); + static asdl_seq *_loop0_210_rule(Parser *p); +-static asdl_seq *_loop1_211_rule(Parser *p); +-static void *_tmp_212_rule(Parser *p); +-static asdl_seq *_loop0_213_rule(Parser *p); +-static asdl_seq *_loop1_214_rule(Parser *p); +-static void *_tmp_215_rule(Parser *p); +-static void *_tmp_216_rule(Parser *p); ++static asdl_seq *_gather_209_rule(Parser *p); ++static void *_tmp_211_rule(Parser *p); ++static asdl_seq *_loop0_212_rule(Parser *p); ++static asdl_seq *_loop1_213_rule(Parser *p); ++static void *_tmp_214_rule(Parser *p); ++static asdl_seq *_loop0_215_rule(Parser *p); ++static asdl_seq *_loop1_216_rule(Parser *p); + static void *_tmp_217_rule(Parser *p); + static void *_tmp_218_rule(Parser *p); + static void *_tmp_219_rule(Parser *p); +@@ -1052,10 +1065,10 @@ static void *_tmp_221_rule(Parser *p); + static void *_tmp_222_rule(Parser *p); + static void *_tmp_223_rule(Parser *p); + static void *_tmp_224_rule(Parser *p); +-static asdl_seq *_loop0_226_rule(Parser *p); +-static asdl_seq *_gather_225_rule(Parser *p); +-static void *_tmp_227_rule(Parser *p); +-static void *_tmp_228_rule(Parser *p); ++static void *_tmp_225_rule(Parser *p); ++static void *_tmp_226_rule(Parser *p); ++static asdl_seq *_loop0_228_rule(Parser *p); ++static asdl_seq *_gather_227_rule(Parser *p); + static void *_tmp_229_rule(Parser *p); + static void *_tmp_230_rule(Parser *p); + static void *_tmp_231_rule(Parser *p); +@@ -1067,9 +1080,9 @@ static void *_tmp_236_rule(Parser *p); + static void *_tmp_237_rule(Parser *p); + static void *_tmp_238_rule(Parser *p); + static void *_tmp_239_rule(Parser *p); +-static asdl_seq *_loop0_240_rule(Parser *p); ++static void *_tmp_240_rule(Parser *p); + static void *_tmp_241_rule(Parser *p); +-static void *_tmp_242_rule(Parser *p); ++static asdl_seq *_loop0_242_rule(Parser *p); + static void *_tmp_243_rule(Parser *p); + static void *_tmp_244_rule(Parser *p); + static void *_tmp_245_rule(Parser *p); +@@ -1100,6 +1113,8 @@ static void *_tmp_269_rule(Parser *p); + static void *_tmp_270_rule(Parser *p); + static void *_tmp_271_rule(Parser *p); + static void *_tmp_272_rule(Parser *p); ++static void *_tmp_273_rule(Parser *p); ++static void *_tmp_274_rule(Parser *p); + + + // file: statements? $ +@@ -1681,6 +1696,7 @@ simple_stmts_rule(Parser *p) + + // simple_stmt: + // | assignment ++// | &"type" type_alias + // | star_expressions + // | &'return' return_stmt + // | &('import' | 'from') import_stmt +@@ -1738,6 +1754,27 @@ simple_stmt_rule(Parser *p) + D(fprintf(stderr, "%*c%s simple_stmt[%d-%d]: %s failed!\n", p->level, ' ', + p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "assignment")); + } ++ { // &"type" type_alias ++ if (p->error_indicator) { ++ p->level--; ++ return NULL; ++ } ++ D(fprintf(stderr, "%*c> simple_stmt[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "&\"type\" type_alias")); ++ stmt_ty type_alias_var; ++ if ( ++ _PyPegen_lookahead_with_string(1, _PyPegen_expect_soft_keyword, p, "type") ++ && ++ (type_alias_var = type_alias_rule(p)) // type_alias ++ ) ++ { ++ D(fprintf(stderr, "%*c+ simple_stmt[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "&\"type\" type_alias")); ++ _res = type_alias_var; ++ goto done; ++ } ++ p->mark = _mark; ++ D(fprintf(stderr, "%*c%s simple_stmt[%d-%d]: %s failed!\n", p->level, ' ', ++ p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "&\"type\" type_alias")); ++ } + { // star_expressions + if (p->error_indicator) { + p->level--; +@@ -4308,7 +4345,9 @@ class_def_rule(Parser *p) + return _res; + } + +-// class_def_raw: invalid_class_def_raw | 'class' NAME ['(' arguments? ')'] ':' block ++// class_def_raw: ++// | invalid_class_def_raw ++// | 'class' NAME type_params? ['(' arguments? ')'] ':' block + static stmt_ty + class_def_raw_rule(Parser *p) + { +@@ -4350,22 +4389,25 @@ class_def_raw_rule(Parser *p) + D(fprintf(stderr, "%*c%s class_def_raw[%d-%d]: %s failed!\n", p->level, ' ', + p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "invalid_class_def_raw")); + } +- { // 'class' NAME ['(' arguments? ')'] ':' block ++ { // 'class' NAME type_params? ['(' arguments? ')'] ':' block + if (p->error_indicator) { + p->level--; + return NULL; + } +- D(fprintf(stderr, "%*c> class_def_raw[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "'class' NAME ['(' arguments? ')'] ':' block")); ++ D(fprintf(stderr, "%*c> class_def_raw[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "'class' NAME type_params? ['(' arguments? ')'] ':' block")); + Token * _keyword; + Token * _literal; + expr_ty a; + void *b; + asdl_stmt_seq* c; ++ void *t; + if ( + (_keyword = _PyPegen_expect_token(p, 654)) // token='class' + && + (a = _PyPegen_name_token(p)) // NAME + && ++ (t = type_params_rule(p), !p->error_indicator) // type_params? ++ && + (b = _tmp_34_rule(p), !p->error_indicator) // ['(' arguments? ')'] + && + (_literal = _PyPegen_expect_token(p, 11)) // token=':' +@@ -4373,7 +4415,7 @@ class_def_raw_rule(Parser *p) + (c = block_rule(p)) // block + ) + { +- D(fprintf(stderr, "%*c+ class_def_raw[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "'class' NAME ['(' arguments? ')'] ':' block")); ++ D(fprintf(stderr, "%*c+ class_def_raw[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "'class' NAME type_params? ['(' arguments? ')'] ':' block")); + Token *_token = _PyPegen_get_last_nonnwhitespace_token(p); + if (_token == NULL) { + p->level--; +@@ -4383,7 +4425,7 @@ class_def_raw_rule(Parser *p) + UNUSED(_end_lineno); // Only used by EXTRA macro + int _end_col_offset = _token->end_col_offset; + UNUSED(_end_col_offset); // Only used by EXTRA macro +- _res = _PyAST_ClassDef ( a -> v . Name . id , ( b ) ? ( ( expr_ty ) b ) -> v . Call . args : NULL , ( b ) ? ( ( expr_ty ) b ) -> v . Call . keywords : NULL , c , NULL , EXTRA ); ++ _res = _PyAST_ClassDef ( a -> v . Name . id , t , ( b ) ? ( ( expr_ty ) b ) -> v . Call . args : NULL , ( b ) ? ( ( expr_ty ) b ) -> v . Call . keywords : NULL , c , NULL , EXTRA ); + if (_res == NULL && PyErr_Occurred()) { + p->error_indicator = 1; + p->level--; +@@ -4393,7 +4435,7 @@ class_def_raw_rule(Parser *p) + } + p->mark = _mark; + D(fprintf(stderr, "%*c%s class_def_raw[%d-%d]: %s failed!\n", p->level, ' ', +- p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "'class' NAME ['(' arguments? ')'] ':' block")); ++ p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "'class' NAME type_params? ['(' arguments? ')'] ':' block")); + } + _res = NULL; + done: +@@ -4469,8 +4511,8 @@ function_def_rule(Parser *p) + + // function_def_raw: + // | invalid_def_raw +-// | 'def' NAME &&'(' params? ')' ['->' expression] &&':' func_type_comment? block +-// | ASYNC 'def' NAME &&'(' params? ')' ['->' expression] &&':' func_type_comment? block ++// | 'def' NAME type_params? &&'(' params? ')' ['->' expression] &&':' func_type_comment? block ++// | ASYNC 'def' NAME type_params? &&'(' params? ')' ['->' expression] &&':' func_type_comment? block + static stmt_ty + function_def_raw_rule(Parser *p) + { +@@ -4512,12 +4554,12 @@ function_def_raw_rule(Parser *p) + D(fprintf(stderr, "%*c%s function_def_raw[%d-%d]: %s failed!\n", p->level, ' ', + p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "invalid_def_raw")); + } +- { // 'def' NAME &&'(' params? ')' ['->' expression] &&':' func_type_comment? block ++ { // 'def' NAME type_params? &&'(' params? ')' ['->' expression] &&':' func_type_comment? block + if (p->error_indicator) { + p->level--; + return NULL; + } +- D(fprintf(stderr, "%*c> function_def_raw[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "'def' NAME &&'(' params? ')' ['->' expression] &&':' func_type_comment? block")); ++ D(fprintf(stderr, "%*c> function_def_raw[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "'def' NAME type_params? &&'(' params? ')' ['->' expression] &&':' func_type_comment? block")); + Token * _keyword; + Token * _literal; + Token * _literal_1; +@@ -4526,12 +4568,15 @@ function_def_raw_rule(Parser *p) + asdl_stmt_seq* b; + expr_ty n; + void *params; ++ void *t; + void *tc; + if ( + (_keyword = _PyPegen_expect_token(p, 652)) // token='def' + && + (n = _PyPegen_name_token(p)) // NAME + && ++ (t = type_params_rule(p), !p->error_indicator) // type_params? ++ && + (_literal = _PyPegen_expect_forced_token(p, 7, "(")) // forced_token='(' + && + (params = params_rule(p), !p->error_indicator) // params? +@@ -4547,7 +4592,7 @@ function_def_raw_rule(Parser *p) + (b = block_rule(p)) // block + ) + { +- D(fprintf(stderr, "%*c+ function_def_raw[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "'def' NAME &&'(' params? ')' ['->' expression] &&':' func_type_comment? block")); ++ D(fprintf(stderr, "%*c+ function_def_raw[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "'def' NAME type_params? &&'(' params? ')' ['->' expression] &&':' func_type_comment? block")); + Token *_token = _PyPegen_get_last_nonnwhitespace_token(p); + if (_token == NULL) { + p->level--; +@@ -4557,7 +4602,7 @@ function_def_raw_rule(Parser *p) + UNUSED(_end_lineno); // Only used by EXTRA macro + int _end_col_offset = _token->end_col_offset; + UNUSED(_end_col_offset); // Only used by EXTRA macro +- _res = _PyAST_FunctionDef ( n -> v . Name . id , ( params ) ? params : CHECK ( arguments_ty , _PyPegen_empty_arguments ( p ) ) , b , NULL , a , NEW_TYPE_COMMENT ( p , tc ) , EXTRA ); ++ _res = _PyAST_FunctionDef ( n -> v . Name . id , t , ( params ) ? params : CHECK ( arguments_ty , _PyPegen_empty_arguments ( p ) ) , b , NULL , a , NEW_TYPE_COMMENT ( p , tc ) , EXTRA ); + if (_res == NULL && PyErr_Occurred()) { + p->error_indicator = 1; + p->level--; +@@ -4567,14 +4612,14 @@ function_def_raw_rule(Parser *p) + } + p->mark = _mark; + D(fprintf(stderr, "%*c%s function_def_raw[%d-%d]: %s failed!\n", p->level, ' ', +- p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "'def' NAME &&'(' params? ')' ['->' expression] &&':' func_type_comment? block")); ++ p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "'def' NAME type_params? &&'(' params? ')' ['->' expression] &&':' func_type_comment? block")); + } +- { // ASYNC 'def' NAME &&'(' params? ')' ['->' expression] &&':' func_type_comment? block ++ { // ASYNC 'def' NAME type_params? &&'(' params? ')' ['->' expression] &&':' func_type_comment? block + if (p->error_indicator) { + p->level--; + return NULL; + } +- D(fprintf(stderr, "%*c> function_def_raw[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "ASYNC 'def' NAME &&'(' params? ')' ['->' expression] &&':' func_type_comment? block")); ++ D(fprintf(stderr, "%*c> function_def_raw[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "ASYNC 'def' NAME type_params? &&'(' params? ')' ['->' expression] &&':' func_type_comment? block")); + Token * _keyword; + Token * _literal; + Token * _literal_1; +@@ -4584,6 +4629,7 @@ function_def_raw_rule(Parser *p) + asdl_stmt_seq* b; + expr_ty n; + void *params; ++ void *t; + void *tc; + if ( + (async_var = _PyPegen_expect_token(p, ASYNC)) // token='ASYNC' +@@ -4592,6 +4638,8 @@ function_def_raw_rule(Parser *p) + && + (n = _PyPegen_name_token(p)) // NAME + && ++ (t = type_params_rule(p), !p->error_indicator) // type_params? ++ && + (_literal = _PyPegen_expect_forced_token(p, 7, "(")) // forced_token='(' + && + (params = params_rule(p), !p->error_indicator) // params? +@@ -4607,7 +4655,7 @@ function_def_raw_rule(Parser *p) + (b = block_rule(p)) // block + ) + { +- D(fprintf(stderr, "%*c+ function_def_raw[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "ASYNC 'def' NAME &&'(' params? ')' ['->' expression] &&':' func_type_comment? block")); ++ D(fprintf(stderr, "%*c+ function_def_raw[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "ASYNC 'def' NAME type_params? &&'(' params? ')' ['->' expression] &&':' func_type_comment? block")); + Token *_token = _PyPegen_get_last_nonnwhitespace_token(p); + if (_token == NULL) { + p->level--; +@@ -4617,7 +4665,7 @@ function_def_raw_rule(Parser *p) + UNUSED(_end_lineno); // Only used by EXTRA macro + int _end_col_offset = _token->end_col_offset; + UNUSED(_end_col_offset); // Only used by EXTRA macro +- _res = CHECK_VERSION ( stmt_ty , 5 , "Async functions are" , _PyAST_AsyncFunctionDef ( n -> v . Name . id , ( params ) ? params : CHECK ( arguments_ty , _PyPegen_empty_arguments ( p ) ) , b , NULL , a , NEW_TYPE_COMMENT ( p , tc ) , EXTRA ) ); ++ _res = CHECK_VERSION ( stmt_ty , 5 , "Async functions are" , _PyAST_AsyncFunctionDef ( n -> v . Name . id , t , ( params ) ? params : CHECK ( arguments_ty , _PyPegen_empty_arguments ( p ) ) , b , NULL , a , NEW_TYPE_COMMENT ( p , tc ) , EXTRA ) ); + if (_res == NULL && PyErr_Occurred()) { + p->error_indicator = 1; + p->level--; +@@ -4627,7 +4675,7 @@ function_def_raw_rule(Parser *p) + } + p->mark = _mark; + D(fprintf(stderr, "%*c%s function_def_raw[%d-%d]: %s failed!\n", p->level, ' ', +- p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "ASYNC 'def' NAME &&'(' params? ')' ['->' expression] &&':' func_type_comment? block")); ++ p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "ASYNC 'def' NAME type_params? &&'(' params? ')' ['->' expression] &&':' func_type_comment? block")); + } + _res = NULL; + done: +@@ -10530,6 +10578,438 @@ keyword_pattern_rule(Parser *p) + return _res; + } + ++// type_alias: "type" NAME type_params? '=' expression ++static stmt_ty ++type_alias_rule(Parser *p) ++{ ++ if (p->level++ == MAXSTACK) { ++ p->error_indicator = 1; ++ PyErr_NoMemory(); ++ } ++ if (p->error_indicator) { ++ p->level--; ++ return NULL; ++ } ++ stmt_ty _res = NULL; ++ int _mark = p->mark; ++ if (p->mark == p->fill && _PyPegen_fill_token(p) < 0) { ++ p->error_indicator = 1; ++ p->level--; ++ return NULL; ++ } ++ int _start_lineno = p->tokens[_mark]->lineno; ++ UNUSED(_start_lineno); // Only used by EXTRA macro ++ int _start_col_offset = p->tokens[_mark]->col_offset; ++ UNUSED(_start_col_offset); // Only used by EXTRA macro ++ { // "type" NAME type_params? '=' expression ++ if (p->error_indicator) { ++ p->level--; ++ return NULL; ++ } ++ D(fprintf(stderr, "%*c> type_alias[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "\"type\" NAME type_params? '=' expression")); ++ expr_ty _keyword; ++ Token * _literal; ++ expr_ty b; ++ expr_ty n; ++ void *t; ++ if ( ++ (_keyword = _PyPegen_expect_soft_keyword(p, "type")) // soft_keyword='"type"' ++ && ++ (n = _PyPegen_name_token(p)) // NAME ++ && ++ (t = type_params_rule(p), !p->error_indicator) // type_params? ++ && ++ (_literal = _PyPegen_expect_token(p, 22)) // token='=' ++ && ++ (b = expression_rule(p)) // expression ++ ) ++ { ++ D(fprintf(stderr, "%*c+ type_alias[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "\"type\" NAME type_params? '=' expression")); ++ Token *_token = _PyPegen_get_last_nonnwhitespace_token(p); ++ if (_token == NULL) { ++ p->level--; ++ return NULL; ++ } ++ int _end_lineno = _token->end_lineno; ++ UNUSED(_end_lineno); // Only used by EXTRA macro ++ int _end_col_offset = _token->end_col_offset; ++ UNUSED(_end_col_offset); // Only used by EXTRA macro ++ _res = CHECK_VERSION ( stmt_ty , 12 , "Type statement is" , _PyAST_TypeAlias ( CHECK ( expr_ty , _PyPegen_set_expr_context ( p , n , Store ) ) , t , b , EXTRA ) ); ++ if (_res == NULL && PyErr_Occurred()) { ++ p->error_indicator = 1; ++ p->level--; ++ return NULL; ++ } ++ goto done; ++ } ++ p->mark = _mark; ++ D(fprintf(stderr, "%*c%s type_alias[%d-%d]: %s failed!\n", p->level, ' ', ++ p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "\"type\" NAME type_params? '=' expression")); ++ } ++ _res = NULL; ++ done: ++ p->level--; ++ return _res; ++} ++ ++// type_params: '[' type_param_seq ']' ++static asdl_typeparam_seq* ++type_params_rule(Parser *p) ++{ ++ if (p->level++ == MAXSTACK) { ++ p->error_indicator = 1; ++ PyErr_NoMemory(); ++ } ++ if (p->error_indicator) { ++ p->level--; ++ return NULL; ++ } ++ asdl_typeparam_seq* _res = NULL; ++ int _mark = p->mark; ++ { // '[' type_param_seq ']' ++ if (p->error_indicator) { ++ p->level--; ++ return NULL; ++ } ++ D(fprintf(stderr, "%*c> type_params[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "'[' type_param_seq ']'")); ++ Token * _literal; ++ Token * _literal_1; ++ asdl_typeparam_seq* t; ++ if ( ++ (_literal = _PyPegen_expect_token(p, 9)) // token='[' ++ && ++ (t = type_param_seq_rule(p)) // type_param_seq ++ && ++ (_literal_1 = _PyPegen_expect_token(p, 10)) // token=']' ++ ) ++ { ++ D(fprintf(stderr, "%*c+ type_params[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "'[' type_param_seq ']'")); ++ _res = CHECK_VERSION ( asdl_typeparam_seq* , 12 , "Type parameter lists are" , t ); ++ if (_res == NULL && PyErr_Occurred()) { ++ p->error_indicator = 1; ++ p->level--; ++ return NULL; ++ } ++ goto done; ++ } ++ p->mark = _mark; ++ D(fprintf(stderr, "%*c%s type_params[%d-%d]: %s failed!\n", p->level, ' ', ++ p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "'[' type_param_seq ']'")); ++ } ++ _res = NULL; ++ done: ++ p->level--; ++ return _res; ++} ++ ++// type_param_seq: ','.type_param+ ','? ++static asdl_typeparam_seq* ++type_param_seq_rule(Parser *p) ++{ ++ if (p->level++ == MAXSTACK) { ++ p->error_indicator = 1; ++ PyErr_NoMemory(); ++ } ++ if (p->error_indicator) { ++ p->level--; ++ return NULL; ++ } ++ asdl_typeparam_seq* _res = NULL; ++ int _mark = p->mark; ++ { // ','.type_param+ ','? ++ if (p->error_indicator) { ++ p->level--; ++ return NULL; ++ } ++ D(fprintf(stderr, "%*c> type_param_seq[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "','.type_param+ ','?")); ++ void *_opt_var; ++ UNUSED(_opt_var); // Silence compiler warnings ++ asdl_typeparam_seq* a; ++ if ( ++ (a = (asdl_typeparam_seq*)_gather_81_rule(p)) // ','.type_param+ ++ && ++ (_opt_var = _PyPegen_expect_token(p, 12), !p->error_indicator) // ','? ++ ) ++ { ++ D(fprintf(stderr, "%*c+ type_param_seq[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "','.type_param+ ','?")); ++ _res = a; ++ if (_res == NULL && PyErr_Occurred()) { ++ p->error_indicator = 1; ++ p->level--; ++ return NULL; ++ } ++ goto done; ++ } ++ p->mark = _mark; ++ D(fprintf(stderr, "%*c%s type_param_seq[%d-%d]: %s failed!\n", p->level, ' ', ++ p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "','.type_param+ ','?")); ++ } ++ _res = NULL; ++ done: ++ p->level--; ++ return _res; ++} ++ ++// type_param: ++// | NAME type_param_bound? ++// | '*' NAME ":" expression ++// | '*' NAME ++// | '**' NAME ":" expression ++// | '**' NAME ++static typeparam_ty ++type_param_rule(Parser *p) ++{ ++ if (p->level++ == MAXSTACK) { ++ p->error_indicator = 1; ++ PyErr_NoMemory(); ++ } ++ if (p->error_indicator) { ++ p->level--; ++ return NULL; ++ } ++ typeparam_ty _res = NULL; ++ if (_PyPegen_is_memoized(p, type_param_type, &_res)) { ++ p->level--; ++ return _res; ++ } ++ int _mark = p->mark; ++ if (p->mark == p->fill && _PyPegen_fill_token(p) < 0) { ++ p->error_indicator = 1; ++ p->level--; ++ return NULL; ++ } ++ int _start_lineno = p->tokens[_mark]->lineno; ++ UNUSED(_start_lineno); // Only used by EXTRA macro ++ int _start_col_offset = p->tokens[_mark]->col_offset; ++ UNUSED(_start_col_offset); // Only used by EXTRA macro ++ { // NAME type_param_bound? ++ if (p->error_indicator) { ++ p->level--; ++ return NULL; ++ } ++ D(fprintf(stderr, "%*c> type_param[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "NAME type_param_bound?")); ++ expr_ty a; ++ void *b; ++ if ( ++ (a = _PyPegen_name_token(p)) // NAME ++ && ++ (b = type_param_bound_rule(p), !p->error_indicator) // type_param_bound? ++ ) ++ { ++ D(fprintf(stderr, "%*c+ type_param[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "NAME type_param_bound?")); ++ Token *_token = _PyPegen_get_last_nonnwhitespace_token(p); ++ if (_token == NULL) { ++ p->level--; ++ return NULL; ++ } ++ int _end_lineno = _token->end_lineno; ++ UNUSED(_end_lineno); // Only used by EXTRA macro ++ int _end_col_offset = _token->end_col_offset; ++ UNUSED(_end_col_offset); // Only used by EXTRA macro ++ _res = _PyAST_TypeVar ( a -> v . Name . id , b , EXTRA ); ++ if (_res == NULL && PyErr_Occurred()) { ++ p->error_indicator = 1; ++ p->level--; ++ return NULL; ++ } ++ goto done; ++ } ++ p->mark = _mark; ++ D(fprintf(stderr, "%*c%s type_param[%d-%d]: %s failed!\n", p->level, ' ', ++ p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "NAME type_param_bound?")); ++ } ++ { // '*' NAME ":" expression ++ if (p->error_indicator) { ++ p->level--; ++ return NULL; ++ } ++ D(fprintf(stderr, "%*c> type_param[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "'*' NAME \":\" expression")); ++ Token * _literal; ++ expr_ty a; ++ Token * colon; ++ expr_ty e; ++ if ( ++ (_literal = _PyPegen_expect_token(p, 16)) // token='*' ++ && ++ (a = _PyPegen_name_token(p)) // NAME ++ && ++ (colon = _PyPegen_expect_token(p, 11)) // token=':' ++ && ++ (e = expression_rule(p)) // expression ++ ) ++ { ++ D(fprintf(stderr, "%*c+ type_param[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "'*' NAME \":\" expression")); ++ _res = RAISE_SYNTAX_ERROR_STARTING_FROM ( colon , e -> kind == Tuple_kind ? "cannot use constraints with TypeVarTuple" : "cannot use bound with TypeVarTuple" ); ++ if (_res == NULL && PyErr_Occurred()) { ++ p->error_indicator = 1; ++ p->level--; ++ return NULL; ++ } ++ goto done; ++ } ++ p->mark = _mark; ++ D(fprintf(stderr, "%*c%s type_param[%d-%d]: %s failed!\n", p->level, ' ', ++ p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "'*' NAME \":\" expression")); ++ } ++ { // '*' NAME ++ if (p->error_indicator) { ++ p->level--; ++ return NULL; ++ } ++ D(fprintf(stderr, "%*c> type_param[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "'*' NAME")); ++ Token * _literal; ++ expr_ty a; ++ if ( ++ (_literal = _PyPegen_expect_token(p, 16)) // token='*' ++ && ++ (a = _PyPegen_name_token(p)) // NAME ++ ) ++ { ++ D(fprintf(stderr, "%*c+ type_param[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "'*' NAME")); ++ Token *_token = _PyPegen_get_last_nonnwhitespace_token(p); ++ if (_token == NULL) { ++ p->level--; ++ return NULL; ++ } ++ int _end_lineno = _token->end_lineno; ++ UNUSED(_end_lineno); // Only used by EXTRA macro ++ int _end_col_offset = _token->end_col_offset; ++ UNUSED(_end_col_offset); // Only used by EXTRA macro ++ _res = _PyAST_TypeVarTuple ( a -> v . Name . id , EXTRA ); ++ if (_res == NULL && PyErr_Occurred()) { ++ p->error_indicator = 1; ++ p->level--; ++ return NULL; ++ } ++ goto done; ++ } ++ p->mark = _mark; ++ D(fprintf(stderr, "%*c%s type_param[%d-%d]: %s failed!\n", p->level, ' ', ++ p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "'*' NAME")); ++ } ++ { // '**' NAME ":" expression ++ if (p->error_indicator) { ++ p->level--; ++ return NULL; ++ } ++ D(fprintf(stderr, "%*c> type_param[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "'**' NAME \":\" expression")); ++ Token * _literal; ++ expr_ty a; ++ Token * colon; ++ expr_ty e; ++ if ( ++ (_literal = _PyPegen_expect_token(p, 35)) // token='**' ++ && ++ (a = _PyPegen_name_token(p)) // NAME ++ && ++ (colon = _PyPegen_expect_token(p, 11)) // token=':' ++ && ++ (e = expression_rule(p)) // expression ++ ) ++ { ++ D(fprintf(stderr, "%*c+ type_param[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "'**' NAME \":\" expression")); ++ _res = RAISE_SYNTAX_ERROR_STARTING_FROM ( colon , e -> kind == Tuple_kind ? "cannot use constraints with ParamSpec" : "cannot use bound with ParamSpec" ); ++ if (_res == NULL && PyErr_Occurred()) { ++ p->error_indicator = 1; ++ p->level--; ++ return NULL; ++ } ++ goto done; ++ } ++ p->mark = _mark; ++ D(fprintf(stderr, "%*c%s type_param[%d-%d]: %s failed!\n", p->level, ' ', ++ p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "'**' NAME \":\" expression")); ++ } ++ { // '**' NAME ++ if (p->error_indicator) { ++ p->level--; ++ return NULL; ++ } ++ D(fprintf(stderr, "%*c> type_param[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "'**' NAME")); ++ Token * _literal; ++ expr_ty a; ++ if ( ++ (_literal = _PyPegen_expect_token(p, 35)) // token='**' ++ && ++ (a = _PyPegen_name_token(p)) // NAME ++ ) ++ { ++ D(fprintf(stderr, "%*c+ type_param[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "'**' NAME")); ++ Token *_token = _PyPegen_get_last_nonnwhitespace_token(p); ++ if (_token == NULL) { ++ p->level--; ++ return NULL; ++ } ++ int _end_lineno = _token->end_lineno; ++ UNUSED(_end_lineno); // Only used by EXTRA macro ++ int _end_col_offset = _token->end_col_offset; ++ UNUSED(_end_col_offset); // Only used by EXTRA macro ++ _res = _PyAST_ParamSpec ( a -> v . Name . id , EXTRA ); ++ if (_res == NULL && PyErr_Occurred()) { ++ p->error_indicator = 1; ++ p->level--; ++ return NULL; ++ } ++ goto done; ++ } ++ p->mark = _mark; ++ D(fprintf(stderr, "%*c%s type_param[%d-%d]: %s failed!\n", p->level, ' ', ++ p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "'**' NAME")); ++ } ++ _res = NULL; ++ done: ++ _PyPegen_insert_memo(p, _mark, type_param_type, _res); ++ p->level--; ++ return _res; ++} ++ ++// type_param_bound: ":" expression ++static expr_ty ++type_param_bound_rule(Parser *p) ++{ ++ if (p->level++ == MAXSTACK) { ++ p->error_indicator = 1; ++ PyErr_NoMemory(); ++ } ++ if (p->error_indicator) { ++ p->level--; ++ return NULL; ++ } ++ expr_ty _res = NULL; ++ int _mark = p->mark; ++ { // ":" expression ++ if (p->error_indicator) { ++ p->level--; ++ return NULL; ++ } ++ D(fprintf(stderr, "%*c> type_param_bound[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "\":\" expression")); ++ Token * _literal; ++ expr_ty e; ++ if ( ++ (_literal = _PyPegen_expect_token(p, 11)) // token=':' ++ && ++ (e = expression_rule(p)) // expression ++ ) ++ { ++ D(fprintf(stderr, "%*c+ type_param_bound[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "\":\" expression")); ++ _res = e; ++ if (_res == NULL && PyErr_Occurred()) { ++ p->error_indicator = 1; ++ p->level--; ++ return NULL; ++ } ++ goto done; ++ } ++ p->mark = _mark; ++ D(fprintf(stderr, "%*c%s type_param_bound[%d-%d]: %s failed!\n", p->level, ' ', ++ p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "\":\" expression")); ++ } ++ _res = NULL; ++ done: ++ p->level--; ++ return _res; ++} ++ + // expressions: expression ((',' expression))+ ','? | expression ',' | expression + static expr_ty + expressions_rule(Parser *p) +@@ -10566,7 +11046,7 @@ expressions_rule(Parser *p) + if ( + (a = expression_rule(p)) // expression + && +- (b = _loop1_81_rule(p)) // ((',' expression))+ ++ (b = _loop1_83_rule(p)) // ((',' expression))+ + && + (_opt_var = _PyPegen_expect_token(p, 12), !p->error_indicator) // ','? + ) +@@ -10957,7 +11437,7 @@ star_expressions_rule(Parser *p) + if ( + (a = star_expression_rule(p)) // star_expression + && +- (b = _loop1_82_rule(p)) // ((',' star_expression))+ ++ (b = _loop1_84_rule(p)) // ((',' star_expression))+ + && + (_opt_var = _PyPegen_expect_token(p, 12), !p->error_indicator) // ','? + ) +@@ -11158,7 +11638,7 @@ star_named_expressions_rule(Parser *p) + UNUSED(_opt_var); // Silence compiler warnings + asdl_expr_seq* a; + if ( +- (a = (asdl_expr_seq*)_gather_83_rule(p)) // ','.star_named_expression+ ++ (a = (asdl_expr_seq*)_gather_85_rule(p)) // ','.star_named_expression+ + && + (_opt_var = _PyPegen_expect_token(p, 12), !p->error_indicator) // ','? + ) +@@ -11458,7 +11938,7 @@ disjunction_rule(Parser *p) + if ( + (a = conjunction_rule(p)) // conjunction + && +- (b = _loop1_85_rule(p)) // (('or' conjunction))+ ++ (b = _loop1_87_rule(p)) // (('or' conjunction))+ + ) + { + D(fprintf(stderr, "%*c+ disjunction[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "conjunction (('or' conjunction))+")); +@@ -11547,7 +12027,7 @@ conjunction_rule(Parser *p) + if ( + (a = inversion_rule(p)) // inversion + && +- (b = _loop1_86_rule(p)) // (('and' inversion))+ ++ (b = _loop1_88_rule(p)) // (('and' inversion))+ + ) + { + D(fprintf(stderr, "%*c+ conjunction[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "inversion (('and' inversion))+")); +@@ -11721,7 +12201,7 @@ comparison_rule(Parser *p) + if ( + (a = bitwise_or_rule(p)) // bitwise_or + && +- (b = _loop1_87_rule(p)) // compare_op_bitwise_or_pair+ ++ (b = _loop1_89_rule(p)) // compare_op_bitwise_or_pair+ + ) + { + D(fprintf(stderr, "%*c+ comparison[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "bitwise_or compare_op_bitwise_or_pair+")); +@@ -12058,10 +12538,10 @@ noteq_bitwise_or_rule(Parser *p) + return NULL; + } + D(fprintf(stderr, "%*c> noteq_bitwise_or[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "('!=') bitwise_or")); +- void *_tmp_88_var; ++ void *_tmp_90_var; + expr_ty a; + if ( +- (_tmp_88_var = _tmp_88_rule(p)) // '!=' ++ (_tmp_90_var = _tmp_90_rule(p)) // '!=' + && + (a = bitwise_or_rule(p)) // bitwise_or + ) +@@ -14096,7 +14576,7 @@ slices_rule(Parser *p) + UNUSED(_opt_var); // Silence compiler warnings + asdl_expr_seq* a; + if ( +- (a = (asdl_expr_seq*)_gather_89_rule(p)) // ','.(slice | starred_expression)+ ++ (a = (asdl_expr_seq*)_gather_91_rule(p)) // ','.(slice | starred_expression)+ + && + (_opt_var = _PyPegen_expect_token(p, 12), !p->error_indicator) // ','? + ) +@@ -14169,7 +14649,7 @@ slice_rule(Parser *p) + && + (b = expression_rule(p), !p->error_indicator) // expression? + && +- (c = _tmp_91_rule(p), !p->error_indicator) // [':' expression?] ++ (c = _tmp_93_rule(p), !p->error_indicator) // [':' expression?] + ) + { + D(fprintf(stderr, "%*c+ slice[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "expression? ':' expression? [':' expression?]")); +@@ -14383,7 +14863,7 @@ atom_rule(Parser *p) + D(fprintf(stderr, "%*c> atom[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "&(STRING | FSTRING_START) strings")); + expr_ty strings_var; + if ( +- _PyPegen_lookahead(1, _tmp_92_rule, p) ++ _PyPegen_lookahead(1, _tmp_94_rule, p) + && + (strings_var = strings_rule(p)) // strings + ) +@@ -14421,15 +14901,15 @@ atom_rule(Parser *p) + return NULL; + } + D(fprintf(stderr, "%*c> atom[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "&'(' (tuple | group | genexp)")); +- void *_tmp_93_var; ++ void *_tmp_95_var; + if ( + _PyPegen_lookahead_with_int(1, _PyPegen_expect_token, p, 7) // token='(' + && +- (_tmp_93_var = _tmp_93_rule(p)) // tuple | group | genexp ++ (_tmp_95_var = _tmp_95_rule(p)) // tuple | group | genexp + ) + { + D(fprintf(stderr, "%*c+ atom[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "&'(' (tuple | group | genexp)")); +- _res = _tmp_93_var; ++ _res = _tmp_95_var; + goto done; + } + p->mark = _mark; +@@ -14442,15 +14922,15 @@ atom_rule(Parser *p) + return NULL; + } + D(fprintf(stderr, "%*c> atom[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "&'[' (list | listcomp)")); +- void *_tmp_94_var; ++ void *_tmp_96_var; + if ( + _PyPegen_lookahead_with_int(1, _PyPegen_expect_token, p, 9) // token='[' + && +- (_tmp_94_var = _tmp_94_rule(p)) // list | listcomp ++ (_tmp_96_var = _tmp_96_rule(p)) // list | listcomp + ) + { + D(fprintf(stderr, "%*c+ atom[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "&'[' (list | listcomp)")); +- _res = _tmp_94_var; ++ _res = _tmp_96_var; + goto done; + } + p->mark = _mark; +@@ -14463,15 +14943,15 @@ atom_rule(Parser *p) + return NULL; + } + D(fprintf(stderr, "%*c> atom[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "&'{' (dict | set | dictcomp | setcomp)")); +- void *_tmp_95_var; ++ void *_tmp_97_var; + if ( + _PyPegen_lookahead_with_int(1, _PyPegen_expect_token, p, 25) // token='{' + && +- (_tmp_95_var = _tmp_95_rule(p)) // dict | set | dictcomp | setcomp ++ (_tmp_97_var = _tmp_97_rule(p)) // dict | set | dictcomp | setcomp + ) + { + D(fprintf(stderr, "%*c+ atom[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "&'{' (dict | set | dictcomp | setcomp)")); +- _res = _tmp_95_var; ++ _res = _tmp_97_var; + goto done; + } + p->mark = _mark; +@@ -14543,7 +15023,7 @@ group_rule(Parser *p) + if ( + (_literal = _PyPegen_expect_token(p, 7)) // token='(' + && +- (a = _tmp_96_rule(p)) // yield_expr | named_expression ++ (a = _tmp_98_rule(p)) // yield_expr | named_expression + && + (_literal_1 = _PyPegen_expect_token(p, 8)) // token=')' + ) +@@ -14747,9 +15227,9 @@ lambda_parameters_rule(Parser *p) + if ( + (a = lambda_slash_no_default_rule(p)) // lambda_slash_no_default + && +- (b = (asdl_arg_seq*)_loop0_97_rule(p)) // lambda_param_no_default* ++ (b = (asdl_arg_seq*)_loop0_99_rule(p)) // lambda_param_no_default* + && +- (c = _loop0_98_rule(p)) // lambda_param_with_default* ++ (c = _loop0_100_rule(p)) // lambda_param_with_default* + && + (d = lambda_star_etc_rule(p), !p->error_indicator) // lambda_star_etc? + ) +@@ -14779,7 +15259,7 @@ lambda_parameters_rule(Parser *p) + if ( + (a = lambda_slash_with_default_rule(p)) // lambda_slash_with_default + && +- (b = _loop0_99_rule(p)) // lambda_param_with_default* ++ (b = _loop0_101_rule(p)) // lambda_param_with_default* + && + (c = lambda_star_etc_rule(p), !p->error_indicator) // lambda_star_etc? + ) +@@ -14807,9 +15287,9 @@ lambda_parameters_rule(Parser *p) + asdl_seq * b; + void *c; + if ( +- (a = (asdl_arg_seq*)_loop1_100_rule(p)) // lambda_param_no_default+ ++ (a = (asdl_arg_seq*)_loop1_102_rule(p)) // lambda_param_no_default+ + && +- (b = _loop0_101_rule(p)) // lambda_param_with_default* ++ (b = _loop0_103_rule(p)) // lambda_param_with_default* + && + (c = lambda_star_etc_rule(p), !p->error_indicator) // lambda_star_etc? + ) +@@ -14836,7 +15316,7 @@ lambda_parameters_rule(Parser *p) + asdl_seq * a; + void *b; + if ( +- (a = _loop1_102_rule(p)) // lambda_param_with_default+ ++ (a = _loop1_104_rule(p)) // lambda_param_with_default+ + && + (b = lambda_star_etc_rule(p), !p->error_indicator) // lambda_star_etc? + ) +@@ -14910,7 +15390,7 @@ lambda_slash_no_default_rule(Parser *p) + Token * _literal_1; + asdl_arg_seq* a; + if ( +- (a = (asdl_arg_seq*)_loop1_103_rule(p)) // lambda_param_no_default+ ++ (a = (asdl_arg_seq*)_loop1_105_rule(p)) // lambda_param_no_default+ + && + (_literal = _PyPegen_expect_token(p, 17)) // token='/' + && +@@ -14939,7 +15419,7 @@ lambda_slash_no_default_rule(Parser *p) + Token * _literal; + asdl_arg_seq* a; + if ( +- (a = (asdl_arg_seq*)_loop1_104_rule(p)) // lambda_param_no_default+ ++ (a = (asdl_arg_seq*)_loop1_106_rule(p)) // lambda_param_no_default+ + && + (_literal = _PyPegen_expect_token(p, 17)) // token='/' + && +@@ -14992,9 +15472,9 @@ lambda_slash_with_default_rule(Parser *p) + asdl_seq * a; + asdl_seq * b; + if ( +- (a = _loop0_105_rule(p)) // lambda_param_no_default* ++ (a = _loop0_107_rule(p)) // lambda_param_no_default* + && +- (b = _loop1_106_rule(p)) // lambda_param_with_default+ ++ (b = _loop1_108_rule(p)) // lambda_param_with_default+ + && + (_literal = _PyPegen_expect_token(p, 17)) // token='/' + && +@@ -15024,9 +15504,9 @@ lambda_slash_with_default_rule(Parser *p) + asdl_seq * a; + asdl_seq * b; + if ( +- (a = _loop0_107_rule(p)) // lambda_param_no_default* ++ (a = _loop0_109_rule(p)) // lambda_param_no_default* + && +- (b = _loop1_108_rule(p)) // lambda_param_with_default+ ++ (b = _loop1_110_rule(p)) // lambda_param_with_default+ + && + (_literal = _PyPegen_expect_token(p, 17)) // token='/' + && +@@ -15104,7 +15584,7 @@ lambda_star_etc_rule(Parser *p) + && + (a = lambda_param_no_default_rule(p)) // lambda_param_no_default + && +- (b = _loop0_109_rule(p)) // lambda_param_maybe_default* ++ (b = _loop0_111_rule(p)) // lambda_param_maybe_default* + && + (c = lambda_kwds_rule(p), !p->error_indicator) // lambda_kwds? + ) +@@ -15137,7 +15617,7 @@ lambda_star_etc_rule(Parser *p) + && + (_literal_1 = _PyPegen_expect_token(p, 12)) // token=',' + && +- (b = _loop1_110_rule(p)) // lambda_param_maybe_default+ ++ (b = _loop1_112_rule(p)) // lambda_param_maybe_default+ + && + (c = lambda_kwds_rule(p), !p->error_indicator) // lambda_kwds? + ) +@@ -15647,7 +16127,7 @@ fstring_replacement_field_rule(Parser *p) + if ( + (_literal = _PyPegen_expect_token(p, 25)) // token='{' + && +- (a = _tmp_111_rule(p)) // yield_expr | star_expressions ++ (a = _tmp_113_rule(p)) // yield_expr | star_expressions + && + (debug_expr = _PyPegen_expect_token(p, 22), !p->error_indicator) // "="? + && +@@ -15786,7 +16266,7 @@ fstring_full_format_spec_rule(Parser *p) + if ( + (colon = _PyPegen_expect_token(p, 11)) // token=':' + && +- (spec = _loop0_112_rule(p)) // fstring_format_spec* ++ (spec = _loop0_114_rule(p)) // fstring_format_spec* + ) + { + D(fprintf(stderr, "%*c+ fstring_full_format_spec[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "':' fstring_format_spec*")); +@@ -15959,7 +16439,7 @@ strings_rule(Parser *p) + D(fprintf(stderr, "%*c> strings[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "((fstring | string))+")); + asdl_expr_seq* a; + if ( +- (a = (asdl_expr_seq*)_loop1_113_rule(p)) // ((fstring | string))+ ++ (a = (asdl_expr_seq*)_loop1_115_rule(p)) // ((fstring | string))+ + ) + { + D(fprintf(stderr, "%*c+ strings[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "((fstring | string))+")); +@@ -16094,7 +16574,7 @@ tuple_rule(Parser *p) + if ( + (_literal = _PyPegen_expect_token(p, 7)) // token='(' + && +- (a = _tmp_114_rule(p), !p->error_indicator) // [star_named_expression ',' star_named_expressions?] ++ (a = _tmp_116_rule(p), !p->error_indicator) // [star_named_expression ',' star_named_expressions?] + && + (_literal_1 = _PyPegen_expect_token(p, 8)) // token=')' + ) +@@ -16312,7 +16792,7 @@ double_starred_kvpairs_rule(Parser *p) + UNUSED(_opt_var); // Silence compiler warnings + asdl_seq * a; + if ( +- (a = _gather_115_rule(p)) // ','.double_starred_kvpair+ ++ (a = _gather_117_rule(p)) // ','.double_starred_kvpair+ + && + (_opt_var = _PyPegen_expect_token(p, 12), !p->error_indicator) // ','? + ) +@@ -16474,7 +16954,7 @@ for_if_clauses_rule(Parser *p) + D(fprintf(stderr, "%*c> for_if_clauses[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "for_if_clause+")); + asdl_comprehension_seq* a; + if ( +- (a = (asdl_comprehension_seq*)_loop1_117_rule(p)) // for_if_clause+ ++ (a = (asdl_comprehension_seq*)_loop1_119_rule(p)) // for_if_clause+ + ) + { + D(fprintf(stderr, "%*c+ for_if_clauses[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "for_if_clause+")); +@@ -16539,7 +17019,7 @@ for_if_clause_rule(Parser *p) + && + (b = disjunction_rule(p)) // disjunction + && +- (c = (asdl_expr_seq*)_loop0_118_rule(p)) // (('if' disjunction))* ++ (c = (asdl_expr_seq*)_loop0_120_rule(p)) // (('if' disjunction))* + ) + { + D(fprintf(stderr, "%*c+ for_if_clause[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "ASYNC 'for' star_targets 'in' ~ disjunction (('if' disjunction))*")); +@@ -16582,7 +17062,7 @@ for_if_clause_rule(Parser *p) + && + (b = disjunction_rule(p)) // disjunction + && +- (c = (asdl_expr_seq*)_loop0_119_rule(p)) // (('if' disjunction))* ++ (c = (asdl_expr_seq*)_loop0_121_rule(p)) // (('if' disjunction))* + ) + { + D(fprintf(stderr, "%*c+ for_if_clause[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "'for' star_targets 'in' ~ disjunction (('if' disjunction))*")); +@@ -16845,7 +17325,7 @@ genexp_rule(Parser *p) + if ( + (_literal = _PyPegen_expect_token(p, 7)) // token='(' + && +- (a = _tmp_120_rule(p)) // assignment_expression | expression !':=' ++ (a = _tmp_122_rule(p)) // assignment_expression | expression !':=' + && + (b = for_if_clauses_rule(p)) // for_if_clauses + && +@@ -17097,9 +17577,9 @@ args_rule(Parser *p) + asdl_expr_seq* a; + void *b; + if ( +- (a = (asdl_expr_seq*)_gather_121_rule(p)) // ','.(starred_expression | (assignment_expression | expression !':=') !'=')+ ++ (a = (asdl_expr_seq*)_gather_123_rule(p)) // ','.(starred_expression | (assignment_expression | expression !':=') !'=')+ + && +- (b = _tmp_123_rule(p), !p->error_indicator) // [',' kwargs] ++ (b = _tmp_125_rule(p), !p->error_indicator) // [',' kwargs] + ) + { + D(fprintf(stderr, "%*c+ args[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "','.(starred_expression | (assignment_expression | expression !':=') !'=')+ [',' kwargs]")); +@@ -17190,11 +17670,11 @@ kwargs_rule(Parser *p) + asdl_seq * a; + asdl_seq * b; + if ( +- (a = _gather_124_rule(p)) // ','.kwarg_or_starred+ ++ (a = _gather_126_rule(p)) // ','.kwarg_or_starred+ + && + (_literal = _PyPegen_expect_token(p, 12)) // token=',' + && +- (b = _gather_126_rule(p)) // ','.kwarg_or_double_starred+ ++ (b = _gather_128_rule(p)) // ','.kwarg_or_double_starred+ + ) + { + D(fprintf(stderr, "%*c+ kwargs[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "','.kwarg_or_starred+ ',' ','.kwarg_or_double_starred+")); +@@ -17216,13 +17696,13 @@ kwargs_rule(Parser *p) + return NULL; + } + D(fprintf(stderr, "%*c> kwargs[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "','.kwarg_or_starred+")); +- asdl_seq * _gather_128_var; ++ asdl_seq * _gather_130_var; + if ( +- (_gather_128_var = _gather_128_rule(p)) // ','.kwarg_or_starred+ ++ (_gather_130_var = _gather_130_rule(p)) // ','.kwarg_or_starred+ + ) + { + D(fprintf(stderr, "%*c+ kwargs[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "','.kwarg_or_starred+")); +- _res = _gather_128_var; ++ _res = _gather_130_var; + goto done; + } + p->mark = _mark; +@@ -17235,13 +17715,13 @@ kwargs_rule(Parser *p) + return NULL; + } + D(fprintf(stderr, "%*c> kwargs[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "','.kwarg_or_double_starred+")); +- asdl_seq * _gather_130_var; ++ asdl_seq * _gather_132_var; + if ( +- (_gather_130_var = _gather_130_rule(p)) // ','.kwarg_or_double_starred+ ++ (_gather_132_var = _gather_132_rule(p)) // ','.kwarg_or_double_starred+ + ) + { + D(fprintf(stderr, "%*c+ kwargs[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "','.kwarg_or_double_starred+")); +- _res = _gather_130_var; ++ _res = _gather_132_var; + goto done; + } + p->mark = _mark; +@@ -17634,7 +18114,7 @@ star_targets_rule(Parser *p) + if ( + (a = star_target_rule(p)) // star_target + && +- (b = _loop0_132_rule(p)) // ((',' star_target))* ++ (b = _loop0_134_rule(p)) // ((',' star_target))* + && + (_opt_var = _PyPegen_expect_token(p, 12), !p->error_indicator) // ','? + ) +@@ -17691,7 +18171,7 @@ star_targets_list_seq_rule(Parser *p) + UNUSED(_opt_var); // Silence compiler warnings + asdl_expr_seq* a; + if ( +- (a = (asdl_expr_seq*)_gather_133_rule(p)) // ','.star_target+ ++ (a = (asdl_expr_seq*)_gather_135_rule(p)) // ','.star_target+ + && + (_opt_var = _PyPegen_expect_token(p, 12), !p->error_indicator) // ','? + ) +@@ -17742,7 +18222,7 @@ star_targets_tuple_seq_rule(Parser *p) + if ( + (a = star_target_rule(p)) // star_target + && +- (b = _loop1_135_rule(p)) // ((',' star_target))+ ++ (b = _loop1_137_rule(p)) // ((',' star_target))+ + && + (_opt_var = _PyPegen_expect_token(p, 12), !p->error_indicator) // ','? + ) +@@ -17831,7 +18311,7 @@ star_target_rule(Parser *p) + if ( + (_literal = _PyPegen_expect_token(p, 16)) // token='*' + && +- (a = _tmp_136_rule(p)) // !'*' star_target ++ (a = _tmp_138_rule(p)) // !'*' star_target + ) + { + D(fprintf(stderr, "%*c+ star_target[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "'*' (!'*' star_target)")); +@@ -18762,7 +19242,7 @@ del_targets_rule(Parser *p) + UNUSED(_opt_var); // Silence compiler warnings + asdl_expr_seq* a; + if ( +- (a = (asdl_expr_seq*)_gather_137_rule(p)) // ','.del_target+ ++ (a = (asdl_expr_seq*)_gather_139_rule(p)) // ','.del_target+ + && + (_opt_var = _PyPegen_expect_token(p, 12), !p->error_indicator) // ','? + ) +@@ -19123,7 +19603,7 @@ type_expressions_rule(Parser *p) + expr_ty b; + expr_ty c; + if ( +- (a = _gather_139_rule(p)) // ','.expression+ ++ (a = _gather_141_rule(p)) // ','.expression+ + && + (_literal = _PyPegen_expect_token(p, 12)) // token=',' + && +@@ -19162,7 +19642,7 @@ type_expressions_rule(Parser *p) + asdl_seq * a; + expr_ty b; + if ( +- (a = _gather_141_rule(p)) // ','.expression+ ++ (a = _gather_143_rule(p)) // ','.expression+ + && + (_literal = _PyPegen_expect_token(p, 12)) // token=',' + && +@@ -19195,7 +19675,7 @@ type_expressions_rule(Parser *p) + asdl_seq * a; + expr_ty b; + if ( +- (a = _gather_143_rule(p)) // ','.expression+ ++ (a = _gather_145_rule(p)) // ','.expression+ + && + (_literal = _PyPegen_expect_token(p, 12)) // token=',' + && +@@ -19315,7 +19795,7 @@ type_expressions_rule(Parser *p) + D(fprintf(stderr, "%*c> type_expressions[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "','.expression+")); + asdl_expr_seq* a; + if ( +- (a = (asdl_expr_seq*)_gather_145_rule(p)) // ','.expression+ ++ (a = (asdl_expr_seq*)_gather_147_rule(p)) // ','.expression+ + ) + { + D(fprintf(stderr, "%*c+ type_expressions[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "','.expression+")); +@@ -19367,7 +19847,7 @@ func_type_comment_rule(Parser *p) + && + (t = _PyPegen_expect_token(p, TYPE_COMMENT)) // token='TYPE_COMMENT' + && +- _PyPegen_lookahead(1, _tmp_147_rule, p) ++ _PyPegen_lookahead(1, _tmp_149_rule, p) + ) + { + D(fprintf(stderr, "%*c+ func_type_comment[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "NEWLINE TYPE_COMMENT &(NEWLINE INDENT)")); +@@ -19496,7 +19976,7 @@ invalid_arguments_rule(Parser *p) + && + (_literal = _PyPegen_expect_token(p, 12)) // token=',' + && +- (_opt_var = _tmp_148_rule(p), !p->error_indicator) // [args | expression for_if_clauses] ++ (_opt_var = _tmp_150_rule(p), !p->error_indicator) // [args | expression for_if_clauses] + ) + { + D(fprintf(stderr, "%*c+ invalid_arguments[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "expression for_if_clauses ',' [args | expression for_if_clauses]")); +@@ -19556,13 +20036,13 @@ invalid_arguments_rule(Parser *p) + expr_ty a; + Token * b; + if ( +- (_opt_var = _tmp_149_rule(p), !p->error_indicator) // [(args ',')] ++ (_opt_var = _tmp_151_rule(p), !p->error_indicator) // [(args ',')] + && + (a = _PyPegen_name_token(p)) // NAME + && + (b = _PyPegen_expect_token(p, 22)) // token='=' + && +- _PyPegen_lookahead(1, _tmp_150_rule, p) ++ _PyPegen_lookahead(1, _tmp_152_rule, p) + ) + { + D(fprintf(stderr, "%*c+ invalid_arguments[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "[(args ',')] NAME '=' &(',' | ')')")); +@@ -19701,7 +20181,7 @@ invalid_kwarg_rule(Parser *p) + Token* a; + Token * b; + if ( +- (a = (Token*)_tmp_151_rule(p)) // 'True' | 'False' | 'None' ++ (a = (Token*)_tmp_153_rule(p)) // 'True' | 'False' | 'None' + && + (b = _PyPegen_expect_token(p, 22)) // token='=' + ) +@@ -19761,7 +20241,7 @@ invalid_kwarg_rule(Parser *p) + expr_ty a; + Token * b; + if ( +- _PyPegen_lookahead(0, _tmp_152_rule, p) ++ _PyPegen_lookahead(0, _tmp_154_rule, p) + && + (a = expression_rule(p)) // expression + && +@@ -20020,7 +20500,7 @@ invalid_expression_rule(Parser *p) + expr_ty a; + expr_ty b; + if ( +- _PyPegen_lookahead(0, _tmp_153_rule, p) ++ _PyPegen_lookahead(0, _tmp_155_rule, p) + && + (a = disjunction_rule(p)) // disjunction + && +@@ -20056,7 +20536,7 @@ invalid_expression_rule(Parser *p) + && + (b = disjunction_rule(p)) // disjunction + && +- _PyPegen_lookahead(0, _tmp_154_rule, p) ++ _PyPegen_lookahead(0, _tmp_156_rule, p) + ) + { + D(fprintf(stderr, "%*c+ invalid_expression[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "disjunction 'if' disjunction !('else' | ':')")); +@@ -20089,7 +20569,7 @@ invalid_expression_rule(Parser *p) + && + (b = _PyPegen_expect_token(p, 11)) // token=':' + && +- _PyPegen_lookahead(1, _tmp_155_rule, p) ++ _PyPegen_lookahead(1, _tmp_157_rule, p) + ) + { + D(fprintf(stderr, "%*c+ invalid_expression[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "'lambda' lambda_params? ':' &(FSTRING_MIDDLE | fstring_replacement_field)")); +@@ -20178,7 +20658,7 @@ invalid_named_expression_rule(Parser *p) + && + (b = bitwise_or_rule(p)) // bitwise_or + && +- _PyPegen_lookahead(0, _tmp_156_rule, p) ++ _PyPegen_lookahead(0, _tmp_158_rule, p) + ) + { + D(fprintf(stderr, "%*c+ invalid_named_expression[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "NAME '=' bitwise_or !('=' | ':=')")); +@@ -20204,7 +20684,7 @@ invalid_named_expression_rule(Parser *p) + Token * b; + expr_ty bitwise_or_var; + if ( +- _PyPegen_lookahead(0, _tmp_157_rule, p) ++ _PyPegen_lookahead(0, _tmp_159_rule, p) + && + (a = bitwise_or_rule(p)) // bitwise_or + && +@@ -20212,7 +20692,7 @@ invalid_named_expression_rule(Parser *p) + && + (bitwise_or_var = bitwise_or_rule(p)) // bitwise_or + && +- _PyPegen_lookahead(0, _tmp_158_rule, p) ++ _PyPegen_lookahead(0, _tmp_160_rule, p) + ) + { + D(fprintf(stderr, "%*c+ invalid_named_expression[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "!(list | tuple | genexp | 'True' | 'None' | 'False') bitwise_or '=' bitwise_or !('=' | ':=')")); +@@ -20293,7 +20773,7 @@ invalid_assignment_rule(Parser *p) + D(fprintf(stderr, "%*c> invalid_assignment[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "star_named_expression ',' star_named_expressions* ':' expression")); + Token * _literal; + Token * _literal_1; +- asdl_seq * _loop0_159_var; ++ asdl_seq * _loop0_161_var; + expr_ty a; + expr_ty expression_var; + if ( +@@ -20301,7 +20781,7 @@ invalid_assignment_rule(Parser *p) + && + (_literal = _PyPegen_expect_token(p, 12)) // token=',' + && +- (_loop0_159_var = _loop0_159_rule(p)) // star_named_expressions* ++ (_loop0_161_var = _loop0_161_rule(p)) // star_named_expressions* + && + (_literal_1 = _PyPegen_expect_token(p, 11)) // token=':' + && +@@ -20358,10 +20838,10 @@ invalid_assignment_rule(Parser *p) + } + D(fprintf(stderr, "%*c> invalid_assignment[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "((star_targets '='))* star_expressions '='")); + Token * _literal; +- asdl_seq * _loop0_160_var; ++ asdl_seq * _loop0_162_var; + expr_ty a; + if ( +- (_loop0_160_var = _loop0_160_rule(p)) // ((star_targets '='))* ++ (_loop0_162_var = _loop0_162_rule(p)) // ((star_targets '='))* + && + (a = star_expressions_rule(p)) // star_expressions + && +@@ -20388,10 +20868,10 @@ invalid_assignment_rule(Parser *p) + } + D(fprintf(stderr, "%*c> invalid_assignment[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "((star_targets '='))* yield_expr '='")); + Token * _literal; +- asdl_seq * _loop0_161_var; ++ asdl_seq * _loop0_163_var; + expr_ty a; + if ( +- (_loop0_161_var = _loop0_161_rule(p)) // ((star_targets '='))* ++ (_loop0_163_var = _loop0_163_rule(p)) // ((star_targets '='))* + && + (a = yield_expr_rule(p)) // yield_expr + && +@@ -20417,7 +20897,7 @@ invalid_assignment_rule(Parser *p) + return NULL; + } + D(fprintf(stderr, "%*c> invalid_assignment[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "star_expressions augassign (yield_expr | star_expressions)")); +- void *_tmp_162_var; ++ void *_tmp_164_var; + expr_ty a; + AugOperator* augassign_var; + if ( +@@ -20425,7 +20905,7 @@ invalid_assignment_rule(Parser *p) + && + (augassign_var = augassign_rule(p)) // augassign + && +- (_tmp_162_var = _tmp_162_rule(p)) // yield_expr | star_expressions ++ (_tmp_164_var = _tmp_164_rule(p)) // yield_expr | star_expressions + ) + { + D(fprintf(stderr, "%*c+ invalid_assignment[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "star_expressions augassign (yield_expr | star_expressions)")); +@@ -20651,11 +21131,11 @@ invalid_comprehension_rule(Parser *p) + return NULL; + } + D(fprintf(stderr, "%*c> invalid_comprehension[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "('[' | '(' | '{') starred_expression for_if_clauses")); +- void *_tmp_163_var; ++ void *_tmp_165_var; + expr_ty a; + asdl_comprehension_seq* for_if_clauses_var; + if ( +- (_tmp_163_var = _tmp_163_rule(p)) // '[' | '(' | '{' ++ (_tmp_165_var = _tmp_165_rule(p)) // '[' | '(' | '{' + && + (a = starred_expression_rule(p)) // starred_expression + && +@@ -20682,12 +21162,12 @@ invalid_comprehension_rule(Parser *p) + } + D(fprintf(stderr, "%*c> invalid_comprehension[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "('[' | '{') star_named_expression ',' star_named_expressions for_if_clauses")); + Token * _literal; +- void *_tmp_164_var; ++ void *_tmp_166_var; + expr_ty a; + asdl_expr_seq* b; + asdl_comprehension_seq* for_if_clauses_var; + if ( +- (_tmp_164_var = _tmp_164_rule(p)) // '[' | '{' ++ (_tmp_166_var = _tmp_166_rule(p)) // '[' | '{' + && + (a = star_named_expression_rule(p)) // star_named_expression + && +@@ -20717,12 +21197,12 @@ invalid_comprehension_rule(Parser *p) + return NULL; + } + D(fprintf(stderr, "%*c> invalid_comprehension[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "('[' | '{') star_named_expression ',' for_if_clauses")); +- void *_tmp_165_var; ++ void *_tmp_167_var; + expr_ty a; + Token * b; + asdl_comprehension_seq* for_if_clauses_var; + if ( +- (_tmp_165_var = _tmp_165_rule(p)) // '[' | '{' ++ (_tmp_167_var = _tmp_167_rule(p)) // '[' | '{' + && + (a = star_named_expression_rule(p)) // star_named_expression + && +@@ -20859,13 +21339,13 @@ invalid_parameters_rule(Parser *p) + return NULL; + } + D(fprintf(stderr, "%*c> invalid_parameters[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "(slash_no_default | slash_with_default) param_maybe_default* '/'")); +- asdl_seq * _loop0_167_var; +- void *_tmp_166_var; ++ asdl_seq * _loop0_169_var; ++ void *_tmp_168_var; + Token * a; + if ( +- (_tmp_166_var = _tmp_166_rule(p)) // slash_no_default | slash_with_default ++ (_tmp_168_var = _tmp_168_rule(p)) // slash_no_default | slash_with_default + && +- (_loop0_167_var = _loop0_167_rule(p)) // param_maybe_default* ++ (_loop0_169_var = _loop0_169_rule(p)) // param_maybe_default* + && + (a = _PyPegen_expect_token(p, 17)) // token='/' + ) +@@ -20889,7 +21369,7 @@ invalid_parameters_rule(Parser *p) + return NULL; + } + D(fprintf(stderr, "%*c> invalid_parameters[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "slash_no_default? param_no_default* invalid_parameters_helper param_no_default")); +- asdl_seq * _loop0_168_var; ++ asdl_seq * _loop0_170_var; + void *_opt_var; + UNUSED(_opt_var); // Silence compiler warnings + arg_ty a; +@@ -20897,7 +21377,7 @@ invalid_parameters_rule(Parser *p) + if ( + (_opt_var = slash_no_default_rule(p), !p->error_indicator) // slash_no_default? + && +- (_loop0_168_var = _loop0_168_rule(p)) // param_no_default* ++ (_loop0_170_var = _loop0_170_rule(p)) // param_no_default* + && + (invalid_parameters_helper_var = invalid_parameters_helper_rule(p)) // invalid_parameters_helper + && +@@ -20923,18 +21403,18 @@ invalid_parameters_rule(Parser *p) + return NULL; + } + D(fprintf(stderr, "%*c> invalid_parameters[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "param_no_default* '(' param_no_default+ ','? ')'")); +- asdl_seq * _loop0_169_var; +- asdl_seq * _loop1_170_var; ++ asdl_seq * _loop0_171_var; ++ asdl_seq * _loop1_172_var; + void *_opt_var; + UNUSED(_opt_var); // Silence compiler warnings + Token * a; + Token * b; + if ( +- (_loop0_169_var = _loop0_169_rule(p)) // param_no_default* ++ (_loop0_171_var = _loop0_171_rule(p)) // param_no_default* + && + (a = _PyPegen_expect_token(p, 7)) // token='(' + && +- (_loop1_170_var = _loop1_170_rule(p)) // param_no_default+ ++ (_loop1_172_var = _loop1_172_rule(p)) // param_no_default+ + && + (_opt_var = _PyPegen_expect_token(p, 12), !p->error_indicator) // ','? + && +@@ -20961,22 +21441,22 @@ invalid_parameters_rule(Parser *p) + } + D(fprintf(stderr, "%*c> invalid_parameters[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "[(slash_no_default | slash_with_default)] param_maybe_default* '*' (',' | param_no_default) param_maybe_default* '/'")); + Token * _literal; +- asdl_seq * _loop0_172_var; + asdl_seq * _loop0_174_var; ++ asdl_seq * _loop0_176_var; + void *_opt_var; + UNUSED(_opt_var); // Silence compiler warnings +- void *_tmp_173_var; ++ void *_tmp_175_var; + Token * a; + if ( +- (_opt_var = _tmp_171_rule(p), !p->error_indicator) // [(slash_no_default | slash_with_default)] ++ (_opt_var = _tmp_173_rule(p), !p->error_indicator) // [(slash_no_default | slash_with_default)] + && +- (_loop0_172_var = _loop0_172_rule(p)) // param_maybe_default* ++ (_loop0_174_var = _loop0_174_rule(p)) // param_maybe_default* + && + (_literal = _PyPegen_expect_token(p, 16)) // token='*' + && +- (_tmp_173_var = _tmp_173_rule(p)) // ',' | param_no_default ++ (_tmp_175_var = _tmp_175_rule(p)) // ',' | param_no_default + && +- (_loop0_174_var = _loop0_174_rule(p)) // param_maybe_default* ++ (_loop0_176_var = _loop0_176_rule(p)) // param_maybe_default* + && + (a = _PyPegen_expect_token(p, 17)) // token='/' + ) +@@ -21001,10 +21481,10 @@ invalid_parameters_rule(Parser *p) + } + D(fprintf(stderr, "%*c> invalid_parameters[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "param_maybe_default+ '/' '*'")); + Token * _literal; +- asdl_seq * _loop1_175_var; ++ asdl_seq * _loop1_177_var; + Token * a; + if ( +- (_loop1_175_var = _loop1_175_rule(p)) // param_maybe_default+ ++ (_loop1_177_var = _loop1_177_rule(p)) // param_maybe_default+ + && + (_literal = _PyPegen_expect_token(p, 17)) // token='/' + && +@@ -21054,7 +21534,7 @@ invalid_default_rule(Parser *p) + if ( + (a = _PyPegen_expect_token(p, 22)) // token='=' + && +- _PyPegen_lookahead(1, _tmp_176_rule, p) ++ _PyPegen_lookahead(1, _tmp_178_rule, p) + ) + { + D(fprintf(stderr, "%*c+ invalid_default[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "'=' &(')' | ',')")); +@@ -21100,12 +21580,12 @@ invalid_star_etc_rule(Parser *p) + return NULL; + } + D(fprintf(stderr, "%*c> invalid_star_etc[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "'*' (')' | ',' (')' | '**'))")); +- void *_tmp_177_var; ++ void *_tmp_179_var; + Token * a; + if ( + (a = _PyPegen_expect_token(p, 16)) // token='*' + && +- (_tmp_177_var = _tmp_177_rule(p)) // ')' | ',' (')' | '**') ++ (_tmp_179_var = _tmp_179_rule(p)) // ')' | ',' (')' | '**') + ) + { + D(fprintf(stderr, "%*c+ invalid_star_etc[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "'*' (')' | ',' (')' | '**'))")); +@@ -21188,20 +21668,20 @@ invalid_star_etc_rule(Parser *p) + } + D(fprintf(stderr, "%*c> invalid_star_etc[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "'*' (param_no_default | ',') param_maybe_default* '*' (param_no_default | ',')")); + Token * _literal; +- asdl_seq * _loop0_179_var; +- void *_tmp_178_var; ++ asdl_seq * _loop0_181_var; + void *_tmp_180_var; ++ void *_tmp_182_var; + Token * a; + if ( + (_literal = _PyPegen_expect_token(p, 16)) // token='*' + && +- (_tmp_178_var = _tmp_178_rule(p)) // param_no_default | ',' ++ (_tmp_180_var = _tmp_180_rule(p)) // param_no_default | ',' + && +- (_loop0_179_var = _loop0_179_rule(p)) // param_maybe_default* ++ (_loop0_181_var = _loop0_181_rule(p)) // param_maybe_default* + && + (a = _PyPegen_expect_token(p, 16)) // token='*' + && +- (_tmp_180_var = _tmp_180_rule(p)) // param_no_default | ',' ++ (_tmp_182_var = _tmp_182_rule(p)) // param_no_default | ',' + ) + { + D(fprintf(stderr, "%*c+ invalid_star_etc[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "'*' (param_no_default | ',') param_maybe_default* '*' (param_no_default | ',')")); +@@ -21317,7 +21797,7 @@ invalid_kwds_rule(Parser *p) + && + (_literal_1 = _PyPegen_expect_token(p, 12)) // token=',' + && +- (a = (Token*)_tmp_181_rule(p)) // '*' | '**' | '/' ++ (a = (Token*)_tmp_183_rule(p)) // '*' | '**' | '/' + ) + { + D(fprintf(stderr, "%*c+ invalid_kwds[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "'**' param ',' ('*' | '**' | '/')")); +@@ -21383,13 +21863,13 @@ invalid_parameters_helper_rule(Parser *p) + return NULL; + } + D(fprintf(stderr, "%*c> invalid_parameters_helper[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "param_with_default+")); +- asdl_seq * _loop1_182_var; ++ asdl_seq * _loop1_184_var; + if ( +- (_loop1_182_var = _loop1_182_rule(p)) // param_with_default+ ++ (_loop1_184_var = _loop1_184_rule(p)) // param_with_default+ + ) + { + D(fprintf(stderr, "%*c+ invalid_parameters_helper[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "param_with_default+")); +- _res = _loop1_182_var; ++ _res = _loop1_184_var; + goto done; + } + p->mark = _mark; +@@ -21455,13 +21935,13 @@ invalid_lambda_parameters_rule(Parser *p) + return NULL; + } + D(fprintf(stderr, "%*c> invalid_lambda_parameters[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "(lambda_slash_no_default | lambda_slash_with_default) lambda_param_maybe_default* '/'")); +- asdl_seq * _loop0_184_var; +- void *_tmp_183_var; ++ asdl_seq * _loop0_186_var; ++ void *_tmp_185_var; + Token * a; + if ( +- (_tmp_183_var = _tmp_183_rule(p)) // lambda_slash_no_default | lambda_slash_with_default ++ (_tmp_185_var = _tmp_185_rule(p)) // lambda_slash_no_default | lambda_slash_with_default + && +- (_loop0_184_var = _loop0_184_rule(p)) // lambda_param_maybe_default* ++ (_loop0_186_var = _loop0_186_rule(p)) // lambda_param_maybe_default* + && + (a = _PyPegen_expect_token(p, 17)) // token='/' + ) +@@ -21485,7 +21965,7 @@ invalid_lambda_parameters_rule(Parser *p) + return NULL; + } + D(fprintf(stderr, "%*c> invalid_lambda_parameters[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "lambda_slash_no_default? lambda_param_no_default* invalid_lambda_parameters_helper lambda_param_no_default")); +- asdl_seq * _loop0_185_var; ++ asdl_seq * _loop0_187_var; + void *_opt_var; + UNUSED(_opt_var); // Silence compiler warnings + arg_ty a; +@@ -21493,7 +21973,7 @@ invalid_lambda_parameters_rule(Parser *p) + if ( + (_opt_var = lambda_slash_no_default_rule(p), !p->error_indicator) // lambda_slash_no_default? + && +- (_loop0_185_var = _loop0_185_rule(p)) // lambda_param_no_default* ++ (_loop0_187_var = _loop0_187_rule(p)) // lambda_param_no_default* + && + (invalid_lambda_parameters_helper_var = invalid_lambda_parameters_helper_rule(p)) // invalid_lambda_parameters_helper + && +@@ -21519,18 +21999,18 @@ invalid_lambda_parameters_rule(Parser *p) + return NULL; + } + D(fprintf(stderr, "%*c> invalid_lambda_parameters[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "lambda_param_no_default* '(' ','.lambda_param+ ','? ')'")); +- asdl_seq * _gather_187_var; +- asdl_seq * _loop0_186_var; ++ asdl_seq * _gather_189_var; ++ asdl_seq * _loop0_188_var; + void *_opt_var; + UNUSED(_opt_var); // Silence compiler warnings + Token * a; + Token * b; + if ( +- (_loop0_186_var = _loop0_186_rule(p)) // lambda_param_no_default* ++ (_loop0_188_var = _loop0_188_rule(p)) // lambda_param_no_default* + && + (a = _PyPegen_expect_token(p, 7)) // token='(' + && +- (_gather_187_var = _gather_187_rule(p)) // ','.lambda_param+ ++ (_gather_189_var = _gather_189_rule(p)) // ','.lambda_param+ + && + (_opt_var = _PyPegen_expect_token(p, 12), !p->error_indicator) // ','? + && +@@ -21557,22 +22037,22 @@ invalid_lambda_parameters_rule(Parser *p) + } + D(fprintf(stderr, "%*c> invalid_lambda_parameters[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "[(lambda_slash_no_default | lambda_slash_with_default)] lambda_param_maybe_default* '*' (',' | lambda_param_no_default) lambda_param_maybe_default* '/'")); + Token * _literal; +- asdl_seq * _loop0_190_var; + asdl_seq * _loop0_192_var; ++ asdl_seq * _loop0_194_var; + void *_opt_var; + UNUSED(_opt_var); // Silence compiler warnings +- void *_tmp_191_var; ++ void *_tmp_193_var; + Token * a; + if ( +- (_opt_var = _tmp_189_rule(p), !p->error_indicator) // [(lambda_slash_no_default | lambda_slash_with_default)] ++ (_opt_var = _tmp_191_rule(p), !p->error_indicator) // [(lambda_slash_no_default | lambda_slash_with_default)] + && +- (_loop0_190_var = _loop0_190_rule(p)) // lambda_param_maybe_default* ++ (_loop0_192_var = _loop0_192_rule(p)) // lambda_param_maybe_default* + && + (_literal = _PyPegen_expect_token(p, 16)) // token='*' + && +- (_tmp_191_var = _tmp_191_rule(p)) // ',' | lambda_param_no_default ++ (_tmp_193_var = _tmp_193_rule(p)) // ',' | lambda_param_no_default + && +- (_loop0_192_var = _loop0_192_rule(p)) // lambda_param_maybe_default* ++ (_loop0_194_var = _loop0_194_rule(p)) // lambda_param_maybe_default* + && + (a = _PyPegen_expect_token(p, 17)) // token='/' + ) +@@ -21597,10 +22077,10 @@ invalid_lambda_parameters_rule(Parser *p) + } + D(fprintf(stderr, "%*c> invalid_lambda_parameters[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "lambda_param_maybe_default+ '/' '*'")); + Token * _literal; +- asdl_seq * _loop1_193_var; ++ asdl_seq * _loop1_195_var; + Token * a; + if ( +- (_loop1_193_var = _loop1_193_rule(p)) // lambda_param_maybe_default+ ++ (_loop1_195_var = _loop1_195_rule(p)) // lambda_param_maybe_default+ + && + (_literal = _PyPegen_expect_token(p, 17)) // token='/' + && +@@ -21672,13 +22152,13 @@ invalid_lambda_parameters_helper_rule(Parser *p) + return NULL; + } + D(fprintf(stderr, "%*c> invalid_lambda_parameters_helper[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "lambda_param_with_default+")); +- asdl_seq * _loop1_194_var; ++ asdl_seq * _loop1_196_var; + if ( +- (_loop1_194_var = _loop1_194_rule(p)) // lambda_param_with_default+ ++ (_loop1_196_var = _loop1_196_rule(p)) // lambda_param_with_default+ + ) + { + D(fprintf(stderr, "%*c+ invalid_lambda_parameters_helper[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "lambda_param_with_default+")); +- _res = _loop1_194_var; ++ _res = _loop1_196_var; + goto done; + } + p->mark = _mark; +@@ -21715,11 +22195,11 @@ invalid_lambda_star_etc_rule(Parser *p) + } + D(fprintf(stderr, "%*c> invalid_lambda_star_etc[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "'*' (':' | ',' (':' | '**'))")); + Token * _literal; +- void *_tmp_195_var; ++ void *_tmp_197_var; + if ( + (_literal = _PyPegen_expect_token(p, 16)) // token='*' + && +- (_tmp_195_var = _tmp_195_rule(p)) // ':' | ',' (':' | '**') ++ (_tmp_197_var = _tmp_197_rule(p)) // ':' | ',' (':' | '**') + ) + { + D(fprintf(stderr, "%*c+ invalid_lambda_star_etc[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "'*' (':' | ',' (':' | '**'))")); +@@ -21772,20 +22252,20 @@ invalid_lambda_star_etc_rule(Parser *p) + } + D(fprintf(stderr, "%*c> invalid_lambda_star_etc[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "'*' (lambda_param_no_default | ',') lambda_param_maybe_default* '*' (lambda_param_no_default | ',')")); + Token * _literal; +- asdl_seq * _loop0_197_var; +- void *_tmp_196_var; ++ asdl_seq * _loop0_199_var; + void *_tmp_198_var; ++ void *_tmp_200_var; + Token * a; + if ( + (_literal = _PyPegen_expect_token(p, 16)) // token='*' + && +- (_tmp_196_var = _tmp_196_rule(p)) // lambda_param_no_default | ',' ++ (_tmp_198_var = _tmp_198_rule(p)) // lambda_param_no_default | ',' + && +- (_loop0_197_var = _loop0_197_rule(p)) // lambda_param_maybe_default* ++ (_loop0_199_var = _loop0_199_rule(p)) // lambda_param_maybe_default* + && + (a = _PyPegen_expect_token(p, 16)) // token='*' + && +- (_tmp_198_var = _tmp_198_rule(p)) // lambda_param_no_default | ',' ++ (_tmp_200_var = _tmp_200_rule(p)) // lambda_param_no_default | ',' + ) + { + D(fprintf(stderr, "%*c+ invalid_lambda_star_etc[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "'*' (lambda_param_no_default | ',') lambda_param_maybe_default* '*' (lambda_param_no_default | ',')")); +@@ -21904,7 +22384,7 @@ invalid_lambda_kwds_rule(Parser *p) + && + (_literal_1 = _PyPegen_expect_token(p, 12)) // token=',' + && +- (a = (Token*)_tmp_199_rule(p)) // '*' | '**' | '/' ++ (a = (Token*)_tmp_201_rule(p)) // '*' | '**' | '/' + ) + { + D(fprintf(stderr, "%*c+ invalid_lambda_kwds[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "'**' lambda_param ',' ('*' | '**' | '/')")); +@@ -22012,7 +22492,7 @@ invalid_with_item_rule(Parser *p) + && + (a = expression_rule(p)) // expression + && +- _PyPegen_lookahead(1, _tmp_200_rule, p) ++ _PyPegen_lookahead(1, _tmp_202_rule, p) + ) + { + D(fprintf(stderr, "%*c+ invalid_with_item[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "expression 'as' expression &(',' | ')' | ':')")); +@@ -22293,7 +22773,7 @@ invalid_with_stmt_rule(Parser *p) + return NULL; + } + D(fprintf(stderr, "%*c> invalid_with_stmt[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "ASYNC? 'with' ','.(expression ['as' star_target])+ NEWLINE")); +- asdl_seq * _gather_201_var; ++ asdl_seq * _gather_203_var; + Token * _keyword; + void *_opt_var; + UNUSED(_opt_var); // Silence compiler warnings +@@ -22303,7 +22783,7 @@ invalid_with_stmt_rule(Parser *p) + && + (_keyword = _PyPegen_expect_token(p, 615)) // token='with' + && +- (_gather_201_var = _gather_201_rule(p)) // ','.(expression ['as' star_target])+ ++ (_gather_203_var = _gather_203_rule(p)) // ','.(expression ['as' star_target])+ + && + (newline_var = _PyPegen_expect_token(p, NEWLINE)) // token='NEWLINE' + ) +@@ -22327,7 +22807,7 @@ invalid_with_stmt_rule(Parser *p) + return NULL; + } + D(fprintf(stderr, "%*c> invalid_with_stmt[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "ASYNC? 'with' '(' ','.(expressions ['as' star_target])+ ','? ')' NEWLINE")); +- asdl_seq * _gather_203_var; ++ asdl_seq * _gather_205_var; + Token * _keyword; + Token * _literal; + Token * _literal_1; +@@ -22343,7 +22823,7 @@ invalid_with_stmt_rule(Parser *p) + && + (_literal = _PyPegen_expect_token(p, 7)) // token='(' + && +- (_gather_203_var = _gather_203_rule(p)) // ','.(expressions ['as' star_target])+ ++ (_gather_205_var = _gather_205_rule(p)) // ','.(expressions ['as' star_target])+ + && + (_opt_var_1 = _PyPegen_expect_token(p, 12), !p->error_indicator) // ','? + && +@@ -22393,7 +22873,7 @@ invalid_with_stmt_indent_rule(Parser *p) + return NULL; + } + D(fprintf(stderr, "%*c> invalid_with_stmt_indent[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "ASYNC? 'with' ','.(expression ['as' star_target])+ ':' NEWLINE !INDENT")); +- asdl_seq * _gather_205_var; ++ asdl_seq * _gather_207_var; + Token * _literal; + void *_opt_var; + UNUSED(_opt_var); // Silence compiler warnings +@@ -22404,7 +22884,7 @@ invalid_with_stmt_indent_rule(Parser *p) + && + (a = _PyPegen_expect_token(p, 615)) // token='with' + && +- (_gather_205_var = _gather_205_rule(p)) // ','.(expression ['as' star_target])+ ++ (_gather_207_var = _gather_207_rule(p)) // ','.(expression ['as' star_target])+ + && + (_literal = _PyPegen_expect_token(p, 11)) // token=':' + && +@@ -22432,7 +22912,7 @@ invalid_with_stmt_indent_rule(Parser *p) + return NULL; + } + D(fprintf(stderr, "%*c> invalid_with_stmt_indent[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "ASYNC? 'with' '(' ','.(expressions ['as' star_target])+ ','? ')' ':' NEWLINE !INDENT")); +- asdl_seq * _gather_207_var; ++ asdl_seq * _gather_209_var; + Token * _literal; + Token * _literal_1; + Token * _literal_2; +@@ -22449,7 +22929,7 @@ invalid_with_stmt_indent_rule(Parser *p) + && + (_literal = _PyPegen_expect_token(p, 7)) // token='(' + && +- (_gather_207_var = _gather_207_rule(p)) // ','.(expressions ['as' star_target])+ ++ (_gather_209_var = _gather_209_rule(p)) // ','.(expressions ['as' star_target])+ + && + (_opt_var_1 = _PyPegen_expect_token(p, 12), !p->error_indicator) // ','? + && +@@ -22547,7 +23027,7 @@ invalid_try_stmt_rule(Parser *p) + && + (block_var = block_rule(p)) // block + && +- _PyPegen_lookahead(0, _tmp_209_rule, p) ++ _PyPegen_lookahead(0, _tmp_211_rule, p) + ) + { + D(fprintf(stderr, "%*c+ invalid_try_stmt[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "'try' ':' block !('except' | 'finally')")); +@@ -22572,8 +23052,8 @@ invalid_try_stmt_rule(Parser *p) + Token * _keyword; + Token * _literal; + Token * _literal_1; +- asdl_seq * _loop0_210_var; +- asdl_seq * _loop1_211_var; ++ asdl_seq * _loop0_212_var; ++ asdl_seq * _loop1_213_var; + void *_opt_var; + UNUSED(_opt_var); // Silence compiler warnings + Token * a; +@@ -22584,9 +23064,9 @@ invalid_try_stmt_rule(Parser *p) + && + (_literal = _PyPegen_expect_token(p, 11)) // token=':' + && +- (_loop0_210_var = _loop0_210_rule(p)) // block* ++ (_loop0_212_var = _loop0_212_rule(p)) // block* + && +- (_loop1_211_var = _loop1_211_rule(p)) // except_block+ ++ (_loop1_213_var = _loop1_213_rule(p)) // except_block+ + && + (a = _PyPegen_expect_token(p, 637)) // token='except' + && +@@ -22594,7 +23074,7 @@ invalid_try_stmt_rule(Parser *p) + && + (expression_var = expression_rule(p)) // expression + && +- (_opt_var = _tmp_212_rule(p), !p->error_indicator) // ['as' NAME] ++ (_opt_var = _tmp_214_rule(p), !p->error_indicator) // ['as' NAME] + && + (_literal_1 = _PyPegen_expect_token(p, 11)) // token=':' + ) +@@ -22621,8 +23101,8 @@ invalid_try_stmt_rule(Parser *p) + Token * _keyword; + Token * _literal; + Token * _literal_1; +- asdl_seq * _loop0_213_var; +- asdl_seq * _loop1_214_var; ++ asdl_seq * _loop0_215_var; ++ asdl_seq * _loop1_216_var; + void *_opt_var; + UNUSED(_opt_var); // Silence compiler warnings + Token * a; +@@ -22631,13 +23111,13 @@ invalid_try_stmt_rule(Parser *p) + && + (_literal = _PyPegen_expect_token(p, 11)) // token=':' + && +- (_loop0_213_var = _loop0_213_rule(p)) // block* ++ (_loop0_215_var = _loop0_215_rule(p)) // block* + && +- (_loop1_214_var = _loop1_214_rule(p)) // except_star_block+ ++ (_loop1_216_var = _loop1_216_rule(p)) // except_star_block+ + && + (a = _PyPegen_expect_token(p, 637)) // token='except' + && +- (_opt_var = _tmp_215_rule(p), !p->error_indicator) // [expression ['as' NAME]] ++ (_opt_var = _tmp_217_rule(p), !p->error_indicator) // [expression ['as' NAME]] + && + (_literal_1 = _PyPegen_expect_token(p, 11)) // token=':' + ) +@@ -22705,7 +23185,7 @@ invalid_except_stmt_rule(Parser *p) + && + (expressions_var = expressions_rule(p)) // expressions + && +- (_opt_var_1 = _tmp_216_rule(p), !p->error_indicator) // ['as' NAME] ++ (_opt_var_1 = _tmp_218_rule(p), !p->error_indicator) // ['as' NAME] + && + (_literal_1 = _PyPegen_expect_token(p, 11)) // token=':' + ) +@@ -22743,7 +23223,7 @@ invalid_except_stmt_rule(Parser *p) + && + (expression_var = expression_rule(p)) // expression + && +- (_opt_var_1 = _tmp_217_rule(p), !p->error_indicator) // ['as' NAME] ++ (_opt_var_1 = _tmp_219_rule(p), !p->error_indicator) // ['as' NAME] + && + (newline_var = _PyPegen_expect_token(p, NEWLINE)) // token='NEWLINE' + ) +@@ -22795,14 +23275,14 @@ invalid_except_stmt_rule(Parser *p) + } + D(fprintf(stderr, "%*c> invalid_except_stmt[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "'except' '*' (NEWLINE | ':')")); + Token * _literal; +- void *_tmp_218_var; ++ void *_tmp_220_var; + Token * a; + if ( + (a = _PyPegen_expect_token(p, 637)) // token='except' + && + (_literal = _PyPegen_expect_token(p, 16)) // token='*' + && +- (_tmp_218_var = _tmp_218_rule(p)) // NEWLINE | ':' ++ (_tmp_220_var = _tmp_220_rule(p)) // NEWLINE | ':' + ) + { + D(fprintf(stderr, "%*c+ invalid_except_stmt[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "'except' '*' (NEWLINE | ':')")); +@@ -22909,7 +23389,7 @@ invalid_except_stmt_indent_rule(Parser *p) + && + (expression_var = expression_rule(p)) // expression + && +- (_opt_var = _tmp_219_rule(p), !p->error_indicator) // ['as' NAME] ++ (_opt_var = _tmp_221_rule(p), !p->error_indicator) // ['as' NAME] + && + (_literal = _PyPegen_expect_token(p, 11)) // token=':' + && +@@ -23004,7 +23484,7 @@ invalid_except_star_stmt_indent_rule(Parser *p) + && + (expression_var = expression_rule(p)) // expression + && +- (_opt_var = _tmp_220_rule(p), !p->error_indicator) // ['as' NAME] ++ (_opt_var = _tmp_222_rule(p), !p->error_indicator) // ['as' NAME] + && + (_literal_1 = _PyPegen_expect_token(p, 11)) // token=':' + && +@@ -23373,7 +23853,7 @@ invalid_class_argument_pattern_rule(Parser *p) + asdl_pattern_seq* a; + asdl_seq* keyword_patterns_var; + if ( +- (_opt_var = _tmp_221_rule(p), !p->error_indicator) // [positional_patterns ','] ++ (_opt_var = _tmp_223_rule(p), !p->error_indicator) // [positional_patterns ','] + && + (keyword_patterns_var = keyword_patterns_rule(p)) // keyword_patterns + && +@@ -23867,7 +24347,7 @@ invalid_def_raw_rule(Parser *p) + && + (_literal_1 = _PyPegen_expect_token(p, 8)) // token=')' + && +- (_opt_var_2 = _tmp_222_rule(p), !p->error_indicator) // ['->' expression] ++ (_opt_var_2 = _tmp_224_rule(p), !p->error_indicator) // ['->' expression] + && + (_literal_2 = _PyPegen_expect_token(p, 11)) // token=':' + && +@@ -23927,7 +24407,7 @@ invalid_class_def_raw_rule(Parser *p) + && + (name_var = _PyPegen_name_token(p)) // NAME + && +- (_opt_var = _tmp_223_rule(p), !p->error_indicator) // ['(' arguments? ')'] ++ (_opt_var = _tmp_225_rule(p), !p->error_indicator) // ['(' arguments? ')'] + && + (newline_var = _PyPegen_expect_token(p, NEWLINE)) // token='NEWLINE' + ) +@@ -23962,7 +24442,7 @@ invalid_class_def_raw_rule(Parser *p) + && + (name_var = _PyPegen_name_token(p)) // NAME + && +- (_opt_var = _tmp_224_rule(p), !p->error_indicator) // ['(' arguments? ')'] ++ (_opt_var = _tmp_226_rule(p), !p->error_indicator) // ['(' arguments? ')'] + && + (_literal = _PyPegen_expect_token(p, 11)) // token=':' + && +@@ -24013,11 +24493,11 @@ invalid_double_starred_kvpairs_rule(Parser *p) + return NULL; + } + D(fprintf(stderr, "%*c> invalid_double_starred_kvpairs[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "','.double_starred_kvpair+ ',' invalid_kvpair")); +- asdl_seq * _gather_225_var; ++ asdl_seq * _gather_227_var; + Token * _literal; + void *invalid_kvpair_var; + if ( +- (_gather_225_var = _gather_225_rule(p)) // ','.double_starred_kvpair+ ++ (_gather_227_var = _gather_227_rule(p)) // ','.double_starred_kvpair+ + && + (_literal = _PyPegen_expect_token(p, 12)) // token=',' + && +@@ -24025,7 +24505,7 @@ invalid_double_starred_kvpairs_rule(Parser *p) + ) + { + D(fprintf(stderr, "%*c+ invalid_double_starred_kvpairs[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "','.double_starred_kvpair+ ',' invalid_kvpair")); +- _res = _PyPegen_dummy_name(p, _gather_225_var, _literal, invalid_kvpair_var); ++ _res = _PyPegen_dummy_name(p, _gather_227_var, _literal, invalid_kvpair_var); + goto done; + } + p->mark = _mark; +@@ -24078,7 +24558,7 @@ invalid_double_starred_kvpairs_rule(Parser *p) + && + (a = _PyPegen_expect_token(p, 11)) // token=':' + && +- _PyPegen_lookahead(1, _tmp_227_rule, p) ++ _PyPegen_lookahead(1, _tmp_229_rule, p) + ) + { + D(fprintf(stderr, "%*c+ invalid_double_starred_kvpairs[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "expression ':' &('}' | ',')")); +@@ -24189,7 +24669,7 @@ invalid_kvpair_rule(Parser *p) + && + (a = _PyPegen_expect_token(p, 11)) // token=':' + && +- _PyPegen_lookahead(1, _tmp_228_rule, p) ++ _PyPegen_lookahead(1, _tmp_230_rule, p) + ) + { + D(fprintf(stderr, "%*c+ invalid_kvpair[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "expression ':' &('}' | ',')")); +@@ -24407,7 +24887,7 @@ invalid_replacement_field_rule(Parser *p) + if ( + (_literal = _PyPegen_expect_token(p, 25)) // token='{' + && +- _PyPegen_lookahead(0, _tmp_229_rule, p) ++ _PyPegen_lookahead(0, _tmp_231_rule, p) + ) + { + D(fprintf(stderr, "%*c+ invalid_replacement_field[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "'{' !(yield_expr | star_expressions)")); +@@ -24430,13 +24910,13 @@ invalid_replacement_field_rule(Parser *p) + } + D(fprintf(stderr, "%*c> invalid_replacement_field[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "'{' (yield_expr | star_expressions) !('=' | '!' | ':' | '}')")); + Token * _literal; +- void *_tmp_230_var; ++ void *_tmp_232_var; + if ( + (_literal = _PyPegen_expect_token(p, 25)) // token='{' + && +- (_tmp_230_var = _tmp_230_rule(p)) // yield_expr | star_expressions ++ (_tmp_232_var = _tmp_232_rule(p)) // yield_expr | star_expressions + && +- _PyPegen_lookahead(0, _tmp_231_rule, p) ++ _PyPegen_lookahead(0, _tmp_233_rule, p) + ) + { + D(fprintf(stderr, "%*c+ invalid_replacement_field[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "'{' (yield_expr | star_expressions) !('=' | '!' | ':' | '}')")); +@@ -24460,15 +24940,15 @@ invalid_replacement_field_rule(Parser *p) + D(fprintf(stderr, "%*c> invalid_replacement_field[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "'{' (yield_expr | star_expressions) '=' !('!' | ':' | '}')")); + Token * _literal; + Token * _literal_1; +- void *_tmp_232_var; ++ void *_tmp_234_var; + if ( + (_literal = _PyPegen_expect_token(p, 25)) // token='{' + && +- (_tmp_232_var = _tmp_232_rule(p)) // yield_expr | star_expressions ++ (_tmp_234_var = _tmp_234_rule(p)) // yield_expr | star_expressions + && + (_literal_1 = _PyPegen_expect_token(p, 22)) // token='=' + && +- _PyPegen_lookahead(0, _tmp_233_rule, p) ++ _PyPegen_lookahead(0, _tmp_235_rule, p) + ) + { + D(fprintf(stderr, "%*c+ invalid_replacement_field[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "'{' (yield_expr | star_expressions) '=' !('!' | ':' | '}')")); +@@ -24493,12 +24973,12 @@ invalid_replacement_field_rule(Parser *p) + Token * _literal; + void *_opt_var; + UNUSED(_opt_var); // Silence compiler warnings +- void *_tmp_234_var; ++ void *_tmp_236_var; + void *invalid_conversion_character_var; + if ( + (_literal = _PyPegen_expect_token(p, 25)) // token='{' + && +- (_tmp_234_var = _tmp_234_rule(p)) // yield_expr | star_expressions ++ (_tmp_236_var = _tmp_236_rule(p)) // yield_expr | star_expressions + && + (_opt_var = _PyPegen_expect_token(p, 22), !p->error_indicator) // '='? + && +@@ -24506,7 +24986,7 @@ invalid_replacement_field_rule(Parser *p) + ) + { + D(fprintf(stderr, "%*c+ invalid_replacement_field[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "'{' (yield_expr | star_expressions) '='? invalid_conversion_character")); +- _res = _PyPegen_dummy_name(p, _literal, _tmp_234_var, _opt_var, invalid_conversion_character_var); ++ _res = _PyPegen_dummy_name(p, _literal, _tmp_236_var, _opt_var, invalid_conversion_character_var); + goto done; + } + p->mark = _mark; +@@ -24524,17 +25004,17 @@ invalid_replacement_field_rule(Parser *p) + UNUSED(_opt_var); // Silence compiler warnings + void *_opt_var_1; + UNUSED(_opt_var_1); // Silence compiler warnings +- void *_tmp_235_var; ++ void *_tmp_237_var; + if ( + (_literal = _PyPegen_expect_token(p, 25)) // token='{' + && +- (_tmp_235_var = _tmp_235_rule(p)) // yield_expr | star_expressions ++ (_tmp_237_var = _tmp_237_rule(p)) // yield_expr | star_expressions + && + (_opt_var = _PyPegen_expect_token(p, 22), !p->error_indicator) // '='? + && +- (_opt_var_1 = _tmp_236_rule(p), !p->error_indicator) // ['!' NAME] ++ (_opt_var_1 = _tmp_238_rule(p), !p->error_indicator) // ['!' NAME] + && +- _PyPegen_lookahead(0, _tmp_237_rule, p) ++ _PyPegen_lookahead(0, _tmp_239_rule, p) + ) + { + D(fprintf(stderr, "%*c+ invalid_replacement_field[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "'{' (yield_expr | star_expressions) '='? ['!' NAME] !(':' | '}')")); +@@ -24558,24 +25038,24 @@ invalid_replacement_field_rule(Parser *p) + D(fprintf(stderr, "%*c> invalid_replacement_field[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "'{' (yield_expr | star_expressions) '='? ['!' NAME] ':' fstring_format_spec* !'}'")); + Token * _literal; + Token * _literal_1; +- asdl_seq * _loop0_240_var; ++ asdl_seq * _loop0_242_var; + void *_opt_var; + UNUSED(_opt_var); // Silence compiler warnings + void *_opt_var_1; + UNUSED(_opt_var_1); // Silence compiler warnings +- void *_tmp_238_var; ++ void *_tmp_240_var; + if ( + (_literal = _PyPegen_expect_token(p, 25)) // token='{' + && +- (_tmp_238_var = _tmp_238_rule(p)) // yield_expr | star_expressions ++ (_tmp_240_var = _tmp_240_rule(p)) // yield_expr | star_expressions + && + (_opt_var = _PyPegen_expect_token(p, 22), !p->error_indicator) // '='? + && +- (_opt_var_1 = _tmp_239_rule(p), !p->error_indicator) // ['!' NAME] ++ (_opt_var_1 = _tmp_241_rule(p), !p->error_indicator) // ['!' NAME] + && + (_literal_1 = _PyPegen_expect_token(p, 11)) // token=':' + && +- (_loop0_240_var = _loop0_240_rule(p)) // fstring_format_spec* ++ (_loop0_242_var = _loop0_242_rule(p)) // fstring_format_spec* + && + _PyPegen_lookahead_with_int(0, _PyPegen_expect_token, p, 26) // token='}' + ) +@@ -24604,15 +25084,15 @@ invalid_replacement_field_rule(Parser *p) + UNUSED(_opt_var); // Silence compiler warnings + void *_opt_var_1; + UNUSED(_opt_var_1); // Silence compiler warnings +- void *_tmp_241_var; ++ void *_tmp_243_var; + if ( + (_literal = _PyPegen_expect_token(p, 25)) // token='{' + && +- (_tmp_241_var = _tmp_241_rule(p)) // yield_expr | star_expressions ++ (_tmp_243_var = _tmp_243_rule(p)) // yield_expr | star_expressions + && + (_opt_var = _PyPegen_expect_token(p, 22), !p->error_indicator) // '='? + && +- (_opt_var_1 = _tmp_242_rule(p), !p->error_indicator) // ['!' NAME] ++ (_opt_var_1 = _tmp_244_rule(p), !p->error_indicator) // ['!' NAME] + && + _PyPegen_lookahead_with_int(0, _PyPegen_expect_token, p, 26) // token='}' + ) +@@ -24660,7 +25140,7 @@ invalid_conversion_character_rule(Parser *p) + if ( + (_literal = _PyPegen_expect_token(p, 54)) // token='!' + && +- _PyPegen_lookahead(1, _tmp_243_rule, p) ++ _PyPegen_lookahead(1, _tmp_245_rule, p) + ) + { + D(fprintf(stderr, "%*c+ invalid_conversion_character[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "'!' &(':' | '}')")); +@@ -25605,12 +26085,12 @@ _loop1_15_rule(Parser *p) + return NULL; + } + D(fprintf(stderr, "%*c> _loop1_15[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "(star_targets '=')")); +- void *_tmp_244_var; ++ void *_tmp_246_var; + while ( +- (_tmp_244_var = _tmp_244_rule(p)) // star_targets '=' ++ (_tmp_246_var = _tmp_246_rule(p)) // star_targets '=' + ) + { +- _res = _tmp_244_var; ++ _res = _tmp_246_var; + if (_n == _children_capacity) { + _children_capacity *= 2; + void **_new_children = PyMem_Realloc(_children, _children_capacity*sizeof(void *)); +@@ -26184,12 +26664,12 @@ _loop0_25_rule(Parser *p) + return NULL; + } + D(fprintf(stderr, "%*c> _loop0_25[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "('.' | '...')")); +- void *_tmp_245_var; ++ void *_tmp_247_var; + while ( +- (_tmp_245_var = _tmp_245_rule(p)) // '.' | '...' ++ (_tmp_247_var = _tmp_247_rule(p)) // '.' | '...' + ) + { +- _res = _tmp_245_var; ++ _res = _tmp_247_var; + if (_n == _children_capacity) { + _children_capacity *= 2; + void **_new_children = PyMem_Realloc(_children, _children_capacity*sizeof(void *)); +@@ -26252,12 +26732,12 @@ _loop1_26_rule(Parser *p) + return NULL; + } + D(fprintf(stderr, "%*c> _loop1_26[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "('.' | '...')")); +- void *_tmp_246_var; ++ void *_tmp_248_var; + while ( +- (_tmp_246_var = _tmp_246_rule(p)) // '.' | '...' ++ (_tmp_248_var = _tmp_248_rule(p)) // '.' | '...' + ) + { +- _res = _tmp_246_var; ++ _res = _tmp_248_var; + if (_n == _children_capacity) { + _children_capacity *= 2; + void **_new_children = PyMem_Realloc(_children, _children_capacity*sizeof(void *)); +@@ -26657,12 +27137,12 @@ _loop1_33_rule(Parser *p) + return NULL; + } + D(fprintf(stderr, "%*c> _loop1_33[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "('@' named_expression NEWLINE)")); +- void *_tmp_247_var; ++ void *_tmp_249_var; + while ( +- (_tmp_247_var = _tmp_247_rule(p)) // '@' named_expression NEWLINE ++ (_tmp_249_var = _tmp_249_rule(p)) // '@' named_expression NEWLINE + ) + { +- _res = _tmp_247_var; ++ _res = _tmp_249_var; + if (_n == _children_capacity) { + _children_capacity *= 2; + void **_new_children = PyMem_Realloc(_children, _children_capacity*sizeof(void *)); +@@ -29511,8 +29991,127 @@ _loop0_78_rule(Parser *p) + _mark = p->mark; + } + p->mark = _mark; +- D(fprintf(stderr, "%*c%s _loop0_78[%d-%d]: %s failed!\n", p->level, ' ', +- p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "',' pattern")); ++ D(fprintf(stderr, "%*c%s _loop0_78[%d-%d]: %s failed!\n", p->level, ' ', ++ p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "',' pattern")); ++ } ++ asdl_seq *_seq = (asdl_seq*)_Py_asdl_generic_seq_new(_n, p->arena); ++ if (!_seq) { ++ PyMem_Free(_children); ++ p->error_indicator = 1; ++ PyErr_NoMemory(); ++ p->level--; ++ return NULL; ++ } ++ for (int i = 0; i < _n; i++) asdl_seq_SET_UNTYPED(_seq, i, _children[i]); ++ PyMem_Free(_children); ++ p->level--; ++ return _seq; ++} ++ ++// _gather_77: pattern _loop0_78 ++static asdl_seq * ++_gather_77_rule(Parser *p) ++{ ++ if (p->level++ == MAXSTACK) { ++ p->error_indicator = 1; ++ PyErr_NoMemory(); ++ } ++ if (p->error_indicator) { ++ p->level--; ++ return NULL; ++ } ++ asdl_seq * _res = NULL; ++ int _mark = p->mark; ++ { // pattern _loop0_78 ++ if (p->error_indicator) { ++ p->level--; ++ return NULL; ++ } ++ D(fprintf(stderr, "%*c> _gather_77[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "pattern _loop0_78")); ++ pattern_ty elem; ++ asdl_seq * seq; ++ if ( ++ (elem = pattern_rule(p)) // pattern ++ && ++ (seq = _loop0_78_rule(p)) // _loop0_78 ++ ) ++ { ++ D(fprintf(stderr, "%*c+ _gather_77[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "pattern _loop0_78")); ++ _res = _PyPegen_seq_insert_in_front(p, elem, seq); ++ goto done; ++ } ++ p->mark = _mark; ++ D(fprintf(stderr, "%*c%s _gather_77[%d-%d]: %s failed!\n", p->level, ' ', ++ p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "pattern _loop0_78")); ++ } ++ _res = NULL; ++ done: ++ p->level--; ++ return _res; ++} ++ ++// _loop0_80: ',' keyword_pattern ++static asdl_seq * ++_loop0_80_rule(Parser *p) ++{ ++ if (p->level++ == MAXSTACK) { ++ p->error_indicator = 1; ++ PyErr_NoMemory(); ++ } ++ if (p->error_indicator) { ++ p->level--; ++ return NULL; ++ } ++ void *_res = NULL; ++ int _mark = p->mark; ++ void **_children = PyMem_Malloc(sizeof(void *)); ++ if (!_children) { ++ p->error_indicator = 1; ++ PyErr_NoMemory(); ++ p->level--; ++ return NULL; ++ } ++ Py_ssize_t _children_capacity = 1; ++ Py_ssize_t _n = 0; ++ { // ',' keyword_pattern ++ if (p->error_indicator) { ++ p->level--; ++ return NULL; ++ } ++ D(fprintf(stderr, "%*c> _loop0_80[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "',' keyword_pattern")); ++ Token * _literal; ++ KeyPatternPair* elem; ++ while ( ++ (_literal = _PyPegen_expect_token(p, 12)) // token=',' ++ && ++ (elem = keyword_pattern_rule(p)) // keyword_pattern ++ ) ++ { ++ _res = elem; ++ if (_res == NULL && PyErr_Occurred()) { ++ p->error_indicator = 1; ++ PyMem_Free(_children); ++ p->level--; ++ return NULL; ++ } ++ if (_n == _children_capacity) { ++ _children_capacity *= 2; ++ void **_new_children = PyMem_Realloc(_children, _children_capacity*sizeof(void *)); ++ if (!_new_children) { ++ PyMem_Free(_children); ++ p->error_indicator = 1; ++ PyErr_NoMemory(); ++ p->level--; ++ return NULL; ++ } ++ _children = _new_children; ++ } ++ _children[_n++] = _res; ++ _mark = p->mark; ++ } ++ p->mark = _mark; ++ D(fprintf(stderr, "%*c%s _loop0_80[%d-%d]: %s failed!\n", p->level, ' ', ++ p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "',' keyword_pattern")); + } + asdl_seq *_seq = (asdl_seq*)_Py_asdl_generic_seq_new(_n, p->arena); + if (!_seq) { +@@ -29528,9 +30127,9 @@ _loop0_78_rule(Parser *p) + return _seq; + } + +-// _gather_77: pattern _loop0_78 ++// _gather_79: keyword_pattern _loop0_80 + static asdl_seq * +-_gather_77_rule(Parser *p) ++_gather_79_rule(Parser *p) + { + if (p->level++ == MAXSTACK) { + p->error_indicator = 1; +@@ -29542,27 +30141,27 @@ _gather_77_rule(Parser *p) + } + asdl_seq * _res = NULL; + int _mark = p->mark; +- { // pattern _loop0_78 ++ { // keyword_pattern _loop0_80 + if (p->error_indicator) { + p->level--; + return NULL; + } +- D(fprintf(stderr, "%*c> _gather_77[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "pattern _loop0_78")); +- pattern_ty elem; ++ D(fprintf(stderr, "%*c> _gather_79[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "keyword_pattern _loop0_80")); ++ KeyPatternPair* elem; + asdl_seq * seq; + if ( +- (elem = pattern_rule(p)) // pattern ++ (elem = keyword_pattern_rule(p)) // keyword_pattern + && +- (seq = _loop0_78_rule(p)) // _loop0_78 ++ (seq = _loop0_80_rule(p)) // _loop0_80 + ) + { +- D(fprintf(stderr, "%*c+ _gather_77[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "pattern _loop0_78")); ++ D(fprintf(stderr, "%*c+ _gather_79[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "keyword_pattern _loop0_80")); + _res = _PyPegen_seq_insert_in_front(p, elem, seq); + goto done; + } + p->mark = _mark; +- D(fprintf(stderr, "%*c%s _gather_77[%d-%d]: %s failed!\n", p->level, ' ', +- p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "pattern _loop0_78")); ++ D(fprintf(stderr, "%*c%s _gather_79[%d-%d]: %s failed!\n", p->level, ' ', ++ p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "keyword_pattern _loop0_80")); + } + _res = NULL; + done: +@@ -29570,9 +30169,9 @@ _gather_77_rule(Parser *p) + return _res; + } + +-// _loop0_80: ',' keyword_pattern ++// _loop0_82: ',' type_param + static asdl_seq * +-_loop0_80_rule(Parser *p) ++_loop0_82_rule(Parser *p) + { + if (p->level++ == MAXSTACK) { + p->error_indicator = 1; +@@ -29593,18 +30192,18 @@ _loop0_80_rule(Parser *p) + } + Py_ssize_t _children_capacity = 1; + Py_ssize_t _n = 0; +- { // ',' keyword_pattern ++ { // ',' type_param + if (p->error_indicator) { + p->level--; + return NULL; + } +- D(fprintf(stderr, "%*c> _loop0_80[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "',' keyword_pattern")); ++ D(fprintf(stderr, "%*c> _loop0_82[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "',' type_param")); + Token * _literal; +- KeyPatternPair* elem; ++ typeparam_ty elem; + while ( + (_literal = _PyPegen_expect_token(p, 12)) // token=',' + && +- (elem = keyword_pattern_rule(p)) // keyword_pattern ++ (elem = type_param_rule(p)) // type_param + ) + { + _res = elem; +@@ -29630,8 +30229,8 @@ _loop0_80_rule(Parser *p) + _mark = p->mark; + } + p->mark = _mark; +- D(fprintf(stderr, "%*c%s _loop0_80[%d-%d]: %s failed!\n", p->level, ' ', +- p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "',' keyword_pattern")); ++ D(fprintf(stderr, "%*c%s _loop0_82[%d-%d]: %s failed!\n", p->level, ' ', ++ p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "',' type_param")); + } + asdl_seq *_seq = (asdl_seq*)_Py_asdl_generic_seq_new(_n, p->arena); + if (!_seq) { +@@ -29647,9 +30246,9 @@ _loop0_80_rule(Parser *p) + return _seq; + } + +-// _gather_79: keyword_pattern _loop0_80 ++// _gather_81: type_param _loop0_82 + static asdl_seq * +-_gather_79_rule(Parser *p) ++_gather_81_rule(Parser *p) + { + if (p->level++ == MAXSTACK) { + p->error_indicator = 1; +@@ -29661,27 +30260,27 @@ _gather_79_rule(Parser *p) + } + asdl_seq * _res = NULL; + int _mark = p->mark; +- { // keyword_pattern _loop0_80 ++ { // type_param _loop0_82 + if (p->error_indicator) { + p->level--; + return NULL; + } +- D(fprintf(stderr, "%*c> _gather_79[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "keyword_pattern _loop0_80")); +- KeyPatternPair* elem; ++ D(fprintf(stderr, "%*c> _gather_81[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "type_param _loop0_82")); ++ typeparam_ty elem; + asdl_seq * seq; + if ( +- (elem = keyword_pattern_rule(p)) // keyword_pattern ++ (elem = type_param_rule(p)) // type_param + && +- (seq = _loop0_80_rule(p)) // _loop0_80 ++ (seq = _loop0_82_rule(p)) // _loop0_82 + ) + { +- D(fprintf(stderr, "%*c+ _gather_79[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "keyword_pattern _loop0_80")); ++ D(fprintf(stderr, "%*c+ _gather_81[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "type_param _loop0_82")); + _res = _PyPegen_seq_insert_in_front(p, elem, seq); + goto done; + } + p->mark = _mark; +- D(fprintf(stderr, "%*c%s _gather_79[%d-%d]: %s failed!\n", p->level, ' ', +- p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "keyword_pattern _loop0_80")); ++ D(fprintf(stderr, "%*c%s _gather_81[%d-%d]: %s failed!\n", p->level, ' ', ++ p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "type_param _loop0_82")); + } + _res = NULL; + done: +@@ -29689,9 +30288,9 @@ _gather_79_rule(Parser *p) + return _res; + } + +-// _loop1_81: (',' expression) ++// _loop1_83: (',' expression) + static asdl_seq * +-_loop1_81_rule(Parser *p) ++_loop1_83_rule(Parser *p) + { + if (p->level++ == MAXSTACK) { + p->error_indicator = 1; +@@ -29717,13 +30316,13 @@ _loop1_81_rule(Parser *p) + p->level--; + return NULL; + } +- D(fprintf(stderr, "%*c> _loop1_81[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "(',' expression)")); +- void *_tmp_248_var; ++ D(fprintf(stderr, "%*c> _loop1_83[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "(',' expression)")); ++ void *_tmp_250_var; + while ( +- (_tmp_248_var = _tmp_248_rule(p)) // ',' expression ++ (_tmp_250_var = _tmp_250_rule(p)) // ',' expression + ) + { +- _res = _tmp_248_var; ++ _res = _tmp_250_var; + if (_n == _children_capacity) { + _children_capacity *= 2; + void **_new_children = PyMem_Realloc(_children, _children_capacity*sizeof(void *)); +@@ -29740,7 +30339,7 @@ _loop1_81_rule(Parser *p) + _mark = p->mark; + } + p->mark = _mark; +- D(fprintf(stderr, "%*c%s _loop1_81[%d-%d]: %s failed!\n", p->level, ' ', ++ D(fprintf(stderr, "%*c%s _loop1_83[%d-%d]: %s failed!\n", p->level, ' ', + p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "(',' expression)")); + } + if (_n == 0 || p->error_indicator) { +@@ -29762,9 +30361,9 @@ _loop1_81_rule(Parser *p) + return _seq; + } + +-// _loop1_82: (',' star_expression) ++// _loop1_84: (',' star_expression) + static asdl_seq * +-_loop1_82_rule(Parser *p) ++_loop1_84_rule(Parser *p) + { + if (p->level++ == MAXSTACK) { + p->error_indicator = 1; +@@ -29790,13 +30389,13 @@ _loop1_82_rule(Parser *p) + p->level--; + return NULL; + } +- D(fprintf(stderr, "%*c> _loop1_82[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "(',' star_expression)")); +- void *_tmp_249_var; ++ D(fprintf(stderr, "%*c> _loop1_84[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "(',' star_expression)")); ++ void *_tmp_251_var; + while ( +- (_tmp_249_var = _tmp_249_rule(p)) // ',' star_expression ++ (_tmp_251_var = _tmp_251_rule(p)) // ',' star_expression + ) + { +- _res = _tmp_249_var; ++ _res = _tmp_251_var; + if (_n == _children_capacity) { + _children_capacity *= 2; + void **_new_children = PyMem_Realloc(_children, _children_capacity*sizeof(void *)); +@@ -29813,7 +30412,7 @@ _loop1_82_rule(Parser *p) + _mark = p->mark; + } + p->mark = _mark; +- D(fprintf(stderr, "%*c%s _loop1_82[%d-%d]: %s failed!\n", p->level, ' ', ++ D(fprintf(stderr, "%*c%s _loop1_84[%d-%d]: %s failed!\n", p->level, ' ', + p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "(',' star_expression)")); + } + if (_n == 0 || p->error_indicator) { +@@ -29835,9 +30434,9 @@ _loop1_82_rule(Parser *p) + return _seq; + } + +-// _loop0_84: ',' star_named_expression ++// _loop0_86: ',' star_named_expression + static asdl_seq * +-_loop0_84_rule(Parser *p) ++_loop0_86_rule(Parser *p) + { + if (p->level++ == MAXSTACK) { + p->error_indicator = 1; +@@ -29863,7 +30462,7 @@ _loop0_84_rule(Parser *p) + p->level--; + return NULL; + } +- D(fprintf(stderr, "%*c> _loop0_84[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "',' star_named_expression")); ++ D(fprintf(stderr, "%*c> _loop0_86[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "',' star_named_expression")); + Token * _literal; + expr_ty elem; + while ( +@@ -29895,7 +30494,7 @@ _loop0_84_rule(Parser *p) + _mark = p->mark; + } + p->mark = _mark; +- D(fprintf(stderr, "%*c%s _loop0_84[%d-%d]: %s failed!\n", p->level, ' ', ++ D(fprintf(stderr, "%*c%s _loop0_86[%d-%d]: %s failed!\n", p->level, ' ', + p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "',' star_named_expression")); + } + asdl_seq *_seq = (asdl_seq*)_Py_asdl_generic_seq_new(_n, p->arena); +@@ -29912,9 +30511,9 @@ _loop0_84_rule(Parser *p) + return _seq; + } + +-// _gather_83: star_named_expression _loop0_84 ++// _gather_85: star_named_expression _loop0_86 + static asdl_seq * +-_gather_83_rule(Parser *p) ++_gather_85_rule(Parser *p) + { + if (p->level++ == MAXSTACK) { + p->error_indicator = 1; +@@ -29926,27 +30525,27 @@ _gather_83_rule(Parser *p) + } + asdl_seq * _res = NULL; + int _mark = p->mark; +- { // star_named_expression _loop0_84 ++ { // star_named_expression _loop0_86 + if (p->error_indicator) { + p->level--; + return NULL; + } +- D(fprintf(stderr, "%*c> _gather_83[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "star_named_expression _loop0_84")); ++ D(fprintf(stderr, "%*c> _gather_85[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "star_named_expression _loop0_86")); + expr_ty elem; + asdl_seq * seq; + if ( + (elem = star_named_expression_rule(p)) // star_named_expression + && +- (seq = _loop0_84_rule(p)) // _loop0_84 ++ (seq = _loop0_86_rule(p)) // _loop0_86 + ) + { +- D(fprintf(stderr, "%*c+ _gather_83[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "star_named_expression _loop0_84")); ++ D(fprintf(stderr, "%*c+ _gather_85[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "star_named_expression _loop0_86")); + _res = _PyPegen_seq_insert_in_front(p, elem, seq); + goto done; + } + p->mark = _mark; +- D(fprintf(stderr, "%*c%s _gather_83[%d-%d]: %s failed!\n", p->level, ' ', +- p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "star_named_expression _loop0_84")); ++ D(fprintf(stderr, "%*c%s _gather_85[%d-%d]: %s failed!\n", p->level, ' ', ++ p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "star_named_expression _loop0_86")); + } + _res = NULL; + done: +@@ -29954,9 +30553,9 @@ _gather_83_rule(Parser *p) + return _res; + } + +-// _loop1_85: ('or' conjunction) ++// _loop1_87: ('or' conjunction) + static asdl_seq * +-_loop1_85_rule(Parser *p) ++_loop1_87_rule(Parser *p) + { + if (p->level++ == MAXSTACK) { + p->error_indicator = 1; +@@ -29982,13 +30581,13 @@ _loop1_85_rule(Parser *p) + p->level--; + return NULL; + } +- D(fprintf(stderr, "%*c> _loop1_85[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "('or' conjunction)")); +- void *_tmp_250_var; ++ D(fprintf(stderr, "%*c> _loop1_87[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "('or' conjunction)")); ++ void *_tmp_252_var; + while ( +- (_tmp_250_var = _tmp_250_rule(p)) // 'or' conjunction ++ (_tmp_252_var = _tmp_252_rule(p)) // 'or' conjunction + ) + { +- _res = _tmp_250_var; ++ _res = _tmp_252_var; + if (_n == _children_capacity) { + _children_capacity *= 2; + void **_new_children = PyMem_Realloc(_children, _children_capacity*sizeof(void *)); +@@ -30005,7 +30604,7 @@ _loop1_85_rule(Parser *p) + _mark = p->mark; + } + p->mark = _mark; +- D(fprintf(stderr, "%*c%s _loop1_85[%d-%d]: %s failed!\n", p->level, ' ', ++ D(fprintf(stderr, "%*c%s _loop1_87[%d-%d]: %s failed!\n", p->level, ' ', + p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "('or' conjunction)")); + } + if (_n == 0 || p->error_indicator) { +@@ -30027,9 +30626,9 @@ _loop1_85_rule(Parser *p) + return _seq; + } + +-// _loop1_86: ('and' inversion) ++// _loop1_88: ('and' inversion) + static asdl_seq * +-_loop1_86_rule(Parser *p) ++_loop1_88_rule(Parser *p) + { + if (p->level++ == MAXSTACK) { + p->error_indicator = 1; +@@ -30055,13 +30654,13 @@ _loop1_86_rule(Parser *p) + p->level--; + return NULL; + } +- D(fprintf(stderr, "%*c> _loop1_86[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "('and' inversion)")); +- void *_tmp_251_var; ++ D(fprintf(stderr, "%*c> _loop1_88[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "('and' inversion)")); ++ void *_tmp_253_var; + while ( +- (_tmp_251_var = _tmp_251_rule(p)) // 'and' inversion ++ (_tmp_253_var = _tmp_253_rule(p)) // 'and' inversion + ) + { +- _res = _tmp_251_var; ++ _res = _tmp_253_var; + if (_n == _children_capacity) { + _children_capacity *= 2; + void **_new_children = PyMem_Realloc(_children, _children_capacity*sizeof(void *)); +@@ -30078,7 +30677,7 @@ _loop1_86_rule(Parser *p) + _mark = p->mark; + } + p->mark = _mark; +- D(fprintf(stderr, "%*c%s _loop1_86[%d-%d]: %s failed!\n", p->level, ' ', ++ D(fprintf(stderr, "%*c%s _loop1_88[%d-%d]: %s failed!\n", p->level, ' ', + p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "('and' inversion)")); + } + if (_n == 0 || p->error_indicator) { +@@ -30100,9 +30699,9 @@ _loop1_86_rule(Parser *p) + return _seq; + } + +-// _loop1_87: compare_op_bitwise_or_pair ++// _loop1_89: compare_op_bitwise_or_pair + static asdl_seq * +-_loop1_87_rule(Parser *p) ++_loop1_89_rule(Parser *p) + { + if (p->level++ == MAXSTACK) { + p->error_indicator = 1; +@@ -30128,7 +30727,7 @@ _loop1_87_rule(Parser *p) + p->level--; + return NULL; + } +- D(fprintf(stderr, "%*c> _loop1_87[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "compare_op_bitwise_or_pair")); ++ D(fprintf(stderr, "%*c> _loop1_89[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "compare_op_bitwise_or_pair")); + CmpopExprPair* compare_op_bitwise_or_pair_var; + while ( + (compare_op_bitwise_or_pair_var = compare_op_bitwise_or_pair_rule(p)) // compare_op_bitwise_or_pair +@@ -30151,7 +30750,7 @@ _loop1_87_rule(Parser *p) + _mark = p->mark; + } + p->mark = _mark; +- D(fprintf(stderr, "%*c%s _loop1_87[%d-%d]: %s failed!\n", p->level, ' ', ++ D(fprintf(stderr, "%*c%s _loop1_89[%d-%d]: %s failed!\n", p->level, ' ', + p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "compare_op_bitwise_or_pair")); + } + if (_n == 0 || p->error_indicator) { +@@ -30173,9 +30772,9 @@ _loop1_87_rule(Parser *p) + return _seq; + } + +-// _tmp_88: '!=' ++// _tmp_90: '!=' + static void * +-_tmp_88_rule(Parser *p) ++_tmp_90_rule(Parser *p) + { + if (p->level++ == MAXSTACK) { + p->error_indicator = 1; +@@ -30192,13 +30791,13 @@ _tmp_88_rule(Parser *p) + p->level--; + return NULL; + } +- D(fprintf(stderr, "%*c> _tmp_88[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "'!='")); ++ D(fprintf(stderr, "%*c> _tmp_90[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "'!='")); + Token * tok; + if ( + (tok = _PyPegen_expect_token(p, 28)) // token='!=' + ) + { +- D(fprintf(stderr, "%*c+ _tmp_88[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "'!='")); ++ D(fprintf(stderr, "%*c+ _tmp_90[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "'!='")); + _res = _PyPegen_check_barry_as_flufl ( p , tok ) ? NULL : tok; + if (_res == NULL && PyErr_Occurred()) { + p->error_indicator = 1; +@@ -30208,7 +30807,7 @@ _tmp_88_rule(Parser *p) + goto done; + } + p->mark = _mark; +- D(fprintf(stderr, "%*c%s _tmp_88[%d-%d]: %s failed!\n", p->level, ' ', ++ D(fprintf(stderr, "%*c%s _tmp_90[%d-%d]: %s failed!\n", p->level, ' ', + p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "'!='")); + } + _res = NULL; +@@ -30217,9 +30816,9 @@ _tmp_88_rule(Parser *p) + return _res; + } + +-// _loop0_90: ',' (slice | starred_expression) ++// _loop0_92: ',' (slice | starred_expression) + static asdl_seq * +-_loop0_90_rule(Parser *p) ++_loop0_92_rule(Parser *p) + { + if (p->level++ == MAXSTACK) { + p->error_indicator = 1; +@@ -30245,13 +30844,13 @@ _loop0_90_rule(Parser *p) + p->level--; + return NULL; + } +- D(fprintf(stderr, "%*c> _loop0_90[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "',' (slice | starred_expression)")); ++ D(fprintf(stderr, "%*c> _loop0_92[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "',' (slice | starred_expression)")); + Token * _literal; + void *elem; + while ( + (_literal = _PyPegen_expect_token(p, 12)) // token=',' + && +- (elem = _tmp_252_rule(p)) // slice | starred_expression ++ (elem = _tmp_254_rule(p)) // slice | starred_expression + ) + { + _res = elem; +@@ -30277,7 +30876,7 @@ _loop0_90_rule(Parser *p) + _mark = p->mark; + } + p->mark = _mark; +- D(fprintf(stderr, "%*c%s _loop0_90[%d-%d]: %s failed!\n", p->level, ' ', ++ D(fprintf(stderr, "%*c%s _loop0_92[%d-%d]: %s failed!\n", p->level, ' ', + p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "',' (slice | starred_expression)")); + } + asdl_seq *_seq = (asdl_seq*)_Py_asdl_generic_seq_new(_n, p->arena); +@@ -30294,9 +30893,9 @@ _loop0_90_rule(Parser *p) + return _seq; + } + +-// _gather_89: (slice | starred_expression) _loop0_90 ++// _gather_91: (slice | starred_expression) _loop0_92 + static asdl_seq * +-_gather_89_rule(Parser *p) ++_gather_91_rule(Parser *p) + { + if (p->level++ == MAXSTACK) { + p->error_indicator = 1; +@@ -30308,27 +30907,27 @@ _gather_89_rule(Parser *p) + } + asdl_seq * _res = NULL; + int _mark = p->mark; +- { // (slice | starred_expression) _loop0_90 ++ { // (slice | starred_expression) _loop0_92 + if (p->error_indicator) { + p->level--; + return NULL; + } +- D(fprintf(stderr, "%*c> _gather_89[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "(slice | starred_expression) _loop0_90")); ++ D(fprintf(stderr, "%*c> _gather_91[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "(slice | starred_expression) _loop0_92")); + void *elem; + asdl_seq * seq; + if ( +- (elem = _tmp_252_rule(p)) // slice | starred_expression ++ (elem = _tmp_254_rule(p)) // slice | starred_expression + && +- (seq = _loop0_90_rule(p)) // _loop0_90 ++ (seq = _loop0_92_rule(p)) // _loop0_92 + ) + { +- D(fprintf(stderr, "%*c+ _gather_89[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "(slice | starred_expression) _loop0_90")); ++ D(fprintf(stderr, "%*c+ _gather_91[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "(slice | starred_expression) _loop0_92")); + _res = _PyPegen_seq_insert_in_front(p, elem, seq); + goto done; + } + p->mark = _mark; +- D(fprintf(stderr, "%*c%s _gather_89[%d-%d]: %s failed!\n", p->level, ' ', +- p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "(slice | starred_expression) _loop0_90")); ++ D(fprintf(stderr, "%*c%s _gather_91[%d-%d]: %s failed!\n", p->level, ' ', ++ p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "(slice | starred_expression) _loop0_92")); + } + _res = NULL; + done: +@@ -30336,9 +30935,9 @@ _gather_89_rule(Parser *p) + return _res; + } + +-// _tmp_91: ':' expression? ++// _tmp_93: ':' expression? + static void * +-_tmp_91_rule(Parser *p) ++_tmp_93_rule(Parser *p) + { + if (p->level++ == MAXSTACK) { + p->error_indicator = 1; +@@ -30355,7 +30954,7 @@ _tmp_91_rule(Parser *p) + p->level--; + return NULL; + } +- D(fprintf(stderr, "%*c> _tmp_91[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "':' expression?")); ++ D(fprintf(stderr, "%*c> _tmp_93[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "':' expression?")); + Token * _literal; + void *d; + if ( +@@ -30364,7 +30963,7 @@ _tmp_91_rule(Parser *p) + (d = expression_rule(p), !p->error_indicator) // expression? + ) + { +- D(fprintf(stderr, "%*c+ _tmp_91[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "':' expression?")); ++ D(fprintf(stderr, "%*c+ _tmp_93[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "':' expression?")); + _res = d; + if (_res == NULL && PyErr_Occurred()) { + p->error_indicator = 1; +@@ -30374,7 +30973,7 @@ _tmp_91_rule(Parser *p) + goto done; + } + p->mark = _mark; +- D(fprintf(stderr, "%*c%s _tmp_91[%d-%d]: %s failed!\n", p->level, ' ', ++ D(fprintf(stderr, "%*c%s _tmp_93[%d-%d]: %s failed!\n", p->level, ' ', + p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "':' expression?")); + } + _res = NULL; +@@ -30383,9 +30982,9 @@ _tmp_91_rule(Parser *p) + return _res; + } + +-// _tmp_92: STRING | FSTRING_START ++// _tmp_94: STRING | FSTRING_START + static void * +-_tmp_92_rule(Parser *p) ++_tmp_94_rule(Parser *p) + { + if (p->level++ == MAXSTACK) { + p->error_indicator = 1; +@@ -30402,18 +31001,18 @@ _tmp_92_rule(Parser *p) + p->level--; + return NULL; + } +- D(fprintf(stderr, "%*c> _tmp_92[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "STRING")); ++ D(fprintf(stderr, "%*c> _tmp_94[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "STRING")); + expr_ty string_var; + if ( + (string_var = _PyPegen_string_token(p)) // STRING + ) + { +- D(fprintf(stderr, "%*c+ _tmp_92[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "STRING")); ++ D(fprintf(stderr, "%*c+ _tmp_94[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "STRING")); + _res = string_var; + goto done; + } + p->mark = _mark; +- D(fprintf(stderr, "%*c%s _tmp_92[%d-%d]: %s failed!\n", p->level, ' ', ++ D(fprintf(stderr, "%*c%s _tmp_94[%d-%d]: %s failed!\n", p->level, ' ', + p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "STRING")); + } + { // FSTRING_START +@@ -30421,18 +31020,18 @@ _tmp_92_rule(Parser *p) + p->level--; + return NULL; + } +- D(fprintf(stderr, "%*c> _tmp_92[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "FSTRING_START")); ++ D(fprintf(stderr, "%*c> _tmp_94[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "FSTRING_START")); + Token * fstring_start_var; + if ( + (fstring_start_var = _PyPegen_expect_token(p, FSTRING_START)) // token='FSTRING_START' + ) + { +- D(fprintf(stderr, "%*c+ _tmp_92[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "FSTRING_START")); ++ D(fprintf(stderr, "%*c+ _tmp_94[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "FSTRING_START")); + _res = fstring_start_var; + goto done; + } + p->mark = _mark; +- D(fprintf(stderr, "%*c%s _tmp_92[%d-%d]: %s failed!\n", p->level, ' ', ++ D(fprintf(stderr, "%*c%s _tmp_94[%d-%d]: %s failed!\n", p->level, ' ', + p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "FSTRING_START")); + } + _res = NULL; +@@ -30441,9 +31040,9 @@ _tmp_92_rule(Parser *p) + return _res; + } + +-// _tmp_93: tuple | group | genexp ++// _tmp_95: tuple | group | genexp + static void * +-_tmp_93_rule(Parser *p) ++_tmp_95_rule(Parser *p) + { + if (p->level++ == MAXSTACK) { + p->error_indicator = 1; +@@ -30460,18 +31059,18 @@ _tmp_93_rule(Parser *p) + p->level--; + return NULL; + } +- D(fprintf(stderr, "%*c> _tmp_93[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "tuple")); ++ D(fprintf(stderr, "%*c> _tmp_95[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "tuple")); + expr_ty tuple_var; + if ( + (tuple_var = tuple_rule(p)) // tuple + ) + { +- D(fprintf(stderr, "%*c+ _tmp_93[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "tuple")); ++ D(fprintf(stderr, "%*c+ _tmp_95[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "tuple")); + _res = tuple_var; + goto done; + } + p->mark = _mark; +- D(fprintf(stderr, "%*c%s _tmp_93[%d-%d]: %s failed!\n", p->level, ' ', ++ D(fprintf(stderr, "%*c%s _tmp_95[%d-%d]: %s failed!\n", p->level, ' ', + p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "tuple")); + } + { // group +@@ -30479,18 +31078,18 @@ _tmp_93_rule(Parser *p) + p->level--; + return NULL; + } +- D(fprintf(stderr, "%*c> _tmp_93[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "group")); ++ D(fprintf(stderr, "%*c> _tmp_95[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "group")); + expr_ty group_var; + if ( + (group_var = group_rule(p)) // group + ) + { +- D(fprintf(stderr, "%*c+ _tmp_93[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "group")); ++ D(fprintf(stderr, "%*c+ _tmp_95[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "group")); + _res = group_var; + goto done; + } + p->mark = _mark; +- D(fprintf(stderr, "%*c%s _tmp_93[%d-%d]: %s failed!\n", p->level, ' ', ++ D(fprintf(stderr, "%*c%s _tmp_95[%d-%d]: %s failed!\n", p->level, ' ', + p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "group")); + } + { // genexp +@@ -30498,18 +31097,18 @@ _tmp_93_rule(Parser *p) + p->level--; + return NULL; + } +- D(fprintf(stderr, "%*c> _tmp_93[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "genexp")); ++ D(fprintf(stderr, "%*c> _tmp_95[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "genexp")); + expr_ty genexp_var; + if ( + (genexp_var = genexp_rule(p)) // genexp + ) + { +- D(fprintf(stderr, "%*c+ _tmp_93[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "genexp")); ++ D(fprintf(stderr, "%*c+ _tmp_95[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "genexp")); + _res = genexp_var; + goto done; + } + p->mark = _mark; +- D(fprintf(stderr, "%*c%s _tmp_93[%d-%d]: %s failed!\n", p->level, ' ', ++ D(fprintf(stderr, "%*c%s _tmp_95[%d-%d]: %s failed!\n", p->level, ' ', + p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "genexp")); + } + _res = NULL; +@@ -30518,9 +31117,9 @@ _tmp_93_rule(Parser *p) + return _res; + } + +-// _tmp_94: list | listcomp ++// _tmp_96: list | listcomp + static void * +-_tmp_94_rule(Parser *p) ++_tmp_96_rule(Parser *p) + { + if (p->level++ == MAXSTACK) { + p->error_indicator = 1; +@@ -30537,18 +31136,18 @@ _tmp_94_rule(Parser *p) + p->level--; + return NULL; + } +- D(fprintf(stderr, "%*c> _tmp_94[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "list")); ++ D(fprintf(stderr, "%*c> _tmp_96[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "list")); + expr_ty list_var; + if ( + (list_var = list_rule(p)) // list + ) + { +- D(fprintf(stderr, "%*c+ _tmp_94[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "list")); ++ D(fprintf(stderr, "%*c+ _tmp_96[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "list")); + _res = list_var; + goto done; + } + p->mark = _mark; +- D(fprintf(stderr, "%*c%s _tmp_94[%d-%d]: %s failed!\n", p->level, ' ', ++ D(fprintf(stderr, "%*c%s _tmp_96[%d-%d]: %s failed!\n", p->level, ' ', + p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "list")); + } + { // listcomp +@@ -30556,18 +31155,18 @@ _tmp_94_rule(Parser *p) + p->level--; + return NULL; + } +- D(fprintf(stderr, "%*c> _tmp_94[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "listcomp")); ++ D(fprintf(stderr, "%*c> _tmp_96[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "listcomp")); + expr_ty listcomp_var; + if ( + (listcomp_var = listcomp_rule(p)) // listcomp + ) + { +- D(fprintf(stderr, "%*c+ _tmp_94[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "listcomp")); ++ D(fprintf(stderr, "%*c+ _tmp_96[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "listcomp")); + _res = listcomp_var; + goto done; + } + p->mark = _mark; +- D(fprintf(stderr, "%*c%s _tmp_94[%d-%d]: %s failed!\n", p->level, ' ', ++ D(fprintf(stderr, "%*c%s _tmp_96[%d-%d]: %s failed!\n", p->level, ' ', + p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "listcomp")); + } + _res = NULL; +@@ -30576,9 +31175,9 @@ _tmp_94_rule(Parser *p) + return _res; + } + +-// _tmp_95: dict | set | dictcomp | setcomp ++// _tmp_97: dict | set | dictcomp | setcomp + static void * +-_tmp_95_rule(Parser *p) ++_tmp_97_rule(Parser *p) + { + if (p->level++ == MAXSTACK) { + p->error_indicator = 1; +@@ -30595,18 +31194,18 @@ _tmp_95_rule(Parser *p) + p->level--; + return NULL; + } +- D(fprintf(stderr, "%*c> _tmp_95[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "dict")); ++ D(fprintf(stderr, "%*c> _tmp_97[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "dict")); + expr_ty dict_var; + if ( + (dict_var = dict_rule(p)) // dict + ) + { +- D(fprintf(stderr, "%*c+ _tmp_95[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "dict")); ++ D(fprintf(stderr, "%*c+ _tmp_97[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "dict")); + _res = dict_var; + goto done; + } + p->mark = _mark; +- D(fprintf(stderr, "%*c%s _tmp_95[%d-%d]: %s failed!\n", p->level, ' ', ++ D(fprintf(stderr, "%*c%s _tmp_97[%d-%d]: %s failed!\n", p->level, ' ', + p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "dict")); + } + { // set +@@ -30614,18 +31213,18 @@ _tmp_95_rule(Parser *p) + p->level--; + return NULL; + } +- D(fprintf(stderr, "%*c> _tmp_95[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "set")); ++ D(fprintf(stderr, "%*c> _tmp_97[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "set")); + expr_ty set_var; + if ( + (set_var = set_rule(p)) // set + ) + { +- D(fprintf(stderr, "%*c+ _tmp_95[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "set")); ++ D(fprintf(stderr, "%*c+ _tmp_97[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "set")); + _res = set_var; + goto done; + } + p->mark = _mark; +- D(fprintf(stderr, "%*c%s _tmp_95[%d-%d]: %s failed!\n", p->level, ' ', ++ D(fprintf(stderr, "%*c%s _tmp_97[%d-%d]: %s failed!\n", p->level, ' ', + p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "set")); + } + { // dictcomp +@@ -30633,18 +31232,18 @@ _tmp_95_rule(Parser *p) + p->level--; + return NULL; + } +- D(fprintf(stderr, "%*c> _tmp_95[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "dictcomp")); ++ D(fprintf(stderr, "%*c> _tmp_97[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "dictcomp")); + expr_ty dictcomp_var; + if ( + (dictcomp_var = dictcomp_rule(p)) // dictcomp + ) + { +- D(fprintf(stderr, "%*c+ _tmp_95[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "dictcomp")); ++ D(fprintf(stderr, "%*c+ _tmp_97[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "dictcomp")); + _res = dictcomp_var; + goto done; + } + p->mark = _mark; +- D(fprintf(stderr, "%*c%s _tmp_95[%d-%d]: %s failed!\n", p->level, ' ', ++ D(fprintf(stderr, "%*c%s _tmp_97[%d-%d]: %s failed!\n", p->level, ' ', + p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "dictcomp")); + } + { // setcomp +@@ -30652,18 +31251,18 @@ _tmp_95_rule(Parser *p) + p->level--; + return NULL; + } +- D(fprintf(stderr, "%*c> _tmp_95[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "setcomp")); ++ D(fprintf(stderr, "%*c> _tmp_97[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "setcomp")); + expr_ty setcomp_var; + if ( + (setcomp_var = setcomp_rule(p)) // setcomp + ) + { +- D(fprintf(stderr, "%*c+ _tmp_95[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "setcomp")); ++ D(fprintf(stderr, "%*c+ _tmp_97[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "setcomp")); + _res = setcomp_var; + goto done; + } + p->mark = _mark; +- D(fprintf(stderr, "%*c%s _tmp_95[%d-%d]: %s failed!\n", p->level, ' ', ++ D(fprintf(stderr, "%*c%s _tmp_97[%d-%d]: %s failed!\n", p->level, ' ', + p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "setcomp")); + } + _res = NULL; +@@ -30672,9 +31271,9 @@ _tmp_95_rule(Parser *p) + return _res; + } + +-// _tmp_96: yield_expr | named_expression ++// _tmp_98: yield_expr | named_expression + static void * +-_tmp_96_rule(Parser *p) ++_tmp_98_rule(Parser *p) + { + if (p->level++ == MAXSTACK) { + p->error_indicator = 1; +@@ -30691,18 +31290,18 @@ _tmp_96_rule(Parser *p) + p->level--; + return NULL; + } +- D(fprintf(stderr, "%*c> _tmp_96[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "yield_expr")); ++ D(fprintf(stderr, "%*c> _tmp_98[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "yield_expr")); + expr_ty yield_expr_var; + if ( + (yield_expr_var = yield_expr_rule(p)) // yield_expr + ) + { +- D(fprintf(stderr, "%*c+ _tmp_96[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "yield_expr")); ++ D(fprintf(stderr, "%*c+ _tmp_98[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "yield_expr")); + _res = yield_expr_var; + goto done; + } + p->mark = _mark; +- D(fprintf(stderr, "%*c%s _tmp_96[%d-%d]: %s failed!\n", p->level, ' ', ++ D(fprintf(stderr, "%*c%s _tmp_98[%d-%d]: %s failed!\n", p->level, ' ', + p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "yield_expr")); + } + { // named_expression +@@ -30710,18 +31309,18 @@ _tmp_96_rule(Parser *p) + p->level--; + return NULL; + } +- D(fprintf(stderr, "%*c> _tmp_96[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "named_expression")); ++ D(fprintf(stderr, "%*c> _tmp_98[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "named_expression")); + expr_ty named_expression_var; + if ( + (named_expression_var = named_expression_rule(p)) // named_expression + ) + { +- D(fprintf(stderr, "%*c+ _tmp_96[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "named_expression")); ++ D(fprintf(stderr, "%*c+ _tmp_98[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "named_expression")); + _res = named_expression_var; + goto done; + } + p->mark = _mark; +- D(fprintf(stderr, "%*c%s _tmp_96[%d-%d]: %s failed!\n", p->level, ' ', ++ D(fprintf(stderr, "%*c%s _tmp_98[%d-%d]: %s failed!\n", p->level, ' ', + p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "named_expression")); + } + _res = NULL; +@@ -30730,9 +31329,9 @@ _tmp_96_rule(Parser *p) + return _res; + } + +-// _loop0_97: lambda_param_no_default ++// _loop0_99: lambda_param_no_default + static asdl_seq * +-_loop0_97_rule(Parser *p) ++_loop0_99_rule(Parser *p) + { + if (p->level++ == MAXSTACK) { + p->error_indicator = 1; +@@ -30758,7 +31357,7 @@ _loop0_97_rule(Parser *p) + p->level--; + return NULL; + } +- D(fprintf(stderr, "%*c> _loop0_97[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "lambda_param_no_default")); ++ D(fprintf(stderr, "%*c> _loop0_99[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "lambda_param_no_default")); + arg_ty lambda_param_no_default_var; + while ( + (lambda_param_no_default_var = lambda_param_no_default_rule(p)) // lambda_param_no_default +@@ -30781,7 +31380,7 @@ _loop0_97_rule(Parser *p) + _mark = p->mark; + } + p->mark = _mark; +- D(fprintf(stderr, "%*c%s _loop0_97[%d-%d]: %s failed!\n", p->level, ' ', ++ D(fprintf(stderr, "%*c%s _loop0_99[%d-%d]: %s failed!\n", p->level, ' ', + p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "lambda_param_no_default")); + } + asdl_seq *_seq = (asdl_seq*)_Py_asdl_generic_seq_new(_n, p->arena); +@@ -30798,9 +31397,9 @@ _loop0_97_rule(Parser *p) + return _seq; + } + +-// _loop0_98: lambda_param_with_default ++// _loop0_100: lambda_param_with_default + static asdl_seq * +-_loop0_98_rule(Parser *p) ++_loop0_100_rule(Parser *p) + { + if (p->level++ == MAXSTACK) { + p->error_indicator = 1; +@@ -30826,7 +31425,7 @@ _loop0_98_rule(Parser *p) + p->level--; + return NULL; + } +- D(fprintf(stderr, "%*c> _loop0_98[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "lambda_param_with_default")); ++ D(fprintf(stderr, "%*c> _loop0_100[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "lambda_param_with_default")); + NameDefaultPair* lambda_param_with_default_var; + while ( + (lambda_param_with_default_var = lambda_param_with_default_rule(p)) // lambda_param_with_default +@@ -30849,7 +31448,7 @@ _loop0_98_rule(Parser *p) + _mark = p->mark; + } + p->mark = _mark; +- D(fprintf(stderr, "%*c%s _loop0_98[%d-%d]: %s failed!\n", p->level, ' ', ++ D(fprintf(stderr, "%*c%s _loop0_100[%d-%d]: %s failed!\n", p->level, ' ', + p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "lambda_param_with_default")); + } + asdl_seq *_seq = (asdl_seq*)_Py_asdl_generic_seq_new(_n, p->arena); +@@ -30866,9 +31465,9 @@ _loop0_98_rule(Parser *p) + return _seq; + } + +-// _loop0_99: lambda_param_with_default ++// _loop0_101: lambda_param_with_default + static asdl_seq * +-_loop0_99_rule(Parser *p) ++_loop0_101_rule(Parser *p) + { + if (p->level++ == MAXSTACK) { + p->error_indicator = 1; +@@ -30894,7 +31493,7 @@ _loop0_99_rule(Parser *p) + p->level--; + return NULL; + } +- D(fprintf(stderr, "%*c> _loop0_99[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "lambda_param_with_default")); ++ D(fprintf(stderr, "%*c> _loop0_101[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "lambda_param_with_default")); + NameDefaultPair* lambda_param_with_default_var; + while ( + (lambda_param_with_default_var = lambda_param_with_default_rule(p)) // lambda_param_with_default +@@ -30917,7 +31516,7 @@ _loop0_99_rule(Parser *p) + _mark = p->mark; + } + p->mark = _mark; +- D(fprintf(stderr, "%*c%s _loop0_99[%d-%d]: %s failed!\n", p->level, ' ', ++ D(fprintf(stderr, "%*c%s _loop0_101[%d-%d]: %s failed!\n", p->level, ' ', + p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "lambda_param_with_default")); + } + asdl_seq *_seq = (asdl_seq*)_Py_asdl_generic_seq_new(_n, p->arena); +@@ -30934,9 +31533,9 @@ _loop0_99_rule(Parser *p) + return _seq; + } + +-// _loop1_100: lambda_param_no_default ++// _loop1_102: lambda_param_no_default + static asdl_seq * +-_loop1_100_rule(Parser *p) ++_loop1_102_rule(Parser *p) + { + if (p->level++ == MAXSTACK) { + p->error_indicator = 1; +@@ -30962,7 +31561,7 @@ _loop1_100_rule(Parser *p) + p->level--; + return NULL; + } +- D(fprintf(stderr, "%*c> _loop1_100[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "lambda_param_no_default")); ++ D(fprintf(stderr, "%*c> _loop1_102[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "lambda_param_no_default")); + arg_ty lambda_param_no_default_var; + while ( + (lambda_param_no_default_var = lambda_param_no_default_rule(p)) // lambda_param_no_default +@@ -30985,7 +31584,7 @@ _loop1_100_rule(Parser *p) + _mark = p->mark; + } + p->mark = _mark; +- D(fprintf(stderr, "%*c%s _loop1_100[%d-%d]: %s failed!\n", p->level, ' ', ++ D(fprintf(stderr, "%*c%s _loop1_102[%d-%d]: %s failed!\n", p->level, ' ', + p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "lambda_param_no_default")); + } + if (_n == 0 || p->error_indicator) { +@@ -31007,9 +31606,9 @@ _loop1_100_rule(Parser *p) + return _seq; + } + +-// _loop0_101: lambda_param_with_default ++// _loop0_103: lambda_param_with_default + static asdl_seq * +-_loop0_101_rule(Parser *p) ++_loop0_103_rule(Parser *p) + { + if (p->level++ == MAXSTACK) { + p->error_indicator = 1; +@@ -31035,7 +31634,7 @@ _loop0_101_rule(Parser *p) + p->level--; + return NULL; + } +- D(fprintf(stderr, "%*c> _loop0_101[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "lambda_param_with_default")); ++ D(fprintf(stderr, "%*c> _loop0_103[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "lambda_param_with_default")); + NameDefaultPair* lambda_param_with_default_var; + while ( + (lambda_param_with_default_var = lambda_param_with_default_rule(p)) // lambda_param_with_default +@@ -31058,7 +31657,7 @@ _loop0_101_rule(Parser *p) + _mark = p->mark; + } + p->mark = _mark; +- D(fprintf(stderr, "%*c%s _loop0_101[%d-%d]: %s failed!\n", p->level, ' ', ++ D(fprintf(stderr, "%*c%s _loop0_103[%d-%d]: %s failed!\n", p->level, ' ', + p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "lambda_param_with_default")); + } + asdl_seq *_seq = (asdl_seq*)_Py_asdl_generic_seq_new(_n, p->arena); +@@ -31075,9 +31674,9 @@ _loop0_101_rule(Parser *p) + return _seq; + } + +-// _loop1_102: lambda_param_with_default ++// _loop1_104: lambda_param_with_default + static asdl_seq * +-_loop1_102_rule(Parser *p) ++_loop1_104_rule(Parser *p) + { + if (p->level++ == MAXSTACK) { + p->error_indicator = 1; +@@ -31103,7 +31702,7 @@ _loop1_102_rule(Parser *p) + p->level--; + return NULL; + } +- D(fprintf(stderr, "%*c> _loop1_102[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "lambda_param_with_default")); ++ D(fprintf(stderr, "%*c> _loop1_104[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "lambda_param_with_default")); + NameDefaultPair* lambda_param_with_default_var; + while ( + (lambda_param_with_default_var = lambda_param_with_default_rule(p)) // lambda_param_with_default +@@ -31126,7 +31725,7 @@ _loop1_102_rule(Parser *p) + _mark = p->mark; + } + p->mark = _mark; +- D(fprintf(stderr, "%*c%s _loop1_102[%d-%d]: %s failed!\n", p->level, ' ', ++ D(fprintf(stderr, "%*c%s _loop1_104[%d-%d]: %s failed!\n", p->level, ' ', + p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "lambda_param_with_default")); + } + if (_n == 0 || p->error_indicator) { +@@ -31148,9 +31747,9 @@ _loop1_102_rule(Parser *p) + return _seq; + } + +-// _loop1_103: lambda_param_no_default ++// _loop1_105: lambda_param_no_default + static asdl_seq * +-_loop1_103_rule(Parser *p) ++_loop1_105_rule(Parser *p) + { + if (p->level++ == MAXSTACK) { + p->error_indicator = 1; +@@ -31176,7 +31775,7 @@ _loop1_103_rule(Parser *p) + p->level--; + return NULL; + } +- D(fprintf(stderr, "%*c> _loop1_103[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "lambda_param_no_default")); ++ D(fprintf(stderr, "%*c> _loop1_105[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "lambda_param_no_default")); + arg_ty lambda_param_no_default_var; + while ( + (lambda_param_no_default_var = lambda_param_no_default_rule(p)) // lambda_param_no_default +@@ -31199,7 +31798,7 @@ _loop1_103_rule(Parser *p) + _mark = p->mark; + } + p->mark = _mark; +- D(fprintf(stderr, "%*c%s _loop1_103[%d-%d]: %s failed!\n", p->level, ' ', ++ D(fprintf(stderr, "%*c%s _loop1_105[%d-%d]: %s failed!\n", p->level, ' ', + p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "lambda_param_no_default")); + } + if (_n == 0 || p->error_indicator) { +@@ -31221,9 +31820,9 @@ _loop1_103_rule(Parser *p) + return _seq; + } + +-// _loop1_104: lambda_param_no_default ++// _loop1_106: lambda_param_no_default + static asdl_seq * +-_loop1_104_rule(Parser *p) ++_loop1_106_rule(Parser *p) + { + if (p->level++ == MAXSTACK) { + p->error_indicator = 1; +@@ -31249,7 +31848,7 @@ _loop1_104_rule(Parser *p) + p->level--; + return NULL; + } +- D(fprintf(stderr, "%*c> _loop1_104[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "lambda_param_no_default")); ++ D(fprintf(stderr, "%*c> _loop1_106[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "lambda_param_no_default")); + arg_ty lambda_param_no_default_var; + while ( + (lambda_param_no_default_var = lambda_param_no_default_rule(p)) // lambda_param_no_default +@@ -31272,7 +31871,7 @@ _loop1_104_rule(Parser *p) + _mark = p->mark; + } + p->mark = _mark; +- D(fprintf(stderr, "%*c%s _loop1_104[%d-%d]: %s failed!\n", p->level, ' ', ++ D(fprintf(stderr, "%*c%s _loop1_106[%d-%d]: %s failed!\n", p->level, ' ', + p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "lambda_param_no_default")); + } + if (_n == 0 || p->error_indicator) { +@@ -31294,9 +31893,9 @@ _loop1_104_rule(Parser *p) + return _seq; + } + +-// _loop0_105: lambda_param_no_default ++// _loop0_107: lambda_param_no_default + static asdl_seq * +-_loop0_105_rule(Parser *p) ++_loop0_107_rule(Parser *p) + { + if (p->level++ == MAXSTACK) { + p->error_indicator = 1; +@@ -31322,7 +31921,7 @@ _loop0_105_rule(Parser *p) + p->level--; + return NULL; + } +- D(fprintf(stderr, "%*c> _loop0_105[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "lambda_param_no_default")); ++ D(fprintf(stderr, "%*c> _loop0_107[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "lambda_param_no_default")); + arg_ty lambda_param_no_default_var; + while ( + (lambda_param_no_default_var = lambda_param_no_default_rule(p)) // lambda_param_no_default +@@ -31345,7 +31944,7 @@ _loop0_105_rule(Parser *p) + _mark = p->mark; + } + p->mark = _mark; +- D(fprintf(stderr, "%*c%s _loop0_105[%d-%d]: %s failed!\n", p->level, ' ', ++ D(fprintf(stderr, "%*c%s _loop0_107[%d-%d]: %s failed!\n", p->level, ' ', + p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "lambda_param_no_default")); + } + asdl_seq *_seq = (asdl_seq*)_Py_asdl_generic_seq_new(_n, p->arena); +@@ -31362,9 +31961,9 @@ _loop0_105_rule(Parser *p) + return _seq; + } + +-// _loop1_106: lambda_param_with_default ++// _loop1_108: lambda_param_with_default + static asdl_seq * +-_loop1_106_rule(Parser *p) ++_loop1_108_rule(Parser *p) + { + if (p->level++ == MAXSTACK) { + p->error_indicator = 1; +@@ -31390,7 +31989,7 @@ _loop1_106_rule(Parser *p) + p->level--; + return NULL; + } +- D(fprintf(stderr, "%*c> _loop1_106[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "lambda_param_with_default")); ++ D(fprintf(stderr, "%*c> _loop1_108[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "lambda_param_with_default")); + NameDefaultPair* lambda_param_with_default_var; + while ( + (lambda_param_with_default_var = lambda_param_with_default_rule(p)) // lambda_param_with_default +@@ -31413,7 +32012,7 @@ _loop1_106_rule(Parser *p) + _mark = p->mark; + } + p->mark = _mark; +- D(fprintf(stderr, "%*c%s _loop1_106[%d-%d]: %s failed!\n", p->level, ' ', ++ D(fprintf(stderr, "%*c%s _loop1_108[%d-%d]: %s failed!\n", p->level, ' ', + p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "lambda_param_with_default")); + } + if (_n == 0 || p->error_indicator) { +@@ -31435,9 +32034,9 @@ _loop1_106_rule(Parser *p) + return _seq; + } + +-// _loop0_107: lambda_param_no_default ++// _loop0_109: lambda_param_no_default + static asdl_seq * +-_loop0_107_rule(Parser *p) ++_loop0_109_rule(Parser *p) + { + if (p->level++ == MAXSTACK) { + p->error_indicator = 1; +@@ -31463,7 +32062,7 @@ _loop0_107_rule(Parser *p) + p->level--; + return NULL; + } +- D(fprintf(stderr, "%*c> _loop0_107[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "lambda_param_no_default")); ++ D(fprintf(stderr, "%*c> _loop0_109[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "lambda_param_no_default")); + arg_ty lambda_param_no_default_var; + while ( + (lambda_param_no_default_var = lambda_param_no_default_rule(p)) // lambda_param_no_default +@@ -31486,7 +32085,7 @@ _loop0_107_rule(Parser *p) + _mark = p->mark; + } + p->mark = _mark; +- D(fprintf(stderr, "%*c%s _loop0_107[%d-%d]: %s failed!\n", p->level, ' ', ++ D(fprintf(stderr, "%*c%s _loop0_109[%d-%d]: %s failed!\n", p->level, ' ', + p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "lambda_param_no_default")); + } + asdl_seq *_seq = (asdl_seq*)_Py_asdl_generic_seq_new(_n, p->arena); +@@ -31503,9 +32102,9 @@ _loop0_107_rule(Parser *p) + return _seq; + } + +-// _loop1_108: lambda_param_with_default ++// _loop1_110: lambda_param_with_default + static asdl_seq * +-_loop1_108_rule(Parser *p) ++_loop1_110_rule(Parser *p) + { + if (p->level++ == MAXSTACK) { + p->error_indicator = 1; +@@ -31531,7 +32130,7 @@ _loop1_108_rule(Parser *p) + p->level--; + return NULL; + } +- D(fprintf(stderr, "%*c> _loop1_108[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "lambda_param_with_default")); ++ D(fprintf(stderr, "%*c> _loop1_110[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "lambda_param_with_default")); + NameDefaultPair* lambda_param_with_default_var; + while ( + (lambda_param_with_default_var = lambda_param_with_default_rule(p)) // lambda_param_with_default +@@ -31554,7 +32153,7 @@ _loop1_108_rule(Parser *p) + _mark = p->mark; + } + p->mark = _mark; +- D(fprintf(stderr, "%*c%s _loop1_108[%d-%d]: %s failed!\n", p->level, ' ', ++ D(fprintf(stderr, "%*c%s _loop1_110[%d-%d]: %s failed!\n", p->level, ' ', + p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "lambda_param_with_default")); + } + if (_n == 0 || p->error_indicator) { +@@ -31576,9 +32175,9 @@ _loop1_108_rule(Parser *p) + return _seq; + } + +-// _loop0_109: lambda_param_maybe_default ++// _loop0_111: lambda_param_maybe_default + static asdl_seq * +-_loop0_109_rule(Parser *p) ++_loop0_111_rule(Parser *p) + { + if (p->level++ == MAXSTACK) { + p->error_indicator = 1; +@@ -31604,7 +32203,7 @@ _loop0_109_rule(Parser *p) + p->level--; + return NULL; + } +- D(fprintf(stderr, "%*c> _loop0_109[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "lambda_param_maybe_default")); ++ D(fprintf(stderr, "%*c> _loop0_111[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "lambda_param_maybe_default")); + NameDefaultPair* lambda_param_maybe_default_var; + while ( + (lambda_param_maybe_default_var = lambda_param_maybe_default_rule(p)) // lambda_param_maybe_default +@@ -31627,7 +32226,7 @@ _loop0_109_rule(Parser *p) + _mark = p->mark; + } + p->mark = _mark; +- D(fprintf(stderr, "%*c%s _loop0_109[%d-%d]: %s failed!\n", p->level, ' ', ++ D(fprintf(stderr, "%*c%s _loop0_111[%d-%d]: %s failed!\n", p->level, ' ', + p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "lambda_param_maybe_default")); + } + asdl_seq *_seq = (asdl_seq*)_Py_asdl_generic_seq_new(_n, p->arena); +@@ -31644,9 +32243,9 @@ _loop0_109_rule(Parser *p) + return _seq; + } + +-// _loop1_110: lambda_param_maybe_default ++// _loop1_112: lambda_param_maybe_default + static asdl_seq * +-_loop1_110_rule(Parser *p) ++_loop1_112_rule(Parser *p) + { + if (p->level++ == MAXSTACK) { + p->error_indicator = 1; +@@ -31672,7 +32271,7 @@ _loop1_110_rule(Parser *p) + p->level--; + return NULL; + } +- D(fprintf(stderr, "%*c> _loop1_110[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "lambda_param_maybe_default")); ++ D(fprintf(stderr, "%*c> _loop1_112[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "lambda_param_maybe_default")); + NameDefaultPair* lambda_param_maybe_default_var; + while ( + (lambda_param_maybe_default_var = lambda_param_maybe_default_rule(p)) // lambda_param_maybe_default +@@ -31695,7 +32294,7 @@ _loop1_110_rule(Parser *p) + _mark = p->mark; + } + p->mark = _mark; +- D(fprintf(stderr, "%*c%s _loop1_110[%d-%d]: %s failed!\n", p->level, ' ', ++ D(fprintf(stderr, "%*c%s _loop1_112[%d-%d]: %s failed!\n", p->level, ' ', + p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "lambda_param_maybe_default")); + } + if (_n == 0 || p->error_indicator) { +@@ -31717,9 +32316,9 @@ _loop1_110_rule(Parser *p) + return _seq; + } + +-// _tmp_111: yield_expr | star_expressions ++// _tmp_113: yield_expr | star_expressions + static void * +-_tmp_111_rule(Parser *p) ++_tmp_113_rule(Parser *p) + { + if (p->level++ == MAXSTACK) { + p->error_indicator = 1; +@@ -31736,18 +32335,18 @@ _tmp_111_rule(Parser *p) + p->level--; + return NULL; + } +- D(fprintf(stderr, "%*c> _tmp_111[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "yield_expr")); ++ D(fprintf(stderr, "%*c> _tmp_113[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "yield_expr")); + expr_ty yield_expr_var; + if ( + (yield_expr_var = yield_expr_rule(p)) // yield_expr + ) + { +- D(fprintf(stderr, "%*c+ _tmp_111[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "yield_expr")); ++ D(fprintf(stderr, "%*c+ _tmp_113[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "yield_expr")); + _res = yield_expr_var; + goto done; + } + p->mark = _mark; +- D(fprintf(stderr, "%*c%s _tmp_111[%d-%d]: %s failed!\n", p->level, ' ', ++ D(fprintf(stderr, "%*c%s _tmp_113[%d-%d]: %s failed!\n", p->level, ' ', + p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "yield_expr")); + } + { // star_expressions +@@ -31755,18 +32354,18 @@ _tmp_111_rule(Parser *p) + p->level--; + return NULL; + } +- D(fprintf(stderr, "%*c> _tmp_111[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "star_expressions")); ++ D(fprintf(stderr, "%*c> _tmp_113[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "star_expressions")); + expr_ty star_expressions_var; + if ( + (star_expressions_var = star_expressions_rule(p)) // star_expressions + ) + { +- D(fprintf(stderr, "%*c+ _tmp_111[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "star_expressions")); ++ D(fprintf(stderr, "%*c+ _tmp_113[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "star_expressions")); + _res = star_expressions_var; + goto done; + } + p->mark = _mark; +- D(fprintf(stderr, "%*c%s _tmp_111[%d-%d]: %s failed!\n", p->level, ' ', ++ D(fprintf(stderr, "%*c%s _tmp_113[%d-%d]: %s failed!\n", p->level, ' ', + p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "star_expressions")); + } + _res = NULL; +@@ -31775,9 +32374,9 @@ _tmp_111_rule(Parser *p) + return _res; + } + +-// _loop0_112: fstring_format_spec ++// _loop0_114: fstring_format_spec + static asdl_seq * +-_loop0_112_rule(Parser *p) ++_loop0_114_rule(Parser *p) + { + if (p->level++ == MAXSTACK) { + p->error_indicator = 1; +@@ -31803,7 +32402,7 @@ _loop0_112_rule(Parser *p) + p->level--; + return NULL; + } +- D(fprintf(stderr, "%*c> _loop0_112[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "fstring_format_spec")); ++ D(fprintf(stderr, "%*c> _loop0_114[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "fstring_format_spec")); + expr_ty fstring_format_spec_var; + while ( + (fstring_format_spec_var = fstring_format_spec_rule(p)) // fstring_format_spec +@@ -31826,7 +32425,7 @@ _loop0_112_rule(Parser *p) + _mark = p->mark; + } + p->mark = _mark; +- D(fprintf(stderr, "%*c%s _loop0_112[%d-%d]: %s failed!\n", p->level, ' ', ++ D(fprintf(stderr, "%*c%s _loop0_114[%d-%d]: %s failed!\n", p->level, ' ', + p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "fstring_format_spec")); + } + asdl_seq *_seq = (asdl_seq*)_Py_asdl_generic_seq_new(_n, p->arena); +@@ -31843,9 +32442,9 @@ _loop0_112_rule(Parser *p) + return _seq; + } + +-// _loop1_113: (fstring | string) ++// _loop1_115: (fstring | string) + static asdl_seq * +-_loop1_113_rule(Parser *p) ++_loop1_115_rule(Parser *p) + { + if (p->level++ == MAXSTACK) { + p->error_indicator = 1; +@@ -31871,13 +32470,13 @@ _loop1_113_rule(Parser *p) + p->level--; + return NULL; + } +- D(fprintf(stderr, "%*c> _loop1_113[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "(fstring | string)")); +- void *_tmp_253_var; ++ D(fprintf(stderr, "%*c> _loop1_115[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "(fstring | string)")); ++ void *_tmp_255_var; + while ( +- (_tmp_253_var = _tmp_253_rule(p)) // fstring | string ++ (_tmp_255_var = _tmp_255_rule(p)) // fstring | string + ) + { +- _res = _tmp_253_var; ++ _res = _tmp_255_var; + if (_n == _children_capacity) { + _children_capacity *= 2; + void **_new_children = PyMem_Realloc(_children, _children_capacity*sizeof(void *)); +@@ -31894,7 +32493,7 @@ _loop1_113_rule(Parser *p) + _mark = p->mark; + } + p->mark = _mark; +- D(fprintf(stderr, "%*c%s _loop1_113[%d-%d]: %s failed!\n", p->level, ' ', ++ D(fprintf(stderr, "%*c%s _loop1_115[%d-%d]: %s failed!\n", p->level, ' ', + p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "(fstring | string)")); + } + if (_n == 0 || p->error_indicator) { +@@ -31916,9 +32515,9 @@ _loop1_113_rule(Parser *p) + return _seq; + } + +-// _tmp_114: star_named_expression ',' star_named_expressions? ++// _tmp_116: star_named_expression ',' star_named_expressions? + static void * +-_tmp_114_rule(Parser *p) ++_tmp_116_rule(Parser *p) + { + if (p->level++ == MAXSTACK) { + p->error_indicator = 1; +@@ -31935,7 +32534,7 @@ _tmp_114_rule(Parser *p) + p->level--; + return NULL; + } +- D(fprintf(stderr, "%*c> _tmp_114[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "star_named_expression ',' star_named_expressions?")); ++ D(fprintf(stderr, "%*c> _tmp_116[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "star_named_expression ',' star_named_expressions?")); + Token * _literal; + expr_ty y; + void *z; +@@ -31947,7 +32546,7 @@ _tmp_114_rule(Parser *p) + (z = star_named_expressions_rule(p), !p->error_indicator) // star_named_expressions? + ) + { +- D(fprintf(stderr, "%*c+ _tmp_114[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "star_named_expression ',' star_named_expressions?")); ++ D(fprintf(stderr, "%*c+ _tmp_116[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "star_named_expression ',' star_named_expressions?")); + _res = _PyPegen_seq_insert_in_front ( p , y , z ); + if (_res == NULL && PyErr_Occurred()) { + p->error_indicator = 1; +@@ -31957,7 +32556,7 @@ _tmp_114_rule(Parser *p) + goto done; + } + p->mark = _mark; +- D(fprintf(stderr, "%*c%s _tmp_114[%d-%d]: %s failed!\n", p->level, ' ', ++ D(fprintf(stderr, "%*c%s _tmp_116[%d-%d]: %s failed!\n", p->level, ' ', + p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "star_named_expression ',' star_named_expressions?")); + } + _res = NULL; +@@ -31966,9 +32565,9 @@ _tmp_114_rule(Parser *p) + return _res; + } + +-// _loop0_116: ',' double_starred_kvpair ++// _loop0_118: ',' double_starred_kvpair + static asdl_seq * +-_loop0_116_rule(Parser *p) ++_loop0_118_rule(Parser *p) + { + if (p->level++ == MAXSTACK) { + p->error_indicator = 1; +@@ -31994,7 +32593,7 @@ _loop0_116_rule(Parser *p) + p->level--; + return NULL; + } +- D(fprintf(stderr, "%*c> _loop0_116[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "',' double_starred_kvpair")); ++ D(fprintf(stderr, "%*c> _loop0_118[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "',' double_starred_kvpair")); + Token * _literal; + KeyValuePair* elem; + while ( +@@ -32026,7 +32625,7 @@ _loop0_116_rule(Parser *p) + _mark = p->mark; + } + p->mark = _mark; +- D(fprintf(stderr, "%*c%s _loop0_116[%d-%d]: %s failed!\n", p->level, ' ', ++ D(fprintf(stderr, "%*c%s _loop0_118[%d-%d]: %s failed!\n", p->level, ' ', + p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "',' double_starred_kvpair")); + } + asdl_seq *_seq = (asdl_seq*)_Py_asdl_generic_seq_new(_n, p->arena); +@@ -32043,9 +32642,9 @@ _loop0_116_rule(Parser *p) + return _seq; + } + +-// _gather_115: double_starred_kvpair _loop0_116 ++// _gather_117: double_starred_kvpair _loop0_118 + static asdl_seq * +-_gather_115_rule(Parser *p) ++_gather_117_rule(Parser *p) + { + if (p->level++ == MAXSTACK) { + p->error_indicator = 1; +@@ -32057,27 +32656,27 @@ _gather_115_rule(Parser *p) + } + asdl_seq * _res = NULL; + int _mark = p->mark; +- { // double_starred_kvpair _loop0_116 ++ { // double_starred_kvpair _loop0_118 + if (p->error_indicator) { + p->level--; + return NULL; + } +- D(fprintf(stderr, "%*c> _gather_115[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "double_starred_kvpair _loop0_116")); ++ D(fprintf(stderr, "%*c> _gather_117[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "double_starred_kvpair _loop0_118")); + KeyValuePair* elem; + asdl_seq * seq; + if ( + (elem = double_starred_kvpair_rule(p)) // double_starred_kvpair + && +- (seq = _loop0_116_rule(p)) // _loop0_116 ++ (seq = _loop0_118_rule(p)) // _loop0_118 + ) + { +- D(fprintf(stderr, "%*c+ _gather_115[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "double_starred_kvpair _loop0_116")); ++ D(fprintf(stderr, "%*c+ _gather_117[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "double_starred_kvpair _loop0_118")); + _res = _PyPegen_seq_insert_in_front(p, elem, seq); + goto done; + } + p->mark = _mark; +- D(fprintf(stderr, "%*c%s _gather_115[%d-%d]: %s failed!\n", p->level, ' ', +- p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "double_starred_kvpair _loop0_116")); ++ D(fprintf(stderr, "%*c%s _gather_117[%d-%d]: %s failed!\n", p->level, ' ', ++ p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "double_starred_kvpair _loop0_118")); + } + _res = NULL; + done: +@@ -32085,9 +32684,9 @@ _gather_115_rule(Parser *p) + return _res; + } + +-// _loop1_117: for_if_clause ++// _loop1_119: for_if_clause + static asdl_seq * +-_loop1_117_rule(Parser *p) ++_loop1_119_rule(Parser *p) + { + if (p->level++ == MAXSTACK) { + p->error_indicator = 1; +@@ -32113,7 +32712,7 @@ _loop1_117_rule(Parser *p) + p->level--; + return NULL; + } +- D(fprintf(stderr, "%*c> _loop1_117[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "for_if_clause")); ++ D(fprintf(stderr, "%*c> _loop1_119[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "for_if_clause")); + comprehension_ty for_if_clause_var; + while ( + (for_if_clause_var = for_if_clause_rule(p)) // for_if_clause +@@ -32136,7 +32735,7 @@ _loop1_117_rule(Parser *p) + _mark = p->mark; + } + p->mark = _mark; +- D(fprintf(stderr, "%*c%s _loop1_117[%d-%d]: %s failed!\n", p->level, ' ', ++ D(fprintf(stderr, "%*c%s _loop1_119[%d-%d]: %s failed!\n", p->level, ' ', + p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "for_if_clause")); + } + if (_n == 0 || p->error_indicator) { +@@ -32158,9 +32757,9 @@ _loop1_117_rule(Parser *p) + return _seq; + } + +-// _loop0_118: ('if' disjunction) ++// _loop0_120: ('if' disjunction) + static asdl_seq * +-_loop0_118_rule(Parser *p) ++_loop0_120_rule(Parser *p) + { + if (p->level++ == MAXSTACK) { + p->error_indicator = 1; +@@ -32186,13 +32785,13 @@ _loop0_118_rule(Parser *p) + p->level--; + return NULL; + } +- D(fprintf(stderr, "%*c> _loop0_118[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "('if' disjunction)")); +- void *_tmp_254_var; ++ D(fprintf(stderr, "%*c> _loop0_120[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "('if' disjunction)")); ++ void *_tmp_256_var; + while ( +- (_tmp_254_var = _tmp_254_rule(p)) // 'if' disjunction ++ (_tmp_256_var = _tmp_256_rule(p)) // 'if' disjunction + ) + { +- _res = _tmp_254_var; ++ _res = _tmp_256_var; + if (_n == _children_capacity) { + _children_capacity *= 2; + void **_new_children = PyMem_Realloc(_children, _children_capacity*sizeof(void *)); +@@ -32209,7 +32808,7 @@ _loop0_118_rule(Parser *p) + _mark = p->mark; + } + p->mark = _mark; +- D(fprintf(stderr, "%*c%s _loop0_118[%d-%d]: %s failed!\n", p->level, ' ', ++ D(fprintf(stderr, "%*c%s _loop0_120[%d-%d]: %s failed!\n", p->level, ' ', + p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "('if' disjunction)")); + } + asdl_seq *_seq = (asdl_seq*)_Py_asdl_generic_seq_new(_n, p->arena); +@@ -32226,9 +32825,9 @@ _loop0_118_rule(Parser *p) + return _seq; + } + +-// _loop0_119: ('if' disjunction) ++// _loop0_121: ('if' disjunction) + static asdl_seq * +-_loop0_119_rule(Parser *p) ++_loop0_121_rule(Parser *p) + { + if (p->level++ == MAXSTACK) { + p->error_indicator = 1; +@@ -32254,13 +32853,13 @@ _loop0_119_rule(Parser *p) + p->level--; + return NULL; + } +- D(fprintf(stderr, "%*c> _loop0_119[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "('if' disjunction)")); +- void *_tmp_255_var; ++ D(fprintf(stderr, "%*c> _loop0_121[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "('if' disjunction)")); ++ void *_tmp_257_var; + while ( +- (_tmp_255_var = _tmp_255_rule(p)) // 'if' disjunction ++ (_tmp_257_var = _tmp_257_rule(p)) // 'if' disjunction + ) + { +- _res = _tmp_255_var; ++ _res = _tmp_257_var; + if (_n == _children_capacity) { + _children_capacity *= 2; + void **_new_children = PyMem_Realloc(_children, _children_capacity*sizeof(void *)); +@@ -32277,7 +32876,7 @@ _loop0_119_rule(Parser *p) + _mark = p->mark; + } + p->mark = _mark; +- D(fprintf(stderr, "%*c%s _loop0_119[%d-%d]: %s failed!\n", p->level, ' ', ++ D(fprintf(stderr, "%*c%s _loop0_121[%d-%d]: %s failed!\n", p->level, ' ', + p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "('if' disjunction)")); + } + asdl_seq *_seq = (asdl_seq*)_Py_asdl_generic_seq_new(_n, p->arena); +@@ -32294,9 +32893,9 @@ _loop0_119_rule(Parser *p) + return _seq; + } + +-// _tmp_120: assignment_expression | expression !':=' ++// _tmp_122: assignment_expression | expression !':=' + static void * +-_tmp_120_rule(Parser *p) ++_tmp_122_rule(Parser *p) + { + if (p->level++ == MAXSTACK) { + p->error_indicator = 1; +@@ -32313,18 +32912,18 @@ _tmp_120_rule(Parser *p) + p->level--; + return NULL; + } +- D(fprintf(stderr, "%*c> _tmp_120[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "assignment_expression")); ++ D(fprintf(stderr, "%*c> _tmp_122[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "assignment_expression")); + expr_ty assignment_expression_var; + if ( + (assignment_expression_var = assignment_expression_rule(p)) // assignment_expression + ) + { +- D(fprintf(stderr, "%*c+ _tmp_120[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "assignment_expression")); ++ D(fprintf(stderr, "%*c+ _tmp_122[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "assignment_expression")); + _res = assignment_expression_var; + goto done; + } + p->mark = _mark; +- D(fprintf(stderr, "%*c%s _tmp_120[%d-%d]: %s failed!\n", p->level, ' ', ++ D(fprintf(stderr, "%*c%s _tmp_122[%d-%d]: %s failed!\n", p->level, ' ', + p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "assignment_expression")); + } + { // expression !':=' +@@ -32332,7 +32931,7 @@ _tmp_120_rule(Parser *p) + p->level--; + return NULL; + } +- D(fprintf(stderr, "%*c> _tmp_120[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "expression !':='")); ++ D(fprintf(stderr, "%*c> _tmp_122[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "expression !':='")); + expr_ty expression_var; + if ( + (expression_var = expression_rule(p)) // expression +@@ -32340,12 +32939,12 @@ _tmp_120_rule(Parser *p) + _PyPegen_lookahead_with_int(0, _PyPegen_expect_token, p, 53) // token=':=' + ) + { +- D(fprintf(stderr, "%*c+ _tmp_120[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "expression !':='")); ++ D(fprintf(stderr, "%*c+ _tmp_122[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "expression !':='")); + _res = expression_var; + goto done; + } + p->mark = _mark; +- D(fprintf(stderr, "%*c%s _tmp_120[%d-%d]: %s failed!\n", p->level, ' ', ++ D(fprintf(stderr, "%*c%s _tmp_122[%d-%d]: %s failed!\n", p->level, ' ', + p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "expression !':='")); + } + _res = NULL; +@@ -32354,9 +32953,9 @@ _tmp_120_rule(Parser *p) + return _res; + } + +-// _loop0_122: ',' (starred_expression | (assignment_expression | expression !':=') !'=') ++// _loop0_124: ',' (starred_expression | (assignment_expression | expression !':=') !'=') + static asdl_seq * +-_loop0_122_rule(Parser *p) ++_loop0_124_rule(Parser *p) + { + if (p->level++ == MAXSTACK) { + p->error_indicator = 1; +@@ -32382,13 +32981,13 @@ _loop0_122_rule(Parser *p) + p->level--; + return NULL; + } +- D(fprintf(stderr, "%*c> _loop0_122[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "',' (starred_expression | (assignment_expression | expression !':=') !'=')")); ++ D(fprintf(stderr, "%*c> _loop0_124[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "',' (starred_expression | (assignment_expression | expression !':=') !'=')")); + Token * _literal; + void *elem; + while ( + (_literal = _PyPegen_expect_token(p, 12)) // token=',' + && +- (elem = _tmp_256_rule(p)) // starred_expression | (assignment_expression | expression !':=') !'=' ++ (elem = _tmp_258_rule(p)) // starred_expression | (assignment_expression | expression !':=') !'=' + ) + { + _res = elem; +@@ -32414,7 +33013,7 @@ _loop0_122_rule(Parser *p) + _mark = p->mark; + } + p->mark = _mark; +- D(fprintf(stderr, "%*c%s _loop0_122[%d-%d]: %s failed!\n", p->level, ' ', ++ D(fprintf(stderr, "%*c%s _loop0_124[%d-%d]: %s failed!\n", p->level, ' ', + p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "',' (starred_expression | (assignment_expression | expression !':=') !'=')")); + } + asdl_seq *_seq = (asdl_seq*)_Py_asdl_generic_seq_new(_n, p->arena); +@@ -32431,10 +33030,10 @@ _loop0_122_rule(Parser *p) + return _seq; + } + +-// _gather_121: +-// | (starred_expression | (assignment_expression | expression !':=') !'=') _loop0_122 ++// _gather_123: ++// | (starred_expression | (assignment_expression | expression !':=') !'=') _loop0_124 + static asdl_seq * +-_gather_121_rule(Parser *p) ++_gather_123_rule(Parser *p) + { + if (p->level++ == MAXSTACK) { + p->error_indicator = 1; +@@ -32446,27 +33045,27 @@ _gather_121_rule(Parser *p) + } + asdl_seq * _res = NULL; + int _mark = p->mark; +- { // (starred_expression | (assignment_expression | expression !':=') !'=') _loop0_122 ++ { // (starred_expression | (assignment_expression | expression !':=') !'=') _loop0_124 + if (p->error_indicator) { + p->level--; + return NULL; + } +- D(fprintf(stderr, "%*c> _gather_121[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "(starred_expression | (assignment_expression | expression !':=') !'=') _loop0_122")); ++ D(fprintf(stderr, "%*c> _gather_123[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "(starred_expression | (assignment_expression | expression !':=') !'=') _loop0_124")); + void *elem; + asdl_seq * seq; + if ( +- (elem = _tmp_256_rule(p)) // starred_expression | (assignment_expression | expression !':=') !'=' ++ (elem = _tmp_258_rule(p)) // starred_expression | (assignment_expression | expression !':=') !'=' + && +- (seq = _loop0_122_rule(p)) // _loop0_122 ++ (seq = _loop0_124_rule(p)) // _loop0_124 + ) + { +- D(fprintf(stderr, "%*c+ _gather_121[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "(starred_expression | (assignment_expression | expression !':=') !'=') _loop0_122")); ++ D(fprintf(stderr, "%*c+ _gather_123[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "(starred_expression | (assignment_expression | expression !':=') !'=') _loop0_124")); + _res = _PyPegen_seq_insert_in_front(p, elem, seq); + goto done; + } + p->mark = _mark; +- D(fprintf(stderr, "%*c%s _gather_121[%d-%d]: %s failed!\n", p->level, ' ', +- p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "(starred_expression | (assignment_expression | expression !':=') !'=') _loop0_122")); ++ D(fprintf(stderr, "%*c%s _gather_123[%d-%d]: %s failed!\n", p->level, ' ', ++ p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "(starred_expression | (assignment_expression | expression !':=') !'=') _loop0_124")); + } + _res = NULL; + done: +@@ -32474,9 +33073,9 @@ _gather_121_rule(Parser *p) + return _res; + } + +-// _tmp_123: ',' kwargs ++// _tmp_125: ',' kwargs + static void * +-_tmp_123_rule(Parser *p) ++_tmp_125_rule(Parser *p) + { + if (p->level++ == MAXSTACK) { + p->error_indicator = 1; +@@ -32493,7 +33092,7 @@ _tmp_123_rule(Parser *p) + p->level--; + return NULL; + } +- D(fprintf(stderr, "%*c> _tmp_123[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "',' kwargs")); ++ D(fprintf(stderr, "%*c> _tmp_125[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "',' kwargs")); + Token * _literal; + asdl_seq* k; + if ( +@@ -32502,7 +33101,7 @@ _tmp_123_rule(Parser *p) + (k = kwargs_rule(p)) // kwargs + ) + { +- D(fprintf(stderr, "%*c+ _tmp_123[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "',' kwargs")); ++ D(fprintf(stderr, "%*c+ _tmp_125[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "',' kwargs")); + _res = k; + if (_res == NULL && PyErr_Occurred()) { + p->error_indicator = 1; +@@ -32512,7 +33111,7 @@ _tmp_123_rule(Parser *p) + goto done; + } + p->mark = _mark; +- D(fprintf(stderr, "%*c%s _tmp_123[%d-%d]: %s failed!\n", p->level, ' ', ++ D(fprintf(stderr, "%*c%s _tmp_125[%d-%d]: %s failed!\n", p->level, ' ', + p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "',' kwargs")); + } + _res = NULL; +@@ -32521,9 +33120,9 @@ _tmp_123_rule(Parser *p) + return _res; + } + +-// _loop0_125: ',' kwarg_or_starred ++// _loop0_127: ',' kwarg_or_starred + static asdl_seq * +-_loop0_125_rule(Parser *p) ++_loop0_127_rule(Parser *p) + { + if (p->level++ == MAXSTACK) { + p->error_indicator = 1; +@@ -32549,7 +33148,7 @@ _loop0_125_rule(Parser *p) + p->level--; + return NULL; + } +- D(fprintf(stderr, "%*c> _loop0_125[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "',' kwarg_or_starred")); ++ D(fprintf(stderr, "%*c> _loop0_127[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "',' kwarg_or_starred")); + Token * _literal; + KeywordOrStarred* elem; + while ( +@@ -32581,127 +33180,8 @@ _loop0_125_rule(Parser *p) + _mark = p->mark; + } + p->mark = _mark; +- D(fprintf(stderr, "%*c%s _loop0_125[%d-%d]: %s failed!\n", p->level, ' ', +- p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "',' kwarg_or_starred")); +- } +- asdl_seq *_seq = (asdl_seq*)_Py_asdl_generic_seq_new(_n, p->arena); +- if (!_seq) { +- PyMem_Free(_children); +- p->error_indicator = 1; +- PyErr_NoMemory(); +- p->level--; +- return NULL; +- } +- for (int i = 0; i < _n; i++) asdl_seq_SET_UNTYPED(_seq, i, _children[i]); +- PyMem_Free(_children); +- p->level--; +- return _seq; +-} +- +-// _gather_124: kwarg_or_starred _loop0_125 +-static asdl_seq * +-_gather_124_rule(Parser *p) +-{ +- if (p->level++ == MAXSTACK) { +- p->error_indicator = 1; +- PyErr_NoMemory(); +- } +- if (p->error_indicator) { +- p->level--; +- return NULL; +- } +- asdl_seq * _res = NULL; +- int _mark = p->mark; +- { // kwarg_or_starred _loop0_125 +- if (p->error_indicator) { +- p->level--; +- return NULL; +- } +- D(fprintf(stderr, "%*c> _gather_124[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "kwarg_or_starred _loop0_125")); +- KeywordOrStarred* elem; +- asdl_seq * seq; +- if ( +- (elem = kwarg_or_starred_rule(p)) // kwarg_or_starred +- && +- (seq = _loop0_125_rule(p)) // _loop0_125 +- ) +- { +- D(fprintf(stderr, "%*c+ _gather_124[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "kwarg_or_starred _loop0_125")); +- _res = _PyPegen_seq_insert_in_front(p, elem, seq); +- goto done; +- } +- p->mark = _mark; +- D(fprintf(stderr, "%*c%s _gather_124[%d-%d]: %s failed!\n", p->level, ' ', +- p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "kwarg_or_starred _loop0_125")); +- } +- _res = NULL; +- done: +- p->level--; +- return _res; +-} +- +-// _loop0_127: ',' kwarg_or_double_starred +-static asdl_seq * +-_loop0_127_rule(Parser *p) +-{ +- if (p->level++ == MAXSTACK) { +- p->error_indicator = 1; +- PyErr_NoMemory(); +- } +- if (p->error_indicator) { +- p->level--; +- return NULL; +- } +- void *_res = NULL; +- int _mark = p->mark; +- void **_children = PyMem_Malloc(sizeof(void *)); +- if (!_children) { +- p->error_indicator = 1; +- PyErr_NoMemory(); +- p->level--; +- return NULL; +- } +- Py_ssize_t _children_capacity = 1; +- Py_ssize_t _n = 0; +- { // ',' kwarg_or_double_starred +- if (p->error_indicator) { +- p->level--; +- return NULL; +- } +- D(fprintf(stderr, "%*c> _loop0_127[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "',' kwarg_or_double_starred")); +- Token * _literal; +- KeywordOrStarred* elem; +- while ( +- (_literal = _PyPegen_expect_token(p, 12)) // token=',' +- && +- (elem = kwarg_or_double_starred_rule(p)) // kwarg_or_double_starred +- ) +- { +- _res = elem; +- if (_res == NULL && PyErr_Occurred()) { +- p->error_indicator = 1; +- PyMem_Free(_children); +- p->level--; +- return NULL; +- } +- if (_n == _children_capacity) { +- _children_capacity *= 2; +- void **_new_children = PyMem_Realloc(_children, _children_capacity*sizeof(void *)); +- if (!_new_children) { +- PyMem_Free(_children); +- p->error_indicator = 1; +- PyErr_NoMemory(); +- p->level--; +- return NULL; +- } +- _children = _new_children; +- } +- _children[_n++] = _res; +- _mark = p->mark; +- } +- p->mark = _mark; + D(fprintf(stderr, "%*c%s _loop0_127[%d-%d]: %s failed!\n", p->level, ' ', +- p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "',' kwarg_or_double_starred")); ++ p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "',' kwarg_or_starred")); + } + asdl_seq *_seq = (asdl_seq*)_Py_asdl_generic_seq_new(_n, p->arena); + if (!_seq) { +@@ -32717,7 +33197,7 @@ _loop0_127_rule(Parser *p) + return _seq; + } + +-// _gather_126: kwarg_or_double_starred _loop0_127 ++// _gather_126: kwarg_or_starred _loop0_127 + static asdl_seq * + _gather_126_rule(Parser *p) + { +@@ -32731,27 +33211,27 @@ _gather_126_rule(Parser *p) + } + asdl_seq * _res = NULL; + int _mark = p->mark; +- { // kwarg_or_double_starred _loop0_127 ++ { // kwarg_or_starred _loop0_127 + if (p->error_indicator) { + p->level--; + return NULL; + } +- D(fprintf(stderr, "%*c> _gather_126[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "kwarg_or_double_starred _loop0_127")); ++ D(fprintf(stderr, "%*c> _gather_126[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "kwarg_or_starred _loop0_127")); + KeywordOrStarred* elem; + asdl_seq * seq; + if ( +- (elem = kwarg_or_double_starred_rule(p)) // kwarg_or_double_starred ++ (elem = kwarg_or_starred_rule(p)) // kwarg_or_starred + && + (seq = _loop0_127_rule(p)) // _loop0_127 + ) + { +- D(fprintf(stderr, "%*c+ _gather_126[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "kwarg_or_double_starred _loop0_127")); ++ D(fprintf(stderr, "%*c+ _gather_126[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "kwarg_or_starred _loop0_127")); + _res = _PyPegen_seq_insert_in_front(p, elem, seq); + goto done; + } + p->mark = _mark; + D(fprintf(stderr, "%*c%s _gather_126[%d-%d]: %s failed!\n", p->level, ' ', +- p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "kwarg_or_double_starred _loop0_127")); ++ p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "kwarg_or_starred _loop0_127")); + } + _res = NULL; + done: +@@ -32759,7 +33239,7 @@ _gather_126_rule(Parser *p) + return _res; + } + +-// _loop0_129: ',' kwarg_or_starred ++// _loop0_129: ',' kwarg_or_double_starred + static asdl_seq * + _loop0_129_rule(Parser *p) + { +@@ -32782,18 +33262,18 @@ _loop0_129_rule(Parser *p) + } + Py_ssize_t _children_capacity = 1; + Py_ssize_t _n = 0; +- { // ',' kwarg_or_starred ++ { // ',' kwarg_or_double_starred + if (p->error_indicator) { + p->level--; + return NULL; + } +- D(fprintf(stderr, "%*c> _loop0_129[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "',' kwarg_or_starred")); ++ D(fprintf(stderr, "%*c> _loop0_129[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "',' kwarg_or_double_starred")); + Token * _literal; + KeywordOrStarred* elem; + while ( + (_literal = _PyPegen_expect_token(p, 12)) // token=',' + && +- (elem = kwarg_or_starred_rule(p)) // kwarg_or_starred ++ (elem = kwarg_or_double_starred_rule(p)) // kwarg_or_double_starred + ) + { + _res = elem; +@@ -32820,7 +33300,7 @@ _loop0_129_rule(Parser *p) + } + p->mark = _mark; + D(fprintf(stderr, "%*c%s _loop0_129[%d-%d]: %s failed!\n", p->level, ' ', +- p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "',' kwarg_or_starred")); ++ p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "',' kwarg_or_double_starred")); + } + asdl_seq *_seq = (asdl_seq*)_Py_asdl_generic_seq_new(_n, p->arena); + if (!_seq) { +@@ -32836,7 +33316,7 @@ _loop0_129_rule(Parser *p) + return _seq; + } + +-// _gather_128: kwarg_or_starred _loop0_129 ++// _gather_128: kwarg_or_double_starred _loop0_129 + static asdl_seq * + _gather_128_rule(Parser *p) + { +@@ -32850,27 +33330,27 @@ _gather_128_rule(Parser *p) + } + asdl_seq * _res = NULL; + int _mark = p->mark; +- { // kwarg_or_starred _loop0_129 ++ { // kwarg_or_double_starred _loop0_129 + if (p->error_indicator) { + p->level--; + return NULL; + } +- D(fprintf(stderr, "%*c> _gather_128[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "kwarg_or_starred _loop0_129")); ++ D(fprintf(stderr, "%*c> _gather_128[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "kwarg_or_double_starred _loop0_129")); + KeywordOrStarred* elem; + asdl_seq * seq; + if ( +- (elem = kwarg_or_starred_rule(p)) // kwarg_or_starred ++ (elem = kwarg_or_double_starred_rule(p)) // kwarg_or_double_starred + && + (seq = _loop0_129_rule(p)) // _loop0_129 + ) + { +- D(fprintf(stderr, "%*c+ _gather_128[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "kwarg_or_starred _loop0_129")); ++ D(fprintf(stderr, "%*c+ _gather_128[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "kwarg_or_double_starred _loop0_129")); + _res = _PyPegen_seq_insert_in_front(p, elem, seq); + goto done; + } + p->mark = _mark; + D(fprintf(stderr, "%*c%s _gather_128[%d-%d]: %s failed!\n", p->level, ' ', +- p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "kwarg_or_starred _loop0_129")); ++ p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "kwarg_or_double_starred _loop0_129")); + } + _res = NULL; + done: +@@ -32878,7 +33358,7 @@ _gather_128_rule(Parser *p) + return _res; + } + +-// _loop0_131: ',' kwarg_or_double_starred ++// _loop0_131: ',' kwarg_or_starred + static asdl_seq * + _loop0_131_rule(Parser *p) + { +@@ -32901,18 +33381,18 @@ _loop0_131_rule(Parser *p) + } + Py_ssize_t _children_capacity = 1; + Py_ssize_t _n = 0; +- { // ',' kwarg_or_double_starred ++ { // ',' kwarg_or_starred + if (p->error_indicator) { + p->level--; + return NULL; + } +- D(fprintf(stderr, "%*c> _loop0_131[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "',' kwarg_or_double_starred")); ++ D(fprintf(stderr, "%*c> _loop0_131[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "',' kwarg_or_starred")); + Token * _literal; + KeywordOrStarred* elem; + while ( + (_literal = _PyPegen_expect_token(p, 12)) // token=',' + && +- (elem = kwarg_or_double_starred_rule(p)) // kwarg_or_double_starred ++ (elem = kwarg_or_starred_rule(p)) // kwarg_or_starred + ) + { + _res = elem; +@@ -32939,7 +33419,7 @@ _loop0_131_rule(Parser *p) + } + p->mark = _mark; + D(fprintf(stderr, "%*c%s _loop0_131[%d-%d]: %s failed!\n", p->level, ' ', +- p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "',' kwarg_or_double_starred")); ++ p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "',' kwarg_or_starred")); + } + asdl_seq *_seq = (asdl_seq*)_Py_asdl_generic_seq_new(_n, p->arena); + if (!_seq) { +@@ -32955,7 +33435,7 @@ _loop0_131_rule(Parser *p) + return _seq; + } + +-// _gather_130: kwarg_or_double_starred _loop0_131 ++// _gather_130: kwarg_or_starred _loop0_131 + static asdl_seq * + _gather_130_rule(Parser *p) + { +@@ -32969,27 +33449,27 @@ _gather_130_rule(Parser *p) + } + asdl_seq * _res = NULL; + int _mark = p->mark; +- { // kwarg_or_double_starred _loop0_131 ++ { // kwarg_or_starred _loop0_131 + if (p->error_indicator) { + p->level--; + return NULL; + } +- D(fprintf(stderr, "%*c> _gather_130[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "kwarg_or_double_starred _loop0_131")); ++ D(fprintf(stderr, "%*c> _gather_130[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "kwarg_or_starred _loop0_131")); + KeywordOrStarred* elem; + asdl_seq * seq; + if ( +- (elem = kwarg_or_double_starred_rule(p)) // kwarg_or_double_starred ++ (elem = kwarg_or_starred_rule(p)) // kwarg_or_starred + && + (seq = _loop0_131_rule(p)) // _loop0_131 + ) + { +- D(fprintf(stderr, "%*c+ _gather_130[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "kwarg_or_double_starred _loop0_131")); ++ D(fprintf(stderr, "%*c+ _gather_130[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "kwarg_or_starred _loop0_131")); + _res = _PyPegen_seq_insert_in_front(p, elem, seq); + goto done; + } + p->mark = _mark; + D(fprintf(stderr, "%*c%s _gather_130[%d-%d]: %s failed!\n", p->level, ' ', +- p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "kwarg_or_double_starred _loop0_131")); ++ p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "kwarg_or_starred _loop0_131")); + } + _res = NULL; + done: +@@ -32997,9 +33477,128 @@ _gather_130_rule(Parser *p) + return _res; + } + +-// _loop0_132: (',' star_target) ++// _loop0_133: ',' kwarg_or_double_starred + static asdl_seq * +-_loop0_132_rule(Parser *p) ++_loop0_133_rule(Parser *p) ++{ ++ if (p->level++ == MAXSTACK) { ++ p->error_indicator = 1; ++ PyErr_NoMemory(); ++ } ++ if (p->error_indicator) { ++ p->level--; ++ return NULL; ++ } ++ void *_res = NULL; ++ int _mark = p->mark; ++ void **_children = PyMem_Malloc(sizeof(void *)); ++ if (!_children) { ++ p->error_indicator = 1; ++ PyErr_NoMemory(); ++ p->level--; ++ return NULL; ++ } ++ Py_ssize_t _children_capacity = 1; ++ Py_ssize_t _n = 0; ++ { // ',' kwarg_or_double_starred ++ if (p->error_indicator) { ++ p->level--; ++ return NULL; ++ } ++ D(fprintf(stderr, "%*c> _loop0_133[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "',' kwarg_or_double_starred")); ++ Token * _literal; ++ KeywordOrStarred* elem; ++ while ( ++ (_literal = _PyPegen_expect_token(p, 12)) // token=',' ++ && ++ (elem = kwarg_or_double_starred_rule(p)) // kwarg_or_double_starred ++ ) ++ { ++ _res = elem; ++ if (_res == NULL && PyErr_Occurred()) { ++ p->error_indicator = 1; ++ PyMem_Free(_children); ++ p->level--; ++ return NULL; ++ } ++ if (_n == _children_capacity) { ++ _children_capacity *= 2; ++ void **_new_children = PyMem_Realloc(_children, _children_capacity*sizeof(void *)); ++ if (!_new_children) { ++ PyMem_Free(_children); ++ p->error_indicator = 1; ++ PyErr_NoMemory(); ++ p->level--; ++ return NULL; ++ } ++ _children = _new_children; ++ } ++ _children[_n++] = _res; ++ _mark = p->mark; ++ } ++ p->mark = _mark; ++ D(fprintf(stderr, "%*c%s _loop0_133[%d-%d]: %s failed!\n", p->level, ' ', ++ p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "',' kwarg_or_double_starred")); ++ } ++ asdl_seq *_seq = (asdl_seq*)_Py_asdl_generic_seq_new(_n, p->arena); ++ if (!_seq) { ++ PyMem_Free(_children); ++ p->error_indicator = 1; ++ PyErr_NoMemory(); ++ p->level--; ++ return NULL; ++ } ++ for (int i = 0; i < _n; i++) asdl_seq_SET_UNTYPED(_seq, i, _children[i]); ++ PyMem_Free(_children); ++ p->level--; ++ return _seq; ++} ++ ++// _gather_132: kwarg_or_double_starred _loop0_133 ++static asdl_seq * ++_gather_132_rule(Parser *p) ++{ ++ if (p->level++ == MAXSTACK) { ++ p->error_indicator = 1; ++ PyErr_NoMemory(); ++ } ++ if (p->error_indicator) { ++ p->level--; ++ return NULL; ++ } ++ asdl_seq * _res = NULL; ++ int _mark = p->mark; ++ { // kwarg_or_double_starred _loop0_133 ++ if (p->error_indicator) { ++ p->level--; ++ return NULL; ++ } ++ D(fprintf(stderr, "%*c> _gather_132[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "kwarg_or_double_starred _loop0_133")); ++ KeywordOrStarred* elem; ++ asdl_seq * seq; ++ if ( ++ (elem = kwarg_or_double_starred_rule(p)) // kwarg_or_double_starred ++ && ++ (seq = _loop0_133_rule(p)) // _loop0_133 ++ ) ++ { ++ D(fprintf(stderr, "%*c+ _gather_132[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "kwarg_or_double_starred _loop0_133")); ++ _res = _PyPegen_seq_insert_in_front(p, elem, seq); ++ goto done; ++ } ++ p->mark = _mark; ++ D(fprintf(stderr, "%*c%s _gather_132[%d-%d]: %s failed!\n", p->level, ' ', ++ p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "kwarg_or_double_starred _loop0_133")); ++ } ++ _res = NULL; ++ done: ++ p->level--; ++ return _res; ++} ++ ++// _loop0_134: (',' star_target) ++static asdl_seq * ++_loop0_134_rule(Parser *p) + { + if (p->level++ == MAXSTACK) { + p->error_indicator = 1; +@@ -33025,13 +33624,13 @@ _loop0_132_rule(Parser *p) + p->level--; + return NULL; + } +- D(fprintf(stderr, "%*c> _loop0_132[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "(',' star_target)")); +- void *_tmp_257_var; ++ D(fprintf(stderr, "%*c> _loop0_134[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "(',' star_target)")); ++ void *_tmp_259_var; + while ( +- (_tmp_257_var = _tmp_257_rule(p)) // ',' star_target ++ (_tmp_259_var = _tmp_259_rule(p)) // ',' star_target + ) + { +- _res = _tmp_257_var; ++ _res = _tmp_259_var; + if (_n == _children_capacity) { + _children_capacity *= 2; + void **_new_children = PyMem_Realloc(_children, _children_capacity*sizeof(void *)); +@@ -33048,7 +33647,7 @@ _loop0_132_rule(Parser *p) + _mark = p->mark; + } + p->mark = _mark; +- D(fprintf(stderr, "%*c%s _loop0_132[%d-%d]: %s failed!\n", p->level, ' ', ++ D(fprintf(stderr, "%*c%s _loop0_134[%d-%d]: %s failed!\n", p->level, ' ', + p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "(',' star_target)")); + } + asdl_seq *_seq = (asdl_seq*)_Py_asdl_generic_seq_new(_n, p->arena); +@@ -33065,9 +33664,9 @@ _loop0_132_rule(Parser *p) + return _seq; + } + +-// _loop0_134: ',' star_target ++// _loop0_136: ',' star_target + static asdl_seq * +-_loop0_134_rule(Parser *p) ++_loop0_136_rule(Parser *p) + { + if (p->level++ == MAXSTACK) { + p->error_indicator = 1; +@@ -33093,7 +33692,7 @@ _loop0_134_rule(Parser *p) + p->level--; + return NULL; + } +- D(fprintf(stderr, "%*c> _loop0_134[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "',' star_target")); ++ D(fprintf(stderr, "%*c> _loop0_136[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "',' star_target")); + Token * _literal; + expr_ty elem; + while ( +@@ -33125,7 +33724,7 @@ _loop0_134_rule(Parser *p) + _mark = p->mark; + } + p->mark = _mark; +- D(fprintf(stderr, "%*c%s _loop0_134[%d-%d]: %s failed!\n", p->level, ' ', ++ D(fprintf(stderr, "%*c%s _loop0_136[%d-%d]: %s failed!\n", p->level, ' ', + p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "',' star_target")); + } + asdl_seq *_seq = (asdl_seq*)_Py_asdl_generic_seq_new(_n, p->arena); +@@ -33142,9 +33741,9 @@ _loop0_134_rule(Parser *p) + return _seq; + } + +-// _gather_133: star_target _loop0_134 ++// _gather_135: star_target _loop0_136 + static asdl_seq * +-_gather_133_rule(Parser *p) ++_gather_135_rule(Parser *p) + { + if (p->level++ == MAXSTACK) { + p->error_indicator = 1; +@@ -33156,27 +33755,27 @@ _gather_133_rule(Parser *p) + } + asdl_seq * _res = NULL; + int _mark = p->mark; +- { // star_target _loop0_134 ++ { // star_target _loop0_136 + if (p->error_indicator) { + p->level--; + return NULL; + } +- D(fprintf(stderr, "%*c> _gather_133[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "star_target _loop0_134")); ++ D(fprintf(stderr, "%*c> _gather_135[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "star_target _loop0_136")); + expr_ty elem; + asdl_seq * seq; + if ( + (elem = star_target_rule(p)) // star_target + && +- (seq = _loop0_134_rule(p)) // _loop0_134 ++ (seq = _loop0_136_rule(p)) // _loop0_136 + ) + { +- D(fprintf(stderr, "%*c+ _gather_133[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "star_target _loop0_134")); ++ D(fprintf(stderr, "%*c+ _gather_135[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "star_target _loop0_136")); + _res = _PyPegen_seq_insert_in_front(p, elem, seq); + goto done; + } + p->mark = _mark; +- D(fprintf(stderr, "%*c%s _gather_133[%d-%d]: %s failed!\n", p->level, ' ', +- p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "star_target _loop0_134")); ++ D(fprintf(stderr, "%*c%s _gather_135[%d-%d]: %s failed!\n", p->level, ' ', ++ p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "star_target _loop0_136")); + } + _res = NULL; + done: +@@ -33184,9 +33783,9 @@ _gather_133_rule(Parser *p) + return _res; + } + +-// _loop1_135: (',' star_target) ++// _loop1_137: (',' star_target) + static asdl_seq * +-_loop1_135_rule(Parser *p) ++_loop1_137_rule(Parser *p) + { + if (p->level++ == MAXSTACK) { + p->error_indicator = 1; +@@ -33212,13 +33811,13 @@ _loop1_135_rule(Parser *p) + p->level--; + return NULL; + } +- D(fprintf(stderr, "%*c> _loop1_135[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "(',' star_target)")); +- void *_tmp_258_var; ++ D(fprintf(stderr, "%*c> _loop1_137[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "(',' star_target)")); ++ void *_tmp_260_var; + while ( +- (_tmp_258_var = _tmp_258_rule(p)) // ',' star_target ++ (_tmp_260_var = _tmp_260_rule(p)) // ',' star_target + ) + { +- _res = _tmp_258_var; ++ _res = _tmp_260_var; + if (_n == _children_capacity) { + _children_capacity *= 2; + void **_new_children = PyMem_Realloc(_children, _children_capacity*sizeof(void *)); +@@ -33235,7 +33834,7 @@ _loop1_135_rule(Parser *p) + _mark = p->mark; + } + p->mark = _mark; +- D(fprintf(stderr, "%*c%s _loop1_135[%d-%d]: %s failed!\n", p->level, ' ', ++ D(fprintf(stderr, "%*c%s _loop1_137[%d-%d]: %s failed!\n", p->level, ' ', + p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "(',' star_target)")); + } + if (_n == 0 || p->error_indicator) { +@@ -33257,9 +33856,9 @@ _loop1_135_rule(Parser *p) + return _seq; + } + +-// _tmp_136: !'*' star_target ++// _tmp_138: !'*' star_target + static void * +-_tmp_136_rule(Parser *p) ++_tmp_138_rule(Parser *p) + { + if (p->level++ == MAXSTACK) { + p->error_indicator = 1; +@@ -33276,7 +33875,7 @@ _tmp_136_rule(Parser *p) + p->level--; + return NULL; + } +- D(fprintf(stderr, "%*c> _tmp_136[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "!'*' star_target")); ++ D(fprintf(stderr, "%*c> _tmp_138[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "!'*' star_target")); + expr_ty star_target_var; + if ( + _PyPegen_lookahead_with_int(0, _PyPegen_expect_token, p, 16) // token='*' +@@ -33284,12 +33883,12 @@ _tmp_136_rule(Parser *p) + (star_target_var = star_target_rule(p)) // star_target + ) + { +- D(fprintf(stderr, "%*c+ _tmp_136[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "!'*' star_target")); ++ D(fprintf(stderr, "%*c+ _tmp_138[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "!'*' star_target")); + _res = star_target_var; + goto done; + } + p->mark = _mark; +- D(fprintf(stderr, "%*c%s _tmp_136[%d-%d]: %s failed!\n", p->level, ' ', ++ D(fprintf(stderr, "%*c%s _tmp_138[%d-%d]: %s failed!\n", p->level, ' ', + p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "!'*' star_target")); + } + _res = NULL; +@@ -33298,9 +33897,9 @@ _tmp_136_rule(Parser *p) + return _res; + } + +-// _loop0_138: ',' del_target ++// _loop0_140: ',' del_target + static asdl_seq * +-_loop0_138_rule(Parser *p) ++_loop0_140_rule(Parser *p) + { + if (p->level++ == MAXSTACK) { + p->error_indicator = 1; +@@ -33326,7 +33925,7 @@ _loop0_138_rule(Parser *p) + p->level--; + return NULL; + } +- D(fprintf(stderr, "%*c> _loop0_138[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "',' del_target")); ++ D(fprintf(stderr, "%*c> _loop0_140[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "',' del_target")); + Token * _literal; + expr_ty elem; + while ( +@@ -33358,7 +33957,7 @@ _loop0_138_rule(Parser *p) + _mark = p->mark; + } + p->mark = _mark; +- D(fprintf(stderr, "%*c%s _loop0_138[%d-%d]: %s failed!\n", p->level, ' ', ++ D(fprintf(stderr, "%*c%s _loop0_140[%d-%d]: %s failed!\n", p->level, ' ', + p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "',' del_target")); + } + asdl_seq *_seq = (asdl_seq*)_Py_asdl_generic_seq_new(_n, p->arena); +@@ -33375,9 +33974,9 @@ _loop0_138_rule(Parser *p) + return _seq; + } + +-// _gather_137: del_target _loop0_138 ++// _gather_139: del_target _loop0_140 + static asdl_seq * +-_gather_137_rule(Parser *p) ++_gather_139_rule(Parser *p) + { + if (p->level++ == MAXSTACK) { + p->error_indicator = 1; +@@ -33389,27 +33988,27 @@ _gather_137_rule(Parser *p) + } + asdl_seq * _res = NULL; + int _mark = p->mark; +- { // del_target _loop0_138 ++ { // del_target _loop0_140 + if (p->error_indicator) { + p->level--; + return NULL; + } +- D(fprintf(stderr, "%*c> _gather_137[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "del_target _loop0_138")); ++ D(fprintf(stderr, "%*c> _gather_139[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "del_target _loop0_140")); + expr_ty elem; + asdl_seq * seq; + if ( + (elem = del_target_rule(p)) // del_target + && +- (seq = _loop0_138_rule(p)) // _loop0_138 ++ (seq = _loop0_140_rule(p)) // _loop0_140 + ) + { +- D(fprintf(stderr, "%*c+ _gather_137[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "del_target _loop0_138")); ++ D(fprintf(stderr, "%*c+ _gather_139[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "del_target _loop0_140")); + _res = _PyPegen_seq_insert_in_front(p, elem, seq); + goto done; + } + p->mark = _mark; +- D(fprintf(stderr, "%*c%s _gather_137[%d-%d]: %s failed!\n", p->level, ' ', +- p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "del_target _loop0_138")); ++ D(fprintf(stderr, "%*c%s _gather_139[%d-%d]: %s failed!\n", p->level, ' ', ++ p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "del_target _loop0_140")); + } + _res = NULL; + done: +@@ -33417,9 +34016,9 @@ _gather_137_rule(Parser *p) + return _res; + } + +-// _loop0_140: ',' expression ++// _loop0_142: ',' expression + static asdl_seq * +-_loop0_140_rule(Parser *p) ++_loop0_142_rule(Parser *p) + { + if (p->level++ == MAXSTACK) { + p->error_indicator = 1; +@@ -33445,7 +34044,7 @@ _loop0_140_rule(Parser *p) + p->level--; + return NULL; + } +- D(fprintf(stderr, "%*c> _loop0_140[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "',' expression")); ++ D(fprintf(stderr, "%*c> _loop0_142[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "',' expression")); + Token * _literal; + expr_ty elem; + while ( +@@ -33477,7 +34076,7 @@ _loop0_140_rule(Parser *p) + _mark = p->mark; + } + p->mark = _mark; +- D(fprintf(stderr, "%*c%s _loop0_140[%d-%d]: %s failed!\n", p->level, ' ', ++ D(fprintf(stderr, "%*c%s _loop0_142[%d-%d]: %s failed!\n", p->level, ' ', + p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "',' expression")); + } + asdl_seq *_seq = (asdl_seq*)_Py_asdl_generic_seq_new(_n, p->arena); +@@ -33494,9 +34093,9 @@ _loop0_140_rule(Parser *p) + return _seq; + } + +-// _gather_139: expression _loop0_140 ++// _gather_141: expression _loop0_142 + static asdl_seq * +-_gather_139_rule(Parser *p) ++_gather_141_rule(Parser *p) + { + if (p->level++ == MAXSTACK) { + p->error_indicator = 1; +@@ -33508,27 +34107,27 @@ _gather_139_rule(Parser *p) + } + asdl_seq * _res = NULL; + int _mark = p->mark; +- { // expression _loop0_140 ++ { // expression _loop0_142 + if (p->error_indicator) { + p->level--; + return NULL; + } +- D(fprintf(stderr, "%*c> _gather_139[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "expression _loop0_140")); ++ D(fprintf(stderr, "%*c> _gather_141[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "expression _loop0_142")); + expr_ty elem; + asdl_seq * seq; + if ( + (elem = expression_rule(p)) // expression + && +- (seq = _loop0_140_rule(p)) // _loop0_140 ++ (seq = _loop0_142_rule(p)) // _loop0_142 + ) + { +- D(fprintf(stderr, "%*c+ _gather_139[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "expression _loop0_140")); ++ D(fprintf(stderr, "%*c+ _gather_141[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "expression _loop0_142")); + _res = _PyPegen_seq_insert_in_front(p, elem, seq); + goto done; + } + p->mark = _mark; +- D(fprintf(stderr, "%*c%s _gather_139[%d-%d]: %s failed!\n", p->level, ' ', +- p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "expression _loop0_140")); ++ D(fprintf(stderr, "%*c%s _gather_141[%d-%d]: %s failed!\n", p->level, ' ', ++ p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "expression _loop0_142")); + } + _res = NULL; + done: +@@ -33536,9 +34135,9 @@ _gather_139_rule(Parser *p) + return _res; + } + +-// _loop0_142: ',' expression ++// _loop0_144: ',' expression + static asdl_seq * +-_loop0_142_rule(Parser *p) ++_loop0_144_rule(Parser *p) + { + if (p->level++ == MAXSTACK) { + p->error_indicator = 1; +@@ -33564,7 +34163,7 @@ _loop0_142_rule(Parser *p) + p->level--; + return NULL; + } +- D(fprintf(stderr, "%*c> _loop0_142[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "',' expression")); ++ D(fprintf(stderr, "%*c> _loop0_144[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "',' expression")); + Token * _literal; + expr_ty elem; + while ( +@@ -33596,7 +34195,7 @@ _loop0_142_rule(Parser *p) + _mark = p->mark; + } + p->mark = _mark; +- D(fprintf(stderr, "%*c%s _loop0_142[%d-%d]: %s failed!\n", p->level, ' ', ++ D(fprintf(stderr, "%*c%s _loop0_144[%d-%d]: %s failed!\n", p->level, ' ', + p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "',' expression")); + } + asdl_seq *_seq = (asdl_seq*)_Py_asdl_generic_seq_new(_n, p->arena); +@@ -33613,9 +34212,9 @@ _loop0_142_rule(Parser *p) + return _seq; + } + +-// _gather_141: expression _loop0_142 ++// _gather_143: expression _loop0_144 + static asdl_seq * +-_gather_141_rule(Parser *p) ++_gather_143_rule(Parser *p) + { + if (p->level++ == MAXSTACK) { + p->error_indicator = 1; +@@ -33627,27 +34226,27 @@ _gather_141_rule(Parser *p) + } + asdl_seq * _res = NULL; + int _mark = p->mark; +- { // expression _loop0_142 ++ { // expression _loop0_144 + if (p->error_indicator) { + p->level--; + return NULL; + } +- D(fprintf(stderr, "%*c> _gather_141[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "expression _loop0_142")); ++ D(fprintf(stderr, "%*c> _gather_143[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "expression _loop0_144")); + expr_ty elem; + asdl_seq * seq; + if ( + (elem = expression_rule(p)) // expression + && +- (seq = _loop0_142_rule(p)) // _loop0_142 ++ (seq = _loop0_144_rule(p)) // _loop0_144 + ) + { +- D(fprintf(stderr, "%*c+ _gather_141[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "expression _loop0_142")); ++ D(fprintf(stderr, "%*c+ _gather_143[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "expression _loop0_144")); + _res = _PyPegen_seq_insert_in_front(p, elem, seq); + goto done; + } + p->mark = _mark; +- D(fprintf(stderr, "%*c%s _gather_141[%d-%d]: %s failed!\n", p->level, ' ', +- p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "expression _loop0_142")); ++ D(fprintf(stderr, "%*c%s _gather_143[%d-%d]: %s failed!\n", p->level, ' ', ++ p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "expression _loop0_144")); + } + _res = NULL; + done: +@@ -33655,9 +34254,9 @@ _gather_141_rule(Parser *p) + return _res; + } + +-// _loop0_144: ',' expression ++// _loop0_146: ',' expression + static asdl_seq * +-_loop0_144_rule(Parser *p) ++_loop0_146_rule(Parser *p) + { + if (p->level++ == MAXSTACK) { + p->error_indicator = 1; +@@ -33683,7 +34282,7 @@ _loop0_144_rule(Parser *p) + p->level--; + return NULL; + } +- D(fprintf(stderr, "%*c> _loop0_144[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "',' expression")); ++ D(fprintf(stderr, "%*c> _loop0_146[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "',' expression")); + Token * _literal; + expr_ty elem; + while ( +@@ -33715,7 +34314,7 @@ _loop0_144_rule(Parser *p) + _mark = p->mark; + } + p->mark = _mark; +- D(fprintf(stderr, "%*c%s _loop0_144[%d-%d]: %s failed!\n", p->level, ' ', ++ D(fprintf(stderr, "%*c%s _loop0_146[%d-%d]: %s failed!\n", p->level, ' ', + p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "',' expression")); + } + asdl_seq *_seq = (asdl_seq*)_Py_asdl_generic_seq_new(_n, p->arena); +@@ -33732,9 +34331,9 @@ _loop0_144_rule(Parser *p) + return _seq; + } + +-// _gather_143: expression _loop0_144 ++// _gather_145: expression _loop0_146 + static asdl_seq * +-_gather_143_rule(Parser *p) ++_gather_145_rule(Parser *p) + { + if (p->level++ == MAXSTACK) { + p->error_indicator = 1; +@@ -33746,27 +34345,27 @@ _gather_143_rule(Parser *p) + } + asdl_seq * _res = NULL; + int _mark = p->mark; +- { // expression _loop0_144 ++ { // expression _loop0_146 + if (p->error_indicator) { + p->level--; + return NULL; + } +- D(fprintf(stderr, "%*c> _gather_143[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "expression _loop0_144")); ++ D(fprintf(stderr, "%*c> _gather_145[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "expression _loop0_146")); + expr_ty elem; + asdl_seq * seq; + if ( + (elem = expression_rule(p)) // expression + && +- (seq = _loop0_144_rule(p)) // _loop0_144 ++ (seq = _loop0_146_rule(p)) // _loop0_146 + ) + { +- D(fprintf(stderr, "%*c+ _gather_143[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "expression _loop0_144")); ++ D(fprintf(stderr, "%*c+ _gather_145[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "expression _loop0_146")); + _res = _PyPegen_seq_insert_in_front(p, elem, seq); + goto done; + } + p->mark = _mark; +- D(fprintf(stderr, "%*c%s _gather_143[%d-%d]: %s failed!\n", p->level, ' ', +- p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "expression _loop0_144")); ++ D(fprintf(stderr, "%*c%s _gather_145[%d-%d]: %s failed!\n", p->level, ' ', ++ p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "expression _loop0_146")); + } + _res = NULL; + done: +@@ -33774,9 +34373,9 @@ _gather_143_rule(Parser *p) + return _res; + } + +-// _loop0_146: ',' expression ++// _loop0_148: ',' expression + static asdl_seq * +-_loop0_146_rule(Parser *p) ++_loop0_148_rule(Parser *p) + { + if (p->level++ == MAXSTACK) { + p->error_indicator = 1; +@@ -33802,7 +34401,7 @@ _loop0_146_rule(Parser *p) + p->level--; + return NULL; + } +- D(fprintf(stderr, "%*c> _loop0_146[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "',' expression")); ++ D(fprintf(stderr, "%*c> _loop0_148[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "',' expression")); + Token * _literal; + expr_ty elem; + while ( +@@ -33834,7 +34433,7 @@ _loop0_146_rule(Parser *p) + _mark = p->mark; + } + p->mark = _mark; +- D(fprintf(stderr, "%*c%s _loop0_146[%d-%d]: %s failed!\n", p->level, ' ', ++ D(fprintf(stderr, "%*c%s _loop0_148[%d-%d]: %s failed!\n", p->level, ' ', + p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "',' expression")); + } + asdl_seq *_seq = (asdl_seq*)_Py_asdl_generic_seq_new(_n, p->arena); +@@ -33851,9 +34450,9 @@ _loop0_146_rule(Parser *p) + return _seq; + } + +-// _gather_145: expression _loop0_146 ++// _gather_147: expression _loop0_148 + static asdl_seq * +-_gather_145_rule(Parser *p) ++_gather_147_rule(Parser *p) + { + if (p->level++ == MAXSTACK) { + p->error_indicator = 1; +@@ -33865,27 +34464,27 @@ _gather_145_rule(Parser *p) + } + asdl_seq * _res = NULL; + int _mark = p->mark; +- { // expression _loop0_146 ++ { // expression _loop0_148 + if (p->error_indicator) { + p->level--; + return NULL; + } +- D(fprintf(stderr, "%*c> _gather_145[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "expression _loop0_146")); ++ D(fprintf(stderr, "%*c> _gather_147[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "expression _loop0_148")); + expr_ty elem; + asdl_seq * seq; + if ( + (elem = expression_rule(p)) // expression + && +- (seq = _loop0_146_rule(p)) // _loop0_146 ++ (seq = _loop0_148_rule(p)) // _loop0_148 + ) + { +- D(fprintf(stderr, "%*c+ _gather_145[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "expression _loop0_146")); ++ D(fprintf(stderr, "%*c+ _gather_147[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "expression _loop0_148")); + _res = _PyPegen_seq_insert_in_front(p, elem, seq); + goto done; + } + p->mark = _mark; +- D(fprintf(stderr, "%*c%s _gather_145[%d-%d]: %s failed!\n", p->level, ' ', +- p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "expression _loop0_146")); ++ D(fprintf(stderr, "%*c%s _gather_147[%d-%d]: %s failed!\n", p->level, ' ', ++ p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "expression _loop0_148")); + } + _res = NULL; + done: +@@ -33893,9 +34492,9 @@ _gather_145_rule(Parser *p) + return _res; + } + +-// _tmp_147: NEWLINE INDENT ++// _tmp_149: NEWLINE INDENT + static void * +-_tmp_147_rule(Parser *p) ++_tmp_149_rule(Parser *p) + { + if (p->level++ == MAXSTACK) { + p->error_indicator = 1; +@@ -33912,7 +34511,7 @@ _tmp_147_rule(Parser *p) + p->level--; + return NULL; + } +- D(fprintf(stderr, "%*c> _tmp_147[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "NEWLINE INDENT")); ++ D(fprintf(stderr, "%*c> _tmp_149[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "NEWLINE INDENT")); + Token * indent_var; + Token * newline_var; + if ( +@@ -33921,12 +34520,12 @@ _tmp_147_rule(Parser *p) + (indent_var = _PyPegen_expect_token(p, INDENT)) // token='INDENT' + ) + { +- D(fprintf(stderr, "%*c+ _tmp_147[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "NEWLINE INDENT")); ++ D(fprintf(stderr, "%*c+ _tmp_149[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "NEWLINE INDENT")); + _res = _PyPegen_dummy_name(p, newline_var, indent_var); + goto done; + } + p->mark = _mark; +- D(fprintf(stderr, "%*c%s _tmp_147[%d-%d]: %s failed!\n", p->level, ' ', ++ D(fprintf(stderr, "%*c%s _tmp_149[%d-%d]: %s failed!\n", p->level, ' ', + p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "NEWLINE INDENT")); + } + _res = NULL; +@@ -33935,9 +34534,9 @@ _tmp_147_rule(Parser *p) + return _res; + } + +-// _tmp_148: args | expression for_if_clauses ++// _tmp_150: args | expression for_if_clauses + static void * +-_tmp_148_rule(Parser *p) ++_tmp_150_rule(Parser *p) + { + if (p->level++ == MAXSTACK) { + p->error_indicator = 1; +@@ -33954,18 +34553,18 @@ _tmp_148_rule(Parser *p) + p->level--; + return NULL; + } +- D(fprintf(stderr, "%*c> _tmp_148[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "args")); ++ D(fprintf(stderr, "%*c> _tmp_150[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "args")); + expr_ty args_var; + if ( + (args_var = args_rule(p)) // args + ) + { +- D(fprintf(stderr, "%*c+ _tmp_148[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "args")); ++ D(fprintf(stderr, "%*c+ _tmp_150[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "args")); + _res = args_var; + goto done; + } + p->mark = _mark; +- D(fprintf(stderr, "%*c%s _tmp_148[%d-%d]: %s failed!\n", p->level, ' ', ++ D(fprintf(stderr, "%*c%s _tmp_150[%d-%d]: %s failed!\n", p->level, ' ', + p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "args")); + } + { // expression for_if_clauses +@@ -33973,7 +34572,7 @@ _tmp_148_rule(Parser *p) + p->level--; + return NULL; + } +- D(fprintf(stderr, "%*c> _tmp_148[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "expression for_if_clauses")); ++ D(fprintf(stderr, "%*c> _tmp_150[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "expression for_if_clauses")); + expr_ty expression_var; + asdl_comprehension_seq* for_if_clauses_var; + if ( +@@ -33982,12 +34581,12 @@ _tmp_148_rule(Parser *p) + (for_if_clauses_var = for_if_clauses_rule(p)) // for_if_clauses + ) + { +- D(fprintf(stderr, "%*c+ _tmp_148[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "expression for_if_clauses")); ++ D(fprintf(stderr, "%*c+ _tmp_150[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "expression for_if_clauses")); + _res = _PyPegen_dummy_name(p, expression_var, for_if_clauses_var); + goto done; + } + p->mark = _mark; +- D(fprintf(stderr, "%*c%s _tmp_148[%d-%d]: %s failed!\n", p->level, ' ', ++ D(fprintf(stderr, "%*c%s _tmp_150[%d-%d]: %s failed!\n", p->level, ' ', + p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "expression for_if_clauses")); + } + _res = NULL; +@@ -33996,9 +34595,9 @@ _tmp_148_rule(Parser *p) + return _res; + } + +-// _tmp_149: args ',' ++// _tmp_151: args ',' + static void * +-_tmp_149_rule(Parser *p) ++_tmp_151_rule(Parser *p) + { + if (p->level++ == MAXSTACK) { + p->error_indicator = 1; +@@ -34015,7 +34614,7 @@ _tmp_149_rule(Parser *p) + p->level--; + return NULL; + } +- D(fprintf(stderr, "%*c> _tmp_149[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "args ','")); ++ D(fprintf(stderr, "%*c> _tmp_151[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "args ','")); + Token * _literal; + expr_ty args_var; + if ( +@@ -34024,12 +34623,12 @@ _tmp_149_rule(Parser *p) + (_literal = _PyPegen_expect_token(p, 12)) // token=',' + ) + { +- D(fprintf(stderr, "%*c+ _tmp_149[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "args ','")); ++ D(fprintf(stderr, "%*c+ _tmp_151[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "args ','")); + _res = _PyPegen_dummy_name(p, args_var, _literal); + goto done; + } + p->mark = _mark; +- D(fprintf(stderr, "%*c%s _tmp_149[%d-%d]: %s failed!\n", p->level, ' ', ++ D(fprintf(stderr, "%*c%s _tmp_151[%d-%d]: %s failed!\n", p->level, ' ', + p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "args ','")); + } + _res = NULL; +@@ -34038,9 +34637,9 @@ _tmp_149_rule(Parser *p) + return _res; + } + +-// _tmp_150: ',' | ')' ++// _tmp_152: ',' | ')' + static void * +-_tmp_150_rule(Parser *p) ++_tmp_152_rule(Parser *p) + { + if (p->level++ == MAXSTACK) { + p->error_indicator = 1; +@@ -34057,18 +34656,18 @@ _tmp_150_rule(Parser *p) + p->level--; + return NULL; + } +- D(fprintf(stderr, "%*c> _tmp_150[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "','")); ++ D(fprintf(stderr, "%*c> _tmp_152[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "','")); + Token * _literal; + if ( + (_literal = _PyPegen_expect_token(p, 12)) // token=',' + ) + { +- D(fprintf(stderr, "%*c+ _tmp_150[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "','")); ++ D(fprintf(stderr, "%*c+ _tmp_152[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "','")); + _res = _literal; + goto done; + } + p->mark = _mark; +- D(fprintf(stderr, "%*c%s _tmp_150[%d-%d]: %s failed!\n", p->level, ' ', ++ D(fprintf(stderr, "%*c%s _tmp_152[%d-%d]: %s failed!\n", p->level, ' ', + p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "','")); + } + { // ')' +@@ -34076,18 +34675,18 @@ _tmp_150_rule(Parser *p) + p->level--; + return NULL; + } +- D(fprintf(stderr, "%*c> _tmp_150[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "')'")); ++ D(fprintf(stderr, "%*c> _tmp_152[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "')'")); + Token * _literal; + if ( + (_literal = _PyPegen_expect_token(p, 8)) // token=')' + ) + { +- D(fprintf(stderr, "%*c+ _tmp_150[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "')'")); ++ D(fprintf(stderr, "%*c+ _tmp_152[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "')'")); + _res = _literal; + goto done; + } + p->mark = _mark; +- D(fprintf(stderr, "%*c%s _tmp_150[%d-%d]: %s failed!\n", p->level, ' ', ++ D(fprintf(stderr, "%*c%s _tmp_152[%d-%d]: %s failed!\n", p->level, ' ', + p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "')'")); + } + _res = NULL; +@@ -34096,9 +34695,9 @@ _tmp_150_rule(Parser *p) + return _res; + } + +-// _tmp_151: 'True' | 'False' | 'None' ++// _tmp_153: 'True' | 'False' | 'None' + static void * +-_tmp_151_rule(Parser *p) ++_tmp_153_rule(Parser *p) + { + if (p->level++ == MAXSTACK) { + p->error_indicator = 1; +@@ -34115,18 +34714,18 @@ _tmp_151_rule(Parser *p) + p->level--; + return NULL; + } +- D(fprintf(stderr, "%*c> _tmp_151[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "'True'")); ++ D(fprintf(stderr, "%*c> _tmp_153[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "'True'")); + Token * _keyword; + if ( + (_keyword = _PyPegen_expect_token(p, 601)) // token='True' + ) + { +- D(fprintf(stderr, "%*c+ _tmp_151[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "'True'")); ++ D(fprintf(stderr, "%*c+ _tmp_153[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "'True'")); + _res = _keyword; + goto done; + } + p->mark = _mark; +- D(fprintf(stderr, "%*c%s _tmp_151[%d-%d]: %s failed!\n", p->level, ' ', ++ D(fprintf(stderr, "%*c%s _tmp_153[%d-%d]: %s failed!\n", p->level, ' ', + p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "'True'")); + } + { // 'False' +@@ -34134,18 +34733,18 @@ _tmp_151_rule(Parser *p) + p->level--; + return NULL; + } +- D(fprintf(stderr, "%*c> _tmp_151[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "'False'")); ++ D(fprintf(stderr, "%*c> _tmp_153[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "'False'")); + Token * _keyword; + if ( + (_keyword = _PyPegen_expect_token(p, 603)) // token='False' + ) + { +- D(fprintf(stderr, "%*c+ _tmp_151[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "'False'")); ++ D(fprintf(stderr, "%*c+ _tmp_153[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "'False'")); + _res = _keyword; + goto done; + } + p->mark = _mark; +- D(fprintf(stderr, "%*c%s _tmp_151[%d-%d]: %s failed!\n", p->level, ' ', ++ D(fprintf(stderr, "%*c%s _tmp_153[%d-%d]: %s failed!\n", p->level, ' ', + p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "'False'")); + } + { // 'None' +@@ -34153,18 +34752,18 @@ _tmp_151_rule(Parser *p) + p->level--; + return NULL; + } +- D(fprintf(stderr, "%*c> _tmp_151[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "'None'")); ++ D(fprintf(stderr, "%*c> _tmp_153[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "'None'")); + Token * _keyword; + if ( + (_keyword = _PyPegen_expect_token(p, 602)) // token='None' + ) + { +- D(fprintf(stderr, "%*c+ _tmp_151[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "'None'")); ++ D(fprintf(stderr, "%*c+ _tmp_153[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "'None'")); + _res = _keyword; + goto done; + } + p->mark = _mark; +- D(fprintf(stderr, "%*c%s _tmp_151[%d-%d]: %s failed!\n", p->level, ' ', ++ D(fprintf(stderr, "%*c%s _tmp_153[%d-%d]: %s failed!\n", p->level, ' ', + p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "'None'")); + } + _res = NULL; +@@ -34173,9 +34772,9 @@ _tmp_151_rule(Parser *p) + return _res; + } + +-// _tmp_152: NAME '=' ++// _tmp_154: NAME '=' + static void * +-_tmp_152_rule(Parser *p) ++_tmp_154_rule(Parser *p) + { + if (p->level++ == MAXSTACK) { + p->error_indicator = 1; +@@ -34192,7 +34791,7 @@ _tmp_152_rule(Parser *p) + p->level--; + return NULL; + } +- D(fprintf(stderr, "%*c> _tmp_152[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "NAME '='")); ++ D(fprintf(stderr, "%*c> _tmp_154[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "NAME '='")); + Token * _literal; + expr_ty name_var; + if ( +@@ -34201,12 +34800,12 @@ _tmp_152_rule(Parser *p) + (_literal = _PyPegen_expect_token(p, 22)) // token='=' + ) + { +- D(fprintf(stderr, "%*c+ _tmp_152[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "NAME '='")); ++ D(fprintf(stderr, "%*c+ _tmp_154[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "NAME '='")); + _res = _PyPegen_dummy_name(p, name_var, _literal); + goto done; + } + p->mark = _mark; +- D(fprintf(stderr, "%*c%s _tmp_152[%d-%d]: %s failed!\n", p->level, ' ', ++ D(fprintf(stderr, "%*c%s _tmp_154[%d-%d]: %s failed!\n", p->level, ' ', + p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "NAME '='")); + } + _res = NULL; +@@ -34215,9 +34814,9 @@ _tmp_152_rule(Parser *p) + return _res; + } + +-// _tmp_153: NAME STRING | SOFT_KEYWORD ++// _tmp_155: NAME STRING | SOFT_KEYWORD + static void * +-_tmp_153_rule(Parser *p) ++_tmp_155_rule(Parser *p) + { + if (p->level++ == MAXSTACK) { + p->error_indicator = 1; +@@ -34234,7 +34833,7 @@ _tmp_153_rule(Parser *p) + p->level--; + return NULL; + } +- D(fprintf(stderr, "%*c> _tmp_153[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "NAME STRING")); ++ D(fprintf(stderr, "%*c> _tmp_155[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "NAME STRING")); + expr_ty name_var; + expr_ty string_var; + if ( +@@ -34243,12 +34842,12 @@ _tmp_153_rule(Parser *p) + (string_var = _PyPegen_string_token(p)) // STRING + ) + { +- D(fprintf(stderr, "%*c+ _tmp_153[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "NAME STRING")); ++ D(fprintf(stderr, "%*c+ _tmp_155[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "NAME STRING")); + _res = _PyPegen_dummy_name(p, name_var, string_var); + goto done; + } + p->mark = _mark; +- D(fprintf(stderr, "%*c%s _tmp_153[%d-%d]: %s failed!\n", p->level, ' ', ++ D(fprintf(stderr, "%*c%s _tmp_155[%d-%d]: %s failed!\n", p->level, ' ', + p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "NAME STRING")); + } + { // SOFT_KEYWORD +@@ -34256,18 +34855,18 @@ _tmp_153_rule(Parser *p) + p->level--; + return NULL; + } +- D(fprintf(stderr, "%*c> _tmp_153[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "SOFT_KEYWORD")); ++ D(fprintf(stderr, "%*c> _tmp_155[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "SOFT_KEYWORD")); + expr_ty soft_keyword_var; + if ( + (soft_keyword_var = _PyPegen_soft_keyword_token(p)) // SOFT_KEYWORD + ) + { +- D(fprintf(stderr, "%*c+ _tmp_153[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "SOFT_KEYWORD")); ++ D(fprintf(stderr, "%*c+ _tmp_155[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "SOFT_KEYWORD")); + _res = soft_keyword_var; + goto done; + } + p->mark = _mark; +- D(fprintf(stderr, "%*c%s _tmp_153[%d-%d]: %s failed!\n", p->level, ' ', ++ D(fprintf(stderr, "%*c%s _tmp_155[%d-%d]: %s failed!\n", p->level, ' ', + p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "SOFT_KEYWORD")); + } + _res = NULL; +@@ -34276,9 +34875,9 @@ _tmp_153_rule(Parser *p) + return _res; + } + +-// _tmp_154: 'else' | ':' ++// _tmp_156: 'else' | ':' + static void * +-_tmp_154_rule(Parser *p) ++_tmp_156_rule(Parser *p) + { + if (p->level++ == MAXSTACK) { + p->error_indicator = 1; +@@ -34295,18 +34894,18 @@ _tmp_154_rule(Parser *p) + p->level--; + return NULL; + } +- D(fprintf(stderr, "%*c> _tmp_154[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "'else'")); ++ D(fprintf(stderr, "%*c> _tmp_156[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "'else'")); + Token * _keyword; + if ( + (_keyword = _PyPegen_expect_token(p, 645)) // token='else' + ) + { +- D(fprintf(stderr, "%*c+ _tmp_154[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "'else'")); ++ D(fprintf(stderr, "%*c+ _tmp_156[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "'else'")); + _res = _keyword; + goto done; + } + p->mark = _mark; +- D(fprintf(stderr, "%*c%s _tmp_154[%d-%d]: %s failed!\n", p->level, ' ', ++ D(fprintf(stderr, "%*c%s _tmp_156[%d-%d]: %s failed!\n", p->level, ' ', + p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "'else'")); + } + { // ':' +@@ -34314,18 +34913,18 @@ _tmp_154_rule(Parser *p) + p->level--; + return NULL; + } +- D(fprintf(stderr, "%*c> _tmp_154[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "':'")); ++ D(fprintf(stderr, "%*c> _tmp_156[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "':'")); + Token * _literal; + if ( + (_literal = _PyPegen_expect_token(p, 11)) // token=':' + ) + { +- D(fprintf(stderr, "%*c+ _tmp_154[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "':'")); ++ D(fprintf(stderr, "%*c+ _tmp_156[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "':'")); + _res = _literal; + goto done; + } + p->mark = _mark; +- D(fprintf(stderr, "%*c%s _tmp_154[%d-%d]: %s failed!\n", p->level, ' ', ++ D(fprintf(stderr, "%*c%s _tmp_156[%d-%d]: %s failed!\n", p->level, ' ', + p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "':'")); + } + _res = NULL; +@@ -34334,9 +34933,9 @@ _tmp_154_rule(Parser *p) + return _res; + } + +-// _tmp_155: FSTRING_MIDDLE | fstring_replacement_field ++// _tmp_157: FSTRING_MIDDLE | fstring_replacement_field + static void * +-_tmp_155_rule(Parser *p) ++_tmp_157_rule(Parser *p) + { + if (p->level++ == MAXSTACK) { + p->error_indicator = 1; +@@ -34353,18 +34952,18 @@ _tmp_155_rule(Parser *p) + p->level--; + return NULL; + } +- D(fprintf(stderr, "%*c> _tmp_155[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "FSTRING_MIDDLE")); ++ D(fprintf(stderr, "%*c> _tmp_157[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "FSTRING_MIDDLE")); + Token * fstring_middle_var; + if ( + (fstring_middle_var = _PyPegen_expect_token(p, FSTRING_MIDDLE)) // token='FSTRING_MIDDLE' + ) + { +- D(fprintf(stderr, "%*c+ _tmp_155[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "FSTRING_MIDDLE")); ++ D(fprintf(stderr, "%*c+ _tmp_157[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "FSTRING_MIDDLE")); + _res = fstring_middle_var; + goto done; + } + p->mark = _mark; +- D(fprintf(stderr, "%*c%s _tmp_155[%d-%d]: %s failed!\n", p->level, ' ', ++ D(fprintf(stderr, "%*c%s _tmp_157[%d-%d]: %s failed!\n", p->level, ' ', + p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "FSTRING_MIDDLE")); + } + { // fstring_replacement_field +@@ -34372,18 +34971,18 @@ _tmp_155_rule(Parser *p) + p->level--; + return NULL; + } +- D(fprintf(stderr, "%*c> _tmp_155[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "fstring_replacement_field")); ++ D(fprintf(stderr, "%*c> _tmp_157[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "fstring_replacement_field")); + expr_ty fstring_replacement_field_var; + if ( + (fstring_replacement_field_var = fstring_replacement_field_rule(p)) // fstring_replacement_field + ) + { +- D(fprintf(stderr, "%*c+ _tmp_155[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "fstring_replacement_field")); ++ D(fprintf(stderr, "%*c+ _tmp_157[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "fstring_replacement_field")); + _res = fstring_replacement_field_var; + goto done; + } + p->mark = _mark; +- D(fprintf(stderr, "%*c%s _tmp_155[%d-%d]: %s failed!\n", p->level, ' ', ++ D(fprintf(stderr, "%*c%s _tmp_157[%d-%d]: %s failed!\n", p->level, ' ', + p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "fstring_replacement_field")); + } + _res = NULL; +@@ -34392,9 +34991,9 @@ _tmp_155_rule(Parser *p) + return _res; + } + +-// _tmp_156: '=' | ':=' ++// _tmp_158: '=' | ':=' + static void * +-_tmp_156_rule(Parser *p) ++_tmp_158_rule(Parser *p) + { + if (p->level++ == MAXSTACK) { + p->error_indicator = 1; +@@ -34411,18 +35010,18 @@ _tmp_156_rule(Parser *p) + p->level--; + return NULL; + } +- D(fprintf(stderr, "%*c> _tmp_156[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "'='")); ++ D(fprintf(stderr, "%*c> _tmp_158[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "'='")); + Token * _literal; + if ( + (_literal = _PyPegen_expect_token(p, 22)) // token='=' + ) + { +- D(fprintf(stderr, "%*c+ _tmp_156[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "'='")); ++ D(fprintf(stderr, "%*c+ _tmp_158[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "'='")); + _res = _literal; + goto done; + } + p->mark = _mark; +- D(fprintf(stderr, "%*c%s _tmp_156[%d-%d]: %s failed!\n", p->level, ' ', ++ D(fprintf(stderr, "%*c%s _tmp_158[%d-%d]: %s failed!\n", p->level, ' ', + p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "'='")); + } + { // ':=' +@@ -34430,18 +35029,18 @@ _tmp_156_rule(Parser *p) + p->level--; + return NULL; + } +- D(fprintf(stderr, "%*c> _tmp_156[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "':='")); ++ D(fprintf(stderr, "%*c> _tmp_158[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "':='")); + Token * _literal; + if ( + (_literal = _PyPegen_expect_token(p, 53)) // token=':=' + ) + { +- D(fprintf(stderr, "%*c+ _tmp_156[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "':='")); ++ D(fprintf(stderr, "%*c+ _tmp_158[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "':='")); + _res = _literal; + goto done; + } + p->mark = _mark; +- D(fprintf(stderr, "%*c%s _tmp_156[%d-%d]: %s failed!\n", p->level, ' ', ++ D(fprintf(stderr, "%*c%s _tmp_158[%d-%d]: %s failed!\n", p->level, ' ', + p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "':='")); + } + _res = NULL; +@@ -34450,9 +35049,9 @@ _tmp_156_rule(Parser *p) + return _res; + } + +-// _tmp_157: list | tuple | genexp | 'True' | 'None' | 'False' ++// _tmp_159: list | tuple | genexp | 'True' | 'None' | 'False' + static void * +-_tmp_157_rule(Parser *p) ++_tmp_159_rule(Parser *p) + { + if (p->level++ == MAXSTACK) { + p->error_indicator = 1; +@@ -34469,18 +35068,18 @@ _tmp_157_rule(Parser *p) + p->level--; + return NULL; + } +- D(fprintf(stderr, "%*c> _tmp_157[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "list")); ++ D(fprintf(stderr, "%*c> _tmp_159[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "list")); + expr_ty list_var; + if ( + (list_var = list_rule(p)) // list + ) + { +- D(fprintf(stderr, "%*c+ _tmp_157[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "list")); ++ D(fprintf(stderr, "%*c+ _tmp_159[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "list")); + _res = list_var; + goto done; + } + p->mark = _mark; +- D(fprintf(stderr, "%*c%s _tmp_157[%d-%d]: %s failed!\n", p->level, ' ', ++ D(fprintf(stderr, "%*c%s _tmp_159[%d-%d]: %s failed!\n", p->level, ' ', + p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "list")); + } + { // tuple +@@ -34488,18 +35087,18 @@ _tmp_157_rule(Parser *p) + p->level--; + return NULL; + } +- D(fprintf(stderr, "%*c> _tmp_157[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "tuple")); ++ D(fprintf(stderr, "%*c> _tmp_159[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "tuple")); + expr_ty tuple_var; + if ( + (tuple_var = tuple_rule(p)) // tuple + ) + { +- D(fprintf(stderr, "%*c+ _tmp_157[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "tuple")); ++ D(fprintf(stderr, "%*c+ _tmp_159[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "tuple")); + _res = tuple_var; + goto done; + } + p->mark = _mark; +- D(fprintf(stderr, "%*c%s _tmp_157[%d-%d]: %s failed!\n", p->level, ' ', ++ D(fprintf(stderr, "%*c%s _tmp_159[%d-%d]: %s failed!\n", p->level, ' ', + p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "tuple")); + } + { // genexp +@@ -34507,18 +35106,18 @@ _tmp_157_rule(Parser *p) + p->level--; + return NULL; + } +- D(fprintf(stderr, "%*c> _tmp_157[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "genexp")); ++ D(fprintf(stderr, "%*c> _tmp_159[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "genexp")); + expr_ty genexp_var; + if ( + (genexp_var = genexp_rule(p)) // genexp + ) + { +- D(fprintf(stderr, "%*c+ _tmp_157[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "genexp")); ++ D(fprintf(stderr, "%*c+ _tmp_159[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "genexp")); + _res = genexp_var; + goto done; + } + p->mark = _mark; +- D(fprintf(stderr, "%*c%s _tmp_157[%d-%d]: %s failed!\n", p->level, ' ', ++ D(fprintf(stderr, "%*c%s _tmp_159[%d-%d]: %s failed!\n", p->level, ' ', + p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "genexp")); + } + { // 'True' +@@ -34526,18 +35125,18 @@ _tmp_157_rule(Parser *p) + p->level--; + return NULL; + } +- D(fprintf(stderr, "%*c> _tmp_157[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "'True'")); ++ D(fprintf(stderr, "%*c> _tmp_159[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "'True'")); + Token * _keyword; + if ( + (_keyword = _PyPegen_expect_token(p, 601)) // token='True' + ) + { +- D(fprintf(stderr, "%*c+ _tmp_157[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "'True'")); ++ D(fprintf(stderr, "%*c+ _tmp_159[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "'True'")); + _res = _keyword; + goto done; + } + p->mark = _mark; +- D(fprintf(stderr, "%*c%s _tmp_157[%d-%d]: %s failed!\n", p->level, ' ', ++ D(fprintf(stderr, "%*c%s _tmp_159[%d-%d]: %s failed!\n", p->level, ' ', + p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "'True'")); + } + { // 'None' +@@ -34545,18 +35144,18 @@ _tmp_157_rule(Parser *p) + p->level--; + return NULL; + } +- D(fprintf(stderr, "%*c> _tmp_157[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "'None'")); ++ D(fprintf(stderr, "%*c> _tmp_159[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "'None'")); + Token * _keyword; + if ( + (_keyword = _PyPegen_expect_token(p, 602)) // token='None' + ) + { +- D(fprintf(stderr, "%*c+ _tmp_157[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "'None'")); ++ D(fprintf(stderr, "%*c+ _tmp_159[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "'None'")); + _res = _keyword; + goto done; + } + p->mark = _mark; +- D(fprintf(stderr, "%*c%s _tmp_157[%d-%d]: %s failed!\n", p->level, ' ', ++ D(fprintf(stderr, "%*c%s _tmp_159[%d-%d]: %s failed!\n", p->level, ' ', + p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "'None'")); + } + { // 'False' +@@ -34564,18 +35163,18 @@ _tmp_157_rule(Parser *p) + p->level--; + return NULL; + } +- D(fprintf(stderr, "%*c> _tmp_157[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "'False'")); ++ D(fprintf(stderr, "%*c> _tmp_159[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "'False'")); + Token * _keyword; + if ( + (_keyword = _PyPegen_expect_token(p, 603)) // token='False' + ) + { +- D(fprintf(stderr, "%*c+ _tmp_157[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "'False'")); ++ D(fprintf(stderr, "%*c+ _tmp_159[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "'False'")); + _res = _keyword; + goto done; + } + p->mark = _mark; +- D(fprintf(stderr, "%*c%s _tmp_157[%d-%d]: %s failed!\n", p->level, ' ', ++ D(fprintf(stderr, "%*c%s _tmp_159[%d-%d]: %s failed!\n", p->level, ' ', + p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "'False'")); + } + _res = NULL; +@@ -34584,9 +35183,9 @@ _tmp_157_rule(Parser *p) + return _res; + } + +-// _tmp_158: '=' | ':=' ++// _tmp_160: '=' | ':=' + static void * +-_tmp_158_rule(Parser *p) ++_tmp_160_rule(Parser *p) + { + if (p->level++ == MAXSTACK) { + p->error_indicator = 1; +@@ -34603,18 +35202,18 @@ _tmp_158_rule(Parser *p) + p->level--; + return NULL; + } +- D(fprintf(stderr, "%*c> _tmp_158[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "'='")); ++ D(fprintf(stderr, "%*c> _tmp_160[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "'='")); + Token * _literal; + if ( + (_literal = _PyPegen_expect_token(p, 22)) // token='=' + ) + { +- D(fprintf(stderr, "%*c+ _tmp_158[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "'='")); ++ D(fprintf(stderr, "%*c+ _tmp_160[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "'='")); + _res = _literal; + goto done; + } + p->mark = _mark; +- D(fprintf(stderr, "%*c%s _tmp_158[%d-%d]: %s failed!\n", p->level, ' ', ++ D(fprintf(stderr, "%*c%s _tmp_160[%d-%d]: %s failed!\n", p->level, ' ', + p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "'='")); + } + { // ':=' +@@ -34622,18 +35221,18 @@ _tmp_158_rule(Parser *p) + p->level--; + return NULL; + } +- D(fprintf(stderr, "%*c> _tmp_158[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "':='")); ++ D(fprintf(stderr, "%*c> _tmp_160[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "':='")); + Token * _literal; + if ( + (_literal = _PyPegen_expect_token(p, 53)) // token=':=' + ) + { +- D(fprintf(stderr, "%*c+ _tmp_158[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "':='")); ++ D(fprintf(stderr, "%*c+ _tmp_160[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "':='")); + _res = _literal; + goto done; + } + p->mark = _mark; +- D(fprintf(stderr, "%*c%s _tmp_158[%d-%d]: %s failed!\n", p->level, ' ', ++ D(fprintf(stderr, "%*c%s _tmp_160[%d-%d]: %s failed!\n", p->level, ' ', + p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "':='")); + } + _res = NULL; +@@ -34642,9 +35241,9 @@ _tmp_158_rule(Parser *p) + return _res; + } + +-// _loop0_159: star_named_expressions ++// _loop0_161: star_named_expressions + static asdl_seq * +-_loop0_159_rule(Parser *p) ++_loop0_161_rule(Parser *p) + { + if (p->level++ == MAXSTACK) { + p->error_indicator = 1; +@@ -34670,7 +35269,7 @@ _loop0_159_rule(Parser *p) + p->level--; + return NULL; + } +- D(fprintf(stderr, "%*c> _loop0_159[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "star_named_expressions")); ++ D(fprintf(stderr, "%*c> _loop0_161[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "star_named_expressions")); + asdl_expr_seq* star_named_expressions_var; + while ( + (star_named_expressions_var = star_named_expressions_rule(p)) // star_named_expressions +@@ -34693,7 +35292,7 @@ _loop0_159_rule(Parser *p) + _mark = p->mark; + } + p->mark = _mark; +- D(fprintf(stderr, "%*c%s _loop0_159[%d-%d]: %s failed!\n", p->level, ' ', ++ D(fprintf(stderr, "%*c%s _loop0_161[%d-%d]: %s failed!\n", p->level, ' ', + p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "star_named_expressions")); + } + asdl_seq *_seq = (asdl_seq*)_Py_asdl_generic_seq_new(_n, p->arena); +@@ -34710,9 +35309,9 @@ _loop0_159_rule(Parser *p) + return _seq; + } + +-// _loop0_160: (star_targets '=') ++// _loop0_162: (star_targets '=') + static asdl_seq * +-_loop0_160_rule(Parser *p) ++_loop0_162_rule(Parser *p) + { + if (p->level++ == MAXSTACK) { + p->error_indicator = 1; +@@ -34738,13 +35337,13 @@ _loop0_160_rule(Parser *p) + p->level--; + return NULL; + } +- D(fprintf(stderr, "%*c> _loop0_160[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "(star_targets '=')")); +- void *_tmp_259_var; ++ D(fprintf(stderr, "%*c> _loop0_162[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "(star_targets '=')")); ++ void *_tmp_261_var; + while ( +- (_tmp_259_var = _tmp_259_rule(p)) // star_targets '=' ++ (_tmp_261_var = _tmp_261_rule(p)) // star_targets '=' + ) + { +- _res = _tmp_259_var; ++ _res = _tmp_261_var; + if (_n == _children_capacity) { + _children_capacity *= 2; + void **_new_children = PyMem_Realloc(_children, _children_capacity*sizeof(void *)); +@@ -34761,7 +35360,7 @@ _loop0_160_rule(Parser *p) + _mark = p->mark; + } + p->mark = _mark; +- D(fprintf(stderr, "%*c%s _loop0_160[%d-%d]: %s failed!\n", p->level, ' ', ++ D(fprintf(stderr, "%*c%s _loop0_162[%d-%d]: %s failed!\n", p->level, ' ', + p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "(star_targets '=')")); + } + asdl_seq *_seq = (asdl_seq*)_Py_asdl_generic_seq_new(_n, p->arena); +@@ -34778,9 +35377,9 @@ _loop0_160_rule(Parser *p) + return _seq; + } + +-// _loop0_161: (star_targets '=') ++// _loop0_163: (star_targets '=') + static asdl_seq * +-_loop0_161_rule(Parser *p) ++_loop0_163_rule(Parser *p) + { + if (p->level++ == MAXSTACK) { + p->error_indicator = 1; +@@ -34806,13 +35405,13 @@ _loop0_161_rule(Parser *p) + p->level--; + return NULL; + } +- D(fprintf(stderr, "%*c> _loop0_161[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "(star_targets '=')")); +- void *_tmp_260_var; ++ D(fprintf(stderr, "%*c> _loop0_163[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "(star_targets '=')")); ++ void *_tmp_262_var; + while ( +- (_tmp_260_var = _tmp_260_rule(p)) // star_targets '=' ++ (_tmp_262_var = _tmp_262_rule(p)) // star_targets '=' + ) + { +- _res = _tmp_260_var; ++ _res = _tmp_262_var; + if (_n == _children_capacity) { + _children_capacity *= 2; + void **_new_children = PyMem_Realloc(_children, _children_capacity*sizeof(void *)); +@@ -34829,7 +35428,7 @@ _loop0_161_rule(Parser *p) + _mark = p->mark; + } + p->mark = _mark; +- D(fprintf(stderr, "%*c%s _loop0_161[%d-%d]: %s failed!\n", p->level, ' ', ++ D(fprintf(stderr, "%*c%s _loop0_163[%d-%d]: %s failed!\n", p->level, ' ', + p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "(star_targets '=')")); + } + asdl_seq *_seq = (asdl_seq*)_Py_asdl_generic_seq_new(_n, p->arena); +@@ -34846,9 +35445,9 @@ _loop0_161_rule(Parser *p) + return _seq; + } + +-// _tmp_162: yield_expr | star_expressions ++// _tmp_164: yield_expr | star_expressions + static void * +-_tmp_162_rule(Parser *p) ++_tmp_164_rule(Parser *p) + { + if (p->level++ == MAXSTACK) { + p->error_indicator = 1; +@@ -34865,18 +35464,18 @@ _tmp_162_rule(Parser *p) + p->level--; + return NULL; + } +- D(fprintf(stderr, "%*c> _tmp_162[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "yield_expr")); ++ D(fprintf(stderr, "%*c> _tmp_164[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "yield_expr")); + expr_ty yield_expr_var; + if ( + (yield_expr_var = yield_expr_rule(p)) // yield_expr + ) + { +- D(fprintf(stderr, "%*c+ _tmp_162[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "yield_expr")); ++ D(fprintf(stderr, "%*c+ _tmp_164[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "yield_expr")); + _res = yield_expr_var; + goto done; + } + p->mark = _mark; +- D(fprintf(stderr, "%*c%s _tmp_162[%d-%d]: %s failed!\n", p->level, ' ', ++ D(fprintf(stderr, "%*c%s _tmp_164[%d-%d]: %s failed!\n", p->level, ' ', + p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "yield_expr")); + } + { // star_expressions +@@ -34884,18 +35483,18 @@ _tmp_162_rule(Parser *p) + p->level--; + return NULL; + } +- D(fprintf(stderr, "%*c> _tmp_162[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "star_expressions")); ++ D(fprintf(stderr, "%*c> _tmp_164[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "star_expressions")); + expr_ty star_expressions_var; + if ( + (star_expressions_var = star_expressions_rule(p)) // star_expressions + ) + { +- D(fprintf(stderr, "%*c+ _tmp_162[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "star_expressions")); ++ D(fprintf(stderr, "%*c+ _tmp_164[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "star_expressions")); + _res = star_expressions_var; + goto done; + } + p->mark = _mark; +- D(fprintf(stderr, "%*c%s _tmp_162[%d-%d]: %s failed!\n", p->level, ' ', ++ D(fprintf(stderr, "%*c%s _tmp_164[%d-%d]: %s failed!\n", p->level, ' ', + p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "star_expressions")); + } + _res = NULL; +@@ -34904,9 +35503,9 @@ _tmp_162_rule(Parser *p) + return _res; + } + +-// _tmp_163: '[' | '(' | '{' ++// _tmp_165: '[' | '(' | '{' + static void * +-_tmp_163_rule(Parser *p) ++_tmp_165_rule(Parser *p) + { + if (p->level++ == MAXSTACK) { + p->error_indicator = 1; +@@ -34923,18 +35522,18 @@ _tmp_163_rule(Parser *p) + p->level--; + return NULL; + } +- D(fprintf(stderr, "%*c> _tmp_163[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "'['")); ++ D(fprintf(stderr, "%*c> _tmp_165[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "'['")); + Token * _literal; + if ( + (_literal = _PyPegen_expect_token(p, 9)) // token='[' + ) + { +- D(fprintf(stderr, "%*c+ _tmp_163[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "'['")); ++ D(fprintf(stderr, "%*c+ _tmp_165[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "'['")); + _res = _literal; + goto done; + } + p->mark = _mark; +- D(fprintf(stderr, "%*c%s _tmp_163[%d-%d]: %s failed!\n", p->level, ' ', ++ D(fprintf(stderr, "%*c%s _tmp_165[%d-%d]: %s failed!\n", p->level, ' ', + p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "'['")); + } + { // '(' +@@ -34942,18 +35541,18 @@ _tmp_163_rule(Parser *p) + p->level--; + return NULL; + } +- D(fprintf(stderr, "%*c> _tmp_163[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "'('")); ++ D(fprintf(stderr, "%*c> _tmp_165[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "'('")); + Token * _literal; + if ( + (_literal = _PyPegen_expect_token(p, 7)) // token='(' + ) + { +- D(fprintf(stderr, "%*c+ _tmp_163[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "'('")); ++ D(fprintf(stderr, "%*c+ _tmp_165[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "'('")); + _res = _literal; + goto done; + } + p->mark = _mark; +- D(fprintf(stderr, "%*c%s _tmp_163[%d-%d]: %s failed!\n", p->level, ' ', ++ D(fprintf(stderr, "%*c%s _tmp_165[%d-%d]: %s failed!\n", p->level, ' ', + p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "'('")); + } + { // '{' +@@ -34961,18 +35560,18 @@ _tmp_163_rule(Parser *p) + p->level--; + return NULL; + } +- D(fprintf(stderr, "%*c> _tmp_163[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "'{'")); ++ D(fprintf(stderr, "%*c> _tmp_165[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "'{'")); + Token * _literal; + if ( + (_literal = _PyPegen_expect_token(p, 25)) // token='{' + ) + { +- D(fprintf(stderr, "%*c+ _tmp_163[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "'{'")); ++ D(fprintf(stderr, "%*c+ _tmp_165[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "'{'")); + _res = _literal; + goto done; + } + p->mark = _mark; +- D(fprintf(stderr, "%*c%s _tmp_163[%d-%d]: %s failed!\n", p->level, ' ', ++ D(fprintf(stderr, "%*c%s _tmp_165[%d-%d]: %s failed!\n", p->level, ' ', + p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "'{'")); + } + _res = NULL; +@@ -34981,9 +35580,9 @@ _tmp_163_rule(Parser *p) + return _res; + } + +-// _tmp_164: '[' | '{' ++// _tmp_166: '[' | '{' + static void * +-_tmp_164_rule(Parser *p) ++_tmp_166_rule(Parser *p) + { + if (p->level++ == MAXSTACK) { + p->error_indicator = 1; +@@ -35000,18 +35599,18 @@ _tmp_164_rule(Parser *p) + p->level--; + return NULL; + } +- D(fprintf(stderr, "%*c> _tmp_164[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "'['")); ++ D(fprintf(stderr, "%*c> _tmp_166[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "'['")); + Token * _literal; + if ( + (_literal = _PyPegen_expect_token(p, 9)) // token='[' + ) + { +- D(fprintf(stderr, "%*c+ _tmp_164[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "'['")); ++ D(fprintf(stderr, "%*c+ _tmp_166[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "'['")); + _res = _literal; + goto done; + } + p->mark = _mark; +- D(fprintf(stderr, "%*c%s _tmp_164[%d-%d]: %s failed!\n", p->level, ' ', ++ D(fprintf(stderr, "%*c%s _tmp_166[%d-%d]: %s failed!\n", p->level, ' ', + p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "'['")); + } + { // '{' +@@ -35019,18 +35618,18 @@ _tmp_164_rule(Parser *p) + p->level--; + return NULL; + } +- D(fprintf(stderr, "%*c> _tmp_164[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "'{'")); ++ D(fprintf(stderr, "%*c> _tmp_166[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "'{'")); + Token * _literal; + if ( + (_literal = _PyPegen_expect_token(p, 25)) // token='{' + ) + { +- D(fprintf(stderr, "%*c+ _tmp_164[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "'{'")); ++ D(fprintf(stderr, "%*c+ _tmp_166[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "'{'")); + _res = _literal; + goto done; + } + p->mark = _mark; +- D(fprintf(stderr, "%*c%s _tmp_164[%d-%d]: %s failed!\n", p->level, ' ', ++ D(fprintf(stderr, "%*c%s _tmp_166[%d-%d]: %s failed!\n", p->level, ' ', + p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "'{'")); + } + _res = NULL; +@@ -35039,9 +35638,9 @@ _tmp_164_rule(Parser *p) + return _res; + } + +-// _tmp_165: '[' | '{' ++// _tmp_167: '[' | '{' + static void * +-_tmp_165_rule(Parser *p) ++_tmp_167_rule(Parser *p) + { + if (p->level++ == MAXSTACK) { + p->error_indicator = 1; +@@ -35058,18 +35657,18 @@ _tmp_165_rule(Parser *p) + p->level--; + return NULL; + } +- D(fprintf(stderr, "%*c> _tmp_165[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "'['")); ++ D(fprintf(stderr, "%*c> _tmp_167[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "'['")); + Token * _literal; + if ( + (_literal = _PyPegen_expect_token(p, 9)) // token='[' + ) + { +- D(fprintf(stderr, "%*c+ _tmp_165[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "'['")); ++ D(fprintf(stderr, "%*c+ _tmp_167[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "'['")); + _res = _literal; + goto done; + } + p->mark = _mark; +- D(fprintf(stderr, "%*c%s _tmp_165[%d-%d]: %s failed!\n", p->level, ' ', ++ D(fprintf(stderr, "%*c%s _tmp_167[%d-%d]: %s failed!\n", p->level, ' ', + p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "'['")); + } + { // '{' +@@ -35077,18 +35676,18 @@ _tmp_165_rule(Parser *p) + p->level--; + return NULL; + } +- D(fprintf(stderr, "%*c> _tmp_165[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "'{'")); ++ D(fprintf(stderr, "%*c> _tmp_167[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "'{'")); + Token * _literal; + if ( + (_literal = _PyPegen_expect_token(p, 25)) // token='{' + ) + { +- D(fprintf(stderr, "%*c+ _tmp_165[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "'{'")); ++ D(fprintf(stderr, "%*c+ _tmp_167[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "'{'")); + _res = _literal; + goto done; + } + p->mark = _mark; +- D(fprintf(stderr, "%*c%s _tmp_165[%d-%d]: %s failed!\n", p->level, ' ', ++ D(fprintf(stderr, "%*c%s _tmp_167[%d-%d]: %s failed!\n", p->level, ' ', + p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "'{'")); + } + _res = NULL; +@@ -35097,9 +35696,9 @@ _tmp_165_rule(Parser *p) + return _res; + } + +-// _tmp_166: slash_no_default | slash_with_default ++// _tmp_168: slash_no_default | slash_with_default + static void * +-_tmp_166_rule(Parser *p) ++_tmp_168_rule(Parser *p) + { + if (p->level++ == MAXSTACK) { + p->error_indicator = 1; +@@ -35116,18 +35715,18 @@ _tmp_166_rule(Parser *p) + p->level--; + return NULL; + } +- D(fprintf(stderr, "%*c> _tmp_166[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "slash_no_default")); ++ D(fprintf(stderr, "%*c> _tmp_168[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "slash_no_default")); + asdl_arg_seq* slash_no_default_var; + if ( + (slash_no_default_var = slash_no_default_rule(p)) // slash_no_default + ) + { +- D(fprintf(stderr, "%*c+ _tmp_166[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "slash_no_default")); ++ D(fprintf(stderr, "%*c+ _tmp_168[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "slash_no_default")); + _res = slash_no_default_var; + goto done; + } + p->mark = _mark; +- D(fprintf(stderr, "%*c%s _tmp_166[%d-%d]: %s failed!\n", p->level, ' ', ++ D(fprintf(stderr, "%*c%s _tmp_168[%d-%d]: %s failed!\n", p->level, ' ', + p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "slash_no_default")); + } + { // slash_with_default +@@ -35135,18 +35734,18 @@ _tmp_166_rule(Parser *p) + p->level--; + return NULL; + } +- D(fprintf(stderr, "%*c> _tmp_166[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "slash_with_default")); ++ D(fprintf(stderr, "%*c> _tmp_168[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "slash_with_default")); + SlashWithDefault* slash_with_default_var; + if ( + (slash_with_default_var = slash_with_default_rule(p)) // slash_with_default + ) + { +- D(fprintf(stderr, "%*c+ _tmp_166[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "slash_with_default")); ++ D(fprintf(stderr, "%*c+ _tmp_168[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "slash_with_default")); + _res = slash_with_default_var; + goto done; + } + p->mark = _mark; +- D(fprintf(stderr, "%*c%s _tmp_166[%d-%d]: %s failed!\n", p->level, ' ', ++ D(fprintf(stderr, "%*c%s _tmp_168[%d-%d]: %s failed!\n", p->level, ' ', + p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "slash_with_default")); + } + _res = NULL; +@@ -35155,9 +35754,9 @@ _tmp_166_rule(Parser *p) + return _res; + } + +-// _loop0_167: param_maybe_default ++// _loop0_169: param_maybe_default + static asdl_seq * +-_loop0_167_rule(Parser *p) ++_loop0_169_rule(Parser *p) + { + if (p->level++ == MAXSTACK) { + p->error_indicator = 1; +@@ -35183,7 +35782,7 @@ _loop0_167_rule(Parser *p) + p->level--; + return NULL; + } +- D(fprintf(stderr, "%*c> _loop0_167[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "param_maybe_default")); ++ D(fprintf(stderr, "%*c> _loop0_169[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "param_maybe_default")); + NameDefaultPair* param_maybe_default_var; + while ( + (param_maybe_default_var = param_maybe_default_rule(p)) // param_maybe_default +@@ -35206,7 +35805,7 @@ _loop0_167_rule(Parser *p) + _mark = p->mark; + } + p->mark = _mark; +- D(fprintf(stderr, "%*c%s _loop0_167[%d-%d]: %s failed!\n", p->level, ' ', ++ D(fprintf(stderr, "%*c%s _loop0_169[%d-%d]: %s failed!\n", p->level, ' ', + p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "param_maybe_default")); + } + asdl_seq *_seq = (asdl_seq*)_Py_asdl_generic_seq_new(_n, p->arena); +@@ -35223,9 +35822,9 @@ _loop0_167_rule(Parser *p) + return _seq; + } + +-// _loop0_168: param_no_default ++// _loop0_170: param_no_default + static asdl_seq * +-_loop0_168_rule(Parser *p) ++_loop0_170_rule(Parser *p) + { + if (p->level++ == MAXSTACK) { + p->error_indicator = 1; +@@ -35251,7 +35850,7 @@ _loop0_168_rule(Parser *p) + p->level--; + return NULL; + } +- D(fprintf(stderr, "%*c> _loop0_168[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "param_no_default")); ++ D(fprintf(stderr, "%*c> _loop0_170[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "param_no_default")); + arg_ty param_no_default_var; + while ( + (param_no_default_var = param_no_default_rule(p)) // param_no_default +@@ -35274,7 +35873,7 @@ _loop0_168_rule(Parser *p) + _mark = p->mark; + } + p->mark = _mark; +- D(fprintf(stderr, "%*c%s _loop0_168[%d-%d]: %s failed!\n", p->level, ' ', ++ D(fprintf(stderr, "%*c%s _loop0_170[%d-%d]: %s failed!\n", p->level, ' ', + p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "param_no_default")); + } + asdl_seq *_seq = (asdl_seq*)_Py_asdl_generic_seq_new(_n, p->arena); +@@ -35291,9 +35890,9 @@ _loop0_168_rule(Parser *p) + return _seq; + } + +-// _loop0_169: param_no_default ++// _loop0_171: param_no_default + static asdl_seq * +-_loop0_169_rule(Parser *p) ++_loop0_171_rule(Parser *p) + { + if (p->level++ == MAXSTACK) { + p->error_indicator = 1; +@@ -35319,7 +35918,7 @@ _loop0_169_rule(Parser *p) + p->level--; + return NULL; + } +- D(fprintf(stderr, "%*c> _loop0_169[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "param_no_default")); ++ D(fprintf(stderr, "%*c> _loop0_171[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "param_no_default")); + arg_ty param_no_default_var; + while ( + (param_no_default_var = param_no_default_rule(p)) // param_no_default +@@ -35342,7 +35941,7 @@ _loop0_169_rule(Parser *p) + _mark = p->mark; + } + p->mark = _mark; +- D(fprintf(stderr, "%*c%s _loop0_169[%d-%d]: %s failed!\n", p->level, ' ', ++ D(fprintf(stderr, "%*c%s _loop0_171[%d-%d]: %s failed!\n", p->level, ' ', + p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "param_no_default")); + } + asdl_seq *_seq = (asdl_seq*)_Py_asdl_generic_seq_new(_n, p->arena); +@@ -35359,9 +35958,9 @@ _loop0_169_rule(Parser *p) + return _seq; + } + +-// _loop1_170: param_no_default ++// _loop1_172: param_no_default + static asdl_seq * +-_loop1_170_rule(Parser *p) ++_loop1_172_rule(Parser *p) + { + if (p->level++ == MAXSTACK) { + p->error_indicator = 1; +@@ -35387,7 +35986,7 @@ _loop1_170_rule(Parser *p) + p->level--; + return NULL; + } +- D(fprintf(stderr, "%*c> _loop1_170[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "param_no_default")); ++ D(fprintf(stderr, "%*c> _loop1_172[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "param_no_default")); + arg_ty param_no_default_var; + while ( + (param_no_default_var = param_no_default_rule(p)) // param_no_default +@@ -35410,7 +36009,7 @@ _loop1_170_rule(Parser *p) + _mark = p->mark; + } + p->mark = _mark; +- D(fprintf(stderr, "%*c%s _loop1_170[%d-%d]: %s failed!\n", p->level, ' ', ++ D(fprintf(stderr, "%*c%s _loop1_172[%d-%d]: %s failed!\n", p->level, ' ', + p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "param_no_default")); + } + if (_n == 0 || p->error_indicator) { +@@ -35432,9 +36031,9 @@ _loop1_170_rule(Parser *p) + return _seq; + } + +-// _tmp_171: slash_no_default | slash_with_default ++// _tmp_173: slash_no_default | slash_with_default + static void * +-_tmp_171_rule(Parser *p) ++_tmp_173_rule(Parser *p) + { + if (p->level++ == MAXSTACK) { + p->error_indicator = 1; +@@ -35451,18 +36050,18 @@ _tmp_171_rule(Parser *p) + p->level--; + return NULL; + } +- D(fprintf(stderr, "%*c> _tmp_171[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "slash_no_default")); ++ D(fprintf(stderr, "%*c> _tmp_173[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "slash_no_default")); + asdl_arg_seq* slash_no_default_var; + if ( + (slash_no_default_var = slash_no_default_rule(p)) // slash_no_default + ) + { +- D(fprintf(stderr, "%*c+ _tmp_171[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "slash_no_default")); ++ D(fprintf(stderr, "%*c+ _tmp_173[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "slash_no_default")); + _res = slash_no_default_var; + goto done; + } + p->mark = _mark; +- D(fprintf(stderr, "%*c%s _tmp_171[%d-%d]: %s failed!\n", p->level, ' ', ++ D(fprintf(stderr, "%*c%s _tmp_173[%d-%d]: %s failed!\n", p->level, ' ', + p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "slash_no_default")); + } + { // slash_with_default +@@ -35470,18 +36069,18 @@ _tmp_171_rule(Parser *p) + p->level--; + return NULL; + } +- D(fprintf(stderr, "%*c> _tmp_171[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "slash_with_default")); ++ D(fprintf(stderr, "%*c> _tmp_173[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "slash_with_default")); + SlashWithDefault* slash_with_default_var; + if ( + (slash_with_default_var = slash_with_default_rule(p)) // slash_with_default + ) + { +- D(fprintf(stderr, "%*c+ _tmp_171[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "slash_with_default")); ++ D(fprintf(stderr, "%*c+ _tmp_173[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "slash_with_default")); + _res = slash_with_default_var; + goto done; + } + p->mark = _mark; +- D(fprintf(stderr, "%*c%s _tmp_171[%d-%d]: %s failed!\n", p->level, ' ', ++ D(fprintf(stderr, "%*c%s _tmp_173[%d-%d]: %s failed!\n", p->level, ' ', + p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "slash_with_default")); + } + _res = NULL; +@@ -35490,9 +36089,9 @@ _tmp_171_rule(Parser *p) + return _res; + } + +-// _loop0_172: param_maybe_default ++// _loop0_174: param_maybe_default + static asdl_seq * +-_loop0_172_rule(Parser *p) ++_loop0_174_rule(Parser *p) + { + if (p->level++ == MAXSTACK) { + p->error_indicator = 1; +@@ -35518,7 +36117,7 @@ _loop0_172_rule(Parser *p) + p->level--; + return NULL; + } +- D(fprintf(stderr, "%*c> _loop0_172[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "param_maybe_default")); ++ D(fprintf(stderr, "%*c> _loop0_174[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "param_maybe_default")); + NameDefaultPair* param_maybe_default_var; + while ( + (param_maybe_default_var = param_maybe_default_rule(p)) // param_maybe_default +@@ -35541,7 +36140,7 @@ _loop0_172_rule(Parser *p) + _mark = p->mark; + } + p->mark = _mark; +- D(fprintf(stderr, "%*c%s _loop0_172[%d-%d]: %s failed!\n", p->level, ' ', ++ D(fprintf(stderr, "%*c%s _loop0_174[%d-%d]: %s failed!\n", p->level, ' ', + p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "param_maybe_default")); + } + asdl_seq *_seq = (asdl_seq*)_Py_asdl_generic_seq_new(_n, p->arena); +@@ -35558,9 +36157,9 @@ _loop0_172_rule(Parser *p) + return _seq; + } + +-// _tmp_173: ',' | param_no_default ++// _tmp_175: ',' | param_no_default + static void * +-_tmp_173_rule(Parser *p) ++_tmp_175_rule(Parser *p) + { + if (p->level++ == MAXSTACK) { + p->error_indicator = 1; +@@ -35577,18 +36176,18 @@ _tmp_173_rule(Parser *p) + p->level--; + return NULL; + } +- D(fprintf(stderr, "%*c> _tmp_173[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "','")); ++ D(fprintf(stderr, "%*c> _tmp_175[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "','")); + Token * _literal; + if ( + (_literal = _PyPegen_expect_token(p, 12)) // token=',' + ) + { +- D(fprintf(stderr, "%*c+ _tmp_173[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "','")); ++ D(fprintf(stderr, "%*c+ _tmp_175[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "','")); + _res = _literal; + goto done; + } + p->mark = _mark; +- D(fprintf(stderr, "%*c%s _tmp_173[%d-%d]: %s failed!\n", p->level, ' ', ++ D(fprintf(stderr, "%*c%s _tmp_175[%d-%d]: %s failed!\n", p->level, ' ', + p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "','")); + } + { // param_no_default +@@ -35596,18 +36195,18 @@ _tmp_173_rule(Parser *p) + p->level--; + return NULL; + } +- D(fprintf(stderr, "%*c> _tmp_173[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "param_no_default")); ++ D(fprintf(stderr, "%*c> _tmp_175[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "param_no_default")); + arg_ty param_no_default_var; + if ( + (param_no_default_var = param_no_default_rule(p)) // param_no_default + ) + { +- D(fprintf(stderr, "%*c+ _tmp_173[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "param_no_default")); ++ D(fprintf(stderr, "%*c+ _tmp_175[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "param_no_default")); + _res = param_no_default_var; + goto done; + } + p->mark = _mark; +- D(fprintf(stderr, "%*c%s _tmp_173[%d-%d]: %s failed!\n", p->level, ' ', ++ D(fprintf(stderr, "%*c%s _tmp_175[%d-%d]: %s failed!\n", p->level, ' ', + p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "param_no_default")); + } + _res = NULL; +@@ -35616,9 +36215,9 @@ _tmp_173_rule(Parser *p) + return _res; + } + +-// _loop0_174: param_maybe_default ++// _loop0_176: param_maybe_default + static asdl_seq * +-_loop0_174_rule(Parser *p) ++_loop0_176_rule(Parser *p) + { + if (p->level++ == MAXSTACK) { + p->error_indicator = 1; +@@ -35644,7 +36243,7 @@ _loop0_174_rule(Parser *p) + p->level--; + return NULL; + } +- D(fprintf(stderr, "%*c> _loop0_174[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "param_maybe_default")); ++ D(fprintf(stderr, "%*c> _loop0_176[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "param_maybe_default")); + NameDefaultPair* param_maybe_default_var; + while ( + (param_maybe_default_var = param_maybe_default_rule(p)) // param_maybe_default +@@ -35667,7 +36266,7 @@ _loop0_174_rule(Parser *p) + _mark = p->mark; + } + p->mark = _mark; +- D(fprintf(stderr, "%*c%s _loop0_174[%d-%d]: %s failed!\n", p->level, ' ', ++ D(fprintf(stderr, "%*c%s _loop0_176[%d-%d]: %s failed!\n", p->level, ' ', + p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "param_maybe_default")); + } + asdl_seq *_seq = (asdl_seq*)_Py_asdl_generic_seq_new(_n, p->arena); +@@ -35684,9 +36283,9 @@ _loop0_174_rule(Parser *p) + return _seq; + } + +-// _loop1_175: param_maybe_default ++// _loop1_177: param_maybe_default + static asdl_seq * +-_loop1_175_rule(Parser *p) ++_loop1_177_rule(Parser *p) + { + if (p->level++ == MAXSTACK) { + p->error_indicator = 1; +@@ -35712,7 +36311,7 @@ _loop1_175_rule(Parser *p) + p->level--; + return NULL; + } +- D(fprintf(stderr, "%*c> _loop1_175[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "param_maybe_default")); ++ D(fprintf(stderr, "%*c> _loop1_177[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "param_maybe_default")); + NameDefaultPair* param_maybe_default_var; + while ( + (param_maybe_default_var = param_maybe_default_rule(p)) // param_maybe_default +@@ -35735,7 +36334,7 @@ _loop1_175_rule(Parser *p) + _mark = p->mark; + } + p->mark = _mark; +- D(fprintf(stderr, "%*c%s _loop1_175[%d-%d]: %s failed!\n", p->level, ' ', ++ D(fprintf(stderr, "%*c%s _loop1_177[%d-%d]: %s failed!\n", p->level, ' ', + p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "param_maybe_default")); + } + if (_n == 0 || p->error_indicator) { +@@ -35757,9 +36356,9 @@ _loop1_175_rule(Parser *p) + return _seq; + } + +-// _tmp_176: ')' | ',' ++// _tmp_178: ')' | ',' + static void * +-_tmp_176_rule(Parser *p) ++_tmp_178_rule(Parser *p) + { + if (p->level++ == MAXSTACK) { + p->error_indicator = 1; +@@ -35776,18 +36375,18 @@ _tmp_176_rule(Parser *p) + p->level--; + return NULL; + } +- D(fprintf(stderr, "%*c> _tmp_176[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "')'")); ++ D(fprintf(stderr, "%*c> _tmp_178[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "')'")); + Token * _literal; + if ( + (_literal = _PyPegen_expect_token(p, 8)) // token=')' + ) + { +- D(fprintf(stderr, "%*c+ _tmp_176[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "')'")); ++ D(fprintf(stderr, "%*c+ _tmp_178[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "')'")); + _res = _literal; + goto done; + } + p->mark = _mark; +- D(fprintf(stderr, "%*c%s _tmp_176[%d-%d]: %s failed!\n", p->level, ' ', ++ D(fprintf(stderr, "%*c%s _tmp_178[%d-%d]: %s failed!\n", p->level, ' ', + p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "')'")); + } + { // ',' +@@ -35795,18 +36394,18 @@ _tmp_176_rule(Parser *p) + p->level--; + return NULL; + } +- D(fprintf(stderr, "%*c> _tmp_176[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "','")); ++ D(fprintf(stderr, "%*c> _tmp_178[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "','")); + Token * _literal; + if ( + (_literal = _PyPegen_expect_token(p, 12)) // token=',' + ) + { +- D(fprintf(stderr, "%*c+ _tmp_176[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "','")); ++ D(fprintf(stderr, "%*c+ _tmp_178[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "','")); + _res = _literal; + goto done; + } + p->mark = _mark; +- D(fprintf(stderr, "%*c%s _tmp_176[%d-%d]: %s failed!\n", p->level, ' ', ++ D(fprintf(stderr, "%*c%s _tmp_178[%d-%d]: %s failed!\n", p->level, ' ', + p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "','")); + } + _res = NULL; +@@ -35815,9 +36414,9 @@ _tmp_176_rule(Parser *p) + return _res; + } + +-// _tmp_177: ')' | ',' (')' | '**') ++// _tmp_179: ')' | ',' (')' | '**') + static void * +-_tmp_177_rule(Parser *p) ++_tmp_179_rule(Parser *p) + { + if (p->level++ == MAXSTACK) { + p->error_indicator = 1; +@@ -35834,18 +36433,18 @@ _tmp_177_rule(Parser *p) + p->level--; + return NULL; + } +- D(fprintf(stderr, "%*c> _tmp_177[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "')'")); ++ D(fprintf(stderr, "%*c> _tmp_179[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "')'")); + Token * _literal; + if ( + (_literal = _PyPegen_expect_token(p, 8)) // token=')' + ) + { +- D(fprintf(stderr, "%*c+ _tmp_177[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "')'")); ++ D(fprintf(stderr, "%*c+ _tmp_179[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "')'")); + _res = _literal; + goto done; + } + p->mark = _mark; +- D(fprintf(stderr, "%*c%s _tmp_177[%d-%d]: %s failed!\n", p->level, ' ', ++ D(fprintf(stderr, "%*c%s _tmp_179[%d-%d]: %s failed!\n", p->level, ' ', + p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "')'")); + } + { // ',' (')' | '**') +@@ -35853,21 +36452,21 @@ _tmp_177_rule(Parser *p) + p->level--; + return NULL; + } +- D(fprintf(stderr, "%*c> _tmp_177[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "',' (')' | '**')")); ++ D(fprintf(stderr, "%*c> _tmp_179[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "',' (')' | '**')")); + Token * _literal; +- void *_tmp_261_var; ++ void *_tmp_263_var; + if ( + (_literal = _PyPegen_expect_token(p, 12)) // token=',' + && +- (_tmp_261_var = _tmp_261_rule(p)) // ')' | '**' ++ (_tmp_263_var = _tmp_263_rule(p)) // ')' | '**' + ) + { +- D(fprintf(stderr, "%*c+ _tmp_177[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "',' (')' | '**')")); +- _res = _PyPegen_dummy_name(p, _literal, _tmp_261_var); ++ D(fprintf(stderr, "%*c+ _tmp_179[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "',' (')' | '**')")); ++ _res = _PyPegen_dummy_name(p, _literal, _tmp_263_var); + goto done; + } + p->mark = _mark; +- D(fprintf(stderr, "%*c%s _tmp_177[%d-%d]: %s failed!\n", p->level, ' ', ++ D(fprintf(stderr, "%*c%s _tmp_179[%d-%d]: %s failed!\n", p->level, ' ', + p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "',' (')' | '**')")); + } + _res = NULL; +@@ -35876,9 +36475,9 @@ _tmp_177_rule(Parser *p) + return _res; + } + +-// _tmp_178: param_no_default | ',' ++// _tmp_180: param_no_default | ',' + static void * +-_tmp_178_rule(Parser *p) ++_tmp_180_rule(Parser *p) + { + if (p->level++ == MAXSTACK) { + p->error_indicator = 1; +@@ -35895,18 +36494,18 @@ _tmp_178_rule(Parser *p) + p->level--; + return NULL; + } +- D(fprintf(stderr, "%*c> _tmp_178[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "param_no_default")); ++ D(fprintf(stderr, "%*c> _tmp_180[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "param_no_default")); + arg_ty param_no_default_var; + if ( + (param_no_default_var = param_no_default_rule(p)) // param_no_default + ) + { +- D(fprintf(stderr, "%*c+ _tmp_178[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "param_no_default")); ++ D(fprintf(stderr, "%*c+ _tmp_180[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "param_no_default")); + _res = param_no_default_var; + goto done; + } + p->mark = _mark; +- D(fprintf(stderr, "%*c%s _tmp_178[%d-%d]: %s failed!\n", p->level, ' ', ++ D(fprintf(stderr, "%*c%s _tmp_180[%d-%d]: %s failed!\n", p->level, ' ', + p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "param_no_default")); + } + { // ',' +@@ -35914,18 +36513,18 @@ _tmp_178_rule(Parser *p) + p->level--; + return NULL; + } +- D(fprintf(stderr, "%*c> _tmp_178[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "','")); ++ D(fprintf(stderr, "%*c> _tmp_180[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "','")); + Token * _literal; + if ( + (_literal = _PyPegen_expect_token(p, 12)) // token=',' + ) + { +- D(fprintf(stderr, "%*c+ _tmp_178[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "','")); ++ D(fprintf(stderr, "%*c+ _tmp_180[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "','")); + _res = _literal; + goto done; + } + p->mark = _mark; +- D(fprintf(stderr, "%*c%s _tmp_178[%d-%d]: %s failed!\n", p->level, ' ', ++ D(fprintf(stderr, "%*c%s _tmp_180[%d-%d]: %s failed!\n", p->level, ' ', + p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "','")); + } + _res = NULL; +@@ -35934,9 +36533,9 @@ _tmp_178_rule(Parser *p) + return _res; + } + +-// _loop0_179: param_maybe_default ++// _loop0_181: param_maybe_default + static asdl_seq * +-_loop0_179_rule(Parser *p) ++_loop0_181_rule(Parser *p) + { + if (p->level++ == MAXSTACK) { + p->error_indicator = 1; +@@ -35962,7 +36561,7 @@ _loop0_179_rule(Parser *p) + p->level--; + return NULL; + } +- D(fprintf(stderr, "%*c> _loop0_179[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "param_maybe_default")); ++ D(fprintf(stderr, "%*c> _loop0_181[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "param_maybe_default")); + NameDefaultPair* param_maybe_default_var; + while ( + (param_maybe_default_var = param_maybe_default_rule(p)) // param_maybe_default +@@ -35985,7 +36584,7 @@ _loop0_179_rule(Parser *p) + _mark = p->mark; + } + p->mark = _mark; +- D(fprintf(stderr, "%*c%s _loop0_179[%d-%d]: %s failed!\n", p->level, ' ', ++ D(fprintf(stderr, "%*c%s _loop0_181[%d-%d]: %s failed!\n", p->level, ' ', + p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "param_maybe_default")); + } + asdl_seq *_seq = (asdl_seq*)_Py_asdl_generic_seq_new(_n, p->arena); +@@ -36002,9 +36601,9 @@ _loop0_179_rule(Parser *p) + return _seq; + } + +-// _tmp_180: param_no_default | ',' ++// _tmp_182: param_no_default | ',' + static void * +-_tmp_180_rule(Parser *p) ++_tmp_182_rule(Parser *p) + { + if (p->level++ == MAXSTACK) { + p->error_indicator = 1; +@@ -36021,18 +36620,18 @@ _tmp_180_rule(Parser *p) + p->level--; + return NULL; + } +- D(fprintf(stderr, "%*c> _tmp_180[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "param_no_default")); ++ D(fprintf(stderr, "%*c> _tmp_182[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "param_no_default")); + arg_ty param_no_default_var; + if ( + (param_no_default_var = param_no_default_rule(p)) // param_no_default + ) + { +- D(fprintf(stderr, "%*c+ _tmp_180[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "param_no_default")); ++ D(fprintf(stderr, "%*c+ _tmp_182[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "param_no_default")); + _res = param_no_default_var; + goto done; + } + p->mark = _mark; +- D(fprintf(stderr, "%*c%s _tmp_180[%d-%d]: %s failed!\n", p->level, ' ', ++ D(fprintf(stderr, "%*c%s _tmp_182[%d-%d]: %s failed!\n", p->level, ' ', + p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "param_no_default")); + } + { // ',' +@@ -36040,18 +36639,18 @@ _tmp_180_rule(Parser *p) + p->level--; + return NULL; + } +- D(fprintf(stderr, "%*c> _tmp_180[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "','")); ++ D(fprintf(stderr, "%*c> _tmp_182[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "','")); + Token * _literal; + if ( + (_literal = _PyPegen_expect_token(p, 12)) // token=',' + ) + { +- D(fprintf(stderr, "%*c+ _tmp_180[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "','")); ++ D(fprintf(stderr, "%*c+ _tmp_182[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "','")); + _res = _literal; + goto done; + } + p->mark = _mark; +- D(fprintf(stderr, "%*c%s _tmp_180[%d-%d]: %s failed!\n", p->level, ' ', ++ D(fprintf(stderr, "%*c%s _tmp_182[%d-%d]: %s failed!\n", p->level, ' ', + p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "','")); + } + _res = NULL; +@@ -36060,9 +36659,9 @@ _tmp_180_rule(Parser *p) + return _res; + } + +-// _tmp_181: '*' | '**' | '/' ++// _tmp_183: '*' | '**' | '/' + static void * +-_tmp_181_rule(Parser *p) ++_tmp_183_rule(Parser *p) + { + if (p->level++ == MAXSTACK) { + p->error_indicator = 1; +@@ -36079,18 +36678,18 @@ _tmp_181_rule(Parser *p) + p->level--; + return NULL; + } +- D(fprintf(stderr, "%*c> _tmp_181[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "'*'")); ++ D(fprintf(stderr, "%*c> _tmp_183[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "'*'")); + Token * _literal; + if ( + (_literal = _PyPegen_expect_token(p, 16)) // token='*' + ) + { +- D(fprintf(stderr, "%*c+ _tmp_181[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "'*'")); ++ D(fprintf(stderr, "%*c+ _tmp_183[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "'*'")); + _res = _literal; + goto done; + } + p->mark = _mark; +- D(fprintf(stderr, "%*c%s _tmp_181[%d-%d]: %s failed!\n", p->level, ' ', ++ D(fprintf(stderr, "%*c%s _tmp_183[%d-%d]: %s failed!\n", p->level, ' ', + p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "'*'")); + } + { // '**' +@@ -36098,18 +36697,18 @@ _tmp_181_rule(Parser *p) + p->level--; + return NULL; + } +- D(fprintf(stderr, "%*c> _tmp_181[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "'**'")); ++ D(fprintf(stderr, "%*c> _tmp_183[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "'**'")); + Token * _literal; + if ( + (_literal = _PyPegen_expect_token(p, 35)) // token='**' + ) + { +- D(fprintf(stderr, "%*c+ _tmp_181[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "'**'")); ++ D(fprintf(stderr, "%*c+ _tmp_183[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "'**'")); + _res = _literal; + goto done; + } + p->mark = _mark; +- D(fprintf(stderr, "%*c%s _tmp_181[%d-%d]: %s failed!\n", p->level, ' ', ++ D(fprintf(stderr, "%*c%s _tmp_183[%d-%d]: %s failed!\n", p->level, ' ', + p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "'**'")); + } + { // '/' +@@ -36117,18 +36716,18 @@ _tmp_181_rule(Parser *p) + p->level--; + return NULL; + } +- D(fprintf(stderr, "%*c> _tmp_181[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "'/'")); ++ D(fprintf(stderr, "%*c> _tmp_183[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "'/'")); + Token * _literal; + if ( + (_literal = _PyPegen_expect_token(p, 17)) // token='/' + ) + { +- D(fprintf(stderr, "%*c+ _tmp_181[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "'/'")); ++ D(fprintf(stderr, "%*c+ _tmp_183[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "'/'")); + _res = _literal; + goto done; + } + p->mark = _mark; +- D(fprintf(stderr, "%*c%s _tmp_181[%d-%d]: %s failed!\n", p->level, ' ', ++ D(fprintf(stderr, "%*c%s _tmp_183[%d-%d]: %s failed!\n", p->level, ' ', + p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "'/'")); + } + _res = NULL; +@@ -36137,9 +36736,9 @@ _tmp_181_rule(Parser *p) + return _res; + } + +-// _loop1_182: param_with_default ++// _loop1_184: param_with_default + static asdl_seq * +-_loop1_182_rule(Parser *p) ++_loop1_184_rule(Parser *p) + { + if (p->level++ == MAXSTACK) { + p->error_indicator = 1; +@@ -36165,7 +36764,7 @@ _loop1_182_rule(Parser *p) + p->level--; + return NULL; + } +- D(fprintf(stderr, "%*c> _loop1_182[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "param_with_default")); ++ D(fprintf(stderr, "%*c> _loop1_184[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "param_with_default")); + NameDefaultPair* param_with_default_var; + while ( + (param_with_default_var = param_with_default_rule(p)) // param_with_default +@@ -36188,7 +36787,7 @@ _loop1_182_rule(Parser *p) + _mark = p->mark; + } + p->mark = _mark; +- D(fprintf(stderr, "%*c%s _loop1_182[%d-%d]: %s failed!\n", p->level, ' ', ++ D(fprintf(stderr, "%*c%s _loop1_184[%d-%d]: %s failed!\n", p->level, ' ', + p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "param_with_default")); + } + if (_n == 0 || p->error_indicator) { +@@ -36210,9 +36809,9 @@ _loop1_182_rule(Parser *p) + return _seq; + } + +-// _tmp_183: lambda_slash_no_default | lambda_slash_with_default ++// _tmp_185: lambda_slash_no_default | lambda_slash_with_default + static void * +-_tmp_183_rule(Parser *p) ++_tmp_185_rule(Parser *p) + { + if (p->level++ == MAXSTACK) { + p->error_indicator = 1; +@@ -36229,18 +36828,18 @@ _tmp_183_rule(Parser *p) + p->level--; + return NULL; + } +- D(fprintf(stderr, "%*c> _tmp_183[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "lambda_slash_no_default")); ++ D(fprintf(stderr, "%*c> _tmp_185[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "lambda_slash_no_default")); + asdl_arg_seq* lambda_slash_no_default_var; + if ( + (lambda_slash_no_default_var = lambda_slash_no_default_rule(p)) // lambda_slash_no_default + ) + { +- D(fprintf(stderr, "%*c+ _tmp_183[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "lambda_slash_no_default")); ++ D(fprintf(stderr, "%*c+ _tmp_185[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "lambda_slash_no_default")); + _res = lambda_slash_no_default_var; + goto done; + } + p->mark = _mark; +- D(fprintf(stderr, "%*c%s _tmp_183[%d-%d]: %s failed!\n", p->level, ' ', ++ D(fprintf(stderr, "%*c%s _tmp_185[%d-%d]: %s failed!\n", p->level, ' ', + p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "lambda_slash_no_default")); + } + { // lambda_slash_with_default +@@ -36248,18 +36847,18 @@ _tmp_183_rule(Parser *p) + p->level--; + return NULL; + } +- D(fprintf(stderr, "%*c> _tmp_183[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "lambda_slash_with_default")); ++ D(fprintf(stderr, "%*c> _tmp_185[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "lambda_slash_with_default")); + SlashWithDefault* lambda_slash_with_default_var; + if ( + (lambda_slash_with_default_var = lambda_slash_with_default_rule(p)) // lambda_slash_with_default + ) + { +- D(fprintf(stderr, "%*c+ _tmp_183[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "lambda_slash_with_default")); ++ D(fprintf(stderr, "%*c+ _tmp_185[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "lambda_slash_with_default")); + _res = lambda_slash_with_default_var; + goto done; + } + p->mark = _mark; +- D(fprintf(stderr, "%*c%s _tmp_183[%d-%d]: %s failed!\n", p->level, ' ', ++ D(fprintf(stderr, "%*c%s _tmp_185[%d-%d]: %s failed!\n", p->level, ' ', + p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "lambda_slash_with_default")); + } + _res = NULL; +@@ -36268,9 +36867,9 @@ _tmp_183_rule(Parser *p) + return _res; + } + +-// _loop0_184: lambda_param_maybe_default ++// _loop0_186: lambda_param_maybe_default + static asdl_seq * +-_loop0_184_rule(Parser *p) ++_loop0_186_rule(Parser *p) + { + if (p->level++ == MAXSTACK) { + p->error_indicator = 1; +@@ -36296,7 +36895,7 @@ _loop0_184_rule(Parser *p) + p->level--; + return NULL; + } +- D(fprintf(stderr, "%*c> _loop0_184[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "lambda_param_maybe_default")); ++ D(fprintf(stderr, "%*c> _loop0_186[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "lambda_param_maybe_default")); + NameDefaultPair* lambda_param_maybe_default_var; + while ( + (lambda_param_maybe_default_var = lambda_param_maybe_default_rule(p)) // lambda_param_maybe_default +@@ -36319,7 +36918,7 @@ _loop0_184_rule(Parser *p) + _mark = p->mark; + } + p->mark = _mark; +- D(fprintf(stderr, "%*c%s _loop0_184[%d-%d]: %s failed!\n", p->level, ' ', ++ D(fprintf(stderr, "%*c%s _loop0_186[%d-%d]: %s failed!\n", p->level, ' ', + p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "lambda_param_maybe_default")); + } + asdl_seq *_seq = (asdl_seq*)_Py_asdl_generic_seq_new(_n, p->arena); +@@ -36336,9 +36935,9 @@ _loop0_184_rule(Parser *p) + return _seq; + } + +-// _loop0_185: lambda_param_no_default ++// _loop0_187: lambda_param_no_default + static asdl_seq * +-_loop0_185_rule(Parser *p) ++_loop0_187_rule(Parser *p) + { + if (p->level++ == MAXSTACK) { + p->error_indicator = 1; +@@ -36364,7 +36963,7 @@ _loop0_185_rule(Parser *p) + p->level--; + return NULL; + } +- D(fprintf(stderr, "%*c> _loop0_185[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "lambda_param_no_default")); ++ D(fprintf(stderr, "%*c> _loop0_187[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "lambda_param_no_default")); + arg_ty lambda_param_no_default_var; + while ( + (lambda_param_no_default_var = lambda_param_no_default_rule(p)) // lambda_param_no_default +@@ -36387,7 +36986,7 @@ _loop0_185_rule(Parser *p) + _mark = p->mark; + } + p->mark = _mark; +- D(fprintf(stderr, "%*c%s _loop0_185[%d-%d]: %s failed!\n", p->level, ' ', ++ D(fprintf(stderr, "%*c%s _loop0_187[%d-%d]: %s failed!\n", p->level, ' ', + p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "lambda_param_no_default")); + } + asdl_seq *_seq = (asdl_seq*)_Py_asdl_generic_seq_new(_n, p->arena); +@@ -36404,9 +37003,9 @@ _loop0_185_rule(Parser *p) + return _seq; + } + +-// _loop0_186: lambda_param_no_default ++// _loop0_188: lambda_param_no_default + static asdl_seq * +-_loop0_186_rule(Parser *p) ++_loop0_188_rule(Parser *p) + { + if (p->level++ == MAXSTACK) { + p->error_indicator = 1; +@@ -36432,7 +37031,7 @@ _loop0_186_rule(Parser *p) + p->level--; + return NULL; + } +- D(fprintf(stderr, "%*c> _loop0_186[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "lambda_param_no_default")); ++ D(fprintf(stderr, "%*c> _loop0_188[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "lambda_param_no_default")); + arg_ty lambda_param_no_default_var; + while ( + (lambda_param_no_default_var = lambda_param_no_default_rule(p)) // lambda_param_no_default +@@ -36455,7 +37054,7 @@ _loop0_186_rule(Parser *p) + _mark = p->mark; + } + p->mark = _mark; +- D(fprintf(stderr, "%*c%s _loop0_186[%d-%d]: %s failed!\n", p->level, ' ', ++ D(fprintf(stderr, "%*c%s _loop0_188[%d-%d]: %s failed!\n", p->level, ' ', + p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "lambda_param_no_default")); + } + asdl_seq *_seq = (asdl_seq*)_Py_asdl_generic_seq_new(_n, p->arena); +@@ -36472,9 +37071,9 @@ _loop0_186_rule(Parser *p) + return _seq; + } + +-// _loop0_188: ',' lambda_param ++// _loop0_190: ',' lambda_param + static asdl_seq * +-_loop0_188_rule(Parser *p) ++_loop0_190_rule(Parser *p) + { + if (p->level++ == MAXSTACK) { + p->error_indicator = 1; +@@ -36500,7 +37099,7 @@ _loop0_188_rule(Parser *p) + p->level--; + return NULL; + } +- D(fprintf(stderr, "%*c> _loop0_188[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "',' lambda_param")); ++ D(fprintf(stderr, "%*c> _loop0_190[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "',' lambda_param")); + Token * _literal; + arg_ty elem; + while ( +@@ -36532,7 +37131,7 @@ _loop0_188_rule(Parser *p) + _mark = p->mark; + } + p->mark = _mark; +- D(fprintf(stderr, "%*c%s _loop0_188[%d-%d]: %s failed!\n", p->level, ' ', ++ D(fprintf(stderr, "%*c%s _loop0_190[%d-%d]: %s failed!\n", p->level, ' ', + p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "',' lambda_param")); + } + asdl_seq *_seq = (asdl_seq*)_Py_asdl_generic_seq_new(_n, p->arena); +@@ -36549,9 +37148,9 @@ _loop0_188_rule(Parser *p) + return _seq; + } + +-// _gather_187: lambda_param _loop0_188 ++// _gather_189: lambda_param _loop0_190 + static asdl_seq * +-_gather_187_rule(Parser *p) ++_gather_189_rule(Parser *p) + { + if (p->level++ == MAXSTACK) { + p->error_indicator = 1; +@@ -36563,27 +37162,27 @@ _gather_187_rule(Parser *p) + } + asdl_seq * _res = NULL; + int _mark = p->mark; +- { // lambda_param _loop0_188 ++ { // lambda_param _loop0_190 + if (p->error_indicator) { + p->level--; + return NULL; + } +- D(fprintf(stderr, "%*c> _gather_187[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "lambda_param _loop0_188")); ++ D(fprintf(stderr, "%*c> _gather_189[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "lambda_param _loop0_190")); + arg_ty elem; + asdl_seq * seq; + if ( + (elem = lambda_param_rule(p)) // lambda_param + && +- (seq = _loop0_188_rule(p)) // _loop0_188 ++ (seq = _loop0_190_rule(p)) // _loop0_190 + ) + { +- D(fprintf(stderr, "%*c+ _gather_187[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "lambda_param _loop0_188")); ++ D(fprintf(stderr, "%*c+ _gather_189[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "lambda_param _loop0_190")); + _res = _PyPegen_seq_insert_in_front(p, elem, seq); + goto done; + } + p->mark = _mark; +- D(fprintf(stderr, "%*c%s _gather_187[%d-%d]: %s failed!\n", p->level, ' ', +- p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "lambda_param _loop0_188")); ++ D(fprintf(stderr, "%*c%s _gather_189[%d-%d]: %s failed!\n", p->level, ' ', ++ p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "lambda_param _loop0_190")); + } + _res = NULL; + done: +@@ -36591,9 +37190,9 @@ _gather_187_rule(Parser *p) + return _res; + } + +-// _tmp_189: lambda_slash_no_default | lambda_slash_with_default ++// _tmp_191: lambda_slash_no_default | lambda_slash_with_default + static void * +-_tmp_189_rule(Parser *p) ++_tmp_191_rule(Parser *p) + { + if (p->level++ == MAXSTACK) { + p->error_indicator = 1; +@@ -36610,18 +37209,18 @@ _tmp_189_rule(Parser *p) + p->level--; + return NULL; + } +- D(fprintf(stderr, "%*c> _tmp_189[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "lambda_slash_no_default")); ++ D(fprintf(stderr, "%*c> _tmp_191[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "lambda_slash_no_default")); + asdl_arg_seq* lambda_slash_no_default_var; + if ( + (lambda_slash_no_default_var = lambda_slash_no_default_rule(p)) // lambda_slash_no_default + ) + { +- D(fprintf(stderr, "%*c+ _tmp_189[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "lambda_slash_no_default")); ++ D(fprintf(stderr, "%*c+ _tmp_191[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "lambda_slash_no_default")); + _res = lambda_slash_no_default_var; + goto done; + } + p->mark = _mark; +- D(fprintf(stderr, "%*c%s _tmp_189[%d-%d]: %s failed!\n", p->level, ' ', ++ D(fprintf(stderr, "%*c%s _tmp_191[%d-%d]: %s failed!\n", p->level, ' ', + p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "lambda_slash_no_default")); + } + { // lambda_slash_with_default +@@ -36629,18 +37228,18 @@ _tmp_189_rule(Parser *p) + p->level--; + return NULL; + } +- D(fprintf(stderr, "%*c> _tmp_189[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "lambda_slash_with_default")); ++ D(fprintf(stderr, "%*c> _tmp_191[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "lambda_slash_with_default")); + SlashWithDefault* lambda_slash_with_default_var; + if ( + (lambda_slash_with_default_var = lambda_slash_with_default_rule(p)) // lambda_slash_with_default + ) + { +- D(fprintf(stderr, "%*c+ _tmp_189[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "lambda_slash_with_default")); ++ D(fprintf(stderr, "%*c+ _tmp_191[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "lambda_slash_with_default")); + _res = lambda_slash_with_default_var; + goto done; + } + p->mark = _mark; +- D(fprintf(stderr, "%*c%s _tmp_189[%d-%d]: %s failed!\n", p->level, ' ', ++ D(fprintf(stderr, "%*c%s _tmp_191[%d-%d]: %s failed!\n", p->level, ' ', + p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "lambda_slash_with_default")); + } + _res = NULL; +@@ -36649,9 +37248,9 @@ _tmp_189_rule(Parser *p) + return _res; + } + +-// _loop0_190: lambda_param_maybe_default ++// _loop0_192: lambda_param_maybe_default + static asdl_seq * +-_loop0_190_rule(Parser *p) ++_loop0_192_rule(Parser *p) + { + if (p->level++ == MAXSTACK) { + p->error_indicator = 1; +@@ -36677,7 +37276,7 @@ _loop0_190_rule(Parser *p) + p->level--; + return NULL; + } +- D(fprintf(stderr, "%*c> _loop0_190[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "lambda_param_maybe_default")); ++ D(fprintf(stderr, "%*c> _loop0_192[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "lambda_param_maybe_default")); + NameDefaultPair* lambda_param_maybe_default_var; + while ( + (lambda_param_maybe_default_var = lambda_param_maybe_default_rule(p)) // lambda_param_maybe_default +@@ -36700,7 +37299,7 @@ _loop0_190_rule(Parser *p) + _mark = p->mark; + } + p->mark = _mark; +- D(fprintf(stderr, "%*c%s _loop0_190[%d-%d]: %s failed!\n", p->level, ' ', ++ D(fprintf(stderr, "%*c%s _loop0_192[%d-%d]: %s failed!\n", p->level, ' ', + p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "lambda_param_maybe_default")); + } + asdl_seq *_seq = (asdl_seq*)_Py_asdl_generic_seq_new(_n, p->arena); +@@ -36717,9 +37316,9 @@ _loop0_190_rule(Parser *p) + return _seq; + } + +-// _tmp_191: ',' | lambda_param_no_default ++// _tmp_193: ',' | lambda_param_no_default + static void * +-_tmp_191_rule(Parser *p) ++_tmp_193_rule(Parser *p) + { + if (p->level++ == MAXSTACK) { + p->error_indicator = 1; +@@ -36736,18 +37335,18 @@ _tmp_191_rule(Parser *p) + p->level--; + return NULL; + } +- D(fprintf(stderr, "%*c> _tmp_191[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "','")); ++ D(fprintf(stderr, "%*c> _tmp_193[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "','")); + Token * _literal; + if ( + (_literal = _PyPegen_expect_token(p, 12)) // token=',' + ) + { +- D(fprintf(stderr, "%*c+ _tmp_191[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "','")); ++ D(fprintf(stderr, "%*c+ _tmp_193[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "','")); + _res = _literal; + goto done; + } + p->mark = _mark; +- D(fprintf(stderr, "%*c%s _tmp_191[%d-%d]: %s failed!\n", p->level, ' ', ++ D(fprintf(stderr, "%*c%s _tmp_193[%d-%d]: %s failed!\n", p->level, ' ', + p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "','")); + } + { // lambda_param_no_default +@@ -36755,18 +37354,18 @@ _tmp_191_rule(Parser *p) + p->level--; + return NULL; + } +- D(fprintf(stderr, "%*c> _tmp_191[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "lambda_param_no_default")); ++ D(fprintf(stderr, "%*c> _tmp_193[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "lambda_param_no_default")); + arg_ty lambda_param_no_default_var; + if ( + (lambda_param_no_default_var = lambda_param_no_default_rule(p)) // lambda_param_no_default + ) + { +- D(fprintf(stderr, "%*c+ _tmp_191[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "lambda_param_no_default")); ++ D(fprintf(stderr, "%*c+ _tmp_193[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "lambda_param_no_default")); + _res = lambda_param_no_default_var; + goto done; + } + p->mark = _mark; +- D(fprintf(stderr, "%*c%s _tmp_191[%d-%d]: %s failed!\n", p->level, ' ', ++ D(fprintf(stderr, "%*c%s _tmp_193[%d-%d]: %s failed!\n", p->level, ' ', + p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "lambda_param_no_default")); + } + _res = NULL; +@@ -36775,9 +37374,9 @@ _tmp_191_rule(Parser *p) + return _res; + } + +-// _loop0_192: lambda_param_maybe_default ++// _loop0_194: lambda_param_maybe_default + static asdl_seq * +-_loop0_192_rule(Parser *p) ++_loop0_194_rule(Parser *p) + { + if (p->level++ == MAXSTACK) { + p->error_indicator = 1; +@@ -36803,7 +37402,7 @@ _loop0_192_rule(Parser *p) + p->level--; + return NULL; + } +- D(fprintf(stderr, "%*c> _loop0_192[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "lambda_param_maybe_default")); ++ D(fprintf(stderr, "%*c> _loop0_194[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "lambda_param_maybe_default")); + NameDefaultPair* lambda_param_maybe_default_var; + while ( + (lambda_param_maybe_default_var = lambda_param_maybe_default_rule(p)) // lambda_param_maybe_default +@@ -36826,7 +37425,7 @@ _loop0_192_rule(Parser *p) + _mark = p->mark; + } + p->mark = _mark; +- D(fprintf(stderr, "%*c%s _loop0_192[%d-%d]: %s failed!\n", p->level, ' ', ++ D(fprintf(stderr, "%*c%s _loop0_194[%d-%d]: %s failed!\n", p->level, ' ', + p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "lambda_param_maybe_default")); + } + asdl_seq *_seq = (asdl_seq*)_Py_asdl_generic_seq_new(_n, p->arena); +@@ -36843,9 +37442,9 @@ _loop0_192_rule(Parser *p) + return _seq; + } + +-// _loop1_193: lambda_param_maybe_default ++// _loop1_195: lambda_param_maybe_default + static asdl_seq * +-_loop1_193_rule(Parser *p) ++_loop1_195_rule(Parser *p) + { + if (p->level++ == MAXSTACK) { + p->error_indicator = 1; +@@ -36871,7 +37470,7 @@ _loop1_193_rule(Parser *p) + p->level--; + return NULL; + } +- D(fprintf(stderr, "%*c> _loop1_193[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "lambda_param_maybe_default")); ++ D(fprintf(stderr, "%*c> _loop1_195[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "lambda_param_maybe_default")); + NameDefaultPair* lambda_param_maybe_default_var; + while ( + (lambda_param_maybe_default_var = lambda_param_maybe_default_rule(p)) // lambda_param_maybe_default +@@ -36894,7 +37493,7 @@ _loop1_193_rule(Parser *p) + _mark = p->mark; + } + p->mark = _mark; +- D(fprintf(stderr, "%*c%s _loop1_193[%d-%d]: %s failed!\n", p->level, ' ', ++ D(fprintf(stderr, "%*c%s _loop1_195[%d-%d]: %s failed!\n", p->level, ' ', + p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "lambda_param_maybe_default")); + } + if (_n == 0 || p->error_indicator) { +@@ -36916,9 +37515,9 @@ _loop1_193_rule(Parser *p) + return _seq; + } + +-// _loop1_194: lambda_param_with_default ++// _loop1_196: lambda_param_with_default + static asdl_seq * +-_loop1_194_rule(Parser *p) ++_loop1_196_rule(Parser *p) + { + if (p->level++ == MAXSTACK) { + p->error_indicator = 1; +@@ -36944,7 +37543,7 @@ _loop1_194_rule(Parser *p) + p->level--; + return NULL; + } +- D(fprintf(stderr, "%*c> _loop1_194[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "lambda_param_with_default")); ++ D(fprintf(stderr, "%*c> _loop1_196[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "lambda_param_with_default")); + NameDefaultPair* lambda_param_with_default_var; + while ( + (lambda_param_with_default_var = lambda_param_with_default_rule(p)) // lambda_param_with_default +@@ -36967,7 +37566,7 @@ _loop1_194_rule(Parser *p) + _mark = p->mark; + } + p->mark = _mark; +- D(fprintf(stderr, "%*c%s _loop1_194[%d-%d]: %s failed!\n", p->level, ' ', ++ D(fprintf(stderr, "%*c%s _loop1_196[%d-%d]: %s failed!\n", p->level, ' ', + p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "lambda_param_with_default")); + } + if (_n == 0 || p->error_indicator) { +@@ -36989,9 +37588,9 @@ _loop1_194_rule(Parser *p) + return _seq; + } + +-// _tmp_195: ':' | ',' (':' | '**') ++// _tmp_197: ':' | ',' (':' | '**') + static void * +-_tmp_195_rule(Parser *p) ++_tmp_197_rule(Parser *p) + { + if (p->level++ == MAXSTACK) { + p->error_indicator = 1; +@@ -37008,18 +37607,18 @@ _tmp_195_rule(Parser *p) + p->level--; + return NULL; + } +- D(fprintf(stderr, "%*c> _tmp_195[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "':'")); ++ D(fprintf(stderr, "%*c> _tmp_197[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "':'")); + Token * _literal; + if ( + (_literal = _PyPegen_expect_token(p, 11)) // token=':' + ) + { +- D(fprintf(stderr, "%*c+ _tmp_195[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "':'")); ++ D(fprintf(stderr, "%*c+ _tmp_197[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "':'")); + _res = _literal; + goto done; + } + p->mark = _mark; +- D(fprintf(stderr, "%*c%s _tmp_195[%d-%d]: %s failed!\n", p->level, ' ', ++ D(fprintf(stderr, "%*c%s _tmp_197[%d-%d]: %s failed!\n", p->level, ' ', + p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "':'")); + } + { // ',' (':' | '**') +@@ -37027,21 +37626,21 @@ _tmp_195_rule(Parser *p) + p->level--; + return NULL; + } +- D(fprintf(stderr, "%*c> _tmp_195[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "',' (':' | '**')")); ++ D(fprintf(stderr, "%*c> _tmp_197[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "',' (':' | '**')")); + Token * _literal; +- void *_tmp_262_var; ++ void *_tmp_264_var; + if ( + (_literal = _PyPegen_expect_token(p, 12)) // token=',' + && +- (_tmp_262_var = _tmp_262_rule(p)) // ':' | '**' ++ (_tmp_264_var = _tmp_264_rule(p)) // ':' | '**' + ) + { +- D(fprintf(stderr, "%*c+ _tmp_195[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "',' (':' | '**')")); +- _res = _PyPegen_dummy_name(p, _literal, _tmp_262_var); ++ D(fprintf(stderr, "%*c+ _tmp_197[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "',' (':' | '**')")); ++ _res = _PyPegen_dummy_name(p, _literal, _tmp_264_var); + goto done; + } + p->mark = _mark; +- D(fprintf(stderr, "%*c%s _tmp_195[%d-%d]: %s failed!\n", p->level, ' ', ++ D(fprintf(stderr, "%*c%s _tmp_197[%d-%d]: %s failed!\n", p->level, ' ', + p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "',' (':' | '**')")); + } + _res = NULL; +@@ -37050,9 +37649,9 @@ _tmp_195_rule(Parser *p) + return _res; + } + +-// _tmp_196: lambda_param_no_default | ',' ++// _tmp_198: lambda_param_no_default | ',' + static void * +-_tmp_196_rule(Parser *p) ++_tmp_198_rule(Parser *p) + { + if (p->level++ == MAXSTACK) { + p->error_indicator = 1; +@@ -37069,18 +37668,18 @@ _tmp_196_rule(Parser *p) + p->level--; + return NULL; + } +- D(fprintf(stderr, "%*c> _tmp_196[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "lambda_param_no_default")); ++ D(fprintf(stderr, "%*c> _tmp_198[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "lambda_param_no_default")); + arg_ty lambda_param_no_default_var; + if ( + (lambda_param_no_default_var = lambda_param_no_default_rule(p)) // lambda_param_no_default + ) + { +- D(fprintf(stderr, "%*c+ _tmp_196[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "lambda_param_no_default")); ++ D(fprintf(stderr, "%*c+ _tmp_198[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "lambda_param_no_default")); + _res = lambda_param_no_default_var; + goto done; + } + p->mark = _mark; +- D(fprintf(stderr, "%*c%s _tmp_196[%d-%d]: %s failed!\n", p->level, ' ', ++ D(fprintf(stderr, "%*c%s _tmp_198[%d-%d]: %s failed!\n", p->level, ' ', + p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "lambda_param_no_default")); + } + { // ',' +@@ -37088,18 +37687,18 @@ _tmp_196_rule(Parser *p) + p->level--; + return NULL; + } +- D(fprintf(stderr, "%*c> _tmp_196[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "','")); ++ D(fprintf(stderr, "%*c> _tmp_198[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "','")); + Token * _literal; + if ( + (_literal = _PyPegen_expect_token(p, 12)) // token=',' + ) + { +- D(fprintf(stderr, "%*c+ _tmp_196[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "','")); ++ D(fprintf(stderr, "%*c+ _tmp_198[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "','")); + _res = _literal; + goto done; + } + p->mark = _mark; +- D(fprintf(stderr, "%*c%s _tmp_196[%d-%d]: %s failed!\n", p->level, ' ', ++ D(fprintf(stderr, "%*c%s _tmp_198[%d-%d]: %s failed!\n", p->level, ' ', + p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "','")); + } + _res = NULL; +@@ -37108,9 +37707,9 @@ _tmp_196_rule(Parser *p) + return _res; + } + +-// _loop0_197: lambda_param_maybe_default ++// _loop0_199: lambda_param_maybe_default + static asdl_seq * +-_loop0_197_rule(Parser *p) ++_loop0_199_rule(Parser *p) + { + if (p->level++ == MAXSTACK) { + p->error_indicator = 1; +@@ -37136,7 +37735,7 @@ _loop0_197_rule(Parser *p) + p->level--; + return NULL; + } +- D(fprintf(stderr, "%*c> _loop0_197[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "lambda_param_maybe_default")); ++ D(fprintf(stderr, "%*c> _loop0_199[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "lambda_param_maybe_default")); + NameDefaultPair* lambda_param_maybe_default_var; + while ( + (lambda_param_maybe_default_var = lambda_param_maybe_default_rule(p)) // lambda_param_maybe_default +@@ -37159,7 +37758,7 @@ _loop0_197_rule(Parser *p) + _mark = p->mark; + } + p->mark = _mark; +- D(fprintf(stderr, "%*c%s _loop0_197[%d-%d]: %s failed!\n", p->level, ' ', ++ D(fprintf(stderr, "%*c%s _loop0_199[%d-%d]: %s failed!\n", p->level, ' ', + p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "lambda_param_maybe_default")); + } + asdl_seq *_seq = (asdl_seq*)_Py_asdl_generic_seq_new(_n, p->arena); +@@ -37176,9 +37775,9 @@ _loop0_197_rule(Parser *p) + return _seq; + } + +-// _tmp_198: lambda_param_no_default | ',' ++// _tmp_200: lambda_param_no_default | ',' + static void * +-_tmp_198_rule(Parser *p) ++_tmp_200_rule(Parser *p) + { + if (p->level++ == MAXSTACK) { + p->error_indicator = 1; +@@ -37195,18 +37794,18 @@ _tmp_198_rule(Parser *p) + p->level--; + return NULL; + } +- D(fprintf(stderr, "%*c> _tmp_198[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "lambda_param_no_default")); ++ D(fprintf(stderr, "%*c> _tmp_200[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "lambda_param_no_default")); + arg_ty lambda_param_no_default_var; + if ( + (lambda_param_no_default_var = lambda_param_no_default_rule(p)) // lambda_param_no_default + ) + { +- D(fprintf(stderr, "%*c+ _tmp_198[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "lambda_param_no_default")); ++ D(fprintf(stderr, "%*c+ _tmp_200[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "lambda_param_no_default")); + _res = lambda_param_no_default_var; + goto done; + } + p->mark = _mark; +- D(fprintf(stderr, "%*c%s _tmp_198[%d-%d]: %s failed!\n", p->level, ' ', ++ D(fprintf(stderr, "%*c%s _tmp_200[%d-%d]: %s failed!\n", p->level, ' ', + p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "lambda_param_no_default")); + } + { // ',' +@@ -37214,18 +37813,18 @@ _tmp_198_rule(Parser *p) + p->level--; + return NULL; + } +- D(fprintf(stderr, "%*c> _tmp_198[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "','")); ++ D(fprintf(stderr, "%*c> _tmp_200[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "','")); + Token * _literal; + if ( + (_literal = _PyPegen_expect_token(p, 12)) // token=',' + ) + { +- D(fprintf(stderr, "%*c+ _tmp_198[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "','")); ++ D(fprintf(stderr, "%*c+ _tmp_200[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "','")); + _res = _literal; + goto done; + } + p->mark = _mark; +- D(fprintf(stderr, "%*c%s _tmp_198[%d-%d]: %s failed!\n", p->level, ' ', ++ D(fprintf(stderr, "%*c%s _tmp_200[%d-%d]: %s failed!\n", p->level, ' ', + p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "','")); + } + _res = NULL; +@@ -37234,9 +37833,9 @@ _tmp_198_rule(Parser *p) + return _res; + } + +-// _tmp_199: '*' | '**' | '/' ++// _tmp_201: '*' | '**' | '/' + static void * +-_tmp_199_rule(Parser *p) ++_tmp_201_rule(Parser *p) + { + if (p->level++ == MAXSTACK) { + p->error_indicator = 1; +@@ -37253,18 +37852,18 @@ _tmp_199_rule(Parser *p) + p->level--; + return NULL; + } +- D(fprintf(stderr, "%*c> _tmp_199[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "'*'")); ++ D(fprintf(stderr, "%*c> _tmp_201[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "'*'")); + Token * _literal; + if ( + (_literal = _PyPegen_expect_token(p, 16)) // token='*' + ) + { +- D(fprintf(stderr, "%*c+ _tmp_199[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "'*'")); ++ D(fprintf(stderr, "%*c+ _tmp_201[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "'*'")); + _res = _literal; + goto done; + } + p->mark = _mark; +- D(fprintf(stderr, "%*c%s _tmp_199[%d-%d]: %s failed!\n", p->level, ' ', ++ D(fprintf(stderr, "%*c%s _tmp_201[%d-%d]: %s failed!\n", p->level, ' ', + p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "'*'")); + } + { // '**' +@@ -37272,18 +37871,18 @@ _tmp_199_rule(Parser *p) + p->level--; + return NULL; + } +- D(fprintf(stderr, "%*c> _tmp_199[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "'**'")); ++ D(fprintf(stderr, "%*c> _tmp_201[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "'**'")); + Token * _literal; + if ( + (_literal = _PyPegen_expect_token(p, 35)) // token='**' + ) + { +- D(fprintf(stderr, "%*c+ _tmp_199[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "'**'")); ++ D(fprintf(stderr, "%*c+ _tmp_201[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "'**'")); + _res = _literal; + goto done; + } + p->mark = _mark; +- D(fprintf(stderr, "%*c%s _tmp_199[%d-%d]: %s failed!\n", p->level, ' ', ++ D(fprintf(stderr, "%*c%s _tmp_201[%d-%d]: %s failed!\n", p->level, ' ', + p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "'**'")); + } + { // '/' +@@ -37291,18 +37890,18 @@ _tmp_199_rule(Parser *p) + p->level--; + return NULL; + } +- D(fprintf(stderr, "%*c> _tmp_199[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "'/'")); ++ D(fprintf(stderr, "%*c> _tmp_201[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "'/'")); + Token * _literal; + if ( + (_literal = _PyPegen_expect_token(p, 17)) // token='/' + ) + { +- D(fprintf(stderr, "%*c+ _tmp_199[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "'/'")); ++ D(fprintf(stderr, "%*c+ _tmp_201[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "'/'")); + _res = _literal; + goto done; + } + p->mark = _mark; +- D(fprintf(stderr, "%*c%s _tmp_199[%d-%d]: %s failed!\n", p->level, ' ', ++ D(fprintf(stderr, "%*c%s _tmp_201[%d-%d]: %s failed!\n", p->level, ' ', + p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "'/'")); + } + _res = NULL; +@@ -37311,9 +37910,9 @@ _tmp_199_rule(Parser *p) + return _res; + } + +-// _tmp_200: ',' | ')' | ':' ++// _tmp_202: ',' | ')' | ':' + static void * +-_tmp_200_rule(Parser *p) ++_tmp_202_rule(Parser *p) + { + if (p->level++ == MAXSTACK) { + p->error_indicator = 1; +@@ -37330,18 +37929,18 @@ _tmp_200_rule(Parser *p) + p->level--; + return NULL; + } +- D(fprintf(stderr, "%*c> _tmp_200[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "','")); ++ D(fprintf(stderr, "%*c> _tmp_202[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "','")); + Token * _literal; + if ( + (_literal = _PyPegen_expect_token(p, 12)) // token=',' + ) + { +- D(fprintf(stderr, "%*c+ _tmp_200[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "','")); ++ D(fprintf(stderr, "%*c+ _tmp_202[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "','")); + _res = _literal; + goto done; + } + p->mark = _mark; +- D(fprintf(stderr, "%*c%s _tmp_200[%d-%d]: %s failed!\n", p->level, ' ', ++ D(fprintf(stderr, "%*c%s _tmp_202[%d-%d]: %s failed!\n", p->level, ' ', + p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "','")); + } + { // ')' +@@ -37349,18 +37948,18 @@ _tmp_200_rule(Parser *p) + p->level--; + return NULL; + } +- D(fprintf(stderr, "%*c> _tmp_200[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "')'")); ++ D(fprintf(stderr, "%*c> _tmp_202[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "')'")); + Token * _literal; + if ( + (_literal = _PyPegen_expect_token(p, 8)) // token=')' + ) + { +- D(fprintf(stderr, "%*c+ _tmp_200[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "')'")); ++ D(fprintf(stderr, "%*c+ _tmp_202[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "')'")); + _res = _literal; + goto done; + } + p->mark = _mark; +- D(fprintf(stderr, "%*c%s _tmp_200[%d-%d]: %s failed!\n", p->level, ' ', ++ D(fprintf(stderr, "%*c%s _tmp_202[%d-%d]: %s failed!\n", p->level, ' ', + p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "')'")); + } + { // ':' +@@ -37368,18 +37967,18 @@ _tmp_200_rule(Parser *p) + p->level--; + return NULL; + } +- D(fprintf(stderr, "%*c> _tmp_200[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "':'")); ++ D(fprintf(stderr, "%*c> _tmp_202[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "':'")); + Token * _literal; + if ( + (_literal = _PyPegen_expect_token(p, 11)) // token=':' + ) + { +- D(fprintf(stderr, "%*c+ _tmp_200[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "':'")); ++ D(fprintf(stderr, "%*c+ _tmp_202[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "':'")); + _res = _literal; + goto done; + } + p->mark = _mark; +- D(fprintf(stderr, "%*c%s _tmp_200[%d-%d]: %s failed!\n", p->level, ' ', ++ D(fprintf(stderr, "%*c%s _tmp_202[%d-%d]: %s failed!\n", p->level, ' ', + p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "':'")); + } + _res = NULL; +@@ -37388,9 +37987,9 @@ _tmp_200_rule(Parser *p) + return _res; + } + +-// _loop0_202: ',' (expression ['as' star_target]) ++// _loop0_204: ',' (expression ['as' star_target]) + static asdl_seq * +-_loop0_202_rule(Parser *p) ++_loop0_204_rule(Parser *p) + { + if (p->level++ == MAXSTACK) { + p->error_indicator = 1; +@@ -37416,13 +38015,13 @@ _loop0_202_rule(Parser *p) + p->level--; + return NULL; + } +- D(fprintf(stderr, "%*c> _loop0_202[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "',' (expression ['as' star_target])")); ++ D(fprintf(stderr, "%*c> _loop0_204[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "',' (expression ['as' star_target])")); + Token * _literal; + void *elem; + while ( + (_literal = _PyPegen_expect_token(p, 12)) // token=',' + && +- (elem = _tmp_263_rule(p)) // expression ['as' star_target] ++ (elem = _tmp_265_rule(p)) // expression ['as' star_target] + ) + { + _res = elem; +@@ -37448,7 +38047,7 @@ _loop0_202_rule(Parser *p) + _mark = p->mark; + } + p->mark = _mark; +- D(fprintf(stderr, "%*c%s _loop0_202[%d-%d]: %s failed!\n", p->level, ' ', ++ D(fprintf(stderr, "%*c%s _loop0_204[%d-%d]: %s failed!\n", p->level, ' ', + p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "',' (expression ['as' star_target])")); + } + asdl_seq *_seq = (asdl_seq*)_Py_asdl_generic_seq_new(_n, p->arena); +@@ -37465,9 +38064,9 @@ _loop0_202_rule(Parser *p) + return _seq; + } + +-// _gather_201: (expression ['as' star_target]) _loop0_202 ++// _gather_203: (expression ['as' star_target]) _loop0_204 + static asdl_seq * +-_gather_201_rule(Parser *p) ++_gather_203_rule(Parser *p) + { + if (p->level++ == MAXSTACK) { + p->error_indicator = 1; +@@ -37479,27 +38078,27 @@ _gather_201_rule(Parser *p) + } + asdl_seq * _res = NULL; + int _mark = p->mark; +- { // (expression ['as' star_target]) _loop0_202 ++ { // (expression ['as' star_target]) _loop0_204 + if (p->error_indicator) { + p->level--; + return NULL; + } +- D(fprintf(stderr, "%*c> _gather_201[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "(expression ['as' star_target]) _loop0_202")); ++ D(fprintf(stderr, "%*c> _gather_203[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "(expression ['as' star_target]) _loop0_204")); + void *elem; + asdl_seq * seq; + if ( +- (elem = _tmp_263_rule(p)) // expression ['as' star_target] ++ (elem = _tmp_265_rule(p)) // expression ['as' star_target] + && +- (seq = _loop0_202_rule(p)) // _loop0_202 ++ (seq = _loop0_204_rule(p)) // _loop0_204 + ) + { +- D(fprintf(stderr, "%*c+ _gather_201[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "(expression ['as' star_target]) _loop0_202")); ++ D(fprintf(stderr, "%*c+ _gather_203[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "(expression ['as' star_target]) _loop0_204")); + _res = _PyPegen_seq_insert_in_front(p, elem, seq); + goto done; + } + p->mark = _mark; +- D(fprintf(stderr, "%*c%s _gather_201[%d-%d]: %s failed!\n", p->level, ' ', +- p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "(expression ['as' star_target]) _loop0_202")); ++ D(fprintf(stderr, "%*c%s _gather_203[%d-%d]: %s failed!\n", p->level, ' ', ++ p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "(expression ['as' star_target]) _loop0_204")); + } + _res = NULL; + done: +@@ -37507,9 +38106,9 @@ _gather_201_rule(Parser *p) + return _res; + } + +-// _loop0_204: ',' (expressions ['as' star_target]) ++// _loop0_206: ',' (expressions ['as' star_target]) + static asdl_seq * +-_loop0_204_rule(Parser *p) ++_loop0_206_rule(Parser *p) + { + if (p->level++ == MAXSTACK) { + p->error_indicator = 1; +@@ -37535,13 +38134,13 @@ _loop0_204_rule(Parser *p) + p->level--; + return NULL; + } +- D(fprintf(stderr, "%*c> _loop0_204[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "',' (expressions ['as' star_target])")); ++ D(fprintf(stderr, "%*c> _loop0_206[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "',' (expressions ['as' star_target])")); + Token * _literal; + void *elem; + while ( + (_literal = _PyPegen_expect_token(p, 12)) // token=',' + && +- (elem = _tmp_264_rule(p)) // expressions ['as' star_target] ++ (elem = _tmp_266_rule(p)) // expressions ['as' star_target] + ) + { + _res = elem; +@@ -37567,7 +38166,7 @@ _loop0_204_rule(Parser *p) + _mark = p->mark; + } + p->mark = _mark; +- D(fprintf(stderr, "%*c%s _loop0_204[%d-%d]: %s failed!\n", p->level, ' ', ++ D(fprintf(stderr, "%*c%s _loop0_206[%d-%d]: %s failed!\n", p->level, ' ', + p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "',' (expressions ['as' star_target])")); + } + asdl_seq *_seq = (asdl_seq*)_Py_asdl_generic_seq_new(_n, p->arena); +@@ -37584,9 +38183,9 @@ _loop0_204_rule(Parser *p) + return _seq; + } + +-// _gather_203: (expressions ['as' star_target]) _loop0_204 ++// _gather_205: (expressions ['as' star_target]) _loop0_206 + static asdl_seq * +-_gather_203_rule(Parser *p) ++_gather_205_rule(Parser *p) + { + if (p->level++ == MAXSTACK) { + p->error_indicator = 1; +@@ -37598,27 +38197,27 @@ _gather_203_rule(Parser *p) + } + asdl_seq * _res = NULL; + int _mark = p->mark; +- { // (expressions ['as' star_target]) _loop0_204 ++ { // (expressions ['as' star_target]) _loop0_206 + if (p->error_indicator) { + p->level--; + return NULL; + } +- D(fprintf(stderr, "%*c> _gather_203[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "(expressions ['as' star_target]) _loop0_204")); ++ D(fprintf(stderr, "%*c> _gather_205[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "(expressions ['as' star_target]) _loop0_206")); + void *elem; + asdl_seq * seq; + if ( +- (elem = _tmp_264_rule(p)) // expressions ['as' star_target] ++ (elem = _tmp_266_rule(p)) // expressions ['as' star_target] + && +- (seq = _loop0_204_rule(p)) // _loop0_204 ++ (seq = _loop0_206_rule(p)) // _loop0_206 + ) + { +- D(fprintf(stderr, "%*c+ _gather_203[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "(expressions ['as' star_target]) _loop0_204")); ++ D(fprintf(stderr, "%*c+ _gather_205[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "(expressions ['as' star_target]) _loop0_206")); + _res = _PyPegen_seq_insert_in_front(p, elem, seq); + goto done; + } + p->mark = _mark; +- D(fprintf(stderr, "%*c%s _gather_203[%d-%d]: %s failed!\n", p->level, ' ', +- p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "(expressions ['as' star_target]) _loop0_204")); ++ D(fprintf(stderr, "%*c%s _gather_205[%d-%d]: %s failed!\n", p->level, ' ', ++ p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "(expressions ['as' star_target]) _loop0_206")); + } + _res = NULL; + done: +@@ -37626,9 +38225,9 @@ _gather_203_rule(Parser *p) + return _res; + } + +-// _loop0_206: ',' (expression ['as' star_target]) ++// _loop0_208: ',' (expression ['as' star_target]) + static asdl_seq * +-_loop0_206_rule(Parser *p) ++_loop0_208_rule(Parser *p) + { + if (p->level++ == MAXSTACK) { + p->error_indicator = 1; +@@ -37654,13 +38253,13 @@ _loop0_206_rule(Parser *p) + p->level--; + return NULL; + } +- D(fprintf(stderr, "%*c> _loop0_206[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "',' (expression ['as' star_target])")); ++ D(fprintf(stderr, "%*c> _loop0_208[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "',' (expression ['as' star_target])")); + Token * _literal; + void *elem; + while ( + (_literal = _PyPegen_expect_token(p, 12)) // token=',' + && +- (elem = _tmp_265_rule(p)) // expression ['as' star_target] ++ (elem = _tmp_267_rule(p)) // expression ['as' star_target] + ) + { + _res = elem; +@@ -37686,7 +38285,7 @@ _loop0_206_rule(Parser *p) + _mark = p->mark; + } + p->mark = _mark; +- D(fprintf(stderr, "%*c%s _loop0_206[%d-%d]: %s failed!\n", p->level, ' ', ++ D(fprintf(stderr, "%*c%s _loop0_208[%d-%d]: %s failed!\n", p->level, ' ', + p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "',' (expression ['as' star_target])")); + } + asdl_seq *_seq = (asdl_seq*)_Py_asdl_generic_seq_new(_n, p->arena); +@@ -37703,9 +38302,9 @@ _loop0_206_rule(Parser *p) + return _seq; + } + +-// _gather_205: (expression ['as' star_target]) _loop0_206 ++// _gather_207: (expression ['as' star_target]) _loop0_208 + static asdl_seq * +-_gather_205_rule(Parser *p) ++_gather_207_rule(Parser *p) + { + if (p->level++ == MAXSTACK) { + p->error_indicator = 1; +@@ -37717,27 +38316,27 @@ _gather_205_rule(Parser *p) + } + asdl_seq * _res = NULL; + int _mark = p->mark; +- { // (expression ['as' star_target]) _loop0_206 ++ { // (expression ['as' star_target]) _loop0_208 + if (p->error_indicator) { + p->level--; + return NULL; + } +- D(fprintf(stderr, "%*c> _gather_205[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "(expression ['as' star_target]) _loop0_206")); ++ D(fprintf(stderr, "%*c> _gather_207[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "(expression ['as' star_target]) _loop0_208")); + void *elem; + asdl_seq * seq; + if ( +- (elem = _tmp_265_rule(p)) // expression ['as' star_target] ++ (elem = _tmp_267_rule(p)) // expression ['as' star_target] + && +- (seq = _loop0_206_rule(p)) // _loop0_206 ++ (seq = _loop0_208_rule(p)) // _loop0_208 + ) + { +- D(fprintf(stderr, "%*c+ _gather_205[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "(expression ['as' star_target]) _loop0_206")); ++ D(fprintf(stderr, "%*c+ _gather_207[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "(expression ['as' star_target]) _loop0_208")); + _res = _PyPegen_seq_insert_in_front(p, elem, seq); + goto done; + } + p->mark = _mark; +- D(fprintf(stderr, "%*c%s _gather_205[%d-%d]: %s failed!\n", p->level, ' ', +- p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "(expression ['as' star_target]) _loop0_206")); ++ D(fprintf(stderr, "%*c%s _gather_207[%d-%d]: %s failed!\n", p->level, ' ', ++ p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "(expression ['as' star_target]) _loop0_208")); + } + _res = NULL; + done: +@@ -37745,9 +38344,9 @@ _gather_205_rule(Parser *p) + return _res; + } + +-// _loop0_208: ',' (expressions ['as' star_target]) ++// _loop0_210: ',' (expressions ['as' star_target]) + static asdl_seq * +-_loop0_208_rule(Parser *p) ++_loop0_210_rule(Parser *p) + { + if (p->level++ == MAXSTACK) { + p->error_indicator = 1; +@@ -37773,13 +38372,13 @@ _loop0_208_rule(Parser *p) + p->level--; + return NULL; + } +- D(fprintf(stderr, "%*c> _loop0_208[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "',' (expressions ['as' star_target])")); ++ D(fprintf(stderr, "%*c> _loop0_210[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "',' (expressions ['as' star_target])")); + Token * _literal; + void *elem; + while ( + (_literal = _PyPegen_expect_token(p, 12)) // token=',' + && +- (elem = _tmp_266_rule(p)) // expressions ['as' star_target] ++ (elem = _tmp_268_rule(p)) // expressions ['as' star_target] + ) + { + _res = elem; +@@ -37805,7 +38404,7 @@ _loop0_208_rule(Parser *p) + _mark = p->mark; + } + p->mark = _mark; +- D(fprintf(stderr, "%*c%s _loop0_208[%d-%d]: %s failed!\n", p->level, ' ', ++ D(fprintf(stderr, "%*c%s _loop0_210[%d-%d]: %s failed!\n", p->level, ' ', + p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "',' (expressions ['as' star_target])")); + } + asdl_seq *_seq = (asdl_seq*)_Py_asdl_generic_seq_new(_n, p->arena); +@@ -37822,9 +38421,9 @@ _loop0_208_rule(Parser *p) + return _seq; + } + +-// _gather_207: (expressions ['as' star_target]) _loop0_208 ++// _gather_209: (expressions ['as' star_target]) _loop0_210 + static asdl_seq * +-_gather_207_rule(Parser *p) ++_gather_209_rule(Parser *p) + { + if (p->level++ == MAXSTACK) { + p->error_indicator = 1; +@@ -37836,27 +38435,27 @@ _gather_207_rule(Parser *p) + } + asdl_seq * _res = NULL; + int _mark = p->mark; +- { // (expressions ['as' star_target]) _loop0_208 ++ { // (expressions ['as' star_target]) _loop0_210 + if (p->error_indicator) { + p->level--; + return NULL; + } +- D(fprintf(stderr, "%*c> _gather_207[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "(expressions ['as' star_target]) _loop0_208")); ++ D(fprintf(stderr, "%*c> _gather_209[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "(expressions ['as' star_target]) _loop0_210")); + void *elem; + asdl_seq * seq; + if ( +- (elem = _tmp_266_rule(p)) // expressions ['as' star_target] ++ (elem = _tmp_268_rule(p)) // expressions ['as' star_target] + && +- (seq = _loop0_208_rule(p)) // _loop0_208 ++ (seq = _loop0_210_rule(p)) // _loop0_210 + ) + { +- D(fprintf(stderr, "%*c+ _gather_207[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "(expressions ['as' star_target]) _loop0_208")); ++ D(fprintf(stderr, "%*c+ _gather_209[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "(expressions ['as' star_target]) _loop0_210")); + _res = _PyPegen_seq_insert_in_front(p, elem, seq); + goto done; + } + p->mark = _mark; +- D(fprintf(stderr, "%*c%s _gather_207[%d-%d]: %s failed!\n", p->level, ' ', +- p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "(expressions ['as' star_target]) _loop0_208")); ++ D(fprintf(stderr, "%*c%s _gather_209[%d-%d]: %s failed!\n", p->level, ' ', ++ p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "(expressions ['as' star_target]) _loop0_210")); + } + _res = NULL; + done: +@@ -37864,9 +38463,9 @@ _gather_207_rule(Parser *p) + return _res; + } + +-// _tmp_209: 'except' | 'finally' ++// _tmp_211: 'except' | 'finally' + static void * +-_tmp_209_rule(Parser *p) ++_tmp_211_rule(Parser *p) + { + if (p->level++ == MAXSTACK) { + p->error_indicator = 1; +@@ -37883,18 +38482,18 @@ _tmp_209_rule(Parser *p) + p->level--; + return NULL; + } +- D(fprintf(stderr, "%*c> _tmp_209[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "'except'")); ++ D(fprintf(stderr, "%*c> _tmp_211[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "'except'")); + Token * _keyword; + if ( + (_keyword = _PyPegen_expect_token(p, 637)) // token='except' + ) + { +- D(fprintf(stderr, "%*c+ _tmp_209[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "'except'")); ++ D(fprintf(stderr, "%*c+ _tmp_211[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "'except'")); + _res = _keyword; + goto done; + } + p->mark = _mark; +- D(fprintf(stderr, "%*c%s _tmp_209[%d-%d]: %s failed!\n", p->level, ' ', ++ D(fprintf(stderr, "%*c%s _tmp_211[%d-%d]: %s failed!\n", p->level, ' ', + p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "'except'")); + } + { // 'finally' +@@ -37902,18 +38501,18 @@ _tmp_209_rule(Parser *p) + p->level--; + return NULL; + } +- D(fprintf(stderr, "%*c> _tmp_209[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "'finally'")); ++ D(fprintf(stderr, "%*c> _tmp_211[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "'finally'")); + Token * _keyword; + if ( + (_keyword = _PyPegen_expect_token(p, 633)) // token='finally' + ) + { +- D(fprintf(stderr, "%*c+ _tmp_209[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "'finally'")); ++ D(fprintf(stderr, "%*c+ _tmp_211[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "'finally'")); + _res = _keyword; + goto done; + } + p->mark = _mark; +- D(fprintf(stderr, "%*c%s _tmp_209[%d-%d]: %s failed!\n", p->level, ' ', ++ D(fprintf(stderr, "%*c%s _tmp_211[%d-%d]: %s failed!\n", p->level, ' ', + p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "'finally'")); + } + _res = NULL; +@@ -37922,9 +38521,9 @@ _tmp_209_rule(Parser *p) + return _res; + } + +-// _loop0_210: block ++// _loop0_212: block + static asdl_seq * +-_loop0_210_rule(Parser *p) ++_loop0_212_rule(Parser *p) + { + if (p->level++ == MAXSTACK) { + p->error_indicator = 1; +@@ -37950,7 +38549,7 @@ _loop0_210_rule(Parser *p) + p->level--; + return NULL; + } +- D(fprintf(stderr, "%*c> _loop0_210[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "block")); ++ D(fprintf(stderr, "%*c> _loop0_212[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "block")); + asdl_stmt_seq* block_var; + while ( + (block_var = block_rule(p)) // block +@@ -37973,7 +38572,7 @@ _loop0_210_rule(Parser *p) + _mark = p->mark; + } + p->mark = _mark; +- D(fprintf(stderr, "%*c%s _loop0_210[%d-%d]: %s failed!\n", p->level, ' ', ++ D(fprintf(stderr, "%*c%s _loop0_212[%d-%d]: %s failed!\n", p->level, ' ', + p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "block")); + } + asdl_seq *_seq = (asdl_seq*)_Py_asdl_generic_seq_new(_n, p->arena); +@@ -37990,9 +38589,9 @@ _loop0_210_rule(Parser *p) + return _seq; + } + +-// _loop1_211: except_block ++// _loop1_213: except_block + static asdl_seq * +-_loop1_211_rule(Parser *p) ++_loop1_213_rule(Parser *p) + { + if (p->level++ == MAXSTACK) { + p->error_indicator = 1; +@@ -38018,7 +38617,7 @@ _loop1_211_rule(Parser *p) + p->level--; + return NULL; + } +- D(fprintf(stderr, "%*c> _loop1_211[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "except_block")); ++ D(fprintf(stderr, "%*c> _loop1_213[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "except_block")); + excepthandler_ty except_block_var; + while ( + (except_block_var = except_block_rule(p)) // except_block +@@ -38041,7 +38640,7 @@ _loop1_211_rule(Parser *p) + _mark = p->mark; + } + p->mark = _mark; +- D(fprintf(stderr, "%*c%s _loop1_211[%d-%d]: %s failed!\n", p->level, ' ', ++ D(fprintf(stderr, "%*c%s _loop1_213[%d-%d]: %s failed!\n", p->level, ' ', + p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "except_block")); + } + if (_n == 0 || p->error_indicator) { +@@ -38063,9 +38662,9 @@ _loop1_211_rule(Parser *p) + return _seq; + } + +-// _tmp_212: 'as' NAME ++// _tmp_214: 'as' NAME + static void * +-_tmp_212_rule(Parser *p) ++_tmp_214_rule(Parser *p) + { + if (p->level++ == MAXSTACK) { + p->error_indicator = 1; +@@ -38082,7 +38681,7 @@ _tmp_212_rule(Parser *p) + p->level--; + return NULL; + } +- D(fprintf(stderr, "%*c> _tmp_212[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "'as' NAME")); ++ D(fprintf(stderr, "%*c> _tmp_214[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "'as' NAME")); + Token * _keyword; + expr_ty name_var; + if ( +@@ -38091,12 +38690,12 @@ _tmp_212_rule(Parser *p) + (name_var = _PyPegen_name_token(p)) // NAME + ) + { +- D(fprintf(stderr, "%*c+ _tmp_212[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "'as' NAME")); ++ D(fprintf(stderr, "%*c+ _tmp_214[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "'as' NAME")); + _res = _PyPegen_dummy_name(p, _keyword, name_var); + goto done; + } + p->mark = _mark; +- D(fprintf(stderr, "%*c%s _tmp_212[%d-%d]: %s failed!\n", p->level, ' ', ++ D(fprintf(stderr, "%*c%s _tmp_214[%d-%d]: %s failed!\n", p->level, ' ', + p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "'as' NAME")); + } + _res = NULL; +@@ -38105,9 +38704,9 @@ _tmp_212_rule(Parser *p) + return _res; + } + +-// _loop0_213: block ++// _loop0_215: block + static asdl_seq * +-_loop0_213_rule(Parser *p) ++_loop0_215_rule(Parser *p) + { + if (p->level++ == MAXSTACK) { + p->error_indicator = 1; +@@ -38133,7 +38732,7 @@ _loop0_213_rule(Parser *p) + p->level--; + return NULL; + } +- D(fprintf(stderr, "%*c> _loop0_213[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "block")); ++ D(fprintf(stderr, "%*c> _loop0_215[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "block")); + asdl_stmt_seq* block_var; + while ( + (block_var = block_rule(p)) // block +@@ -38156,7 +38755,7 @@ _loop0_213_rule(Parser *p) + _mark = p->mark; + } + p->mark = _mark; +- D(fprintf(stderr, "%*c%s _loop0_213[%d-%d]: %s failed!\n", p->level, ' ', ++ D(fprintf(stderr, "%*c%s _loop0_215[%d-%d]: %s failed!\n", p->level, ' ', + p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "block")); + } + asdl_seq *_seq = (asdl_seq*)_Py_asdl_generic_seq_new(_n, p->arena); +@@ -38173,9 +38772,9 @@ _loop0_213_rule(Parser *p) + return _seq; + } + +-// _loop1_214: except_star_block ++// _loop1_216: except_star_block + static asdl_seq * +-_loop1_214_rule(Parser *p) ++_loop1_216_rule(Parser *p) + { + if (p->level++ == MAXSTACK) { + p->error_indicator = 1; +@@ -38201,7 +38800,7 @@ _loop1_214_rule(Parser *p) + p->level--; + return NULL; + } +- D(fprintf(stderr, "%*c> _loop1_214[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "except_star_block")); ++ D(fprintf(stderr, "%*c> _loop1_216[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "except_star_block")); + excepthandler_ty except_star_block_var; + while ( + (except_star_block_var = except_star_block_rule(p)) // except_star_block +@@ -38224,7 +38823,7 @@ _loop1_214_rule(Parser *p) + _mark = p->mark; + } + p->mark = _mark; +- D(fprintf(stderr, "%*c%s _loop1_214[%d-%d]: %s failed!\n", p->level, ' ', ++ D(fprintf(stderr, "%*c%s _loop1_216[%d-%d]: %s failed!\n", p->level, ' ', + p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "except_star_block")); + } + if (_n == 0 || p->error_indicator) { +@@ -38246,9 +38845,9 @@ _loop1_214_rule(Parser *p) + return _seq; + } + +-// _tmp_215: expression ['as' NAME] ++// _tmp_217: expression ['as' NAME] + static void * +-_tmp_215_rule(Parser *p) ++_tmp_217_rule(Parser *p) + { + if (p->level++ == MAXSTACK) { + p->error_indicator = 1; +@@ -38265,22 +38864,22 @@ _tmp_215_rule(Parser *p) + p->level--; + return NULL; + } +- D(fprintf(stderr, "%*c> _tmp_215[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "expression ['as' NAME]")); ++ D(fprintf(stderr, "%*c> _tmp_217[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "expression ['as' NAME]")); + void *_opt_var; + UNUSED(_opt_var); // Silence compiler warnings + expr_ty expression_var; + if ( + (expression_var = expression_rule(p)) // expression + && +- (_opt_var = _tmp_267_rule(p), !p->error_indicator) // ['as' NAME] ++ (_opt_var = _tmp_269_rule(p), !p->error_indicator) // ['as' NAME] + ) + { +- D(fprintf(stderr, "%*c+ _tmp_215[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "expression ['as' NAME]")); ++ D(fprintf(stderr, "%*c+ _tmp_217[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "expression ['as' NAME]")); + _res = _PyPegen_dummy_name(p, expression_var, _opt_var); + goto done; + } + p->mark = _mark; +- D(fprintf(stderr, "%*c%s _tmp_215[%d-%d]: %s failed!\n", p->level, ' ', ++ D(fprintf(stderr, "%*c%s _tmp_217[%d-%d]: %s failed!\n", p->level, ' ', + p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "expression ['as' NAME]")); + } + _res = NULL; +@@ -38289,9 +38888,9 @@ _tmp_215_rule(Parser *p) + return _res; + } + +-// _tmp_216: 'as' NAME ++// _tmp_218: 'as' NAME + static void * +-_tmp_216_rule(Parser *p) ++_tmp_218_rule(Parser *p) + { + if (p->level++ == MAXSTACK) { + p->error_indicator = 1; +@@ -38308,7 +38907,7 @@ _tmp_216_rule(Parser *p) + p->level--; + return NULL; + } +- D(fprintf(stderr, "%*c> _tmp_216[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "'as' NAME")); ++ D(fprintf(stderr, "%*c> _tmp_218[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "'as' NAME")); + Token * _keyword; + expr_ty name_var; + if ( +@@ -38317,12 +38916,12 @@ _tmp_216_rule(Parser *p) + (name_var = _PyPegen_name_token(p)) // NAME + ) + { +- D(fprintf(stderr, "%*c+ _tmp_216[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "'as' NAME")); ++ D(fprintf(stderr, "%*c+ _tmp_218[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "'as' NAME")); + _res = _PyPegen_dummy_name(p, _keyword, name_var); + goto done; + } + p->mark = _mark; +- D(fprintf(stderr, "%*c%s _tmp_216[%d-%d]: %s failed!\n", p->level, ' ', ++ D(fprintf(stderr, "%*c%s _tmp_218[%d-%d]: %s failed!\n", p->level, ' ', + p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "'as' NAME")); + } + _res = NULL; +@@ -38331,9 +38930,9 @@ _tmp_216_rule(Parser *p) + return _res; + } + +-// _tmp_217: 'as' NAME ++// _tmp_219: 'as' NAME + static void * +-_tmp_217_rule(Parser *p) ++_tmp_219_rule(Parser *p) + { + if (p->level++ == MAXSTACK) { + p->error_indicator = 1; +@@ -38350,7 +38949,7 @@ _tmp_217_rule(Parser *p) + p->level--; + return NULL; + } +- D(fprintf(stderr, "%*c> _tmp_217[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "'as' NAME")); ++ D(fprintf(stderr, "%*c> _tmp_219[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "'as' NAME")); + Token * _keyword; + expr_ty name_var; + if ( +@@ -38359,12 +38958,12 @@ _tmp_217_rule(Parser *p) + (name_var = _PyPegen_name_token(p)) // NAME + ) + { +- D(fprintf(stderr, "%*c+ _tmp_217[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "'as' NAME")); ++ D(fprintf(stderr, "%*c+ _tmp_219[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "'as' NAME")); + _res = _PyPegen_dummy_name(p, _keyword, name_var); + goto done; + } + p->mark = _mark; +- D(fprintf(stderr, "%*c%s _tmp_217[%d-%d]: %s failed!\n", p->level, ' ', ++ D(fprintf(stderr, "%*c%s _tmp_219[%d-%d]: %s failed!\n", p->level, ' ', + p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "'as' NAME")); + } + _res = NULL; +@@ -38373,9 +38972,9 @@ _tmp_217_rule(Parser *p) + return _res; + } + +-// _tmp_218: NEWLINE | ':' ++// _tmp_220: NEWLINE | ':' + static void * +-_tmp_218_rule(Parser *p) ++_tmp_220_rule(Parser *p) + { + if (p->level++ == MAXSTACK) { + p->error_indicator = 1; +@@ -38392,18 +38991,18 @@ _tmp_218_rule(Parser *p) + p->level--; + return NULL; + } +- D(fprintf(stderr, "%*c> _tmp_218[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "NEWLINE")); ++ D(fprintf(stderr, "%*c> _tmp_220[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "NEWLINE")); + Token * newline_var; + if ( + (newline_var = _PyPegen_expect_token(p, NEWLINE)) // token='NEWLINE' + ) + { +- D(fprintf(stderr, "%*c+ _tmp_218[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "NEWLINE")); ++ D(fprintf(stderr, "%*c+ _tmp_220[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "NEWLINE")); + _res = newline_var; + goto done; + } + p->mark = _mark; +- D(fprintf(stderr, "%*c%s _tmp_218[%d-%d]: %s failed!\n", p->level, ' ', ++ D(fprintf(stderr, "%*c%s _tmp_220[%d-%d]: %s failed!\n", p->level, ' ', + p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "NEWLINE")); + } + { // ':' +@@ -38411,18 +39010,18 @@ _tmp_218_rule(Parser *p) + p->level--; + return NULL; + } +- D(fprintf(stderr, "%*c> _tmp_218[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "':'")); ++ D(fprintf(stderr, "%*c> _tmp_220[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "':'")); + Token * _literal; + if ( + (_literal = _PyPegen_expect_token(p, 11)) // token=':' + ) + { +- D(fprintf(stderr, "%*c+ _tmp_218[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "':'")); ++ D(fprintf(stderr, "%*c+ _tmp_220[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "':'")); + _res = _literal; + goto done; + } + p->mark = _mark; +- D(fprintf(stderr, "%*c%s _tmp_218[%d-%d]: %s failed!\n", p->level, ' ', ++ D(fprintf(stderr, "%*c%s _tmp_220[%d-%d]: %s failed!\n", p->level, ' ', + p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "':'")); + } + _res = NULL; +@@ -38431,9 +39030,9 @@ _tmp_218_rule(Parser *p) + return _res; + } + +-// _tmp_219: 'as' NAME ++// _tmp_221: 'as' NAME + static void * +-_tmp_219_rule(Parser *p) ++_tmp_221_rule(Parser *p) + { + if (p->level++ == MAXSTACK) { + p->error_indicator = 1; +@@ -38450,7 +39049,7 @@ _tmp_219_rule(Parser *p) + p->level--; + return NULL; + } +- D(fprintf(stderr, "%*c> _tmp_219[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "'as' NAME")); ++ D(fprintf(stderr, "%*c> _tmp_221[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "'as' NAME")); + Token * _keyword; + expr_ty name_var; + if ( +@@ -38459,12 +39058,12 @@ _tmp_219_rule(Parser *p) + (name_var = _PyPegen_name_token(p)) // NAME + ) + { +- D(fprintf(stderr, "%*c+ _tmp_219[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "'as' NAME")); ++ D(fprintf(stderr, "%*c+ _tmp_221[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "'as' NAME")); + _res = _PyPegen_dummy_name(p, _keyword, name_var); + goto done; + } + p->mark = _mark; +- D(fprintf(stderr, "%*c%s _tmp_219[%d-%d]: %s failed!\n", p->level, ' ', ++ D(fprintf(stderr, "%*c%s _tmp_221[%d-%d]: %s failed!\n", p->level, ' ', + p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "'as' NAME")); + } + _res = NULL; +@@ -38473,9 +39072,9 @@ _tmp_219_rule(Parser *p) + return _res; + } + +-// _tmp_220: 'as' NAME ++// _tmp_222: 'as' NAME + static void * +-_tmp_220_rule(Parser *p) ++_tmp_222_rule(Parser *p) + { + if (p->level++ == MAXSTACK) { + p->error_indicator = 1; +@@ -38492,7 +39091,7 @@ _tmp_220_rule(Parser *p) + p->level--; + return NULL; + } +- D(fprintf(stderr, "%*c> _tmp_220[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "'as' NAME")); ++ D(fprintf(stderr, "%*c> _tmp_222[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "'as' NAME")); + Token * _keyword; + expr_ty name_var; + if ( +@@ -38501,12 +39100,12 @@ _tmp_220_rule(Parser *p) + (name_var = _PyPegen_name_token(p)) // NAME + ) + { +- D(fprintf(stderr, "%*c+ _tmp_220[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "'as' NAME")); ++ D(fprintf(stderr, "%*c+ _tmp_222[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "'as' NAME")); + _res = _PyPegen_dummy_name(p, _keyword, name_var); + goto done; + } + p->mark = _mark; +- D(fprintf(stderr, "%*c%s _tmp_220[%d-%d]: %s failed!\n", p->level, ' ', ++ D(fprintf(stderr, "%*c%s _tmp_222[%d-%d]: %s failed!\n", p->level, ' ', + p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "'as' NAME")); + } + _res = NULL; +@@ -38515,9 +39114,9 @@ _tmp_220_rule(Parser *p) + return _res; + } + +-// _tmp_221: positional_patterns ',' ++// _tmp_223: positional_patterns ',' + static void * +-_tmp_221_rule(Parser *p) ++_tmp_223_rule(Parser *p) + { + if (p->level++ == MAXSTACK) { + p->error_indicator = 1; +@@ -38534,7 +39133,7 @@ _tmp_221_rule(Parser *p) + p->level--; + return NULL; + } +- D(fprintf(stderr, "%*c> _tmp_221[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "positional_patterns ','")); ++ D(fprintf(stderr, "%*c> _tmp_223[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "positional_patterns ','")); + Token * _literal; + asdl_pattern_seq* positional_patterns_var; + if ( +@@ -38543,12 +39142,12 @@ _tmp_221_rule(Parser *p) + (_literal = _PyPegen_expect_token(p, 12)) // token=',' + ) + { +- D(fprintf(stderr, "%*c+ _tmp_221[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "positional_patterns ','")); ++ D(fprintf(stderr, "%*c+ _tmp_223[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "positional_patterns ','")); + _res = _PyPegen_dummy_name(p, positional_patterns_var, _literal); + goto done; + } + p->mark = _mark; +- D(fprintf(stderr, "%*c%s _tmp_221[%d-%d]: %s failed!\n", p->level, ' ', ++ D(fprintf(stderr, "%*c%s _tmp_223[%d-%d]: %s failed!\n", p->level, ' ', + p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "positional_patterns ','")); + } + _res = NULL; +@@ -38557,9 +39156,9 @@ _tmp_221_rule(Parser *p) + return _res; + } + +-// _tmp_222: '->' expression ++// _tmp_224: '->' expression + static void * +-_tmp_222_rule(Parser *p) ++_tmp_224_rule(Parser *p) + { + if (p->level++ == MAXSTACK) { + p->error_indicator = 1; +@@ -38576,7 +39175,7 @@ _tmp_222_rule(Parser *p) + p->level--; + return NULL; + } +- D(fprintf(stderr, "%*c> _tmp_222[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "'->' expression")); ++ D(fprintf(stderr, "%*c> _tmp_224[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "'->' expression")); + Token * _literal; + expr_ty expression_var; + if ( +@@ -38585,12 +39184,12 @@ _tmp_222_rule(Parser *p) + (expression_var = expression_rule(p)) // expression + ) + { +- D(fprintf(stderr, "%*c+ _tmp_222[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "'->' expression")); ++ D(fprintf(stderr, "%*c+ _tmp_224[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "'->' expression")); + _res = _PyPegen_dummy_name(p, _literal, expression_var); + goto done; + } + p->mark = _mark; +- D(fprintf(stderr, "%*c%s _tmp_222[%d-%d]: %s failed!\n", p->level, ' ', ++ D(fprintf(stderr, "%*c%s _tmp_224[%d-%d]: %s failed!\n", p->level, ' ', + p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "'->' expression")); + } + _res = NULL; +@@ -38599,9 +39198,9 @@ _tmp_222_rule(Parser *p) + return _res; + } + +-// _tmp_223: '(' arguments? ')' ++// _tmp_225: '(' arguments? ')' + static void * +-_tmp_223_rule(Parser *p) ++_tmp_225_rule(Parser *p) + { + if (p->level++ == MAXSTACK) { + p->error_indicator = 1; +@@ -38618,7 +39217,7 @@ _tmp_223_rule(Parser *p) + p->level--; + return NULL; + } +- D(fprintf(stderr, "%*c> _tmp_223[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "'(' arguments? ')'")); ++ D(fprintf(stderr, "%*c> _tmp_225[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "'(' arguments? ')'")); + Token * _literal; + Token * _literal_1; + void *_opt_var; +@@ -38631,12 +39230,12 @@ _tmp_223_rule(Parser *p) + (_literal_1 = _PyPegen_expect_token(p, 8)) // token=')' + ) + { +- D(fprintf(stderr, "%*c+ _tmp_223[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "'(' arguments? ')'")); ++ D(fprintf(stderr, "%*c+ _tmp_225[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "'(' arguments? ')'")); + _res = _PyPegen_dummy_name(p, _literal, _opt_var, _literal_1); + goto done; + } + p->mark = _mark; +- D(fprintf(stderr, "%*c%s _tmp_223[%d-%d]: %s failed!\n", p->level, ' ', ++ D(fprintf(stderr, "%*c%s _tmp_225[%d-%d]: %s failed!\n", p->level, ' ', + p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "'(' arguments? ')'")); + } + _res = NULL; +@@ -38645,9 +39244,9 @@ _tmp_223_rule(Parser *p) + return _res; + } + +-// _tmp_224: '(' arguments? ')' ++// _tmp_226: '(' arguments? ')' + static void * +-_tmp_224_rule(Parser *p) ++_tmp_226_rule(Parser *p) + { + if (p->level++ == MAXSTACK) { + p->error_indicator = 1; +@@ -38664,7 +39263,7 @@ _tmp_224_rule(Parser *p) + p->level--; + return NULL; + } +- D(fprintf(stderr, "%*c> _tmp_224[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "'(' arguments? ')'")); ++ D(fprintf(stderr, "%*c> _tmp_226[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "'(' arguments? ')'")); + Token * _literal; + Token * _literal_1; + void *_opt_var; +@@ -38677,12 +39276,12 @@ _tmp_224_rule(Parser *p) + (_literal_1 = _PyPegen_expect_token(p, 8)) // token=')' + ) + { +- D(fprintf(stderr, "%*c+ _tmp_224[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "'(' arguments? ')'")); ++ D(fprintf(stderr, "%*c+ _tmp_226[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "'(' arguments? ')'")); + _res = _PyPegen_dummy_name(p, _literal, _opt_var, _literal_1); + goto done; + } + p->mark = _mark; +- D(fprintf(stderr, "%*c%s _tmp_224[%d-%d]: %s failed!\n", p->level, ' ', ++ D(fprintf(stderr, "%*c%s _tmp_226[%d-%d]: %s failed!\n", p->level, ' ', + p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "'(' arguments? ')'")); + } + _res = NULL; +@@ -38691,9 +39290,9 @@ _tmp_224_rule(Parser *p) + return _res; + } + +-// _loop0_226: ',' double_starred_kvpair ++// _loop0_228: ',' double_starred_kvpair + static asdl_seq * +-_loop0_226_rule(Parser *p) ++_loop0_228_rule(Parser *p) + { + if (p->level++ == MAXSTACK) { + p->error_indicator = 1; +@@ -38719,7 +39318,7 @@ _loop0_226_rule(Parser *p) + p->level--; + return NULL; + } +- D(fprintf(stderr, "%*c> _loop0_226[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "',' double_starred_kvpair")); ++ D(fprintf(stderr, "%*c> _loop0_228[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "',' double_starred_kvpair")); + Token * _literal; + KeyValuePair* elem; + while ( +@@ -38751,7 +39350,7 @@ _loop0_226_rule(Parser *p) + _mark = p->mark; + } + p->mark = _mark; +- D(fprintf(stderr, "%*c%s _loop0_226[%d-%d]: %s failed!\n", p->level, ' ', ++ D(fprintf(stderr, "%*c%s _loop0_228[%d-%d]: %s failed!\n", p->level, ' ', + p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "',' double_starred_kvpair")); + } + asdl_seq *_seq = (asdl_seq*)_Py_asdl_generic_seq_new(_n, p->arena); +@@ -38768,9 +39367,9 @@ _loop0_226_rule(Parser *p) + return _seq; + } + +-// _gather_225: double_starred_kvpair _loop0_226 ++// _gather_227: double_starred_kvpair _loop0_228 + static asdl_seq * +-_gather_225_rule(Parser *p) ++_gather_227_rule(Parser *p) + { + if (p->level++ == MAXSTACK) { + p->error_indicator = 1; +@@ -38782,27 +39381,27 @@ _gather_225_rule(Parser *p) + } + asdl_seq * _res = NULL; + int _mark = p->mark; +- { // double_starred_kvpair _loop0_226 ++ { // double_starred_kvpair _loop0_228 + if (p->error_indicator) { + p->level--; + return NULL; + } +- D(fprintf(stderr, "%*c> _gather_225[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "double_starred_kvpair _loop0_226")); ++ D(fprintf(stderr, "%*c> _gather_227[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "double_starred_kvpair _loop0_228")); + KeyValuePair* elem; + asdl_seq * seq; + if ( + (elem = double_starred_kvpair_rule(p)) // double_starred_kvpair + && +- (seq = _loop0_226_rule(p)) // _loop0_226 ++ (seq = _loop0_228_rule(p)) // _loop0_228 + ) + { +- D(fprintf(stderr, "%*c+ _gather_225[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "double_starred_kvpair _loop0_226")); ++ D(fprintf(stderr, "%*c+ _gather_227[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "double_starred_kvpair _loop0_228")); + _res = _PyPegen_seq_insert_in_front(p, elem, seq); + goto done; + } + p->mark = _mark; +- D(fprintf(stderr, "%*c%s _gather_225[%d-%d]: %s failed!\n", p->level, ' ', +- p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "double_starred_kvpair _loop0_226")); ++ D(fprintf(stderr, "%*c%s _gather_227[%d-%d]: %s failed!\n", p->level, ' ', ++ p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "double_starred_kvpair _loop0_228")); + } + _res = NULL; + done: +@@ -38810,9 +39409,9 @@ _gather_225_rule(Parser *p) + return _res; + } + +-// _tmp_227: '}' | ',' ++// _tmp_229: '}' | ',' + static void * +-_tmp_227_rule(Parser *p) ++_tmp_229_rule(Parser *p) + { + if (p->level++ == MAXSTACK) { + p->error_indicator = 1; +@@ -38829,18 +39428,18 @@ _tmp_227_rule(Parser *p) + p->level--; + return NULL; + } +- D(fprintf(stderr, "%*c> _tmp_227[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "'}'")); ++ D(fprintf(stderr, "%*c> _tmp_229[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "'}'")); + Token * _literal; + if ( + (_literal = _PyPegen_expect_token(p, 26)) // token='}' + ) + { +- D(fprintf(stderr, "%*c+ _tmp_227[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "'}'")); ++ D(fprintf(stderr, "%*c+ _tmp_229[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "'}'")); + _res = _literal; + goto done; + } + p->mark = _mark; +- D(fprintf(stderr, "%*c%s _tmp_227[%d-%d]: %s failed!\n", p->level, ' ', ++ D(fprintf(stderr, "%*c%s _tmp_229[%d-%d]: %s failed!\n", p->level, ' ', + p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "'}'")); + } + { // ',' +@@ -38848,18 +39447,18 @@ _tmp_227_rule(Parser *p) + p->level--; + return NULL; + } +- D(fprintf(stderr, "%*c> _tmp_227[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "','")); ++ D(fprintf(stderr, "%*c> _tmp_229[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "','")); + Token * _literal; + if ( + (_literal = _PyPegen_expect_token(p, 12)) // token=',' + ) + { +- D(fprintf(stderr, "%*c+ _tmp_227[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "','")); ++ D(fprintf(stderr, "%*c+ _tmp_229[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "','")); + _res = _literal; + goto done; + } + p->mark = _mark; +- D(fprintf(stderr, "%*c%s _tmp_227[%d-%d]: %s failed!\n", p->level, ' ', ++ D(fprintf(stderr, "%*c%s _tmp_229[%d-%d]: %s failed!\n", p->level, ' ', + p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "','")); + } + _res = NULL; +@@ -38868,9 +39467,9 @@ _tmp_227_rule(Parser *p) + return _res; + } + +-// _tmp_228: '}' | ',' ++// _tmp_230: '}' | ',' + static void * +-_tmp_228_rule(Parser *p) ++_tmp_230_rule(Parser *p) + { + if (p->level++ == MAXSTACK) { + p->error_indicator = 1; +@@ -38887,18 +39486,18 @@ _tmp_228_rule(Parser *p) + p->level--; + return NULL; + } +- D(fprintf(stderr, "%*c> _tmp_228[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "'}'")); ++ D(fprintf(stderr, "%*c> _tmp_230[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "'}'")); + Token * _literal; + if ( + (_literal = _PyPegen_expect_token(p, 26)) // token='}' + ) + { +- D(fprintf(stderr, "%*c+ _tmp_228[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "'}'")); ++ D(fprintf(stderr, "%*c+ _tmp_230[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "'}'")); + _res = _literal; + goto done; + } + p->mark = _mark; +- D(fprintf(stderr, "%*c%s _tmp_228[%d-%d]: %s failed!\n", p->level, ' ', ++ D(fprintf(stderr, "%*c%s _tmp_230[%d-%d]: %s failed!\n", p->level, ' ', + p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "'}'")); + } + { // ',' +@@ -38906,18 +39505,18 @@ _tmp_228_rule(Parser *p) + p->level--; + return NULL; + } +- D(fprintf(stderr, "%*c> _tmp_228[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "','")); ++ D(fprintf(stderr, "%*c> _tmp_230[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "','")); + Token * _literal; + if ( + (_literal = _PyPegen_expect_token(p, 12)) // token=',' + ) + { +- D(fprintf(stderr, "%*c+ _tmp_228[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "','")); ++ D(fprintf(stderr, "%*c+ _tmp_230[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "','")); + _res = _literal; + goto done; + } + p->mark = _mark; +- D(fprintf(stderr, "%*c%s _tmp_228[%d-%d]: %s failed!\n", p->level, ' ', ++ D(fprintf(stderr, "%*c%s _tmp_230[%d-%d]: %s failed!\n", p->level, ' ', + p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "','")); + } + _res = NULL; +@@ -38926,9 +39525,9 @@ _tmp_228_rule(Parser *p) + return _res; + } + +-// _tmp_229: yield_expr | star_expressions ++// _tmp_231: yield_expr | star_expressions + static void * +-_tmp_229_rule(Parser *p) ++_tmp_231_rule(Parser *p) + { + if (p->level++ == MAXSTACK) { + p->error_indicator = 1; +@@ -38945,18 +39544,18 @@ _tmp_229_rule(Parser *p) + p->level--; + return NULL; + } +- D(fprintf(stderr, "%*c> _tmp_229[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "yield_expr")); ++ D(fprintf(stderr, "%*c> _tmp_231[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "yield_expr")); + expr_ty yield_expr_var; + if ( + (yield_expr_var = yield_expr_rule(p)) // yield_expr + ) + { +- D(fprintf(stderr, "%*c+ _tmp_229[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "yield_expr")); ++ D(fprintf(stderr, "%*c+ _tmp_231[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "yield_expr")); + _res = yield_expr_var; + goto done; + } + p->mark = _mark; +- D(fprintf(stderr, "%*c%s _tmp_229[%d-%d]: %s failed!\n", p->level, ' ', ++ D(fprintf(stderr, "%*c%s _tmp_231[%d-%d]: %s failed!\n", p->level, ' ', + p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "yield_expr")); + } + { // star_expressions +@@ -38964,18 +39563,18 @@ _tmp_229_rule(Parser *p) + p->level--; + return NULL; + } +- D(fprintf(stderr, "%*c> _tmp_229[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "star_expressions")); ++ D(fprintf(stderr, "%*c> _tmp_231[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "star_expressions")); + expr_ty star_expressions_var; + if ( + (star_expressions_var = star_expressions_rule(p)) // star_expressions + ) + { +- D(fprintf(stderr, "%*c+ _tmp_229[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "star_expressions")); ++ D(fprintf(stderr, "%*c+ _tmp_231[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "star_expressions")); + _res = star_expressions_var; + goto done; + } + p->mark = _mark; +- D(fprintf(stderr, "%*c%s _tmp_229[%d-%d]: %s failed!\n", p->level, ' ', ++ D(fprintf(stderr, "%*c%s _tmp_231[%d-%d]: %s failed!\n", p->level, ' ', + p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "star_expressions")); + } + _res = NULL; +@@ -38984,9 +39583,9 @@ _tmp_229_rule(Parser *p) + return _res; + } + +-// _tmp_230: yield_expr | star_expressions ++// _tmp_232: yield_expr | star_expressions + static void * +-_tmp_230_rule(Parser *p) ++_tmp_232_rule(Parser *p) + { + if (p->level++ == MAXSTACK) { + p->error_indicator = 1; +@@ -39003,18 +39602,18 @@ _tmp_230_rule(Parser *p) + p->level--; + return NULL; + } +- D(fprintf(stderr, "%*c> _tmp_230[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "yield_expr")); ++ D(fprintf(stderr, "%*c> _tmp_232[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "yield_expr")); + expr_ty yield_expr_var; + if ( + (yield_expr_var = yield_expr_rule(p)) // yield_expr + ) + { +- D(fprintf(stderr, "%*c+ _tmp_230[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "yield_expr")); ++ D(fprintf(stderr, "%*c+ _tmp_232[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "yield_expr")); + _res = yield_expr_var; + goto done; + } + p->mark = _mark; +- D(fprintf(stderr, "%*c%s _tmp_230[%d-%d]: %s failed!\n", p->level, ' ', ++ D(fprintf(stderr, "%*c%s _tmp_232[%d-%d]: %s failed!\n", p->level, ' ', + p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "yield_expr")); + } + { // star_expressions +@@ -39022,18 +39621,18 @@ _tmp_230_rule(Parser *p) + p->level--; + return NULL; + } +- D(fprintf(stderr, "%*c> _tmp_230[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "star_expressions")); ++ D(fprintf(stderr, "%*c> _tmp_232[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "star_expressions")); + expr_ty star_expressions_var; + if ( + (star_expressions_var = star_expressions_rule(p)) // star_expressions + ) + { +- D(fprintf(stderr, "%*c+ _tmp_230[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "star_expressions")); ++ D(fprintf(stderr, "%*c+ _tmp_232[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "star_expressions")); + _res = star_expressions_var; + goto done; + } + p->mark = _mark; +- D(fprintf(stderr, "%*c%s _tmp_230[%d-%d]: %s failed!\n", p->level, ' ', ++ D(fprintf(stderr, "%*c%s _tmp_232[%d-%d]: %s failed!\n", p->level, ' ', + p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "star_expressions")); + } + _res = NULL; +@@ -39042,9 +39641,9 @@ _tmp_230_rule(Parser *p) + return _res; + } + +-// _tmp_231: '=' | '!' | ':' | '}' ++// _tmp_233: '=' | '!' | ':' | '}' + static void * +-_tmp_231_rule(Parser *p) ++_tmp_233_rule(Parser *p) + { + if (p->level++ == MAXSTACK) { + p->error_indicator = 1; +@@ -39061,18 +39660,18 @@ _tmp_231_rule(Parser *p) + p->level--; + return NULL; + } +- D(fprintf(stderr, "%*c> _tmp_231[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "'='")); ++ D(fprintf(stderr, "%*c> _tmp_233[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "'='")); + Token * _literal; + if ( + (_literal = _PyPegen_expect_token(p, 22)) // token='=' + ) + { +- D(fprintf(stderr, "%*c+ _tmp_231[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "'='")); ++ D(fprintf(stderr, "%*c+ _tmp_233[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "'='")); + _res = _literal; + goto done; + } + p->mark = _mark; +- D(fprintf(stderr, "%*c%s _tmp_231[%d-%d]: %s failed!\n", p->level, ' ', ++ D(fprintf(stderr, "%*c%s _tmp_233[%d-%d]: %s failed!\n", p->level, ' ', + p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "'='")); + } + { // '!' +@@ -39080,18 +39679,18 @@ _tmp_231_rule(Parser *p) + p->level--; + return NULL; + } +- D(fprintf(stderr, "%*c> _tmp_231[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "'!'")); ++ D(fprintf(stderr, "%*c> _tmp_233[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "'!'")); + Token * _literal; + if ( + (_literal = _PyPegen_expect_token(p, 54)) // token='!' + ) + { +- D(fprintf(stderr, "%*c+ _tmp_231[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "'!'")); ++ D(fprintf(stderr, "%*c+ _tmp_233[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "'!'")); + _res = _literal; + goto done; + } + p->mark = _mark; +- D(fprintf(stderr, "%*c%s _tmp_231[%d-%d]: %s failed!\n", p->level, ' ', ++ D(fprintf(stderr, "%*c%s _tmp_233[%d-%d]: %s failed!\n", p->level, ' ', + p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "'!'")); + } + { // ':' +@@ -39099,18 +39698,18 @@ _tmp_231_rule(Parser *p) + p->level--; + return NULL; + } +- D(fprintf(stderr, "%*c> _tmp_231[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "':'")); ++ D(fprintf(stderr, "%*c> _tmp_233[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "':'")); + Token * _literal; + if ( + (_literal = _PyPegen_expect_token(p, 11)) // token=':' + ) + { +- D(fprintf(stderr, "%*c+ _tmp_231[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "':'")); ++ D(fprintf(stderr, "%*c+ _tmp_233[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "':'")); + _res = _literal; + goto done; + } + p->mark = _mark; +- D(fprintf(stderr, "%*c%s _tmp_231[%d-%d]: %s failed!\n", p->level, ' ', ++ D(fprintf(stderr, "%*c%s _tmp_233[%d-%d]: %s failed!\n", p->level, ' ', + p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "':'")); + } + { // '}' +@@ -39118,18 +39717,18 @@ _tmp_231_rule(Parser *p) + p->level--; + return NULL; + } +- D(fprintf(stderr, "%*c> _tmp_231[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "'}'")); ++ D(fprintf(stderr, "%*c> _tmp_233[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "'}'")); + Token * _literal; + if ( + (_literal = _PyPegen_expect_token(p, 26)) // token='}' + ) + { +- D(fprintf(stderr, "%*c+ _tmp_231[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "'}'")); ++ D(fprintf(stderr, "%*c+ _tmp_233[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "'}'")); + _res = _literal; + goto done; + } + p->mark = _mark; +- D(fprintf(stderr, "%*c%s _tmp_231[%d-%d]: %s failed!\n", p->level, ' ', ++ D(fprintf(stderr, "%*c%s _tmp_233[%d-%d]: %s failed!\n", p->level, ' ', + p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "'}'")); + } + _res = NULL; +@@ -39138,9 +39737,9 @@ _tmp_231_rule(Parser *p) + return _res; + } + +-// _tmp_232: yield_expr | star_expressions ++// _tmp_234: yield_expr | star_expressions + static void * +-_tmp_232_rule(Parser *p) ++_tmp_234_rule(Parser *p) + { + if (p->level++ == MAXSTACK) { + p->error_indicator = 1; +@@ -39157,18 +39756,18 @@ _tmp_232_rule(Parser *p) + p->level--; + return NULL; + } +- D(fprintf(stderr, "%*c> _tmp_232[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "yield_expr")); ++ D(fprintf(stderr, "%*c> _tmp_234[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "yield_expr")); + expr_ty yield_expr_var; + if ( + (yield_expr_var = yield_expr_rule(p)) // yield_expr + ) + { +- D(fprintf(stderr, "%*c+ _tmp_232[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "yield_expr")); ++ D(fprintf(stderr, "%*c+ _tmp_234[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "yield_expr")); + _res = yield_expr_var; + goto done; + } + p->mark = _mark; +- D(fprintf(stderr, "%*c%s _tmp_232[%d-%d]: %s failed!\n", p->level, ' ', ++ D(fprintf(stderr, "%*c%s _tmp_234[%d-%d]: %s failed!\n", p->level, ' ', + p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "yield_expr")); + } + { // star_expressions +@@ -39176,18 +39775,18 @@ _tmp_232_rule(Parser *p) + p->level--; + return NULL; + } +- D(fprintf(stderr, "%*c> _tmp_232[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "star_expressions")); ++ D(fprintf(stderr, "%*c> _tmp_234[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "star_expressions")); + expr_ty star_expressions_var; + if ( + (star_expressions_var = star_expressions_rule(p)) // star_expressions + ) + { +- D(fprintf(stderr, "%*c+ _tmp_232[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "star_expressions")); ++ D(fprintf(stderr, "%*c+ _tmp_234[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "star_expressions")); + _res = star_expressions_var; + goto done; + } + p->mark = _mark; +- D(fprintf(stderr, "%*c%s _tmp_232[%d-%d]: %s failed!\n", p->level, ' ', ++ D(fprintf(stderr, "%*c%s _tmp_234[%d-%d]: %s failed!\n", p->level, ' ', + p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "star_expressions")); + } + _res = NULL; +@@ -39196,9 +39795,9 @@ _tmp_232_rule(Parser *p) + return _res; + } + +-// _tmp_233: '!' | ':' | '}' ++// _tmp_235: '!' | ':' | '}' + static void * +-_tmp_233_rule(Parser *p) ++_tmp_235_rule(Parser *p) + { + if (p->level++ == MAXSTACK) { + p->error_indicator = 1; +@@ -39215,18 +39814,18 @@ _tmp_233_rule(Parser *p) + p->level--; + return NULL; + } +- D(fprintf(stderr, "%*c> _tmp_233[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "'!'")); ++ D(fprintf(stderr, "%*c> _tmp_235[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "'!'")); + Token * _literal; + if ( + (_literal = _PyPegen_expect_token(p, 54)) // token='!' + ) + { +- D(fprintf(stderr, "%*c+ _tmp_233[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "'!'")); ++ D(fprintf(stderr, "%*c+ _tmp_235[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "'!'")); + _res = _literal; + goto done; + } + p->mark = _mark; +- D(fprintf(stderr, "%*c%s _tmp_233[%d-%d]: %s failed!\n", p->level, ' ', ++ D(fprintf(stderr, "%*c%s _tmp_235[%d-%d]: %s failed!\n", p->level, ' ', + p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "'!'")); + } + { // ':' +@@ -39234,18 +39833,18 @@ _tmp_233_rule(Parser *p) + p->level--; + return NULL; + } +- D(fprintf(stderr, "%*c> _tmp_233[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "':'")); ++ D(fprintf(stderr, "%*c> _tmp_235[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "':'")); + Token * _literal; + if ( + (_literal = _PyPegen_expect_token(p, 11)) // token=':' + ) + { +- D(fprintf(stderr, "%*c+ _tmp_233[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "':'")); ++ D(fprintf(stderr, "%*c+ _tmp_235[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "':'")); + _res = _literal; + goto done; + } + p->mark = _mark; +- D(fprintf(stderr, "%*c%s _tmp_233[%d-%d]: %s failed!\n", p->level, ' ', ++ D(fprintf(stderr, "%*c%s _tmp_235[%d-%d]: %s failed!\n", p->level, ' ', + p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "':'")); + } + { // '}' +@@ -39253,18 +39852,18 @@ _tmp_233_rule(Parser *p) + p->level--; + return NULL; + } +- D(fprintf(stderr, "%*c> _tmp_233[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "'}'")); ++ D(fprintf(stderr, "%*c> _tmp_235[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "'}'")); + Token * _literal; + if ( + (_literal = _PyPegen_expect_token(p, 26)) // token='}' + ) + { +- D(fprintf(stderr, "%*c+ _tmp_233[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "'}'")); ++ D(fprintf(stderr, "%*c+ _tmp_235[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "'}'")); + _res = _literal; + goto done; + } + p->mark = _mark; +- D(fprintf(stderr, "%*c%s _tmp_233[%d-%d]: %s failed!\n", p->level, ' ', ++ D(fprintf(stderr, "%*c%s _tmp_235[%d-%d]: %s failed!\n", p->level, ' ', + p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "'}'")); + } + _res = NULL; +@@ -39273,9 +39872,9 @@ _tmp_233_rule(Parser *p) + return _res; + } + +-// _tmp_234: yield_expr | star_expressions ++// _tmp_236: yield_expr | star_expressions + static void * +-_tmp_234_rule(Parser *p) ++_tmp_236_rule(Parser *p) + { + if (p->level++ == MAXSTACK) { + p->error_indicator = 1; +@@ -39292,18 +39891,18 @@ _tmp_234_rule(Parser *p) + p->level--; + return NULL; + } +- D(fprintf(stderr, "%*c> _tmp_234[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "yield_expr")); ++ D(fprintf(stderr, "%*c> _tmp_236[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "yield_expr")); + expr_ty yield_expr_var; + if ( + (yield_expr_var = yield_expr_rule(p)) // yield_expr + ) + { +- D(fprintf(stderr, "%*c+ _tmp_234[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "yield_expr")); ++ D(fprintf(stderr, "%*c+ _tmp_236[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "yield_expr")); + _res = yield_expr_var; + goto done; + } + p->mark = _mark; +- D(fprintf(stderr, "%*c%s _tmp_234[%d-%d]: %s failed!\n", p->level, ' ', ++ D(fprintf(stderr, "%*c%s _tmp_236[%d-%d]: %s failed!\n", p->level, ' ', + p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "yield_expr")); + } + { // star_expressions +@@ -39311,18 +39910,18 @@ _tmp_234_rule(Parser *p) + p->level--; + return NULL; + } +- D(fprintf(stderr, "%*c> _tmp_234[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "star_expressions")); ++ D(fprintf(stderr, "%*c> _tmp_236[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "star_expressions")); + expr_ty star_expressions_var; + if ( + (star_expressions_var = star_expressions_rule(p)) // star_expressions + ) + { +- D(fprintf(stderr, "%*c+ _tmp_234[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "star_expressions")); ++ D(fprintf(stderr, "%*c+ _tmp_236[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "star_expressions")); + _res = star_expressions_var; + goto done; + } + p->mark = _mark; +- D(fprintf(stderr, "%*c%s _tmp_234[%d-%d]: %s failed!\n", p->level, ' ', ++ D(fprintf(stderr, "%*c%s _tmp_236[%d-%d]: %s failed!\n", p->level, ' ', + p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "star_expressions")); + } + _res = NULL; +@@ -39331,9 +39930,9 @@ _tmp_234_rule(Parser *p) + return _res; + } + +-// _tmp_235: yield_expr | star_expressions ++// _tmp_237: yield_expr | star_expressions + static void * +-_tmp_235_rule(Parser *p) ++_tmp_237_rule(Parser *p) + { + if (p->level++ == MAXSTACK) { + p->error_indicator = 1; +@@ -39350,18 +39949,18 @@ _tmp_235_rule(Parser *p) + p->level--; + return NULL; + } +- D(fprintf(stderr, "%*c> _tmp_235[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "yield_expr")); ++ D(fprintf(stderr, "%*c> _tmp_237[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "yield_expr")); + expr_ty yield_expr_var; + if ( + (yield_expr_var = yield_expr_rule(p)) // yield_expr + ) + { +- D(fprintf(stderr, "%*c+ _tmp_235[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "yield_expr")); ++ D(fprintf(stderr, "%*c+ _tmp_237[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "yield_expr")); + _res = yield_expr_var; + goto done; + } + p->mark = _mark; +- D(fprintf(stderr, "%*c%s _tmp_235[%d-%d]: %s failed!\n", p->level, ' ', ++ D(fprintf(stderr, "%*c%s _tmp_237[%d-%d]: %s failed!\n", p->level, ' ', + p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "yield_expr")); + } + { // star_expressions +@@ -39369,18 +39968,18 @@ _tmp_235_rule(Parser *p) + p->level--; + return NULL; + } +- D(fprintf(stderr, "%*c> _tmp_235[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "star_expressions")); ++ D(fprintf(stderr, "%*c> _tmp_237[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "star_expressions")); + expr_ty star_expressions_var; + if ( + (star_expressions_var = star_expressions_rule(p)) // star_expressions + ) + { +- D(fprintf(stderr, "%*c+ _tmp_235[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "star_expressions")); ++ D(fprintf(stderr, "%*c+ _tmp_237[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "star_expressions")); + _res = star_expressions_var; + goto done; + } + p->mark = _mark; +- D(fprintf(stderr, "%*c%s _tmp_235[%d-%d]: %s failed!\n", p->level, ' ', ++ D(fprintf(stderr, "%*c%s _tmp_237[%d-%d]: %s failed!\n", p->level, ' ', + p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "star_expressions")); + } + _res = NULL; +@@ -39389,9 +39988,9 @@ _tmp_235_rule(Parser *p) + return _res; + } + +-// _tmp_236: '!' NAME ++// _tmp_238: '!' NAME + static void * +-_tmp_236_rule(Parser *p) ++_tmp_238_rule(Parser *p) + { + if (p->level++ == MAXSTACK) { + p->error_indicator = 1; +@@ -39408,7 +40007,7 @@ _tmp_236_rule(Parser *p) + p->level--; + return NULL; + } +- D(fprintf(stderr, "%*c> _tmp_236[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "'!' NAME")); ++ D(fprintf(stderr, "%*c> _tmp_238[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "'!' NAME")); + Token * _literal; + expr_ty name_var; + if ( +@@ -39417,12 +40016,12 @@ _tmp_236_rule(Parser *p) + (name_var = _PyPegen_name_token(p)) // NAME + ) + { +- D(fprintf(stderr, "%*c+ _tmp_236[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "'!' NAME")); ++ D(fprintf(stderr, "%*c+ _tmp_238[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "'!' NAME")); + _res = _PyPegen_dummy_name(p, _literal, name_var); + goto done; + } + p->mark = _mark; +- D(fprintf(stderr, "%*c%s _tmp_236[%d-%d]: %s failed!\n", p->level, ' ', ++ D(fprintf(stderr, "%*c%s _tmp_238[%d-%d]: %s failed!\n", p->level, ' ', + p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "'!' NAME")); + } + _res = NULL; +@@ -39431,9 +40030,9 @@ _tmp_236_rule(Parser *p) + return _res; + } + +-// _tmp_237: ':' | '}' ++// _tmp_239: ':' | '}' + static void * +-_tmp_237_rule(Parser *p) ++_tmp_239_rule(Parser *p) + { + if (p->level++ == MAXSTACK) { + p->error_indicator = 1; +@@ -39450,18 +40049,18 @@ _tmp_237_rule(Parser *p) + p->level--; + return NULL; + } +- D(fprintf(stderr, "%*c> _tmp_237[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "':'")); ++ D(fprintf(stderr, "%*c> _tmp_239[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "':'")); + Token * _literal; + if ( + (_literal = _PyPegen_expect_token(p, 11)) // token=':' + ) + { +- D(fprintf(stderr, "%*c+ _tmp_237[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "':'")); ++ D(fprintf(stderr, "%*c+ _tmp_239[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "':'")); + _res = _literal; + goto done; + } + p->mark = _mark; +- D(fprintf(stderr, "%*c%s _tmp_237[%d-%d]: %s failed!\n", p->level, ' ', ++ D(fprintf(stderr, "%*c%s _tmp_239[%d-%d]: %s failed!\n", p->level, ' ', + p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "':'")); + } + { // '}' +@@ -39469,18 +40068,18 @@ _tmp_237_rule(Parser *p) + p->level--; + return NULL; + } +- D(fprintf(stderr, "%*c> _tmp_237[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "'}'")); ++ D(fprintf(stderr, "%*c> _tmp_239[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "'}'")); + Token * _literal; + if ( + (_literal = _PyPegen_expect_token(p, 26)) // token='}' + ) + { +- D(fprintf(stderr, "%*c+ _tmp_237[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "'}'")); ++ D(fprintf(stderr, "%*c+ _tmp_239[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "'}'")); + _res = _literal; + goto done; + } + p->mark = _mark; +- D(fprintf(stderr, "%*c%s _tmp_237[%d-%d]: %s failed!\n", p->level, ' ', ++ D(fprintf(stderr, "%*c%s _tmp_239[%d-%d]: %s failed!\n", p->level, ' ', + p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "'}'")); + } + _res = NULL; +@@ -39489,9 +40088,9 @@ _tmp_237_rule(Parser *p) + return _res; + } + +-// _tmp_238: yield_expr | star_expressions ++// _tmp_240: yield_expr | star_expressions + static void * +-_tmp_238_rule(Parser *p) ++_tmp_240_rule(Parser *p) + { + if (p->level++ == MAXSTACK) { + p->error_indicator = 1; +@@ -39508,18 +40107,18 @@ _tmp_238_rule(Parser *p) + p->level--; + return NULL; + } +- D(fprintf(stderr, "%*c> _tmp_238[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "yield_expr")); ++ D(fprintf(stderr, "%*c> _tmp_240[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "yield_expr")); + expr_ty yield_expr_var; + if ( + (yield_expr_var = yield_expr_rule(p)) // yield_expr + ) + { +- D(fprintf(stderr, "%*c+ _tmp_238[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "yield_expr")); ++ D(fprintf(stderr, "%*c+ _tmp_240[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "yield_expr")); + _res = yield_expr_var; + goto done; + } + p->mark = _mark; +- D(fprintf(stderr, "%*c%s _tmp_238[%d-%d]: %s failed!\n", p->level, ' ', ++ D(fprintf(stderr, "%*c%s _tmp_240[%d-%d]: %s failed!\n", p->level, ' ', + p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "yield_expr")); + } + { // star_expressions +@@ -39527,18 +40126,18 @@ _tmp_238_rule(Parser *p) + p->level--; + return NULL; + } +- D(fprintf(stderr, "%*c> _tmp_238[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "star_expressions")); ++ D(fprintf(stderr, "%*c> _tmp_240[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "star_expressions")); + expr_ty star_expressions_var; + if ( + (star_expressions_var = star_expressions_rule(p)) // star_expressions + ) + { +- D(fprintf(stderr, "%*c+ _tmp_238[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "star_expressions")); ++ D(fprintf(stderr, "%*c+ _tmp_240[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "star_expressions")); + _res = star_expressions_var; + goto done; + } + p->mark = _mark; +- D(fprintf(stderr, "%*c%s _tmp_238[%d-%d]: %s failed!\n", p->level, ' ', ++ D(fprintf(stderr, "%*c%s _tmp_240[%d-%d]: %s failed!\n", p->level, ' ', + p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "star_expressions")); + } + _res = NULL; +@@ -39547,9 +40146,9 @@ _tmp_238_rule(Parser *p) + return _res; + } + +-// _tmp_239: '!' NAME ++// _tmp_241: '!' NAME + static void * +-_tmp_239_rule(Parser *p) ++_tmp_241_rule(Parser *p) + { + if (p->level++ == MAXSTACK) { + p->error_indicator = 1; +@@ -39566,7 +40165,7 @@ _tmp_239_rule(Parser *p) + p->level--; + return NULL; + } +- D(fprintf(stderr, "%*c> _tmp_239[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "'!' NAME")); ++ D(fprintf(stderr, "%*c> _tmp_241[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "'!' NAME")); + Token * _literal; + expr_ty name_var; + if ( +@@ -39575,12 +40174,12 @@ _tmp_239_rule(Parser *p) + (name_var = _PyPegen_name_token(p)) // NAME + ) + { +- D(fprintf(stderr, "%*c+ _tmp_239[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "'!' NAME")); ++ D(fprintf(stderr, "%*c+ _tmp_241[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "'!' NAME")); + _res = _PyPegen_dummy_name(p, _literal, name_var); + goto done; + } + p->mark = _mark; +- D(fprintf(stderr, "%*c%s _tmp_239[%d-%d]: %s failed!\n", p->level, ' ', ++ D(fprintf(stderr, "%*c%s _tmp_241[%d-%d]: %s failed!\n", p->level, ' ', + p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "'!' NAME")); + } + _res = NULL; +@@ -39589,9 +40188,9 @@ _tmp_239_rule(Parser *p) + return _res; + } + +-// _loop0_240: fstring_format_spec ++// _loop0_242: fstring_format_spec + static asdl_seq * +-_loop0_240_rule(Parser *p) ++_loop0_242_rule(Parser *p) + { + if (p->level++ == MAXSTACK) { + p->error_indicator = 1; +@@ -39617,7 +40216,7 @@ _loop0_240_rule(Parser *p) + p->level--; + return NULL; + } +- D(fprintf(stderr, "%*c> _loop0_240[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "fstring_format_spec")); ++ D(fprintf(stderr, "%*c> _loop0_242[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "fstring_format_spec")); + expr_ty fstring_format_spec_var; + while ( + (fstring_format_spec_var = fstring_format_spec_rule(p)) // fstring_format_spec +@@ -39640,7 +40239,7 @@ _loop0_240_rule(Parser *p) + _mark = p->mark; + } + p->mark = _mark; +- D(fprintf(stderr, "%*c%s _loop0_240[%d-%d]: %s failed!\n", p->level, ' ', ++ D(fprintf(stderr, "%*c%s _loop0_242[%d-%d]: %s failed!\n", p->level, ' ', + p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "fstring_format_spec")); + } + asdl_seq *_seq = (asdl_seq*)_Py_asdl_generic_seq_new(_n, p->arena); +@@ -39657,9 +40256,9 @@ _loop0_240_rule(Parser *p) + return _seq; + } + +-// _tmp_241: yield_expr | star_expressions ++// _tmp_243: yield_expr | star_expressions + static void * +-_tmp_241_rule(Parser *p) ++_tmp_243_rule(Parser *p) + { + if (p->level++ == MAXSTACK) { + p->error_indicator = 1; +@@ -39676,18 +40275,18 @@ _tmp_241_rule(Parser *p) + p->level--; + return NULL; + } +- D(fprintf(stderr, "%*c> _tmp_241[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "yield_expr")); ++ D(fprintf(stderr, "%*c> _tmp_243[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "yield_expr")); + expr_ty yield_expr_var; + if ( + (yield_expr_var = yield_expr_rule(p)) // yield_expr + ) + { +- D(fprintf(stderr, "%*c+ _tmp_241[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "yield_expr")); ++ D(fprintf(stderr, "%*c+ _tmp_243[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "yield_expr")); + _res = yield_expr_var; + goto done; + } + p->mark = _mark; +- D(fprintf(stderr, "%*c%s _tmp_241[%d-%d]: %s failed!\n", p->level, ' ', ++ D(fprintf(stderr, "%*c%s _tmp_243[%d-%d]: %s failed!\n", p->level, ' ', + p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "yield_expr")); + } + { // star_expressions +@@ -39695,18 +40294,18 @@ _tmp_241_rule(Parser *p) + p->level--; + return NULL; + } +- D(fprintf(stderr, "%*c> _tmp_241[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "star_expressions")); ++ D(fprintf(stderr, "%*c> _tmp_243[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "star_expressions")); + expr_ty star_expressions_var; + if ( + (star_expressions_var = star_expressions_rule(p)) // star_expressions + ) + { +- D(fprintf(stderr, "%*c+ _tmp_241[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "star_expressions")); ++ D(fprintf(stderr, "%*c+ _tmp_243[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "star_expressions")); + _res = star_expressions_var; + goto done; + } + p->mark = _mark; +- D(fprintf(stderr, "%*c%s _tmp_241[%d-%d]: %s failed!\n", p->level, ' ', ++ D(fprintf(stderr, "%*c%s _tmp_243[%d-%d]: %s failed!\n", p->level, ' ', + p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "star_expressions")); + } + _res = NULL; +@@ -39715,9 +40314,9 @@ _tmp_241_rule(Parser *p) + return _res; + } + +-// _tmp_242: '!' NAME ++// _tmp_244: '!' NAME + static void * +-_tmp_242_rule(Parser *p) ++_tmp_244_rule(Parser *p) + { + if (p->level++ == MAXSTACK) { + p->error_indicator = 1; +@@ -39734,7 +40333,7 @@ _tmp_242_rule(Parser *p) + p->level--; + return NULL; + } +- D(fprintf(stderr, "%*c> _tmp_242[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "'!' NAME")); ++ D(fprintf(stderr, "%*c> _tmp_244[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "'!' NAME")); + Token * _literal; + expr_ty name_var; + if ( +@@ -39743,12 +40342,12 @@ _tmp_242_rule(Parser *p) + (name_var = _PyPegen_name_token(p)) // NAME + ) + { +- D(fprintf(stderr, "%*c+ _tmp_242[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "'!' NAME")); ++ D(fprintf(stderr, "%*c+ _tmp_244[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "'!' NAME")); + _res = _PyPegen_dummy_name(p, _literal, name_var); + goto done; + } + p->mark = _mark; +- D(fprintf(stderr, "%*c%s _tmp_242[%d-%d]: %s failed!\n", p->level, ' ', ++ D(fprintf(stderr, "%*c%s _tmp_244[%d-%d]: %s failed!\n", p->level, ' ', + p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "'!' NAME")); + } + _res = NULL; +@@ -39757,9 +40356,9 @@ _tmp_242_rule(Parser *p) + return _res; + } + +-// _tmp_243: ':' | '}' ++// _tmp_245: ':' | '}' + static void * +-_tmp_243_rule(Parser *p) ++_tmp_245_rule(Parser *p) + { + if (p->level++ == MAXSTACK) { + p->error_indicator = 1; +@@ -39776,18 +40375,18 @@ _tmp_243_rule(Parser *p) + p->level--; + return NULL; + } +- D(fprintf(stderr, "%*c> _tmp_243[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "':'")); ++ D(fprintf(stderr, "%*c> _tmp_245[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "':'")); + Token * _literal; + if ( + (_literal = _PyPegen_expect_token(p, 11)) // token=':' + ) + { +- D(fprintf(stderr, "%*c+ _tmp_243[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "':'")); ++ D(fprintf(stderr, "%*c+ _tmp_245[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "':'")); + _res = _literal; + goto done; + } + p->mark = _mark; +- D(fprintf(stderr, "%*c%s _tmp_243[%d-%d]: %s failed!\n", p->level, ' ', ++ D(fprintf(stderr, "%*c%s _tmp_245[%d-%d]: %s failed!\n", p->level, ' ', + p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "':'")); + } + { // '}' +@@ -39795,18 +40394,18 @@ _tmp_243_rule(Parser *p) + p->level--; + return NULL; + } +- D(fprintf(stderr, "%*c> _tmp_243[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "'}'")); ++ D(fprintf(stderr, "%*c> _tmp_245[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "'}'")); + Token * _literal; + if ( + (_literal = _PyPegen_expect_token(p, 26)) // token='}' + ) + { +- D(fprintf(stderr, "%*c+ _tmp_243[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "'}'")); ++ D(fprintf(stderr, "%*c+ _tmp_245[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "'}'")); + _res = _literal; + goto done; + } + p->mark = _mark; +- D(fprintf(stderr, "%*c%s _tmp_243[%d-%d]: %s failed!\n", p->level, ' ', ++ D(fprintf(stderr, "%*c%s _tmp_245[%d-%d]: %s failed!\n", p->level, ' ', + p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "'}'")); + } + _res = NULL; +@@ -39815,9 +40414,9 @@ _tmp_243_rule(Parser *p) + return _res; + } + +-// _tmp_244: star_targets '=' ++// _tmp_246: star_targets '=' + static void * +-_tmp_244_rule(Parser *p) ++_tmp_246_rule(Parser *p) + { + if (p->level++ == MAXSTACK) { + p->error_indicator = 1; +@@ -39834,7 +40433,7 @@ _tmp_244_rule(Parser *p) + p->level--; + return NULL; + } +- D(fprintf(stderr, "%*c> _tmp_244[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "star_targets '='")); ++ D(fprintf(stderr, "%*c> _tmp_246[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "star_targets '='")); + Token * _literal; + expr_ty z; + if ( +@@ -39843,7 +40442,7 @@ _tmp_244_rule(Parser *p) + (_literal = _PyPegen_expect_token(p, 22)) // token='=' + ) + { +- D(fprintf(stderr, "%*c+ _tmp_244[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "star_targets '='")); ++ D(fprintf(stderr, "%*c+ _tmp_246[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "star_targets '='")); + _res = z; + if (_res == NULL && PyErr_Occurred()) { + p->error_indicator = 1; +@@ -39853,7 +40452,7 @@ _tmp_244_rule(Parser *p) + goto done; + } + p->mark = _mark; +- D(fprintf(stderr, "%*c%s _tmp_244[%d-%d]: %s failed!\n", p->level, ' ', ++ D(fprintf(stderr, "%*c%s _tmp_246[%d-%d]: %s failed!\n", p->level, ' ', + p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "star_targets '='")); + } + _res = NULL; +@@ -39862,9 +40461,9 @@ _tmp_244_rule(Parser *p) + return _res; + } + +-// _tmp_245: '.' | '...' ++// _tmp_247: '.' | '...' + static void * +-_tmp_245_rule(Parser *p) ++_tmp_247_rule(Parser *p) + { + if (p->level++ == MAXSTACK) { + p->error_indicator = 1; +@@ -39881,18 +40480,18 @@ _tmp_245_rule(Parser *p) + p->level--; + return NULL; + } +- D(fprintf(stderr, "%*c> _tmp_245[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "'.'")); ++ D(fprintf(stderr, "%*c> _tmp_247[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "'.'")); + Token * _literal; + if ( + (_literal = _PyPegen_expect_token(p, 23)) // token='.' + ) + { +- D(fprintf(stderr, "%*c+ _tmp_245[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "'.'")); ++ D(fprintf(stderr, "%*c+ _tmp_247[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "'.'")); + _res = _literal; + goto done; + } + p->mark = _mark; +- D(fprintf(stderr, "%*c%s _tmp_245[%d-%d]: %s failed!\n", p->level, ' ', ++ D(fprintf(stderr, "%*c%s _tmp_247[%d-%d]: %s failed!\n", p->level, ' ', + p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "'.'")); + } + { // '...' +@@ -39900,18 +40499,18 @@ _tmp_245_rule(Parser *p) + p->level--; + return NULL; + } +- D(fprintf(stderr, "%*c> _tmp_245[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "'...'")); ++ D(fprintf(stderr, "%*c> _tmp_247[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "'...'")); + Token * _literal; + if ( + (_literal = _PyPegen_expect_token(p, 52)) // token='...' + ) + { +- D(fprintf(stderr, "%*c+ _tmp_245[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "'...'")); ++ D(fprintf(stderr, "%*c+ _tmp_247[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "'...'")); + _res = _literal; + goto done; + } + p->mark = _mark; +- D(fprintf(stderr, "%*c%s _tmp_245[%d-%d]: %s failed!\n", p->level, ' ', ++ D(fprintf(stderr, "%*c%s _tmp_247[%d-%d]: %s failed!\n", p->level, ' ', + p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "'...'")); + } + _res = NULL; +@@ -39920,9 +40519,9 @@ _tmp_245_rule(Parser *p) + return _res; + } + +-// _tmp_246: '.' | '...' ++// _tmp_248: '.' | '...' + static void * +-_tmp_246_rule(Parser *p) ++_tmp_248_rule(Parser *p) + { + if (p->level++ == MAXSTACK) { + p->error_indicator = 1; +@@ -39939,18 +40538,18 @@ _tmp_246_rule(Parser *p) + p->level--; + return NULL; + } +- D(fprintf(stderr, "%*c> _tmp_246[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "'.'")); ++ D(fprintf(stderr, "%*c> _tmp_248[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "'.'")); + Token * _literal; + if ( + (_literal = _PyPegen_expect_token(p, 23)) // token='.' + ) + { +- D(fprintf(stderr, "%*c+ _tmp_246[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "'.'")); ++ D(fprintf(stderr, "%*c+ _tmp_248[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "'.'")); + _res = _literal; + goto done; + } + p->mark = _mark; +- D(fprintf(stderr, "%*c%s _tmp_246[%d-%d]: %s failed!\n", p->level, ' ', ++ D(fprintf(stderr, "%*c%s _tmp_248[%d-%d]: %s failed!\n", p->level, ' ', + p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "'.'")); + } + { // '...' +@@ -39958,18 +40557,18 @@ _tmp_246_rule(Parser *p) + p->level--; + return NULL; + } +- D(fprintf(stderr, "%*c> _tmp_246[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "'...'")); ++ D(fprintf(stderr, "%*c> _tmp_248[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "'...'")); + Token * _literal; + if ( + (_literal = _PyPegen_expect_token(p, 52)) // token='...' + ) + { +- D(fprintf(stderr, "%*c+ _tmp_246[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "'...'")); ++ D(fprintf(stderr, "%*c+ _tmp_248[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "'...'")); + _res = _literal; + goto done; + } + p->mark = _mark; +- D(fprintf(stderr, "%*c%s _tmp_246[%d-%d]: %s failed!\n", p->level, ' ', ++ D(fprintf(stderr, "%*c%s _tmp_248[%d-%d]: %s failed!\n", p->level, ' ', + p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "'...'")); + } + _res = NULL; +@@ -39978,9 +40577,9 @@ _tmp_246_rule(Parser *p) + return _res; + } + +-// _tmp_247: '@' named_expression NEWLINE ++// _tmp_249: '@' named_expression NEWLINE + static void * +-_tmp_247_rule(Parser *p) ++_tmp_249_rule(Parser *p) + { + if (p->level++ == MAXSTACK) { + p->error_indicator = 1; +@@ -39997,7 +40596,7 @@ _tmp_247_rule(Parser *p) + p->level--; + return NULL; + } +- D(fprintf(stderr, "%*c> _tmp_247[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "'@' named_expression NEWLINE")); ++ D(fprintf(stderr, "%*c> _tmp_249[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "'@' named_expression NEWLINE")); + Token * _literal; + expr_ty f; + Token * newline_var; +@@ -40009,7 +40608,7 @@ _tmp_247_rule(Parser *p) + (newline_var = _PyPegen_expect_token(p, NEWLINE)) // token='NEWLINE' + ) + { +- D(fprintf(stderr, "%*c+ _tmp_247[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "'@' named_expression NEWLINE")); ++ D(fprintf(stderr, "%*c+ _tmp_249[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "'@' named_expression NEWLINE")); + _res = f; + if (_res == NULL && PyErr_Occurred()) { + p->error_indicator = 1; +@@ -40019,7 +40618,7 @@ _tmp_247_rule(Parser *p) + goto done; + } + p->mark = _mark; +- D(fprintf(stderr, "%*c%s _tmp_247[%d-%d]: %s failed!\n", p->level, ' ', ++ D(fprintf(stderr, "%*c%s _tmp_249[%d-%d]: %s failed!\n", p->level, ' ', + p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "'@' named_expression NEWLINE")); + } + _res = NULL; +@@ -40028,9 +40627,9 @@ _tmp_247_rule(Parser *p) + return _res; + } + +-// _tmp_248: ',' expression ++// _tmp_250: ',' expression + static void * +-_tmp_248_rule(Parser *p) ++_tmp_250_rule(Parser *p) + { + if (p->level++ == MAXSTACK) { + p->error_indicator = 1; +@@ -40047,7 +40646,7 @@ _tmp_248_rule(Parser *p) + p->level--; + return NULL; + } +- D(fprintf(stderr, "%*c> _tmp_248[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "',' expression")); ++ D(fprintf(stderr, "%*c> _tmp_250[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "',' expression")); + Token * _literal; + expr_ty c; + if ( +@@ -40056,7 +40655,7 @@ _tmp_248_rule(Parser *p) + (c = expression_rule(p)) // expression + ) + { +- D(fprintf(stderr, "%*c+ _tmp_248[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "',' expression")); ++ D(fprintf(stderr, "%*c+ _tmp_250[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "',' expression")); + _res = c; + if (_res == NULL && PyErr_Occurred()) { + p->error_indicator = 1; +@@ -40066,7 +40665,7 @@ _tmp_248_rule(Parser *p) + goto done; + } + p->mark = _mark; +- D(fprintf(stderr, "%*c%s _tmp_248[%d-%d]: %s failed!\n", p->level, ' ', ++ D(fprintf(stderr, "%*c%s _tmp_250[%d-%d]: %s failed!\n", p->level, ' ', + p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "',' expression")); + } + _res = NULL; +@@ -40075,9 +40674,9 @@ _tmp_248_rule(Parser *p) + return _res; + } + +-// _tmp_249: ',' star_expression ++// _tmp_251: ',' star_expression + static void * +-_tmp_249_rule(Parser *p) ++_tmp_251_rule(Parser *p) + { + if (p->level++ == MAXSTACK) { + p->error_indicator = 1; +@@ -40094,7 +40693,7 @@ _tmp_249_rule(Parser *p) + p->level--; + return NULL; + } +- D(fprintf(stderr, "%*c> _tmp_249[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "',' star_expression")); ++ D(fprintf(stderr, "%*c> _tmp_251[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "',' star_expression")); + Token * _literal; + expr_ty c; + if ( +@@ -40103,7 +40702,7 @@ _tmp_249_rule(Parser *p) + (c = star_expression_rule(p)) // star_expression + ) + { +- D(fprintf(stderr, "%*c+ _tmp_249[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "',' star_expression")); ++ D(fprintf(stderr, "%*c+ _tmp_251[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "',' star_expression")); + _res = c; + if (_res == NULL && PyErr_Occurred()) { + p->error_indicator = 1; +@@ -40113,7 +40712,7 @@ _tmp_249_rule(Parser *p) + goto done; + } + p->mark = _mark; +- D(fprintf(stderr, "%*c%s _tmp_249[%d-%d]: %s failed!\n", p->level, ' ', ++ D(fprintf(stderr, "%*c%s _tmp_251[%d-%d]: %s failed!\n", p->level, ' ', + p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "',' star_expression")); + } + _res = NULL; +@@ -40122,9 +40721,9 @@ _tmp_249_rule(Parser *p) + return _res; + } + +-// _tmp_250: 'or' conjunction ++// _tmp_252: 'or' conjunction + static void * +-_tmp_250_rule(Parser *p) ++_tmp_252_rule(Parser *p) + { + if (p->level++ == MAXSTACK) { + p->error_indicator = 1; +@@ -40141,7 +40740,7 @@ _tmp_250_rule(Parser *p) + p->level--; + return NULL; + } +- D(fprintf(stderr, "%*c> _tmp_250[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "'or' conjunction")); ++ D(fprintf(stderr, "%*c> _tmp_252[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "'or' conjunction")); + Token * _keyword; + expr_ty c; + if ( +@@ -40150,7 +40749,7 @@ _tmp_250_rule(Parser *p) + (c = conjunction_rule(p)) // conjunction + ) + { +- D(fprintf(stderr, "%*c+ _tmp_250[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "'or' conjunction")); ++ D(fprintf(stderr, "%*c+ _tmp_252[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "'or' conjunction")); + _res = c; + if (_res == NULL && PyErr_Occurred()) { + p->error_indicator = 1; +@@ -40160,7 +40759,7 @@ _tmp_250_rule(Parser *p) + goto done; + } + p->mark = _mark; +- D(fprintf(stderr, "%*c%s _tmp_250[%d-%d]: %s failed!\n", p->level, ' ', ++ D(fprintf(stderr, "%*c%s _tmp_252[%d-%d]: %s failed!\n", p->level, ' ', + p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "'or' conjunction")); + } + _res = NULL; +@@ -40169,9 +40768,9 @@ _tmp_250_rule(Parser *p) + return _res; + } + +-// _tmp_251: 'and' inversion ++// _tmp_253: 'and' inversion + static void * +-_tmp_251_rule(Parser *p) ++_tmp_253_rule(Parser *p) + { + if (p->level++ == MAXSTACK) { + p->error_indicator = 1; +@@ -40188,7 +40787,7 @@ _tmp_251_rule(Parser *p) + p->level--; + return NULL; + } +- D(fprintf(stderr, "%*c> _tmp_251[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "'and' inversion")); ++ D(fprintf(stderr, "%*c> _tmp_253[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "'and' inversion")); + Token * _keyword; + expr_ty c; + if ( +@@ -40197,7 +40796,7 @@ _tmp_251_rule(Parser *p) + (c = inversion_rule(p)) // inversion + ) + { +- D(fprintf(stderr, "%*c+ _tmp_251[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "'and' inversion")); ++ D(fprintf(stderr, "%*c+ _tmp_253[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "'and' inversion")); + _res = c; + if (_res == NULL && PyErr_Occurred()) { + p->error_indicator = 1; +@@ -40207,7 +40806,7 @@ _tmp_251_rule(Parser *p) + goto done; + } + p->mark = _mark; +- D(fprintf(stderr, "%*c%s _tmp_251[%d-%d]: %s failed!\n", p->level, ' ', ++ D(fprintf(stderr, "%*c%s _tmp_253[%d-%d]: %s failed!\n", p->level, ' ', + p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "'and' inversion")); + } + _res = NULL; +@@ -40216,9 +40815,9 @@ _tmp_251_rule(Parser *p) + return _res; + } + +-// _tmp_252: slice | starred_expression ++// _tmp_254: slice | starred_expression + static void * +-_tmp_252_rule(Parser *p) ++_tmp_254_rule(Parser *p) + { + if (p->level++ == MAXSTACK) { + p->error_indicator = 1; +@@ -40235,18 +40834,18 @@ _tmp_252_rule(Parser *p) + p->level--; + return NULL; + } +- D(fprintf(stderr, "%*c> _tmp_252[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "slice")); ++ D(fprintf(stderr, "%*c> _tmp_254[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "slice")); + expr_ty slice_var; + if ( + (slice_var = slice_rule(p)) // slice + ) + { +- D(fprintf(stderr, "%*c+ _tmp_252[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "slice")); ++ D(fprintf(stderr, "%*c+ _tmp_254[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "slice")); + _res = slice_var; + goto done; + } + p->mark = _mark; +- D(fprintf(stderr, "%*c%s _tmp_252[%d-%d]: %s failed!\n", p->level, ' ', ++ D(fprintf(stderr, "%*c%s _tmp_254[%d-%d]: %s failed!\n", p->level, ' ', + p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "slice")); + } + { // starred_expression +@@ -40254,18 +40853,18 @@ _tmp_252_rule(Parser *p) + p->level--; + return NULL; + } +- D(fprintf(stderr, "%*c> _tmp_252[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "starred_expression")); ++ D(fprintf(stderr, "%*c> _tmp_254[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "starred_expression")); + expr_ty starred_expression_var; + if ( + (starred_expression_var = starred_expression_rule(p)) // starred_expression + ) + { +- D(fprintf(stderr, "%*c+ _tmp_252[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "starred_expression")); ++ D(fprintf(stderr, "%*c+ _tmp_254[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "starred_expression")); + _res = starred_expression_var; + goto done; + } + p->mark = _mark; +- D(fprintf(stderr, "%*c%s _tmp_252[%d-%d]: %s failed!\n", p->level, ' ', ++ D(fprintf(stderr, "%*c%s _tmp_254[%d-%d]: %s failed!\n", p->level, ' ', + p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "starred_expression")); + } + _res = NULL; +@@ -40274,9 +40873,9 @@ _tmp_252_rule(Parser *p) + return _res; + } + +-// _tmp_253: fstring | string ++// _tmp_255: fstring | string + static void * +-_tmp_253_rule(Parser *p) ++_tmp_255_rule(Parser *p) + { + if (p->level++ == MAXSTACK) { + p->error_indicator = 1; +@@ -40293,18 +40892,18 @@ _tmp_253_rule(Parser *p) + p->level--; + return NULL; + } +- D(fprintf(stderr, "%*c> _tmp_253[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "fstring")); ++ D(fprintf(stderr, "%*c> _tmp_255[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "fstring")); + expr_ty fstring_var; + if ( + (fstring_var = fstring_rule(p)) // fstring + ) + { +- D(fprintf(stderr, "%*c+ _tmp_253[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "fstring")); ++ D(fprintf(stderr, "%*c+ _tmp_255[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "fstring")); + _res = fstring_var; + goto done; + } + p->mark = _mark; +- D(fprintf(stderr, "%*c%s _tmp_253[%d-%d]: %s failed!\n", p->level, ' ', ++ D(fprintf(stderr, "%*c%s _tmp_255[%d-%d]: %s failed!\n", p->level, ' ', + p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "fstring")); + } + { // string +@@ -40312,18 +40911,18 @@ _tmp_253_rule(Parser *p) + p->level--; + return NULL; + } +- D(fprintf(stderr, "%*c> _tmp_253[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "string")); ++ D(fprintf(stderr, "%*c> _tmp_255[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "string")); + expr_ty string_var; + if ( + (string_var = string_rule(p)) // string + ) + { +- D(fprintf(stderr, "%*c+ _tmp_253[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "string")); ++ D(fprintf(stderr, "%*c+ _tmp_255[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "string")); + _res = string_var; + goto done; + } + p->mark = _mark; +- D(fprintf(stderr, "%*c%s _tmp_253[%d-%d]: %s failed!\n", p->level, ' ', ++ D(fprintf(stderr, "%*c%s _tmp_255[%d-%d]: %s failed!\n", p->level, ' ', + p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "string")); + } + _res = NULL; +@@ -40332,9 +40931,9 @@ _tmp_253_rule(Parser *p) + return _res; + } + +-// _tmp_254: 'if' disjunction ++// _tmp_256: 'if' disjunction + static void * +-_tmp_254_rule(Parser *p) ++_tmp_256_rule(Parser *p) + { + if (p->level++ == MAXSTACK) { + p->error_indicator = 1; +@@ -40351,7 +40950,7 @@ _tmp_254_rule(Parser *p) + p->level--; + return NULL; + } +- D(fprintf(stderr, "%*c> _tmp_254[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "'if' disjunction")); ++ D(fprintf(stderr, "%*c> _tmp_256[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "'if' disjunction")); + Token * _keyword; + expr_ty z; + if ( +@@ -40360,7 +40959,7 @@ _tmp_254_rule(Parser *p) + (z = disjunction_rule(p)) // disjunction + ) + { +- D(fprintf(stderr, "%*c+ _tmp_254[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "'if' disjunction")); ++ D(fprintf(stderr, "%*c+ _tmp_256[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "'if' disjunction")); + _res = z; + if (_res == NULL && PyErr_Occurred()) { + p->error_indicator = 1; +@@ -40370,7 +40969,7 @@ _tmp_254_rule(Parser *p) + goto done; + } + p->mark = _mark; +- D(fprintf(stderr, "%*c%s _tmp_254[%d-%d]: %s failed!\n", p->level, ' ', ++ D(fprintf(stderr, "%*c%s _tmp_256[%d-%d]: %s failed!\n", p->level, ' ', + p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "'if' disjunction")); + } + _res = NULL; +@@ -40379,9 +40978,9 @@ _tmp_254_rule(Parser *p) + return _res; + } + +-// _tmp_255: 'if' disjunction ++// _tmp_257: 'if' disjunction + static void * +-_tmp_255_rule(Parser *p) ++_tmp_257_rule(Parser *p) + { + if (p->level++ == MAXSTACK) { + p->error_indicator = 1; +@@ -40398,7 +40997,7 @@ _tmp_255_rule(Parser *p) + p->level--; + return NULL; + } +- D(fprintf(stderr, "%*c> _tmp_255[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "'if' disjunction")); ++ D(fprintf(stderr, "%*c> _tmp_257[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "'if' disjunction")); + Token * _keyword; + expr_ty z; + if ( +@@ -40407,7 +41006,7 @@ _tmp_255_rule(Parser *p) + (z = disjunction_rule(p)) // disjunction + ) + { +- D(fprintf(stderr, "%*c+ _tmp_255[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "'if' disjunction")); ++ D(fprintf(stderr, "%*c+ _tmp_257[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "'if' disjunction")); + _res = z; + if (_res == NULL && PyErr_Occurred()) { + p->error_indicator = 1; +@@ -40417,7 +41016,7 @@ _tmp_255_rule(Parser *p) + goto done; + } + p->mark = _mark; +- D(fprintf(stderr, "%*c%s _tmp_255[%d-%d]: %s failed!\n", p->level, ' ', ++ D(fprintf(stderr, "%*c%s _tmp_257[%d-%d]: %s failed!\n", p->level, ' ', + p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "'if' disjunction")); + } + _res = NULL; +@@ -40426,9 +41025,9 @@ _tmp_255_rule(Parser *p) + return _res; + } + +-// _tmp_256: starred_expression | (assignment_expression | expression !':=') !'=' ++// _tmp_258: starred_expression | (assignment_expression | expression !':=') !'=' + static void * +-_tmp_256_rule(Parser *p) ++_tmp_258_rule(Parser *p) + { + if (p->level++ == MAXSTACK) { + p->error_indicator = 1; +@@ -40445,18 +41044,18 @@ _tmp_256_rule(Parser *p) + p->level--; + return NULL; + } +- D(fprintf(stderr, "%*c> _tmp_256[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "starred_expression")); ++ D(fprintf(stderr, "%*c> _tmp_258[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "starred_expression")); + expr_ty starred_expression_var; + if ( + (starred_expression_var = starred_expression_rule(p)) // starred_expression + ) + { +- D(fprintf(stderr, "%*c+ _tmp_256[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "starred_expression")); ++ D(fprintf(stderr, "%*c+ _tmp_258[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "starred_expression")); + _res = starred_expression_var; + goto done; + } + p->mark = _mark; +- D(fprintf(stderr, "%*c%s _tmp_256[%d-%d]: %s failed!\n", p->level, ' ', ++ D(fprintf(stderr, "%*c%s _tmp_258[%d-%d]: %s failed!\n", p->level, ' ', + p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "starred_expression")); + } + { // (assignment_expression | expression !':=') !'=' +@@ -40464,20 +41063,20 @@ _tmp_256_rule(Parser *p) + p->level--; + return NULL; + } +- D(fprintf(stderr, "%*c> _tmp_256[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "(assignment_expression | expression !':=') !'='")); +- void *_tmp_268_var; ++ D(fprintf(stderr, "%*c> _tmp_258[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "(assignment_expression | expression !':=') !'='")); ++ void *_tmp_270_var; + if ( +- (_tmp_268_var = _tmp_268_rule(p)) // assignment_expression | expression !':=' ++ (_tmp_270_var = _tmp_270_rule(p)) // assignment_expression | expression !':=' + && + _PyPegen_lookahead_with_int(0, _PyPegen_expect_token, p, 22) // token='=' + ) + { +- D(fprintf(stderr, "%*c+ _tmp_256[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "(assignment_expression | expression !':=') !'='")); +- _res = _tmp_268_var; ++ D(fprintf(stderr, "%*c+ _tmp_258[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "(assignment_expression | expression !':=') !'='")); ++ _res = _tmp_270_var; + goto done; + } + p->mark = _mark; +- D(fprintf(stderr, "%*c%s _tmp_256[%d-%d]: %s failed!\n", p->level, ' ', ++ D(fprintf(stderr, "%*c%s _tmp_258[%d-%d]: %s failed!\n", p->level, ' ', + p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "(assignment_expression | expression !':=') !'='")); + } + _res = NULL; +@@ -40486,9 +41085,9 @@ _tmp_256_rule(Parser *p) + return _res; + } + +-// _tmp_257: ',' star_target ++// _tmp_259: ',' star_target + static void * +-_tmp_257_rule(Parser *p) ++_tmp_259_rule(Parser *p) + { + if (p->level++ == MAXSTACK) { + p->error_indicator = 1; +@@ -40505,7 +41104,7 @@ _tmp_257_rule(Parser *p) + p->level--; + return NULL; + } +- D(fprintf(stderr, "%*c> _tmp_257[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "',' star_target")); ++ D(fprintf(stderr, "%*c> _tmp_259[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "',' star_target")); + Token * _literal; + expr_ty c; + if ( +@@ -40514,7 +41113,7 @@ _tmp_257_rule(Parser *p) + (c = star_target_rule(p)) // star_target + ) + { +- D(fprintf(stderr, "%*c+ _tmp_257[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "',' star_target")); ++ D(fprintf(stderr, "%*c+ _tmp_259[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "',' star_target")); + _res = c; + if (_res == NULL && PyErr_Occurred()) { + p->error_indicator = 1; +@@ -40524,7 +41123,7 @@ _tmp_257_rule(Parser *p) + goto done; + } + p->mark = _mark; +- D(fprintf(stderr, "%*c%s _tmp_257[%d-%d]: %s failed!\n", p->level, ' ', ++ D(fprintf(stderr, "%*c%s _tmp_259[%d-%d]: %s failed!\n", p->level, ' ', + p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "',' star_target")); + } + _res = NULL; +@@ -40533,9 +41132,9 @@ _tmp_257_rule(Parser *p) + return _res; + } + +-// _tmp_258: ',' star_target ++// _tmp_260: ',' star_target + static void * +-_tmp_258_rule(Parser *p) ++_tmp_260_rule(Parser *p) + { + if (p->level++ == MAXSTACK) { + p->error_indicator = 1; +@@ -40552,7 +41151,7 @@ _tmp_258_rule(Parser *p) + p->level--; + return NULL; + } +- D(fprintf(stderr, "%*c> _tmp_258[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "',' star_target")); ++ D(fprintf(stderr, "%*c> _tmp_260[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "',' star_target")); + Token * _literal; + expr_ty c; + if ( +@@ -40561,7 +41160,7 @@ _tmp_258_rule(Parser *p) + (c = star_target_rule(p)) // star_target + ) + { +- D(fprintf(stderr, "%*c+ _tmp_258[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "',' star_target")); ++ D(fprintf(stderr, "%*c+ _tmp_260[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "',' star_target")); + _res = c; + if (_res == NULL && PyErr_Occurred()) { + p->error_indicator = 1; +@@ -40571,7 +41170,7 @@ _tmp_258_rule(Parser *p) + goto done; + } + p->mark = _mark; +- D(fprintf(stderr, "%*c%s _tmp_258[%d-%d]: %s failed!\n", p->level, ' ', ++ D(fprintf(stderr, "%*c%s _tmp_260[%d-%d]: %s failed!\n", p->level, ' ', + p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "',' star_target")); + } + _res = NULL; +@@ -40580,9 +41179,9 @@ _tmp_258_rule(Parser *p) + return _res; + } + +-// _tmp_259: star_targets '=' ++// _tmp_261: star_targets '=' + static void * +-_tmp_259_rule(Parser *p) ++_tmp_261_rule(Parser *p) + { + if (p->level++ == MAXSTACK) { + p->error_indicator = 1; +@@ -40599,7 +41198,7 @@ _tmp_259_rule(Parser *p) + p->level--; + return NULL; + } +- D(fprintf(stderr, "%*c> _tmp_259[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "star_targets '='")); ++ D(fprintf(stderr, "%*c> _tmp_261[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "star_targets '='")); + Token * _literal; + expr_ty star_targets_var; + if ( +@@ -40608,12 +41207,12 @@ _tmp_259_rule(Parser *p) + (_literal = _PyPegen_expect_token(p, 22)) // token='=' + ) + { +- D(fprintf(stderr, "%*c+ _tmp_259[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "star_targets '='")); ++ D(fprintf(stderr, "%*c+ _tmp_261[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "star_targets '='")); + _res = _PyPegen_dummy_name(p, star_targets_var, _literal); + goto done; + } + p->mark = _mark; +- D(fprintf(stderr, "%*c%s _tmp_259[%d-%d]: %s failed!\n", p->level, ' ', ++ D(fprintf(stderr, "%*c%s _tmp_261[%d-%d]: %s failed!\n", p->level, ' ', + p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "star_targets '='")); + } + _res = NULL; +@@ -40622,9 +41221,9 @@ _tmp_259_rule(Parser *p) + return _res; + } + +-// _tmp_260: star_targets '=' ++// _tmp_262: star_targets '=' + static void * +-_tmp_260_rule(Parser *p) ++_tmp_262_rule(Parser *p) + { + if (p->level++ == MAXSTACK) { + p->error_indicator = 1; +@@ -40641,7 +41240,7 @@ _tmp_260_rule(Parser *p) + p->level--; + return NULL; + } +- D(fprintf(stderr, "%*c> _tmp_260[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "star_targets '='")); ++ D(fprintf(stderr, "%*c> _tmp_262[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "star_targets '='")); + Token * _literal; + expr_ty star_targets_var; + if ( +@@ -40650,12 +41249,12 @@ _tmp_260_rule(Parser *p) + (_literal = _PyPegen_expect_token(p, 22)) // token='=' + ) + { +- D(fprintf(stderr, "%*c+ _tmp_260[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "star_targets '='")); ++ D(fprintf(stderr, "%*c+ _tmp_262[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "star_targets '='")); + _res = _PyPegen_dummy_name(p, star_targets_var, _literal); + goto done; + } + p->mark = _mark; +- D(fprintf(stderr, "%*c%s _tmp_260[%d-%d]: %s failed!\n", p->level, ' ', ++ D(fprintf(stderr, "%*c%s _tmp_262[%d-%d]: %s failed!\n", p->level, ' ', + p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "star_targets '='")); + } + _res = NULL; +@@ -40664,9 +41263,9 @@ _tmp_260_rule(Parser *p) + return _res; + } + +-// _tmp_261: ')' | '**' ++// _tmp_263: ')' | '**' + static void * +-_tmp_261_rule(Parser *p) ++_tmp_263_rule(Parser *p) + { + if (p->level++ == MAXSTACK) { + p->error_indicator = 1; +@@ -40683,18 +41282,18 @@ _tmp_261_rule(Parser *p) + p->level--; + return NULL; + } +- D(fprintf(stderr, "%*c> _tmp_261[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "')'")); ++ D(fprintf(stderr, "%*c> _tmp_263[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "')'")); + Token * _literal; + if ( + (_literal = _PyPegen_expect_token(p, 8)) // token=')' + ) + { +- D(fprintf(stderr, "%*c+ _tmp_261[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "')'")); ++ D(fprintf(stderr, "%*c+ _tmp_263[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "')'")); + _res = _literal; + goto done; + } + p->mark = _mark; +- D(fprintf(stderr, "%*c%s _tmp_261[%d-%d]: %s failed!\n", p->level, ' ', ++ D(fprintf(stderr, "%*c%s _tmp_263[%d-%d]: %s failed!\n", p->level, ' ', + p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "')'")); + } + { // '**' +@@ -40702,18 +41301,18 @@ _tmp_261_rule(Parser *p) + p->level--; + return NULL; + } +- D(fprintf(stderr, "%*c> _tmp_261[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "'**'")); ++ D(fprintf(stderr, "%*c> _tmp_263[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "'**'")); + Token * _literal; + if ( + (_literal = _PyPegen_expect_token(p, 35)) // token='**' + ) + { +- D(fprintf(stderr, "%*c+ _tmp_261[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "'**'")); ++ D(fprintf(stderr, "%*c+ _tmp_263[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "'**'")); + _res = _literal; + goto done; + } + p->mark = _mark; +- D(fprintf(stderr, "%*c%s _tmp_261[%d-%d]: %s failed!\n", p->level, ' ', ++ D(fprintf(stderr, "%*c%s _tmp_263[%d-%d]: %s failed!\n", p->level, ' ', + p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "'**'")); + } + _res = NULL; +@@ -40722,9 +41321,9 @@ _tmp_261_rule(Parser *p) + return _res; + } + +-// _tmp_262: ':' | '**' ++// _tmp_264: ':' | '**' + static void * +-_tmp_262_rule(Parser *p) ++_tmp_264_rule(Parser *p) + { + if (p->level++ == MAXSTACK) { + p->error_indicator = 1; +@@ -40741,18 +41340,18 @@ _tmp_262_rule(Parser *p) + p->level--; + return NULL; + } +- D(fprintf(stderr, "%*c> _tmp_262[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "':'")); ++ D(fprintf(stderr, "%*c> _tmp_264[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "':'")); + Token * _literal; + if ( + (_literal = _PyPegen_expect_token(p, 11)) // token=':' + ) + { +- D(fprintf(stderr, "%*c+ _tmp_262[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "':'")); ++ D(fprintf(stderr, "%*c+ _tmp_264[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "':'")); + _res = _literal; + goto done; + } + p->mark = _mark; +- D(fprintf(stderr, "%*c%s _tmp_262[%d-%d]: %s failed!\n", p->level, ' ', ++ D(fprintf(stderr, "%*c%s _tmp_264[%d-%d]: %s failed!\n", p->level, ' ', + p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "':'")); + } + { // '**' +@@ -40760,18 +41359,18 @@ _tmp_262_rule(Parser *p) + p->level--; + return NULL; + } +- D(fprintf(stderr, "%*c> _tmp_262[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "'**'")); ++ D(fprintf(stderr, "%*c> _tmp_264[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "'**'")); + Token * _literal; + if ( + (_literal = _PyPegen_expect_token(p, 35)) // token='**' + ) + { +- D(fprintf(stderr, "%*c+ _tmp_262[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "'**'")); ++ D(fprintf(stderr, "%*c+ _tmp_264[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "'**'")); + _res = _literal; + goto done; + } + p->mark = _mark; +- D(fprintf(stderr, "%*c%s _tmp_262[%d-%d]: %s failed!\n", p->level, ' ', ++ D(fprintf(stderr, "%*c%s _tmp_264[%d-%d]: %s failed!\n", p->level, ' ', + p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "'**'")); + } + _res = NULL; +@@ -40780,9 +41379,9 @@ _tmp_262_rule(Parser *p) + return _res; + } + +-// _tmp_263: expression ['as' star_target] ++// _tmp_265: expression ['as' star_target] + static void * +-_tmp_263_rule(Parser *p) ++_tmp_265_rule(Parser *p) + { + if (p->level++ == MAXSTACK) { + p->error_indicator = 1; +@@ -40799,22 +41398,22 @@ _tmp_263_rule(Parser *p) + p->level--; + return NULL; + } +- D(fprintf(stderr, "%*c> _tmp_263[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "expression ['as' star_target]")); ++ D(fprintf(stderr, "%*c> _tmp_265[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "expression ['as' star_target]")); + void *_opt_var; + UNUSED(_opt_var); // Silence compiler warnings + expr_ty expression_var; + if ( + (expression_var = expression_rule(p)) // expression + && +- (_opt_var = _tmp_269_rule(p), !p->error_indicator) // ['as' star_target] ++ (_opt_var = _tmp_271_rule(p), !p->error_indicator) // ['as' star_target] + ) + { +- D(fprintf(stderr, "%*c+ _tmp_263[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "expression ['as' star_target]")); ++ D(fprintf(stderr, "%*c+ _tmp_265[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "expression ['as' star_target]")); + _res = _PyPegen_dummy_name(p, expression_var, _opt_var); + goto done; + } + p->mark = _mark; +- D(fprintf(stderr, "%*c%s _tmp_263[%d-%d]: %s failed!\n", p->level, ' ', ++ D(fprintf(stderr, "%*c%s _tmp_265[%d-%d]: %s failed!\n", p->level, ' ', + p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "expression ['as' star_target]")); + } + _res = NULL; +@@ -40823,9 +41422,9 @@ _tmp_263_rule(Parser *p) + return _res; + } + +-// _tmp_264: expressions ['as' star_target] ++// _tmp_266: expressions ['as' star_target] + static void * +-_tmp_264_rule(Parser *p) ++_tmp_266_rule(Parser *p) + { + if (p->level++ == MAXSTACK) { + p->error_indicator = 1; +@@ -40842,22 +41441,22 @@ _tmp_264_rule(Parser *p) + p->level--; + return NULL; + } +- D(fprintf(stderr, "%*c> _tmp_264[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "expressions ['as' star_target]")); ++ D(fprintf(stderr, "%*c> _tmp_266[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "expressions ['as' star_target]")); + void *_opt_var; + UNUSED(_opt_var); // Silence compiler warnings + expr_ty expressions_var; + if ( + (expressions_var = expressions_rule(p)) // expressions + && +- (_opt_var = _tmp_270_rule(p), !p->error_indicator) // ['as' star_target] ++ (_opt_var = _tmp_272_rule(p), !p->error_indicator) // ['as' star_target] + ) + { +- D(fprintf(stderr, "%*c+ _tmp_264[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "expressions ['as' star_target]")); ++ D(fprintf(stderr, "%*c+ _tmp_266[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "expressions ['as' star_target]")); + _res = _PyPegen_dummy_name(p, expressions_var, _opt_var); + goto done; + } + p->mark = _mark; +- D(fprintf(stderr, "%*c%s _tmp_264[%d-%d]: %s failed!\n", p->level, ' ', ++ D(fprintf(stderr, "%*c%s _tmp_266[%d-%d]: %s failed!\n", p->level, ' ', + p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "expressions ['as' star_target]")); + } + _res = NULL; +@@ -40866,9 +41465,9 @@ _tmp_264_rule(Parser *p) + return _res; + } + +-// _tmp_265: expression ['as' star_target] ++// _tmp_267: expression ['as' star_target] + static void * +-_tmp_265_rule(Parser *p) ++_tmp_267_rule(Parser *p) + { + if (p->level++ == MAXSTACK) { + p->error_indicator = 1; +@@ -40885,22 +41484,22 @@ _tmp_265_rule(Parser *p) + p->level--; + return NULL; + } +- D(fprintf(stderr, "%*c> _tmp_265[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "expression ['as' star_target]")); ++ D(fprintf(stderr, "%*c> _tmp_267[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "expression ['as' star_target]")); + void *_opt_var; + UNUSED(_opt_var); // Silence compiler warnings + expr_ty expression_var; + if ( + (expression_var = expression_rule(p)) // expression + && +- (_opt_var = _tmp_271_rule(p), !p->error_indicator) // ['as' star_target] ++ (_opt_var = _tmp_273_rule(p), !p->error_indicator) // ['as' star_target] + ) + { +- D(fprintf(stderr, "%*c+ _tmp_265[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "expression ['as' star_target]")); ++ D(fprintf(stderr, "%*c+ _tmp_267[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "expression ['as' star_target]")); + _res = _PyPegen_dummy_name(p, expression_var, _opt_var); + goto done; + } + p->mark = _mark; +- D(fprintf(stderr, "%*c%s _tmp_265[%d-%d]: %s failed!\n", p->level, ' ', ++ D(fprintf(stderr, "%*c%s _tmp_267[%d-%d]: %s failed!\n", p->level, ' ', + p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "expression ['as' star_target]")); + } + _res = NULL; +@@ -40909,9 +41508,9 @@ _tmp_265_rule(Parser *p) + return _res; + } + +-// _tmp_266: expressions ['as' star_target] ++// _tmp_268: expressions ['as' star_target] + static void * +-_tmp_266_rule(Parser *p) ++_tmp_268_rule(Parser *p) + { + if (p->level++ == MAXSTACK) { + p->error_indicator = 1; +@@ -40928,22 +41527,22 @@ _tmp_266_rule(Parser *p) + p->level--; + return NULL; + } +- D(fprintf(stderr, "%*c> _tmp_266[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "expressions ['as' star_target]")); ++ D(fprintf(stderr, "%*c> _tmp_268[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "expressions ['as' star_target]")); + void *_opt_var; + UNUSED(_opt_var); // Silence compiler warnings + expr_ty expressions_var; + if ( + (expressions_var = expressions_rule(p)) // expressions + && +- (_opt_var = _tmp_272_rule(p), !p->error_indicator) // ['as' star_target] ++ (_opt_var = _tmp_274_rule(p), !p->error_indicator) // ['as' star_target] + ) + { +- D(fprintf(stderr, "%*c+ _tmp_266[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "expressions ['as' star_target]")); ++ D(fprintf(stderr, "%*c+ _tmp_268[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "expressions ['as' star_target]")); + _res = _PyPegen_dummy_name(p, expressions_var, _opt_var); + goto done; + } + p->mark = _mark; +- D(fprintf(stderr, "%*c%s _tmp_266[%d-%d]: %s failed!\n", p->level, ' ', ++ D(fprintf(stderr, "%*c%s _tmp_268[%d-%d]: %s failed!\n", p->level, ' ', + p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "expressions ['as' star_target]")); + } + _res = NULL; +@@ -40952,9 +41551,9 @@ _tmp_266_rule(Parser *p) + return _res; + } + +-// _tmp_267: 'as' NAME ++// _tmp_269: 'as' NAME + static void * +-_tmp_267_rule(Parser *p) ++_tmp_269_rule(Parser *p) + { + if (p->level++ == MAXSTACK) { + p->error_indicator = 1; +@@ -40971,7 +41570,7 @@ _tmp_267_rule(Parser *p) + p->level--; + return NULL; + } +- D(fprintf(stderr, "%*c> _tmp_267[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "'as' NAME")); ++ D(fprintf(stderr, "%*c> _tmp_269[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "'as' NAME")); + Token * _keyword; + expr_ty name_var; + if ( +@@ -40980,12 +41579,12 @@ _tmp_267_rule(Parser *p) + (name_var = _PyPegen_name_token(p)) // NAME + ) + { +- D(fprintf(stderr, "%*c+ _tmp_267[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "'as' NAME")); ++ D(fprintf(stderr, "%*c+ _tmp_269[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "'as' NAME")); + _res = _PyPegen_dummy_name(p, _keyword, name_var); + goto done; + } + p->mark = _mark; +- D(fprintf(stderr, "%*c%s _tmp_267[%d-%d]: %s failed!\n", p->level, ' ', ++ D(fprintf(stderr, "%*c%s _tmp_269[%d-%d]: %s failed!\n", p->level, ' ', + p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "'as' NAME")); + } + _res = NULL; +@@ -40994,9 +41593,9 @@ _tmp_267_rule(Parser *p) + return _res; + } + +-// _tmp_268: assignment_expression | expression !':=' ++// _tmp_270: assignment_expression | expression !':=' + static void * +-_tmp_268_rule(Parser *p) ++_tmp_270_rule(Parser *p) + { + if (p->level++ == MAXSTACK) { + p->error_indicator = 1; +@@ -41013,18 +41612,18 @@ _tmp_268_rule(Parser *p) + p->level--; + return NULL; + } +- D(fprintf(stderr, "%*c> _tmp_268[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "assignment_expression")); ++ D(fprintf(stderr, "%*c> _tmp_270[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "assignment_expression")); + expr_ty assignment_expression_var; + if ( + (assignment_expression_var = assignment_expression_rule(p)) // assignment_expression + ) + { +- D(fprintf(stderr, "%*c+ _tmp_268[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "assignment_expression")); ++ D(fprintf(stderr, "%*c+ _tmp_270[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "assignment_expression")); + _res = assignment_expression_var; + goto done; + } + p->mark = _mark; +- D(fprintf(stderr, "%*c%s _tmp_268[%d-%d]: %s failed!\n", p->level, ' ', ++ D(fprintf(stderr, "%*c%s _tmp_270[%d-%d]: %s failed!\n", p->level, ' ', + p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "assignment_expression")); + } + { // expression !':=' +@@ -41032,7 +41631,7 @@ _tmp_268_rule(Parser *p) + p->level--; + return NULL; + } +- D(fprintf(stderr, "%*c> _tmp_268[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "expression !':='")); ++ D(fprintf(stderr, "%*c> _tmp_270[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "expression !':='")); + expr_ty expression_var; + if ( + (expression_var = expression_rule(p)) // expression +@@ -41040,12 +41639,12 @@ _tmp_268_rule(Parser *p) + _PyPegen_lookahead_with_int(0, _PyPegen_expect_token, p, 53) // token=':=' + ) + { +- D(fprintf(stderr, "%*c+ _tmp_268[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "expression !':='")); ++ D(fprintf(stderr, "%*c+ _tmp_270[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "expression !':='")); + _res = expression_var; + goto done; + } + p->mark = _mark; +- D(fprintf(stderr, "%*c%s _tmp_268[%d-%d]: %s failed!\n", p->level, ' ', ++ D(fprintf(stderr, "%*c%s _tmp_270[%d-%d]: %s failed!\n", p->level, ' ', + p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "expression !':='")); + } + _res = NULL; +@@ -41054,9 +41653,9 @@ _tmp_268_rule(Parser *p) + return _res; + } + +-// _tmp_269: 'as' star_target ++// _tmp_271: 'as' star_target + static void * +-_tmp_269_rule(Parser *p) ++_tmp_271_rule(Parser *p) + { + if (p->level++ == MAXSTACK) { + p->error_indicator = 1; +@@ -41073,7 +41672,7 @@ _tmp_269_rule(Parser *p) + p->level--; + return NULL; + } +- D(fprintf(stderr, "%*c> _tmp_269[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "'as' star_target")); ++ D(fprintf(stderr, "%*c> _tmp_271[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "'as' star_target")); + Token * _keyword; + expr_ty star_target_var; + if ( +@@ -41082,12 +41681,12 @@ _tmp_269_rule(Parser *p) + (star_target_var = star_target_rule(p)) // star_target + ) + { +- D(fprintf(stderr, "%*c+ _tmp_269[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "'as' star_target")); ++ D(fprintf(stderr, "%*c+ _tmp_271[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "'as' star_target")); + _res = _PyPegen_dummy_name(p, _keyword, star_target_var); + goto done; + } + p->mark = _mark; +- D(fprintf(stderr, "%*c%s _tmp_269[%d-%d]: %s failed!\n", p->level, ' ', ++ D(fprintf(stderr, "%*c%s _tmp_271[%d-%d]: %s failed!\n", p->level, ' ', + p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "'as' star_target")); + } + _res = NULL; +@@ -41096,9 +41695,9 @@ _tmp_269_rule(Parser *p) + return _res; + } + +-// _tmp_270: 'as' star_target ++// _tmp_272: 'as' star_target + static void * +-_tmp_270_rule(Parser *p) ++_tmp_272_rule(Parser *p) + { + if (p->level++ == MAXSTACK) { + p->error_indicator = 1; +@@ -41115,7 +41714,7 @@ _tmp_270_rule(Parser *p) + p->level--; + return NULL; + } +- D(fprintf(stderr, "%*c> _tmp_270[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "'as' star_target")); ++ D(fprintf(stderr, "%*c> _tmp_272[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "'as' star_target")); + Token * _keyword; + expr_ty star_target_var; + if ( +@@ -41124,12 +41723,12 @@ _tmp_270_rule(Parser *p) + (star_target_var = star_target_rule(p)) // star_target + ) + { +- D(fprintf(stderr, "%*c+ _tmp_270[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "'as' star_target")); ++ D(fprintf(stderr, "%*c+ _tmp_272[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "'as' star_target")); + _res = _PyPegen_dummy_name(p, _keyword, star_target_var); + goto done; + } + p->mark = _mark; +- D(fprintf(stderr, "%*c%s _tmp_270[%d-%d]: %s failed!\n", p->level, ' ', ++ D(fprintf(stderr, "%*c%s _tmp_272[%d-%d]: %s failed!\n", p->level, ' ', + p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "'as' star_target")); + } + _res = NULL; +@@ -41138,9 +41737,9 @@ _tmp_270_rule(Parser *p) + return _res; + } + +-// _tmp_271: 'as' star_target ++// _tmp_273: 'as' star_target + static void * +-_tmp_271_rule(Parser *p) ++_tmp_273_rule(Parser *p) + { + if (p->level++ == MAXSTACK) { + p->error_indicator = 1; +@@ -41157,7 +41756,7 @@ _tmp_271_rule(Parser *p) + p->level--; + return NULL; + } +- D(fprintf(stderr, "%*c> _tmp_271[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "'as' star_target")); ++ D(fprintf(stderr, "%*c> _tmp_273[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "'as' star_target")); + Token * _keyword; + expr_ty star_target_var; + if ( +@@ -41166,12 +41765,12 @@ _tmp_271_rule(Parser *p) + (star_target_var = star_target_rule(p)) // star_target + ) + { +- D(fprintf(stderr, "%*c+ _tmp_271[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "'as' star_target")); ++ D(fprintf(stderr, "%*c+ _tmp_273[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "'as' star_target")); + _res = _PyPegen_dummy_name(p, _keyword, star_target_var); + goto done; + } + p->mark = _mark; +- D(fprintf(stderr, "%*c%s _tmp_271[%d-%d]: %s failed!\n", p->level, ' ', ++ D(fprintf(stderr, "%*c%s _tmp_273[%d-%d]: %s failed!\n", p->level, ' ', + p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "'as' star_target")); + } + _res = NULL; +@@ -41180,9 +41779,9 @@ _tmp_271_rule(Parser *p) + return _res; + } + +-// _tmp_272: 'as' star_target ++// _tmp_274: 'as' star_target + static void * +-_tmp_272_rule(Parser *p) ++_tmp_274_rule(Parser *p) + { + if (p->level++ == MAXSTACK) { + p->error_indicator = 1; +@@ -41199,7 +41798,7 @@ _tmp_272_rule(Parser *p) + p->level--; + return NULL; + } +- D(fprintf(stderr, "%*c> _tmp_272[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "'as' star_target")); ++ D(fprintf(stderr, "%*c> _tmp_274[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "'as' star_target")); + Token * _keyword; + expr_ty star_target_var; + if ( +@@ -41208,12 +41807,12 @@ _tmp_272_rule(Parser *p) + (star_target_var = star_target_rule(p)) // star_target + ) + { +- D(fprintf(stderr, "%*c+ _tmp_272[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "'as' star_target")); ++ D(fprintf(stderr, "%*c+ _tmp_274[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "'as' star_target")); + _res = _PyPegen_dummy_name(p, _keyword, star_target_var); + goto done; + } + p->mark = _mark; +- D(fprintf(stderr, "%*c%s _tmp_272[%d-%d]: %s failed!\n", p->level, ' ', ++ D(fprintf(stderr, "%*c%s _tmp_274[%d-%d]: %s failed!\n", p->level, ' ', + p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "'as' star_target")); + } + _res = NULL; +diff --git a/Python/Python-ast.c b/Python/Python-ast.c +index 81ab71c0fc..d62cccbb6e 100644 +--- a/Python/Python-ast.c ++++ b/Python/Python-ast.c +@@ -131,6 +131,7 @@ void _PyAST_Fini(PyInterpreterState *interp) + Py_CLEAR(state->Not_type); + Py_CLEAR(state->Or_singleton); + Py_CLEAR(state->Or_type); ++ Py_CLEAR(state->ParamSpec_type); + Py_CLEAR(state->Pass_type); + Py_CLEAR(state->Pow_singleton); + Py_CLEAR(state->Pow_type); +@@ -150,7 +151,10 @@ void _PyAST_Fini(PyInterpreterState *interp) + Py_CLEAR(state->TryStar_type); + Py_CLEAR(state->Try_type); + Py_CLEAR(state->Tuple_type); ++ Py_CLEAR(state->TypeAlias_type); + Py_CLEAR(state->TypeIgnore_type); ++ Py_CLEAR(state->TypeVarTuple_type); ++ Py_CLEAR(state->TypeVar_type); + Py_CLEAR(state->UAdd_singleton); + Py_CLEAR(state->UAdd_type); + Py_CLEAR(state->USub_singleton); +@@ -179,6 +183,7 @@ void _PyAST_Fini(PyInterpreterState *interp) + Py_CLEAR(state->bases); + Py_CLEAR(state->body); + Py_CLEAR(state->boolop_type); ++ Py_CLEAR(state->bound); + Py_CLEAR(state->cases); + Py_CLEAR(state->cause); + Py_CLEAR(state->cls); +@@ -256,6 +261,8 @@ void _PyAST_Fini(PyInterpreterState *interp) + Py_CLEAR(state->type_comment); + Py_CLEAR(state->type_ignore_type); + Py_CLEAR(state->type_ignores); ++ Py_CLEAR(state->typeparam_type); ++ Py_CLEAR(state->typeparams); + Py_CLEAR(state->unaryop_type); + Py_CLEAR(state->upper); + Py_CLEAR(state->value); +@@ -289,6 +296,7 @@ static int init_identifiers(struct ast_state *state) + if ((state->attr = PyUnicode_InternFromString("attr")) == NULL) return 0; + if ((state->bases = PyUnicode_InternFromString("bases")) == NULL) return 0; + if ((state->body = PyUnicode_InternFromString("body")) == NULL) return 0; ++ if ((state->bound = PyUnicode_InternFromString("bound")) == NULL) return 0; + if ((state->cases = PyUnicode_InternFromString("cases")) == NULL) return 0; + if ((state->cause = PyUnicode_InternFromString("cause")) == NULL) return 0; + if ((state->cls = PyUnicode_InternFromString("cls")) == NULL) return 0; +@@ -354,6 +362,7 @@ static int init_identifiers(struct ast_state *state) + if ((state->type = PyUnicode_InternFromString("type")) == NULL) return 0; + if ((state->type_comment = PyUnicode_InternFromString("type_comment")) == NULL) return 0; + if ((state->type_ignores = PyUnicode_InternFromString("type_ignores")) == NULL) return 0; ++ if ((state->typeparams = PyUnicode_InternFromString("typeparams")) == NULL) return 0; + if ((state->upper = PyUnicode_InternFromString("upper")) == NULL) return 0; + if ((state->value = PyUnicode_InternFromString("value")) == NULL) return 0; + if ((state->values = PyUnicode_InternFromString("values")) == NULL) return 0; +@@ -374,6 +383,7 @@ GENERATE_ASDL_SEQ_CONSTRUCTOR(withitem, withitem_ty) + GENERATE_ASDL_SEQ_CONSTRUCTOR(match_case, match_case_ty) + GENERATE_ASDL_SEQ_CONSTRUCTOR(pattern, pattern_ty) + GENERATE_ASDL_SEQ_CONSTRUCTOR(type_ignore, type_ignore_ty) ++GENERATE_ASDL_SEQ_CONSTRUCTOR(typeparam, typeparam_ty) + + static PyObject* ast2obj_mod(struct ast_state *state, void*); + static const char * const Module_fields[]={ +@@ -399,6 +409,7 @@ static const char * const stmt_attributes[] = { + static PyObject* ast2obj_stmt(struct ast_state *state, void*); + static const char * const FunctionDef_fields[]={ + "name", ++ "typeparams", + "args", + "body", + "decorator_list", +@@ -407,6 +418,7 @@ static const char * const FunctionDef_fields[]={ + }; + static const char * const AsyncFunctionDef_fields[]={ + "name", ++ "typeparams", + "args", + "body", + "decorator_list", +@@ -415,6 +427,7 @@ static const char * const AsyncFunctionDef_fields[]={ + }; + static const char * const ClassDef_fields[]={ + "name", ++ "typeparams", + "bases", + "keywords", + "body", +@@ -431,6 +444,11 @@ static const char * const Assign_fields[]={ + "value", + "type_comment", + }; ++static const char * const TypeAlias_fields[]={ ++ "name", ++ "typeparams", ++ "value", ++}; + static const char * const AugAssign_fields[]={ + "target", + "op", +@@ -757,6 +775,23 @@ static const char * const TypeIgnore_fields[]={ + "lineno", + "tag", + }; ++static const char * const typeparam_attributes[] = { ++ "lineno", ++ "col_offset", ++ "end_lineno", ++ "end_col_offset", ++}; ++static PyObject* ast2obj_typeparam(struct ast_state *state, void*); ++static const char * const TypeVar_fields[]={ ++ "name", ++ "bound", ++}; ++static const char * const ParamSpec_fields[]={ ++ "name", ++}; ++static const char * const TypeVarTuple_fields[]={ ++ "name", ++}; + + + +@@ -1134,12 +1169,13 @@ init_types(struct ast_state *state) + "FunctionType(expr* argtypes, expr returns)"); + if (!state->FunctionType_type) return 0; + state->stmt_type = make_type(state, "stmt", state->AST_type, NULL, 0, +- "stmt = FunctionDef(identifier name, arguments args, stmt* body, expr* decorator_list, expr? returns, string? type_comment)\n" +- " | AsyncFunctionDef(identifier name, arguments args, stmt* body, expr* decorator_list, expr? returns, string? type_comment)\n" +- " | ClassDef(identifier name, expr* bases, keyword* keywords, stmt* body, expr* decorator_list)\n" ++ "stmt = FunctionDef(identifier name, typeparam* typeparams, arguments args, stmt* body, expr* decorator_list, expr? returns, string? type_comment)\n" ++ " | AsyncFunctionDef(identifier name, typeparam* typeparams, arguments args, stmt* body, expr* decorator_list, expr? returns, string? type_comment)\n" ++ " | ClassDef(identifier name, typeparam* typeparams, expr* bases, keyword* keywords, stmt* body, expr* decorator_list)\n" + " | Return(expr? value)\n" + " | Delete(expr* targets)\n" + " | Assign(expr* targets, expr value, string? type_comment)\n" ++ " | TypeAlias(expr name, typeparam* typeparams, expr value)\n" + " | AugAssign(expr target, operator op, expr value)\n" + " | AnnAssign(expr target, expr annotation, expr? value, int simple)\n" + " | For(expr target, expr iter, stmt* body, stmt* orelse, string? type_comment)\n" +@@ -1169,8 +1205,8 @@ init_types(struct ast_state *state) + -1) + return 0; + state->FunctionDef_type = make_type(state, "FunctionDef", state->stmt_type, +- FunctionDef_fields, 6, +- "FunctionDef(identifier name, arguments args, stmt* body, expr* decorator_list, expr? returns, string? type_comment)"); ++ FunctionDef_fields, 7, ++ "FunctionDef(identifier name, typeparam* typeparams, arguments args, stmt* body, expr* decorator_list, expr? returns, string? type_comment)"); + if (!state->FunctionDef_type) return 0; + if (PyObject_SetAttr(state->FunctionDef_type, state->returns, Py_None) == + -1) +@@ -1180,8 +1216,8 @@ init_types(struct ast_state *state) + return 0; + state->AsyncFunctionDef_type = make_type(state, "AsyncFunctionDef", + state->stmt_type, +- AsyncFunctionDef_fields, 6, +- "AsyncFunctionDef(identifier name, arguments args, stmt* body, expr* decorator_list, expr? returns, string? type_comment)"); ++ AsyncFunctionDef_fields, 7, ++ "AsyncFunctionDef(identifier name, typeparam* typeparams, arguments args, stmt* body, expr* decorator_list, expr? returns, string? type_comment)"); + if (!state->AsyncFunctionDef_type) return 0; + if (PyObject_SetAttr(state->AsyncFunctionDef_type, state->returns, Py_None) + == -1) +@@ -1190,8 +1226,8 @@ init_types(struct ast_state *state) + Py_None) == -1) + return 0; + state->ClassDef_type = make_type(state, "ClassDef", state->stmt_type, +- ClassDef_fields, 5, +- "ClassDef(identifier name, expr* bases, keyword* keywords, stmt* body, expr* decorator_list)"); ++ ClassDef_fields, 6, ++ "ClassDef(identifier name, typeparam* typeparams, expr* bases, keyword* keywords, stmt* body, expr* decorator_list)"); + if (!state->ClassDef_type) return 0; + state->Return_type = make_type(state, "Return", state->stmt_type, + Return_fields, 1, +@@ -1210,6 +1246,10 @@ init_types(struct ast_state *state) + if (PyObject_SetAttr(state->Assign_type, state->type_comment, Py_None) == + -1) + return 0; ++ state->TypeAlias_type = make_type(state, "TypeAlias", state->stmt_type, ++ TypeAlias_fields, 3, ++ "TypeAlias(expr name, typeparam* typeparams, expr value)"); ++ if (!state->TypeAlias_type) return 0; + state->AugAssign_type = make_type(state, "AugAssign", state->stmt_type, + AugAssign_fields, 3, + "AugAssign(expr target, operator op, expr value)"); +@@ -1854,6 +1894,36 @@ init_types(struct ast_state *state) + TypeIgnore_fields, 2, + "TypeIgnore(int lineno, string tag)"); + if (!state->TypeIgnore_type) return 0; ++ state->typeparam_type = make_type(state, "typeparam", state->AST_type, ++ NULL, 0, ++ "typeparam = TypeVar(identifier name, expr? bound)\n" ++ " | ParamSpec(identifier name)\n" ++ " | TypeVarTuple(identifier name)"); ++ if (!state->typeparam_type) return 0; ++ if (!add_attributes(state, state->typeparam_type, typeparam_attributes, 4)) ++ return 0; ++ if (PyObject_SetAttr(state->typeparam_type, state->end_lineno, Py_None) == ++ -1) ++ return 0; ++ if (PyObject_SetAttr(state->typeparam_type, state->end_col_offset, Py_None) ++ == -1) ++ return 0; ++ state->TypeVar_type = make_type(state, "TypeVar", state->typeparam_type, ++ TypeVar_fields, 2, ++ "TypeVar(identifier name, expr? bound)"); ++ if (!state->TypeVar_type) return 0; ++ if (PyObject_SetAttr(state->TypeVar_type, state->bound, Py_None) == -1) ++ return 0; ++ state->ParamSpec_type = make_type(state, "ParamSpec", ++ state->typeparam_type, ParamSpec_fields, ++ 1, ++ "ParamSpec(identifier name)"); ++ if (!state->ParamSpec_type) return 0; ++ state->TypeVarTuple_type = make_type(state, "TypeVarTuple", ++ state->typeparam_type, ++ TypeVarTuple_fields, 1, ++ "TypeVarTuple(identifier name)"); ++ if (!state->TypeVarTuple_type) return 0; + + state->recursion_depth = 0; + state->recursion_limit = 0; +@@ -1897,6 +1967,8 @@ static int obj2ast_pattern(struct ast_state *state, PyObject* obj, pattern_ty* + out, PyArena* arena); + static int obj2ast_type_ignore(struct ast_state *state, PyObject* obj, + type_ignore_ty* out, PyArena* arena); ++static int obj2ast_typeparam(struct ast_state *state, PyObject* obj, ++ typeparam_ty* out, PyArena* arena); + + mod_ty + _PyAST_Module(asdl_stmt_seq * body, asdl_type_ignore_seq * type_ignores, +@@ -1960,10 +2032,11 @@ _PyAST_FunctionType(asdl_expr_seq * argtypes, expr_ty returns, PyArena *arena) + } + + stmt_ty +-_PyAST_FunctionDef(identifier name, arguments_ty args, asdl_stmt_seq * body, +- asdl_expr_seq * decorator_list, expr_ty returns, string +- type_comment, int lineno, int col_offset, int end_lineno, +- int end_col_offset, PyArena *arena) ++_PyAST_FunctionDef(identifier name, asdl_typeparam_seq * typeparams, ++ arguments_ty args, asdl_stmt_seq * body, asdl_expr_seq * ++ decorator_list, expr_ty returns, string type_comment, int ++ lineno, int col_offset, int end_lineno, int end_col_offset, ++ PyArena *arena) + { + stmt_ty p; + if (!name) { +@@ -1981,6 +2054,7 @@ _PyAST_FunctionDef(identifier name, arguments_ty args, asdl_stmt_seq * body, + return NULL; + p->kind = FunctionDef_kind; + p->v.FunctionDef.name = name; ++ p->v.FunctionDef.typeparams = typeparams; + p->v.FunctionDef.args = args; + p->v.FunctionDef.body = body; + p->v.FunctionDef.decorator_list = decorator_list; +@@ -1994,10 +2068,11 @@ _PyAST_FunctionDef(identifier name, arguments_ty args, asdl_stmt_seq * body, + } + + stmt_ty +-_PyAST_AsyncFunctionDef(identifier name, arguments_ty args, asdl_stmt_seq * +- body, asdl_expr_seq * decorator_list, expr_ty returns, +- string type_comment, int lineno, int col_offset, int +- end_lineno, int end_col_offset, PyArena *arena) ++_PyAST_AsyncFunctionDef(identifier name, asdl_typeparam_seq * typeparams, ++ arguments_ty args, asdl_stmt_seq * body, asdl_expr_seq ++ * decorator_list, expr_ty returns, string type_comment, ++ int lineno, int col_offset, int end_lineno, int ++ end_col_offset, PyArena *arena) + { + stmt_ty p; + if (!name) { +@@ -2015,6 +2090,7 @@ _PyAST_AsyncFunctionDef(identifier name, arguments_ty args, asdl_stmt_seq * + return NULL; + p->kind = AsyncFunctionDef_kind; + p->v.AsyncFunctionDef.name = name; ++ p->v.AsyncFunctionDef.typeparams = typeparams; + p->v.AsyncFunctionDef.args = args; + p->v.AsyncFunctionDef.body = body; + p->v.AsyncFunctionDef.decorator_list = decorator_list; +@@ -2028,10 +2104,10 @@ _PyAST_AsyncFunctionDef(identifier name, arguments_ty args, asdl_stmt_seq * + } + + stmt_ty +-_PyAST_ClassDef(identifier name, asdl_expr_seq * bases, asdl_keyword_seq * +- keywords, asdl_stmt_seq * body, asdl_expr_seq * decorator_list, +- int lineno, int col_offset, int end_lineno, int end_col_offset, +- PyArena *arena) ++_PyAST_ClassDef(identifier name, asdl_typeparam_seq * typeparams, asdl_expr_seq ++ * bases, asdl_keyword_seq * keywords, asdl_stmt_seq * body, ++ asdl_expr_seq * decorator_list, int lineno, int col_offset, int ++ end_lineno, int end_col_offset, PyArena *arena) + { + stmt_ty p; + if (!name) { +@@ -2044,6 +2120,7 @@ _PyAST_ClassDef(identifier name, asdl_expr_seq * bases, asdl_keyword_seq * + return NULL; + p->kind = ClassDef_kind; + p->v.ClassDef.name = name; ++ p->v.ClassDef.typeparams = typeparams; + p->v.ClassDef.bases = bases; + p->v.ClassDef.keywords = keywords; + p->v.ClassDef.body = body; +@@ -2114,6 +2191,36 @@ _PyAST_Assign(asdl_expr_seq * targets, expr_ty value, string type_comment, int + return p; + } + ++stmt_ty ++_PyAST_TypeAlias(expr_ty name, asdl_typeparam_seq * typeparams, expr_ty value, ++ int lineno, int col_offset, int end_lineno, int ++ end_col_offset, PyArena *arena) ++{ ++ stmt_ty p; ++ if (!name) { ++ PyErr_SetString(PyExc_ValueError, ++ "field 'name' is required for TypeAlias"); ++ return NULL; ++ } ++ if (!value) { ++ PyErr_SetString(PyExc_ValueError, ++ "field 'value' is required for TypeAlias"); ++ return NULL; ++ } ++ p = (stmt_ty)_PyArena_Malloc(arena, sizeof(*p)); ++ if (!p) ++ return NULL; ++ p->kind = TypeAlias_kind; ++ p->v.TypeAlias.name = name; ++ p->v.TypeAlias.typeparams = typeparams; ++ p->v.TypeAlias.value = value; ++ p->lineno = lineno; ++ p->col_offset = col_offset; ++ p->end_lineno = end_lineno; ++ p->end_col_offset = end_col_offset; ++ return p; ++} ++ + stmt_ty + _PyAST_AugAssign(expr_ty target, operator_ty op, expr_ty value, int lineno, int + col_offset, int end_lineno, int end_col_offset, PyArena *arena) +@@ -3606,6 +3713,73 @@ _PyAST_TypeIgnore(int lineno, string tag, PyArena *arena) + return p; + } + ++typeparam_ty ++_PyAST_TypeVar(identifier name, expr_ty bound, int lineno, int col_offset, int ++ end_lineno, int end_col_offset, PyArena *arena) ++{ ++ typeparam_ty p; ++ if (!name) { ++ PyErr_SetString(PyExc_ValueError, ++ "field 'name' is required for TypeVar"); ++ return NULL; ++ } ++ p = (typeparam_ty)_PyArena_Malloc(arena, sizeof(*p)); ++ if (!p) ++ return NULL; ++ p->kind = TypeVar_kind; ++ p->v.TypeVar.name = name; ++ p->v.TypeVar.bound = bound; ++ p->lineno = lineno; ++ p->col_offset = col_offset; ++ p->end_lineno = end_lineno; ++ p->end_col_offset = end_col_offset; ++ return p; ++} ++ ++typeparam_ty ++_PyAST_ParamSpec(identifier name, int lineno, int col_offset, int end_lineno, ++ int end_col_offset, PyArena *arena) ++{ ++ typeparam_ty p; ++ if (!name) { ++ PyErr_SetString(PyExc_ValueError, ++ "field 'name' is required for ParamSpec"); ++ return NULL; ++ } ++ p = (typeparam_ty)_PyArena_Malloc(arena, sizeof(*p)); ++ if (!p) ++ return NULL; ++ p->kind = ParamSpec_kind; ++ p->v.ParamSpec.name = name; ++ p->lineno = lineno; ++ p->col_offset = col_offset; ++ p->end_lineno = end_lineno; ++ p->end_col_offset = end_col_offset; ++ return p; ++} ++ ++typeparam_ty ++_PyAST_TypeVarTuple(identifier name, int lineno, int col_offset, int ++ end_lineno, int end_col_offset, PyArena *arena) ++{ ++ typeparam_ty p; ++ if (!name) { ++ PyErr_SetString(PyExc_ValueError, ++ "field 'name' is required for TypeVarTuple"); ++ return NULL; ++ } ++ p = (typeparam_ty)_PyArena_Malloc(arena, sizeof(*p)); ++ if (!p) ++ return NULL; ++ p->kind = TypeVarTuple_kind; ++ p->v.TypeVarTuple.name = name; ++ p->lineno = lineno; ++ p->col_offset = col_offset; ++ p->end_lineno = end_lineno; ++ p->end_col_offset = end_col_offset; ++ return p; ++} ++ + + PyObject* + ast2obj_mod(struct ast_state *state, void* _o) +@@ -3708,6 +3882,12 @@ ast2obj_stmt(struct ast_state *state, void* _o) + if (PyObject_SetAttr(result, state->name, value) == -1) + goto failed; + Py_DECREF(value); ++ value = ast2obj_list(state, (asdl_seq*)o->v.FunctionDef.typeparams, ++ ast2obj_typeparam); ++ if (!value) goto failed; ++ if (PyObject_SetAttr(result, state->typeparams, value) == -1) ++ goto failed; ++ Py_DECREF(value); + value = ast2obj_arguments(state, o->v.FunctionDef.args); + if (!value) goto failed; + if (PyObject_SetAttr(result, state->args, value) == -1) +@@ -3745,6 +3925,13 @@ ast2obj_stmt(struct ast_state *state, void* _o) + if (PyObject_SetAttr(result, state->name, value) == -1) + goto failed; + Py_DECREF(value); ++ value = ast2obj_list(state, ++ (asdl_seq*)o->v.AsyncFunctionDef.typeparams, ++ ast2obj_typeparam); ++ if (!value) goto failed; ++ if (PyObject_SetAttr(result, state->typeparams, value) == -1) ++ goto failed; ++ Py_DECREF(value); + value = ast2obj_arguments(state, o->v.AsyncFunctionDef.args); + if (!value) goto failed; + if (PyObject_SetAttr(result, state->args, value) == -1) +@@ -3783,6 +3970,12 @@ ast2obj_stmt(struct ast_state *state, void* _o) + if (PyObject_SetAttr(result, state->name, value) == -1) + goto failed; + Py_DECREF(value); ++ value = ast2obj_list(state, (asdl_seq*)o->v.ClassDef.typeparams, ++ ast2obj_typeparam); ++ if (!value) goto failed; ++ if (PyObject_SetAttr(result, state->typeparams, value) == -1) ++ goto failed; ++ Py_DECREF(value); + value = ast2obj_list(state, (asdl_seq*)o->v.ClassDef.bases, + ast2obj_expr); + if (!value) goto failed; +@@ -3850,6 +4043,27 @@ ast2obj_stmt(struct ast_state *state, void* _o) + goto failed; + Py_DECREF(value); + break; ++ case TypeAlias_kind: ++ tp = (PyTypeObject *)state->TypeAlias_type; ++ result = PyType_GenericNew(tp, NULL, NULL); ++ if (!result) goto failed; ++ value = ast2obj_expr(state, o->v.TypeAlias.name); ++ if (!value) goto failed; ++ if (PyObject_SetAttr(result, state->name, value) == -1) ++ goto failed; ++ Py_DECREF(value); ++ value = ast2obj_list(state, (asdl_seq*)o->v.TypeAlias.typeparams, ++ ast2obj_typeparam); ++ if (!value) goto failed; ++ if (PyObject_SetAttr(result, state->typeparams, value) == -1) ++ goto failed; ++ Py_DECREF(value); ++ value = ast2obj_expr(state, o->v.TypeAlias.value); ++ if (!value) goto failed; ++ if (PyObject_SetAttr(result, state->value, value) == -1) ++ goto failed; ++ Py_DECREF(value); ++ break; + case AugAssign_kind: + tp = (PyTypeObject *)state->AugAssign_type; + result = PyType_GenericNew(tp, NULL, NULL); +@@ -5441,6 +5655,85 @@ failed: + return NULL; + } + ++PyObject* ++ast2obj_typeparam(struct ast_state *state, void* _o) ++{ ++ typeparam_ty o = (typeparam_ty)_o; ++ PyObject *result = NULL, *value = NULL; ++ PyTypeObject *tp; ++ if (!o) { ++ Py_RETURN_NONE; ++ } ++ if (++state->recursion_depth > state->recursion_limit) { ++ PyErr_SetString(PyExc_RecursionError, ++ "maximum recursion depth exceeded during ast construction"); ++ return 0; ++ } ++ switch (o->kind) { ++ case TypeVar_kind: ++ tp = (PyTypeObject *)state->TypeVar_type; ++ result = PyType_GenericNew(tp, NULL, NULL); ++ if (!result) goto failed; ++ value = ast2obj_identifier(state, o->v.TypeVar.name); ++ if (!value) goto failed; ++ if (PyObject_SetAttr(result, state->name, value) == -1) ++ goto failed; ++ Py_DECREF(value); ++ value = ast2obj_expr(state, o->v.TypeVar.bound); ++ if (!value) goto failed; ++ if (PyObject_SetAttr(result, state->bound, value) == -1) ++ goto failed; ++ Py_DECREF(value); ++ break; ++ case ParamSpec_kind: ++ tp = (PyTypeObject *)state->ParamSpec_type; ++ result = PyType_GenericNew(tp, NULL, NULL); ++ if (!result) goto failed; ++ value = ast2obj_identifier(state, o->v.ParamSpec.name); ++ if (!value) goto failed; ++ if (PyObject_SetAttr(result, state->name, value) == -1) ++ goto failed; ++ Py_DECREF(value); ++ break; ++ case TypeVarTuple_kind: ++ tp = (PyTypeObject *)state->TypeVarTuple_type; ++ result = PyType_GenericNew(tp, NULL, NULL); ++ if (!result) goto failed; ++ value = ast2obj_identifier(state, o->v.TypeVarTuple.name); ++ if (!value) goto failed; ++ if (PyObject_SetAttr(result, state->name, value) == -1) ++ goto failed; ++ Py_DECREF(value); ++ break; ++ } ++ value = ast2obj_int(state, o->lineno); ++ if (!value) goto failed; ++ if (PyObject_SetAttr(result, state->lineno, value) < 0) ++ goto failed; ++ Py_DECREF(value); ++ value = ast2obj_int(state, o->col_offset); ++ if (!value) goto failed; ++ if (PyObject_SetAttr(result, state->col_offset, value) < 0) ++ goto failed; ++ Py_DECREF(value); ++ value = ast2obj_int(state, o->end_lineno); ++ if (!value) goto failed; ++ if (PyObject_SetAttr(result, state->end_lineno, value) < 0) ++ goto failed; ++ Py_DECREF(value); ++ value = ast2obj_int(state, o->end_col_offset); ++ if (!value) goto failed; ++ if (PyObject_SetAttr(result, state->end_col_offset, value) < 0) ++ goto failed; ++ Py_DECREF(value); ++ state->recursion_depth--; ++ return result; ++failed: ++ Py_XDECREF(value); ++ Py_XDECREF(result); ++ return NULL; ++} ++ + + int + obj2ast_mod(struct ast_state *state, PyObject* obj, mod_ty* out, PyArena* arena) +@@ -5781,6 +6074,7 @@ obj2ast_stmt(struct ast_state *state, PyObject* obj, stmt_ty* out, PyArena* + } + if (isinstance) { + identifier name; ++ asdl_typeparam_seq* typeparams; + arguments_ty args; + asdl_stmt_seq* body; + asdl_expr_seq* decorator_list; +@@ -5804,6 +6098,42 @@ obj2ast_stmt(struct ast_state *state, PyObject* obj, stmt_ty* out, PyArena* + if (res != 0) goto failed; + Py_CLEAR(tmp); + } ++ if (_PyObject_LookupAttr(obj, state->typeparams, &tmp) < 0) { ++ return 1; ++ } ++ if (tmp == NULL) { ++ PyErr_SetString(PyExc_TypeError, "required field \"typeparams\" missing from FunctionDef"); ++ return 1; ++ } ++ else { ++ int res; ++ Py_ssize_t len; ++ Py_ssize_t i; ++ if (!PyList_Check(tmp)) { ++ PyErr_Format(PyExc_TypeError, "FunctionDef field \"typeparams\" must be a list, not a %.200s", _PyType_Name(Py_TYPE(tmp))); ++ goto failed; ++ } ++ len = PyList_GET_SIZE(tmp); ++ typeparams = _Py_asdl_typeparam_seq_new(len, arena); ++ if (typeparams == NULL) goto failed; ++ for (i = 0; i < len; i++) { ++ typeparam_ty val; ++ PyObject *tmp2 = Py_NewRef(PyList_GET_ITEM(tmp, i)); ++ if (_Py_EnterRecursiveCall(" while traversing 'FunctionDef' node")) { ++ goto failed; ++ } ++ res = obj2ast_typeparam(state, tmp2, &val, arena); ++ _Py_LeaveRecursiveCall(); ++ Py_DECREF(tmp2); ++ if (res != 0) goto failed; ++ if (len != PyList_GET_SIZE(tmp)) { ++ PyErr_SetString(PyExc_RuntimeError, "FunctionDef field \"typeparams\" changed size during iteration"); ++ goto failed; ++ } ++ asdl_seq_SET(typeparams, i, val); ++ } ++ Py_CLEAR(tmp); ++ } + if (_PyObject_LookupAttr(obj, state->args, &tmp) < 0) { + return 1; + } +@@ -5927,9 +6257,9 @@ obj2ast_stmt(struct ast_state *state, PyObject* obj, stmt_ty* out, PyArena* + if (res != 0) goto failed; + Py_CLEAR(tmp); + } +- *out = _PyAST_FunctionDef(name, args, body, decorator_list, returns, +- type_comment, lineno, col_offset, end_lineno, +- end_col_offset, arena); ++ *out = _PyAST_FunctionDef(name, typeparams, args, body, decorator_list, ++ returns, type_comment, lineno, col_offset, ++ end_lineno, end_col_offset, arena); + if (*out == NULL) goto failed; + return 0; + } +@@ -5940,6 +6270,7 @@ obj2ast_stmt(struct ast_state *state, PyObject* obj, stmt_ty* out, PyArena* + } + if (isinstance) { + identifier name; ++ asdl_typeparam_seq* typeparams; + arguments_ty args; + asdl_stmt_seq* body; + asdl_expr_seq* decorator_list; +@@ -5963,6 +6294,42 @@ obj2ast_stmt(struct ast_state *state, PyObject* obj, stmt_ty* out, PyArena* + if (res != 0) goto failed; + Py_CLEAR(tmp); + } ++ if (_PyObject_LookupAttr(obj, state->typeparams, &tmp) < 0) { ++ return 1; ++ } ++ if (tmp == NULL) { ++ PyErr_SetString(PyExc_TypeError, "required field \"typeparams\" missing from AsyncFunctionDef"); ++ return 1; ++ } ++ else { ++ int res; ++ Py_ssize_t len; ++ Py_ssize_t i; ++ if (!PyList_Check(tmp)) { ++ PyErr_Format(PyExc_TypeError, "AsyncFunctionDef field \"typeparams\" must be a list, not a %.200s", _PyType_Name(Py_TYPE(tmp))); ++ goto failed; ++ } ++ len = PyList_GET_SIZE(tmp); ++ typeparams = _Py_asdl_typeparam_seq_new(len, arena); ++ if (typeparams == NULL) goto failed; ++ for (i = 0; i < len; i++) { ++ typeparam_ty val; ++ PyObject *tmp2 = Py_NewRef(PyList_GET_ITEM(tmp, i)); ++ if (_Py_EnterRecursiveCall(" while traversing 'AsyncFunctionDef' node")) { ++ goto failed; ++ } ++ res = obj2ast_typeparam(state, tmp2, &val, arena); ++ _Py_LeaveRecursiveCall(); ++ Py_DECREF(tmp2); ++ if (res != 0) goto failed; ++ if (len != PyList_GET_SIZE(tmp)) { ++ PyErr_SetString(PyExc_RuntimeError, "AsyncFunctionDef field \"typeparams\" changed size during iteration"); ++ goto failed; ++ } ++ asdl_seq_SET(typeparams, i, val); ++ } ++ Py_CLEAR(tmp); ++ } + if (_PyObject_LookupAttr(obj, state->args, &tmp) < 0) { + return 1; + } +@@ -6086,10 +6453,10 @@ obj2ast_stmt(struct ast_state *state, PyObject* obj, stmt_ty* out, PyArena* + if (res != 0) goto failed; + Py_CLEAR(tmp); + } +- *out = _PyAST_AsyncFunctionDef(name, args, body, decorator_list, +- returns, type_comment, lineno, +- col_offset, end_lineno, end_col_offset, +- arena); ++ *out = _PyAST_AsyncFunctionDef(name, typeparams, args, body, ++ decorator_list, returns, type_comment, ++ lineno, col_offset, end_lineno, ++ end_col_offset, arena); + if (*out == NULL) goto failed; + return 0; + } +@@ -6100,6 +6467,7 @@ obj2ast_stmt(struct ast_state *state, PyObject* obj, stmt_ty* out, PyArena* + } + if (isinstance) { + identifier name; ++ asdl_typeparam_seq* typeparams; + asdl_expr_seq* bases; + asdl_keyword_seq* keywords; + asdl_stmt_seq* body; +@@ -6122,6 +6490,42 @@ obj2ast_stmt(struct ast_state *state, PyObject* obj, stmt_ty* out, PyArena* + if (res != 0) goto failed; + Py_CLEAR(tmp); + } ++ if (_PyObject_LookupAttr(obj, state->typeparams, &tmp) < 0) { ++ return 1; ++ } ++ if (tmp == NULL) { ++ PyErr_SetString(PyExc_TypeError, "required field \"typeparams\" missing from ClassDef"); ++ return 1; ++ } ++ else { ++ int res; ++ Py_ssize_t len; ++ Py_ssize_t i; ++ if (!PyList_Check(tmp)) { ++ PyErr_Format(PyExc_TypeError, "ClassDef field \"typeparams\" must be a list, not a %.200s", _PyType_Name(Py_TYPE(tmp))); ++ goto failed; ++ } ++ len = PyList_GET_SIZE(tmp); ++ typeparams = _Py_asdl_typeparam_seq_new(len, arena); ++ if (typeparams == NULL) goto failed; ++ for (i = 0; i < len; i++) { ++ typeparam_ty val; ++ PyObject *tmp2 = Py_NewRef(PyList_GET_ITEM(tmp, i)); ++ if (_Py_EnterRecursiveCall(" while traversing 'ClassDef' node")) { ++ goto failed; ++ } ++ res = obj2ast_typeparam(state, tmp2, &val, arena); ++ _Py_LeaveRecursiveCall(); ++ Py_DECREF(tmp2); ++ if (res != 0) goto failed; ++ if (len != PyList_GET_SIZE(tmp)) { ++ PyErr_SetString(PyExc_RuntimeError, "ClassDef field \"typeparams\" changed size during iteration"); ++ goto failed; ++ } ++ asdl_seq_SET(typeparams, i, val); ++ } ++ Py_CLEAR(tmp); ++ } + if (_PyObject_LookupAttr(obj, state->bases, &tmp) < 0) { + return 1; + } +@@ -6266,9 +6670,9 @@ obj2ast_stmt(struct ast_state *state, PyObject* obj, stmt_ty* out, PyArena* + } + Py_CLEAR(tmp); + } +- *out = _PyAST_ClassDef(name, bases, keywords, body, decorator_list, +- lineno, col_offset, end_lineno, end_col_offset, +- arena); ++ *out = _PyAST_ClassDef(name, typeparams, bases, keywords, body, ++ decorator_list, lineno, col_offset, end_lineno, ++ end_col_offset, arena); + if (*out == NULL) goto failed; + return 0; + } +@@ -6436,6 +6840,91 @@ obj2ast_stmt(struct ast_state *state, PyObject* obj, stmt_ty* out, PyArena* + if (*out == NULL) goto failed; + return 0; + } ++ tp = state->TypeAlias_type; ++ isinstance = PyObject_IsInstance(obj, tp); ++ if (isinstance == -1) { ++ return 1; ++ } ++ if (isinstance) { ++ expr_ty name; ++ asdl_typeparam_seq* typeparams; ++ expr_ty value; ++ ++ if (_PyObject_LookupAttr(obj, state->name, &tmp) < 0) { ++ return 1; ++ } ++ if (tmp == NULL) { ++ PyErr_SetString(PyExc_TypeError, "required field \"name\" missing from TypeAlias"); ++ return 1; ++ } ++ else { ++ int res; ++ if (_Py_EnterRecursiveCall(" while traversing 'TypeAlias' node")) { ++ goto failed; ++ } ++ res = obj2ast_expr(state, tmp, &name, arena); ++ _Py_LeaveRecursiveCall(); ++ if (res != 0) goto failed; ++ Py_CLEAR(tmp); ++ } ++ if (_PyObject_LookupAttr(obj, state->typeparams, &tmp) < 0) { ++ return 1; ++ } ++ if (tmp == NULL) { ++ PyErr_SetString(PyExc_TypeError, "required field \"typeparams\" missing from TypeAlias"); ++ return 1; ++ } ++ else { ++ int res; ++ Py_ssize_t len; ++ Py_ssize_t i; ++ if (!PyList_Check(tmp)) { ++ PyErr_Format(PyExc_TypeError, "TypeAlias field \"typeparams\" must be a list, not a %.200s", _PyType_Name(Py_TYPE(tmp))); ++ goto failed; ++ } ++ len = PyList_GET_SIZE(tmp); ++ typeparams = _Py_asdl_typeparam_seq_new(len, arena); ++ if (typeparams == NULL) goto failed; ++ for (i = 0; i < len; i++) { ++ typeparam_ty val; ++ PyObject *tmp2 = Py_NewRef(PyList_GET_ITEM(tmp, i)); ++ if (_Py_EnterRecursiveCall(" while traversing 'TypeAlias' node")) { ++ goto failed; ++ } ++ res = obj2ast_typeparam(state, tmp2, &val, arena); ++ _Py_LeaveRecursiveCall(); ++ Py_DECREF(tmp2); ++ if (res != 0) goto failed; ++ if (len != PyList_GET_SIZE(tmp)) { ++ PyErr_SetString(PyExc_RuntimeError, "TypeAlias field \"typeparams\" changed size during iteration"); ++ goto failed; ++ } ++ asdl_seq_SET(typeparams, i, val); ++ } ++ Py_CLEAR(tmp); ++ } ++ if (_PyObject_LookupAttr(obj, state->value, &tmp) < 0) { ++ return 1; ++ } ++ if (tmp == NULL) { ++ PyErr_SetString(PyExc_TypeError, "required field \"value\" missing from TypeAlias"); ++ return 1; ++ } ++ else { ++ int res; ++ if (_Py_EnterRecursiveCall(" while traversing 'TypeAlias' node")) { ++ goto failed; ++ } ++ res = obj2ast_expr(state, tmp, &value, arena); ++ _Py_LeaveRecursiveCall(); ++ if (res != 0) goto failed; ++ Py_CLEAR(tmp); ++ } ++ *out = _PyAST_TypeAlias(name, typeparams, value, lineno, col_offset, ++ end_lineno, end_col_offset, arena); ++ if (*out == NULL) goto failed; ++ return 0; ++ } + tp = state->AugAssign_type; + isinstance = PyObject_IsInstance(obj, tp); + if (isinstance == -1) { +@@ -11803,6 +12292,206 @@ obj2ast_type_ignore(struct ast_state *state, PyObject* obj, type_ignore_ty* + return 1; + } + ++int ++obj2ast_typeparam(struct ast_state *state, PyObject* obj, typeparam_ty* out, ++ PyArena* arena) ++{ ++ int isinstance; ++ ++ PyObject *tmp = NULL; ++ PyObject *tp; ++ int lineno; ++ int col_offset; ++ int end_lineno; ++ int end_col_offset; ++ ++ if (obj == Py_None) { ++ *out = NULL; ++ return 0; ++ } ++ if (_PyObject_LookupAttr(obj, state->lineno, &tmp) < 0) { ++ return 1; ++ } ++ if (tmp == NULL) { ++ PyErr_SetString(PyExc_TypeError, "required field \"lineno\" missing from typeparam"); ++ return 1; ++ } ++ else { ++ int res; ++ if (_Py_EnterRecursiveCall(" while traversing 'typeparam' node")) { ++ goto failed; ++ } ++ res = obj2ast_int(state, tmp, &lineno, arena); ++ _Py_LeaveRecursiveCall(); ++ if (res != 0) goto failed; ++ Py_CLEAR(tmp); ++ } ++ if (_PyObject_LookupAttr(obj, state->col_offset, &tmp) < 0) { ++ return 1; ++ } ++ if (tmp == NULL) { ++ PyErr_SetString(PyExc_TypeError, "required field \"col_offset\" missing from typeparam"); ++ return 1; ++ } ++ else { ++ int res; ++ if (_Py_EnterRecursiveCall(" while traversing 'typeparam' node")) { ++ goto failed; ++ } ++ res = obj2ast_int(state, tmp, &col_offset, arena); ++ _Py_LeaveRecursiveCall(); ++ if (res != 0) goto failed; ++ Py_CLEAR(tmp); ++ } ++ if (_PyObject_LookupAttr(obj, state->end_lineno, &tmp) < 0) { ++ return 1; ++ } ++ if (tmp == NULL || tmp == Py_None) { ++ Py_CLEAR(tmp); ++ end_lineno = lineno; ++ } ++ else { ++ int res; ++ if (_Py_EnterRecursiveCall(" while traversing 'typeparam' node")) { ++ goto failed; ++ } ++ res = obj2ast_int(state, tmp, &end_lineno, arena); ++ _Py_LeaveRecursiveCall(); ++ if (res != 0) goto failed; ++ Py_CLEAR(tmp); ++ } ++ if (_PyObject_LookupAttr(obj, state->end_col_offset, &tmp) < 0) { ++ return 1; ++ } ++ if (tmp == NULL || tmp == Py_None) { ++ Py_CLEAR(tmp); ++ end_col_offset = col_offset; ++ } ++ else { ++ int res; ++ if (_Py_EnterRecursiveCall(" while traversing 'typeparam' node")) { ++ goto failed; ++ } ++ res = obj2ast_int(state, tmp, &end_col_offset, arena); ++ _Py_LeaveRecursiveCall(); ++ if (res != 0) goto failed; ++ Py_CLEAR(tmp); ++ } ++ tp = state->TypeVar_type; ++ isinstance = PyObject_IsInstance(obj, tp); ++ if (isinstance == -1) { ++ return 1; ++ } ++ if (isinstance) { ++ identifier name; ++ expr_ty bound; ++ ++ if (_PyObject_LookupAttr(obj, state->name, &tmp) < 0) { ++ return 1; ++ } ++ if (tmp == NULL) { ++ PyErr_SetString(PyExc_TypeError, "required field \"name\" missing from TypeVar"); ++ return 1; ++ } ++ else { ++ int res; ++ if (_Py_EnterRecursiveCall(" while traversing 'TypeVar' node")) { ++ goto failed; ++ } ++ res = obj2ast_identifier(state, tmp, &name, arena); ++ _Py_LeaveRecursiveCall(); ++ if (res != 0) goto failed; ++ Py_CLEAR(tmp); ++ } ++ if (_PyObject_LookupAttr(obj, state->bound, &tmp) < 0) { ++ return 1; ++ } ++ if (tmp == NULL || tmp == Py_None) { ++ Py_CLEAR(tmp); ++ bound = NULL; ++ } ++ else { ++ int res; ++ if (_Py_EnterRecursiveCall(" while traversing 'TypeVar' node")) { ++ goto failed; ++ } ++ res = obj2ast_expr(state, tmp, &bound, arena); ++ _Py_LeaveRecursiveCall(); ++ if (res != 0) goto failed; ++ Py_CLEAR(tmp); ++ } ++ *out = _PyAST_TypeVar(name, bound, lineno, col_offset, end_lineno, ++ end_col_offset, arena); ++ if (*out == NULL) goto failed; ++ return 0; ++ } ++ tp = state->ParamSpec_type; ++ isinstance = PyObject_IsInstance(obj, tp); ++ if (isinstance == -1) { ++ return 1; ++ } ++ if (isinstance) { ++ identifier name; ++ ++ if (_PyObject_LookupAttr(obj, state->name, &tmp) < 0) { ++ return 1; ++ } ++ if (tmp == NULL) { ++ PyErr_SetString(PyExc_TypeError, "required field \"name\" missing from ParamSpec"); ++ return 1; ++ } ++ else { ++ int res; ++ if (_Py_EnterRecursiveCall(" while traversing 'ParamSpec' node")) { ++ goto failed; ++ } ++ res = obj2ast_identifier(state, tmp, &name, arena); ++ _Py_LeaveRecursiveCall(); ++ if (res != 0) goto failed; ++ Py_CLEAR(tmp); ++ } ++ *out = _PyAST_ParamSpec(name, lineno, col_offset, end_lineno, ++ end_col_offset, arena); ++ if (*out == NULL) goto failed; ++ return 0; ++ } ++ tp = state->TypeVarTuple_type; ++ isinstance = PyObject_IsInstance(obj, tp); ++ if (isinstance == -1) { ++ return 1; ++ } ++ if (isinstance) { ++ identifier name; ++ ++ if (_PyObject_LookupAttr(obj, state->name, &tmp) < 0) { ++ return 1; ++ } ++ if (tmp == NULL) { ++ PyErr_SetString(PyExc_TypeError, "required field \"name\" missing from TypeVarTuple"); ++ return 1; ++ } ++ else { ++ int res; ++ if (_Py_EnterRecursiveCall(" while traversing 'TypeVarTuple' node")) { ++ goto failed; ++ } ++ res = obj2ast_identifier(state, tmp, &name, arena); ++ _Py_LeaveRecursiveCall(); ++ if (res != 0) goto failed; ++ Py_CLEAR(tmp); ++ } ++ *out = _PyAST_TypeVarTuple(name, lineno, col_offset, end_lineno, ++ end_col_offset, arena); ++ if (*out == NULL) goto failed; ++ return 0; ++ } ++ ++ PyErr_Format(PyExc_TypeError, "expected some sort of typeparam, but got %R", obj); ++ failed: ++ Py_XDECREF(tmp); ++ return 1; ++} ++ + + static int + astmodule_exec(PyObject *m) +@@ -11861,6 +12550,9 @@ astmodule_exec(PyObject *m) + if (PyModule_AddObjectRef(m, "Assign", state->Assign_type) < 0) { + return -1; + } ++ if (PyModule_AddObjectRef(m, "TypeAlias", state->TypeAlias_type) < 0) { ++ return -1; ++ } + if (PyModule_AddObjectRef(m, "AugAssign", state->AugAssign_type) < 0) { + return -1; + } +@@ -12188,6 +12880,19 @@ astmodule_exec(PyObject *m) + if (PyModule_AddObjectRef(m, "TypeIgnore", state->TypeIgnore_type) < 0) { + return -1; + } ++ if (PyModule_AddObjectRef(m, "typeparam", state->typeparam_type) < 0) { ++ return -1; ++ } ++ if (PyModule_AddObjectRef(m, "TypeVar", state->TypeVar_type) < 0) { ++ return -1; ++ } ++ if (PyModule_AddObjectRef(m, "ParamSpec", state->ParamSpec_type) < 0) { ++ return -1; ++ } ++ if (PyModule_AddObjectRef(m, "TypeVarTuple", state->TypeVarTuple_type) < 0) ++ { ++ return -1; ++ } + return 0; + } + +diff --git a/Python/ast.c b/Python/ast.c +index f079e64bbd..0844f2afa0 100644 +--- a/Python/ast.c ++++ b/Python/ast.c +@@ -17,10 +17,12 @@ struct validator { + static int validate_stmts(struct validator *, asdl_stmt_seq *); + static int validate_exprs(struct validator *, asdl_expr_seq *, expr_context_ty, int); + static int validate_patterns(struct validator *, asdl_pattern_seq *, int); ++static int validate_typeparams(struct validator *, asdl_typeparam_seq *); + static int _validate_nonempty_seq(asdl_seq *, const char *, const char *); + static int validate_stmt(struct validator *, stmt_ty); + static int validate_expr(struct validator *, expr_ty, expr_context_ty); + static int validate_pattern(struct validator *, pattern_ty, int); ++static int validate_typeparam(struct validator *, typeparam_ty); + + #define VALIDATE_POSITIONS(node) \ + if (node->lineno > node->end_lineno) { \ +@@ -726,6 +728,7 @@ validate_stmt(struct validator *state, stmt_ty stmt) + switch (stmt->kind) { + case FunctionDef_kind: + ret = validate_body(state, stmt->v.FunctionDef.body, "FunctionDef") && ++ validate_typeparams(state, stmt->v.FunctionDef.typeparams) && + validate_arguments(state, stmt->v.FunctionDef.args) && + validate_exprs(state, stmt->v.FunctionDef.decorator_list, Load, 0) && + (!stmt->v.FunctionDef.returns || +@@ -733,6 +736,7 @@ validate_stmt(struct validator *state, stmt_ty stmt) + break; + case ClassDef_kind: + ret = validate_body(state, stmt->v.ClassDef.body, "ClassDef") && ++ validate_typeparams(state, stmt->v.ClassDef.typeparams) && + validate_exprs(state, stmt->v.ClassDef.bases, Load, 0) && + validate_keywords(state, stmt->v.ClassDef.keywords) && + validate_exprs(state, stmt->v.ClassDef.decorator_list, Load, 0); +@@ -763,6 +767,11 @@ validate_stmt(struct validator *state, stmt_ty stmt) + validate_expr(state, stmt->v.AnnAssign.value, Load)) && + validate_expr(state, stmt->v.AnnAssign.annotation, Load); + break; ++ case TypeAlias_kind: ++ ret = validate_expr(state, stmt->v.TypeAlias.name, Store) && ++ validate_typeparams(state, stmt->v.TypeAlias.typeparams) && ++ validate_expr(state, stmt->v.TypeAlias.value, Load); ++ break; + case For_kind: + ret = validate_expr(state, stmt->v.For.target, Store) && + validate_expr(state, stmt->v.For.iter, Load) && +@@ -910,6 +919,7 @@ validate_stmt(struct validator *state, stmt_ty stmt) + break; + case AsyncFunctionDef_kind: + ret = validate_body(state, stmt->v.AsyncFunctionDef.body, "AsyncFunctionDef") && ++ validate_typeparams(state, stmt->v.AsyncFunctionDef.typeparams) && + validate_arguments(state, stmt->v.AsyncFunctionDef.args) && + validate_exprs(state, stmt->v.AsyncFunctionDef.decorator_list, Load, 0) && + (!stmt->v.AsyncFunctionDef.returns || +@@ -982,6 +992,41 @@ validate_patterns(struct validator *state, asdl_pattern_seq *patterns, int star_ + return 1; + } + ++static int ++validate_typeparam(struct validator *state, typeparam_ty tp) ++{ ++ VALIDATE_POSITIONS(tp); ++ int ret = -1; ++ switch (tp->kind) { ++ case TypeVar_kind: ++ ret = validate_name(tp->v.TypeVar.name) && ++ (!tp->v.TypeVar.bound || ++ validate_expr(state, tp->v.TypeVar.bound, Load)); ++ break; ++ case ParamSpec_kind: ++ ret = validate_name(tp->v.ParamSpec.name); ++ break; ++ case TypeVarTuple_kind: ++ ret = validate_name(tp->v.TypeVarTuple.name); ++ break; ++ } ++ return ret; ++} ++ ++static int ++validate_typeparams(struct validator *state, asdl_typeparam_seq *tps) ++{ ++ Py_ssize_t i; ++ for (i = 0; i < asdl_seq_LEN(tps); i++) { ++ typeparam_ty tp = asdl_seq_GET(tps, i); ++ if (tp) { ++ if (!validate_typeparam(state, tp)) ++ return 0; ++ } ++ } ++ return 1; ++} ++ + + /* See comments in symtable.c. */ + #define COMPILER_STACK_FRAME_SCALE 3 +diff --git a/Python/ast_opt.c b/Python/ast_opt.c +index 3883ec9e21..c5b3e07546 100644 +--- a/Python/ast_opt.c ++++ b/Python/ast_opt.c +@@ -642,6 +642,7 @@ static int astfold_withitem(withitem_ty node_, PyArena *ctx_, _PyASTOptimizeStat + static int astfold_excepthandler(excepthandler_ty node_, PyArena *ctx_, _PyASTOptimizeState *state); + static int astfold_match_case(match_case_ty node_, PyArena *ctx_, _PyASTOptimizeState *state); + static int astfold_pattern(pattern_ty node_, PyArena *ctx_, _PyASTOptimizeState *state); ++static int astfold_typeparam(typeparam_ty node_, PyArena *ctx_, _PyASTOptimizeState *state); + + #define CALL(FUNC, TYPE, ARG) \ + if (!FUNC((ARG), ctx_, state)) \ +@@ -880,6 +881,7 @@ astfold_stmt(stmt_ty node_, PyArena *ctx_, _PyASTOptimizeState *state) + } + switch (node_->kind) { + case FunctionDef_kind: ++ CALL_SEQ(astfold_typeparam, typeparam, node_->v.FunctionDef.typeparams); + CALL(astfold_arguments, arguments_ty, node_->v.FunctionDef.args); + CALL(astfold_body, asdl_seq, node_->v.FunctionDef.body); + CALL_SEQ(astfold_expr, expr, node_->v.FunctionDef.decorator_list); +@@ -888,6 +890,7 @@ astfold_stmt(stmt_ty node_, PyArena *ctx_, _PyASTOptimizeState *state) + } + break; + case AsyncFunctionDef_kind: ++ CALL_SEQ(astfold_typeparam, typeparam, node_->v.AsyncFunctionDef.typeparams); + CALL(astfold_arguments, arguments_ty, node_->v.AsyncFunctionDef.args); + CALL(astfold_body, asdl_seq, node_->v.AsyncFunctionDef.body); + CALL_SEQ(astfold_expr, expr, node_->v.AsyncFunctionDef.decorator_list); +@@ -896,6 +899,7 @@ astfold_stmt(stmt_ty node_, PyArena *ctx_, _PyASTOptimizeState *state) + } + break; + case ClassDef_kind: ++ CALL_SEQ(astfold_typeparam, typeparam, node_->v.ClassDef.typeparams); + CALL_SEQ(astfold_expr, expr, node_->v.ClassDef.bases); + CALL_SEQ(astfold_keyword, keyword, node_->v.ClassDef.keywords); + CALL(astfold_body, asdl_seq, node_->v.ClassDef.body); +@@ -922,6 +926,11 @@ astfold_stmt(stmt_ty node_, PyArena *ctx_, _PyASTOptimizeState *state) + } + CALL_OPT(astfold_expr, expr_ty, node_->v.AnnAssign.value); + break; ++ case TypeAlias_kind: ++ CALL(astfold_expr, expr_ty, node_->v.TypeAlias.name); ++ CALL_SEQ(astfold_typeparam, typeparam, node_->v.TypeAlias.typeparams); ++ CALL(astfold_expr, expr_ty, node_->v.TypeAlias.value); ++ break; + case For_kind: + CALL(astfold_expr, expr_ty, node_->v.For.target); + CALL(astfold_expr, expr_ty, node_->v.For.iter); +@@ -1074,6 +1083,21 @@ astfold_match_case(match_case_ty node_, PyArena *ctx_, _PyASTOptimizeState *stat + return 1; + } + ++static int ++astfold_typeparam(typeparam_ty node_, PyArena *ctx_, _PyASTOptimizeState *state) ++{ ++ switch (node_->kind) { ++ case TypeVar_kind: ++ CALL_OPT(astfold_expr, expr_ty, node_->v.TypeVar.bound); ++ break; ++ case ParamSpec_kind: ++ break; ++ case TypeVarTuple_kind: ++ break; ++ } ++ return 1; ++} ++ + #undef CALL + #undef CALL_OPT + #undef CALL_SEQ +diff --git a/Python/bytecodes.c b/Python/bytecodes.c +index d84a078f11..1b8820f94d 100644 +--- a/Python/bytecodes.c ++++ b/Python/bytecodes.c +@@ -56,7 +56,7 @@ static PyObject *value, *value1, *value2, *left, *right, *res, *sum, *prod, *sub + static PyObject *container, *start, *stop, *v, *lhs, *rhs, *res2; + static PyObject *list, *tuple, *dict, *owner, *set, *str, *tup, *map, *keys; + static PyObject *exit_func, *lasti, *val, *retval, *obj, *iter; +-static PyObject *aiter, *awaitable, *iterable, *w, *exc_value, *bc; ++static PyObject *aiter, *awaitable, *iterable, *w, *exc_value, *bc, *locals; + static PyObject *orig, *excs, *update, *b, *fromlist, *level, *from; + static PyObject **pieces, **values; + static size_t jump; +@@ -125,6 +125,7 @@ dummy_func( + PyObject *subject; + PyObject *top; + PyObject *type; ++ PyObject *typevars; + int values_or_none; + + switch (opcode) { +@@ -1002,6 +1003,7 @@ dummy_func( + } + } + ++ + inst(STORE_NAME, (v -- )) { + PyObject *name = GETITEM(frame->f_code->co_names, oparg); + PyObject *ns = LOCALS(); +@@ -1158,31 +1160,41 @@ dummy_func( + } + } + +- inst(LOAD_NAME, ( -- v)) { +- PyObject *name = GETITEM(frame->f_code->co_names, oparg); +- PyObject *locals = LOCALS(); ++ op(_LOAD_LOCALS, ( -- locals)) { ++ locals = LOCALS(); + if (locals == NULL) { +- _PyErr_Format(tstate, PyExc_SystemError, +- "no locals when loading %R", name); +- goto error; ++ _PyErr_SetString(tstate, PyExc_SystemError, ++ "no locals found"); ++ ERROR_IF(true, error); + } +- if (PyDict_CheckExact(locals)) { +- v = PyDict_GetItemWithError(locals, name); ++ Py_INCREF(locals); ++ } ++ ++ macro(LOAD_LOCALS) = _LOAD_LOCALS; ++ ++ op(_LOAD_FROM_DICT_OR_GLOBALS, (mod_or_class_dict -- v)) { ++ PyObject *name = GETITEM(frame->f_code->co_names, oparg); ++ if (PyDict_CheckExact(mod_or_class_dict)) { ++ v = PyDict_GetItemWithError(mod_or_class_dict, name); + if (v != NULL) { + Py_INCREF(v); + } + else if (_PyErr_Occurred(tstate)) { ++ Py_DECREF(mod_or_class_dict); + goto error; + } + } + else { +- v = PyObject_GetItem(locals, name); ++ v = PyObject_GetItem(mod_or_class_dict, name); + if (v == NULL) { +- if (!_PyErr_ExceptionMatches(tstate, PyExc_KeyError)) ++ if (!_PyErr_ExceptionMatches(tstate, PyExc_KeyError)) { ++ Py_DECREF(mod_or_class_dict); + goto error; ++ } + _PyErr_Clear(tstate); + } + } ++ Py_DECREF(mod_or_class_dict); + if (v == NULL) { + v = PyDict_GetItemWithError(GLOBALS(), name); + if (v != NULL) { +@@ -1219,6 +1231,10 @@ dummy_func( + } + } + ++ macro(LOAD_NAME) = _LOAD_LOCALS + _LOAD_FROM_DICT_OR_GLOBALS; ++ ++ macro(LOAD_FROM_DICT_OR_GLOBALS) = _LOAD_FROM_DICT_OR_GLOBALS; ++ + family(load_global, INLINE_CACHE_ENTRIES_LOAD_GLOBAL) = { + LOAD_GLOBAL, + LOAD_GLOBAL_MODULE, +@@ -1339,29 +1355,32 @@ dummy_func( + Py_DECREF(oldobj); + } + +- inst(LOAD_CLASSDEREF, ( -- value)) { +- PyObject *name, *locals = LOCALS(); +- assert(locals); ++ inst(LOAD_FROM_DICT_OR_DEREF, (class_dict -- value)) { ++ PyObject *name; ++ assert(class_dict); + assert(oparg >= 0 && oparg < frame->f_code->co_nlocalsplus); + name = PyTuple_GET_ITEM(frame->f_code->co_localsplusnames, oparg); +- if (PyDict_CheckExact(locals)) { +- value = PyDict_GetItemWithError(locals, name); ++ if (PyDict_CheckExact(class_dict)) { ++ value = PyDict_GetItemWithError(class_dict, name); + if (value != NULL) { + Py_INCREF(value); + } + else if (_PyErr_Occurred(tstate)) { ++ Py_DECREF(class_dict); + goto error; + } + } + else { +- value = PyObject_GetItem(locals, name); ++ value = PyObject_GetItem(class_dict, name); + if (value == NULL) { + if (!_PyErr_ExceptionMatches(tstate, PyExc_KeyError)) { ++ Py_DECREF(class_dict); + goto error; + } + _PyErr_Clear(tstate); + } + } ++ Py_DECREF(class_dict); + if (!value) { + PyObject *cell = GETLOCAL(oparg); + value = PyCell_GET(cell); +diff --git a/Python/compile.c b/Python/compile.c +index bf5e4a5248..7adbf92089 100644 +--- a/Python/compile.c ++++ b/Python/compile.c +@@ -147,6 +147,7 @@ enum { + COMPILER_SCOPE_ASYNC_FUNCTION, + COMPILER_SCOPE_LAMBDA, + COMPILER_SCOPE_COMPREHENSION, ++ COMPILER_SCOPE_TYPEPARAMS, + }; + + +@@ -231,6 +232,7 @@ instr_sequence_next_inst(instr_sequence *seq) { + &seq->s_allocated, + INITIAL_INSTR_SEQUENCE_SIZE, + sizeof(instruction))); ++ assert(seq->s_allocated >= 0); + assert(seq->s_used < seq->s_allocated); + return seq->s_used++; + } +@@ -714,6 +716,19 @@ compiler_set_qualname(struct compiler *c) + capsule = PyList_GET_ITEM(c->c_stack, stack_size - 1); + parent = (struct compiler_unit *)PyCapsule_GetPointer(capsule, CAPSULE_NAME); + assert(parent); ++ if (parent->u_scope_type == COMPILER_SCOPE_TYPEPARAMS) { ++ /* The parent is a type parameter scope, so we need to ++ look at the grandparent. */ ++ if (stack_size == 2) { ++ // If we're immediately within the module, we can skip ++ // the rest and just set the qualname to be the same as name. ++ u->u_metadata.u_qualname = Py_NewRef(u->u_metadata.u_name); ++ return SUCCESS; ++ } ++ capsule = PyList_GET_ITEM(c->c_stack, stack_size - 2); ++ parent = (struct compiler_unit *)PyCapsule_GetPointer(capsule, CAPSULE_NAME); ++ assert(parent); ++ } + + if (u->u_scope_type == COMPILER_SCOPE_FUNCTION + || u->u_scope_type == COMPILER_SCOPE_ASYNC_FUNCTION +@@ -1114,16 +1129,18 @@ codegen_addop_j(instr_sequence *seq, location loc, + return instr_sequence_addop(seq, opcode, target.id, loc); + } + +-#define ADDOP(C, LOC, OP) \ +- RETURN_IF_ERROR(codegen_addop_noarg(INSTR_SEQUENCE(C), (OP), (LOC))) +- +-#define ADDOP_IN_SCOPE(C, LOC, OP) { \ +- if (codegen_addop_noarg(INSTR_SEQUENCE(C), (OP), (LOC)) < 0) { \ +- compiler_exit_scope(C); \ ++#define RETURN_IF_ERROR_IN_SCOPE(C, CALL) { \ ++ if ((CALL) < 0) { \ ++ compiler_exit_scope((C)); \ + return ERROR; \ + } \ + } + ++#define ADDOP(C, LOC, OP) \ ++ RETURN_IF_ERROR(codegen_addop_noarg(INSTR_SEQUENCE(C), (OP), (LOC))) ++ ++#define ADDOP_IN_SCOPE(C, LOC, OP) RETURN_IF_ERROR_IN_SCOPE((C), codegen_addop_noarg(INSTR_SEQUENCE(C), (OP), (LOC))) ++ + #define ADDOP_LOAD_CONST(C, LOC, O) \ + RETURN_IF_ERROR(compiler_addop_load_const((C)->c_const_cache, (C)->u, (LOC), (O))) + +@@ -1183,12 +1200,8 @@ codegen_addop_j(instr_sequence *seq, location loc, + #define VISIT(C, TYPE, V) \ + RETURN_IF_ERROR(compiler_visit_ ## TYPE((C), (V))); + +-#define VISIT_IN_SCOPE(C, TYPE, V) {\ +- if (compiler_visit_ ## TYPE((C), (V)) < 0) { \ +- compiler_exit_scope(C); \ +- return ERROR; \ +- } \ +-} ++#define VISIT_IN_SCOPE(C, TYPE, V) \ ++ RETURN_IF_ERROR_IN_SCOPE((C), compiler_visit_ ## TYPE((C), (V))) + + #define VISIT_SEQ(C, TYPE, SEQ) { \ + int _i; \ +@@ -1252,6 +1265,16 @@ compiler_enter_scope(struct compiler *c, identifier name, + return ERROR; + } + } ++ if (u->u_ste->ste_needs_classdict) { ++ /* Cook up an implicit __classdict__ cell. */ ++ Py_ssize_t res; ++ assert(u->u_scope_type == COMPILER_SCOPE_CLASS); ++ res = dict_add_o(u->u_metadata.u_cellvars, &_Py_ID(__classdict__)); ++ if (res < 0) { ++ compiler_unit_free(u); ++ return ERROR; ++ } ++ } + + u->u_metadata.u_freevars = dictbytype(u->u_ste->ste_symbols, FREE, DEF_FREE_CLASS, + PyDict_GET_SIZE(u->u_metadata.u_cellvars)); +@@ -1718,8 +1741,10 @@ get_ref_type(struct compiler *c, PyObject *name) + { + int scope; + if (c->u->u_scope_type == COMPILER_SCOPE_CLASS && +- _PyUnicode_EqualToASCIIString(name, "__class__")) ++ (_PyUnicode_EqualToASCIIString(name, "__class__") || ++ _PyUnicode_EqualToASCIIString(name, "__classdict__"))) { + return CELL; ++ } + scope = _PyST_GetScope(c->u->u_ste, name); + if (scope == 0) { + PyErr_Format(PyExc_SystemError, +@@ -2085,26 +2110,81 @@ wrap_in_stopiteration_handler(struct compiler *c) + } + + static int +-compiler_function(struct compiler *c, stmt_ty s, int is_async) ++compiler_type_params(struct compiler *c, asdl_typeparam_seq *typeparams) ++{ ++ if (!typeparams) { ++ return SUCCESS; ++ } ++ Py_ssize_t n = asdl_seq_LEN(typeparams); ++ ++ for (Py_ssize_t i = 0; i < n; i++) { ++ typeparam_ty typeparam = asdl_seq_GET(typeparams, i); ++ location loc = LOC(typeparam); ++ switch(typeparam->kind) { ++ case TypeVar_kind: ++ ADDOP_LOAD_CONST(c, loc, typeparam->v.TypeVar.name); ++ if (typeparam->v.TypeVar.bound) { ++ expr_ty bound = typeparam->v.TypeVar.bound; ++ if (compiler_enter_scope(c, typeparam->v.TypeVar.name, COMPILER_SCOPE_TYPEPARAMS, ++ (void *)typeparam, bound->lineno) == -1) { ++ return ERROR; ++ } ++ VISIT_IN_SCOPE(c, expr, bound); ++ ADDOP_IN_SCOPE(c, loc, RETURN_VALUE); ++ PyCodeObject *co = optimize_and_assemble(c, 1); ++ compiler_exit_scope(c); ++ if (co == NULL) { ++ return ERROR; ++ } ++ if (compiler_make_closure(c, loc, co, 0) < 0) { ++ Py_DECREF(co); ++ return ERROR; ++ } ++ Py_DECREF(co); ++ ++ int intrinsic = bound->kind == Tuple_kind ++ ? INTRINSIC_TYPEVAR_WITH_CONSTRAINTS ++ : INTRINSIC_TYPEVAR_WITH_BOUND; ++ ADDOP_I(c, loc, CALL_INTRINSIC_2, intrinsic); ++ } ++ else { ++ ADDOP_I(c, loc, CALL_INTRINSIC_1, INTRINSIC_TYPEVAR); ++ } ++ ADDOP_I(c, loc, COPY, 1); ++ RETURN_IF_ERROR(compiler_nameop(c, loc, typeparam->v.TypeVar.name, Store)); ++ break; ++ case TypeVarTuple_kind: ++ ADDOP_LOAD_CONST(c, loc, typeparam->v.TypeVarTuple.name); ++ ADDOP_I(c, loc, CALL_INTRINSIC_1, INTRINSIC_TYPEVARTUPLE); ++ ADDOP_I(c, loc, COPY, 1); ++ RETURN_IF_ERROR(compiler_nameop(c, loc, typeparam->v.TypeVarTuple.name, Store)); ++ break; ++ case ParamSpec_kind: ++ ADDOP_LOAD_CONST(c, loc, typeparam->v.ParamSpec.name); ++ ADDOP_I(c, loc, CALL_INTRINSIC_1, INTRINSIC_PARAMSPEC); ++ ADDOP_I(c, loc, COPY, 1); ++ RETURN_IF_ERROR(compiler_nameop(c, loc, typeparam->v.ParamSpec.name, Store)); ++ break; ++ } ++ } ++ ADDOP_I(c, LOC(asdl_seq_GET(typeparams, 0)), BUILD_TUPLE, n); ++ return SUCCESS; ++} ++ ++static int ++compiler_function_body(struct compiler *c, stmt_ty s, int is_async, Py_ssize_t funcflags, ++ int firstlineno) + { +- PyCodeObject *co; + PyObject *docstring = NULL; + arguments_ty args; +- expr_ty returns; + identifier name; +- asdl_expr_seq* decos; + asdl_stmt_seq *body; +- Py_ssize_t i, funcflags; +- int annotations; + int scope_type; +- int firstlineno; + + if (is_async) { + assert(s->kind == AsyncFunctionDef_kind); + + args = s->v.AsyncFunctionDef.args; +- returns = s->v.AsyncFunctionDef.returns; +- decos = s->v.AsyncFunctionDef.decorator_list; + name = s->v.AsyncFunctionDef.name; + body = s->v.AsyncFunctionDef.body; + +@@ -2113,33 +2193,12 @@ compiler_function(struct compiler *c, stmt_ty s, int is_async) + assert(s->kind == FunctionDef_kind); + + args = s->v.FunctionDef.args; +- returns = s->v.FunctionDef.returns; +- decos = s->v.FunctionDef.decorator_list; + name = s->v.FunctionDef.name; + body = s->v.FunctionDef.body; + + scope_type = COMPILER_SCOPE_FUNCTION; + } + +- RETURN_IF_ERROR(compiler_check_debug_args(c, args)); +- RETURN_IF_ERROR(compiler_decorators(c, decos)); +- +- firstlineno = s->lineno; +- if (asdl_seq_LEN(decos)) { +- firstlineno = ((expr_ty)asdl_seq_GET(decos, 0))->lineno; +- } +- +- location loc = LOC(s); +- funcflags = compiler_default_arguments(c, loc, args); +- if (funcflags == -1) { +- return ERROR; +- } +- annotations = compiler_visit_annotations(c, loc, args, returns); +- RETURN_IF_ERROR(annotations); +- if (annotations > 0) { +- funcflags |= 0x04; +- } +- + RETURN_IF_ERROR( + compiler_enter_scope(c, name, scope_type, (void *)s, firstlineno)); + +@@ -2155,7 +2214,7 @@ compiler_function(struct compiler *c, stmt_ty s, int is_async) + c->u->u_metadata.u_argcount = asdl_seq_LEN(args->args); + c->u->u_metadata.u_posonlyargcount = asdl_seq_LEN(args->posonlyargs); + c->u->u_metadata.u_kwonlyargcount = asdl_seq_LEN(args->kwonlyargs); +- for (i = docstring ? 1 : 0; i < asdl_seq_LEN(body); i++) { ++ for (Py_ssize_t i = docstring ? 1 : 0; i < asdl_seq_LEN(body); i++) { + VISIT_IN_SCOPE(c, stmt, (stmt_ty)asdl_seq_GET(body, i)); + } + if (c->u->u_ste->ste_coroutine || c->u->u_ste->ste_generator) { +@@ -2164,29 +2223,52 @@ compiler_function(struct compiler *c, stmt_ty s, int is_async) + return ERROR; + } + } +- co = optimize_and_assemble(c, 1); ++ PyCodeObject *co = optimize_and_assemble(c, 1); + compiler_exit_scope(c); + if (co == NULL) { + Py_XDECREF(co); + return ERROR; + } ++ location loc = LOC(s); + if (compiler_make_closure(c, loc, co, funcflags) < 0) { + Py_DECREF(co); + return ERROR; + } + Py_DECREF(co); +- +- RETURN_IF_ERROR(compiler_apply_decorators(c, decos)); +- return compiler_nameop(c, loc, name, Store); ++ return SUCCESS; + } + + static int +-compiler_class(struct compiler *c, stmt_ty s) ++compiler_function(struct compiler *c, stmt_ty s, int is_async) + { +- PyCodeObject *co; +- int i, firstlineno; +- asdl_expr_seq *decos = s->v.ClassDef.decorator_list; ++ arguments_ty args; ++ expr_ty returns; ++ identifier name; ++ asdl_expr_seq *decos; ++ asdl_typeparam_seq *typeparams; ++ Py_ssize_t funcflags; ++ int annotations; ++ int firstlineno; ++ ++ if (is_async) { ++ assert(s->kind == AsyncFunctionDef_kind); + ++ args = s->v.AsyncFunctionDef.args; ++ returns = s->v.AsyncFunctionDef.returns; ++ decos = s->v.AsyncFunctionDef.decorator_list; ++ name = s->v.AsyncFunctionDef.name; ++ typeparams = s->v.AsyncFunctionDef.typeparams; ++ } else { ++ assert(s->kind == FunctionDef_kind); ++ ++ args = s->v.FunctionDef.args; ++ returns = s->v.FunctionDef.returns; ++ decos = s->v.FunctionDef.decorator_list; ++ name = s->v.FunctionDef.name; ++ typeparams = s->v.FunctionDef.typeparams; ++ } ++ ++ RETURN_IF_ERROR(compiler_check_debug_args(c, args)); + RETURN_IF_ERROR(compiler_decorators(c, decos)); + + firstlineno = s->lineno; +@@ -2194,6 +2276,108 @@ compiler_class(struct compiler *c, stmt_ty s) + firstlineno = ((expr_ty)asdl_seq_GET(decos, 0))->lineno; + } + ++ location loc = LOC(s); ++ ++ int is_generic = asdl_seq_LEN(typeparams) > 0; ++ ++ if (is_generic) { ++ // Used by the CALL to the type parameters function. ++ ADDOP(c, loc, PUSH_NULL); ++ } ++ ++ funcflags = compiler_default_arguments(c, loc, args); ++ if (funcflags == -1) { ++ return ERROR; ++ } ++ ++ int num_typeparam_args = 0; ++ ++ if (is_generic) { ++ if (funcflags & 0x01) { ++ num_typeparam_args += 1; ++ } ++ if (funcflags & 0x02) { ++ num_typeparam_args += 1; ++ } ++ if (num_typeparam_args == 2) { ++ ADDOP_I(c, loc, SWAP, 2); ++ } ++ PyObject *typeparams_name = PyUnicode_FromFormat("", name); ++ if (!typeparams_name) { ++ return ERROR; ++ } ++ if (compiler_enter_scope(c, typeparams_name, COMPILER_SCOPE_TYPEPARAMS, ++ (void *)typeparams, firstlineno) == -1) { ++ Py_DECREF(typeparams_name); ++ return ERROR; ++ } ++ Py_DECREF(typeparams_name); ++ RETURN_IF_ERROR_IN_SCOPE(c, compiler_type_params(c, typeparams)); ++ if ((funcflags & 0x01) || (funcflags & 0x02)) { ++ RETURN_IF_ERROR_IN_SCOPE(c, codegen_addop_i(INSTR_SEQUENCE(c), LOAD_FAST, 0, loc)); ++ } ++ if ((funcflags & 0x01) && (funcflags & 0x02)) { ++ RETURN_IF_ERROR_IN_SCOPE(c, codegen_addop_i(INSTR_SEQUENCE(c), LOAD_FAST, 1, loc)); ++ } ++ } ++ ++ annotations = compiler_visit_annotations(c, loc, args, returns); ++ if (annotations < 0) { ++ if (is_generic) { ++ compiler_exit_scope(c); ++ } ++ return ERROR; ++ } ++ if (annotations > 0) { ++ funcflags |= 0x04; ++ } ++ ++ if (compiler_function_body(c, s, is_async, funcflags, firstlineno) < 0) { ++ if (is_generic) { ++ compiler_exit_scope(c); ++ } ++ return ERROR; ++ } ++ ++ if (is_generic) { ++ RETURN_IF_ERROR_IN_SCOPE(c, codegen_addop_i( ++ INSTR_SEQUENCE(c), SWAP, 2, loc)); ++ RETURN_IF_ERROR_IN_SCOPE(c, codegen_addop_i( ++ INSTR_SEQUENCE(c), CALL_INTRINSIC_2, INTRINSIC_SET_FUNCTION_TYPE_PARAMS, loc)); ++ ++ c->u->u_metadata.u_argcount = num_typeparam_args; ++ PyCodeObject *co = optimize_and_assemble(c, 0); ++ compiler_exit_scope(c); ++ if (co == NULL) { ++ return ERROR; ++ } ++ if (compiler_make_closure(c, loc, co, 0) < 0) { ++ Py_DECREF(co); ++ return ERROR; ++ } ++ Py_DECREF(co); ++ if (num_typeparam_args > 0) { ++ ADDOP_I(c, loc, SWAP, num_typeparam_args + 1); ++ } ++ ADDOP_I(c, loc, CALL, num_typeparam_args); ++ } ++ ++ RETURN_IF_ERROR(compiler_apply_decorators(c, decos)); ++ return compiler_nameop(c, loc, name, Store); ++} ++ ++static int ++compiler_set_type_params_in_class(struct compiler *c, location loc) ++{ ++ _Py_DECLARE_STR(type_params, ".type_params"); ++ RETURN_IF_ERROR(compiler_nameop(c, loc, &_Py_STR(type_params), Load)); ++ RETURN_IF_ERROR(compiler_nameop(c, loc, &_Py_ID(__type_params__), Store)); ++ return 1; ++} ++ ++static int ++compiler_class_body(struct compiler *c, stmt_ty s, int firstlineno) ++{ + /* ultimately generate code for: + = __build_class__(, , *, **) + where: +@@ -2204,68 +2388,100 @@ compiler_class(struct compiler *c, stmt_ty s) + is the keyword arguments and **kwds argument + This borrows from compiler_call. + */ ++ + /* 1. compile the class body into a code object */ + RETURN_IF_ERROR( + compiler_enter_scope(c, s->v.ClassDef.name, + COMPILER_SCOPE_CLASS, (void *)s, firstlineno)); + +- /* this block represents what we do in the new scope */ +- { +- location loc = LOCATION(firstlineno, firstlineno, 0, 0); +- /* use the class name for name mangling */ +- Py_XSETREF(c->u->u_private, Py_NewRef(s->v.ClassDef.name)); +- /* load (global) __name__ ... */ +- if (compiler_nameop(c, loc, &_Py_ID(__name__), Load) < 0) { ++ location loc = LOCATION(firstlineno, firstlineno, 0, 0); ++ /* use the class name for name mangling */ ++ Py_XSETREF(c->u->u_private, Py_NewRef(s->v.ClassDef.name)); ++ /* load (global) __name__ ... */ ++ if (compiler_nameop(c, loc, &_Py_ID(__name__), Load) < 0) { ++ compiler_exit_scope(c); ++ return ERROR; ++ } ++ /* ... and store it as __module__ */ ++ if (compiler_nameop(c, loc, &_Py_ID(__module__), Store) < 0) { ++ compiler_exit_scope(c); ++ return ERROR; ++ } ++ assert(c->u->u_metadata.u_qualname); ++ ADDOP_LOAD_CONST(c, loc, c->u->u_metadata.u_qualname); ++ if (compiler_nameop(c, loc, &_Py_ID(__qualname__), Store) < 0) { ++ compiler_exit_scope(c); ++ return ERROR; ++ } ++ asdl_typeparam_seq *typeparams = s->v.ClassDef.typeparams; ++ if (asdl_seq_LEN(typeparams) > 0) { ++ if (!compiler_set_type_params_in_class(c, loc)) { + compiler_exit_scope(c); + return ERROR; + } +- /* ... and store it as __module__ */ +- if (compiler_nameop(c, loc, &_Py_ID(__module__), Store) < 0) { ++ } ++ if (c->u->u_ste->ste_needs_classdict) { ++ ADDOP(c, loc, LOAD_LOCALS); ++ ++ // We can't use compiler_nameop here because we need to generate a ++ // STORE_DEREF in a class namespace, and compiler_nameop() won't do ++ // that by default. ++ PyObject *cellvars = c->u->u_metadata.u_cellvars; ++ if (compiler_addop_o(c->u, loc, STORE_DEREF, cellvars, ++ &_Py_ID(__classdict__)) < 0) { + compiler_exit_scope(c); + return ERROR; + } +- assert(c->u->u_metadata.u_qualname); +- ADDOP_LOAD_CONST(c, loc, c->u->u_metadata.u_qualname); +- if (compiler_nameop(c, loc, &_Py_ID(__qualname__), Store) < 0) { ++ } ++ /* compile the body proper */ ++ if (compiler_body(c, loc, s->v.ClassDef.body) < 0) { ++ compiler_exit_scope(c); ++ return ERROR; ++ } ++ /* The following code is artificial */ ++ /* Set __classdictcell__ if necessary */ ++ if (c->u->u_ste->ste_needs_classdict) { ++ /* Store __classdictcell__ into class namespace */ ++ int i = compiler_lookup_arg(c->u->u_metadata.u_cellvars, &_Py_ID(__classdict__)); ++ if (i < 0) { + compiler_exit_scope(c); + return ERROR; + } +- /* compile the body proper */ +- if (compiler_body(c, loc, s->v.ClassDef.body) < 0) { ++ ADDOP_I(c, NO_LOCATION, LOAD_CLOSURE, i); ++ if (compiler_nameop(c, NO_LOCATION, &_Py_ID(__classdictcell__), Store) < 0) { + compiler_exit_scope(c); + return ERROR; + } +- /* The following code is artificial */ +- /* Return __classcell__ if it is referenced, otherwise return None */ +- if (c->u->u_ste->ste_needs_class_closure) { +- /* Store __classcell__ into class namespace & return it */ +- i = compiler_lookup_arg(c->u->u_metadata.u_cellvars, &_Py_ID(__class__)); +- if (i < 0) { +- compiler_exit_scope(c); +- return ERROR; +- } +- ADDOP_I(c, NO_LOCATION, LOAD_CLOSURE, i); +- ADDOP_I(c, NO_LOCATION, COPY, 1); +- if (compiler_nameop(c, NO_LOCATION, &_Py_ID(__classcell__), Store) < 0) { +- compiler_exit_scope(c); +- return ERROR; +- } ++ } ++ /* Return __classcell__ if it is referenced, otherwise return None */ ++ if (c->u->u_ste->ste_needs_class_closure) { ++ /* Store __classcell__ into class namespace & return it */ ++ int i = compiler_lookup_arg(c->u->u_metadata.u_cellvars, &_Py_ID(__class__)); ++ if (i < 0) { ++ compiler_exit_scope(c); ++ return ERROR; + } +- else { +- /* No methods referenced __class__, so just return None */ +- ADDOP_LOAD_CONST(c, NO_LOCATION, Py_None); ++ ADDOP_I(c, NO_LOCATION, LOAD_CLOSURE, i); ++ ADDOP_I(c, NO_LOCATION, COPY, 1); ++ if (compiler_nameop(c, NO_LOCATION, &_Py_ID(__classcell__), Store) < 0) { ++ compiler_exit_scope(c); ++ return ERROR; + } +- ADDOP_IN_SCOPE(c, NO_LOCATION, RETURN_VALUE); +- /* create the code object */ +- co = optimize_and_assemble(c, 1); + } ++ else { ++ /* No methods referenced __class__, so just return None */ ++ ADDOP_LOAD_CONST(c, NO_LOCATION, Py_None); ++ } ++ ADDOP_IN_SCOPE(c, NO_LOCATION, RETURN_VALUE); ++ /* create the code object */ ++ PyCodeObject *co = optimize_and_assemble(c, 1); ++ + /* leave the new scope */ + compiler_exit_scope(c); + if (co == NULL) { + return ERROR; + } + +- location loc = LOC(s); + /* 2. load the 'build_class' function */ + ADDOP(c, loc, PUSH_NULL); + ADDOP(c, loc, LOAD_BUILD_CLASS); +@@ -2280,10 +2496,100 @@ compiler_class(struct compiler *c, stmt_ty s) + /* 4. load class name */ + ADDOP_LOAD_CONST(c, loc, s->v.ClassDef.name); + +- /* 5. generate the rest of the code for the call */ +- RETURN_IF_ERROR(compiler_call_helper(c, loc, 2, +- s->v.ClassDef.bases, +- s->v.ClassDef.keywords)); ++ return SUCCESS; ++} ++ ++static int ++compiler_class(struct compiler *c, stmt_ty s) ++{ ++ asdl_expr_seq *decos = s->v.ClassDef.decorator_list; ++ ++ RETURN_IF_ERROR(compiler_decorators(c, decos)); ++ ++ int firstlineno = s->lineno; ++ if (asdl_seq_LEN(decos)) { ++ firstlineno = ((expr_ty)asdl_seq_GET(decos, 0))->lineno; ++ } ++ location loc = LOC(s); ++ ++ asdl_typeparam_seq *typeparams = s->v.ClassDef.typeparams; ++ int is_generic = asdl_seq_LEN(typeparams) > 0; ++ if (is_generic) { ++ Py_XSETREF(c->u->u_private, Py_NewRef(s->v.ClassDef.name)); ++ ADDOP(c, loc, PUSH_NULL); ++ PyObject *typeparams_name = PyUnicode_FromFormat("", ++ s->v.ClassDef.name); ++ if (!typeparams_name) { ++ return ERROR; ++ } ++ if (compiler_enter_scope(c, typeparams_name, COMPILER_SCOPE_TYPEPARAMS, ++ (void *)typeparams, firstlineno) == -1) { ++ Py_DECREF(typeparams_name); ++ return ERROR; ++ } ++ Py_DECREF(typeparams_name); ++ RETURN_IF_ERROR_IN_SCOPE(c, compiler_type_params(c, typeparams)); ++ _Py_DECLARE_STR(type_params, ".type_params"); ++ RETURN_IF_ERROR_IN_SCOPE(c, compiler_nameop(c, loc, &_Py_STR(type_params), Store)); ++ } ++ ++ if (compiler_class_body(c, s, firstlineno) < 0) { ++ if (is_generic) { ++ compiler_exit_scope(c); ++ } ++ return ERROR; ++ } ++ ++ /* generate the rest of the code for the call */ ++ ++ if (is_generic) { ++ _Py_DECLARE_STR(type_params, ".type_params"); ++ _Py_DECLARE_STR(generic_base, ".generic_base"); ++ RETURN_IF_ERROR_IN_SCOPE(c, compiler_nameop(c, loc, &_Py_STR(type_params), Load)); ++ RETURN_IF_ERROR_IN_SCOPE( ++ c, codegen_addop_i(INSTR_SEQUENCE(c), CALL_INTRINSIC_1, INTRINSIC_SUBSCRIPT_GENERIC, loc) ++ ) ++ RETURN_IF_ERROR_IN_SCOPE(c, compiler_nameop(c, loc, &_Py_STR(generic_base), Store)); ++ ++ Py_ssize_t original_len = asdl_seq_LEN(s->v.ClassDef.bases); ++ asdl_expr_seq *bases = _Py_asdl_expr_seq_new( ++ original_len + 1, c->c_arena); ++ if (bases == NULL) { ++ compiler_exit_scope(c); ++ return ERROR; ++ } ++ for (Py_ssize_t i = 0; i < original_len; i++) { ++ asdl_seq_SET(bases, i, asdl_seq_GET(s->v.ClassDef.bases, i)); ++ } ++ expr_ty name_node = _PyAST_Name( ++ &_Py_STR(generic_base), Load, ++ loc.lineno, loc.col_offset, loc.end_lineno, loc.end_col_offset, c->c_arena ++ ); ++ if (name_node == NULL) { ++ compiler_exit_scope(c); ++ return ERROR; ++ } ++ asdl_seq_SET(bases, original_len, name_node); ++ RETURN_IF_ERROR_IN_SCOPE(c, compiler_call_helper(c, loc, 2, ++ bases, ++ s->v.ClassDef.keywords)); ++ ++ PyCodeObject *co = optimize_and_assemble(c, 0); ++ compiler_exit_scope(c); ++ if (co == NULL) { ++ return ERROR; ++ } ++ if (compiler_make_closure(c, loc, co, 0) < 0) { ++ Py_DECREF(co); ++ return ERROR; ++ } ++ Py_DECREF(co); ++ ADDOP_I(c, loc, CALL, 0); ++ } else { ++ RETURN_IF_ERROR(compiler_call_helper(c, loc, 2, ++ s->v.ClassDef.bases, ++ s->v.ClassDef.keywords)); ++ } + + /* 6. apply decorators */ + RETURN_IF_ERROR(compiler_apply_decorators(c, decos)); +@@ -2293,6 +2599,87 @@ compiler_class(struct compiler *c, stmt_ty s) + return SUCCESS; + } + ++static int ++compiler_typealias_body(struct compiler *c, stmt_ty s) ++{ ++ location loc = LOC(s); ++ PyObject *name = s->v.TypeAlias.name->v.Name.id; ++ RETURN_IF_ERROR( ++ compiler_enter_scope(c, name, COMPILER_SCOPE_FUNCTION, s, loc.lineno)); ++ /* Make None the first constant, so the evaluate function can't have a ++ docstring. */ ++ RETURN_IF_ERROR(compiler_add_const(c->c_const_cache, c->u, Py_None)); ++ VISIT_IN_SCOPE(c, expr, s->v.TypeAlias.value); ++ ADDOP_IN_SCOPE(c, loc, RETURN_VALUE); ++ PyCodeObject *co = optimize_and_assemble(c, 0); ++ compiler_exit_scope(c); ++ if (co == NULL) { ++ return ERROR; ++ } ++ if (compiler_make_closure(c, loc, co, 0) < 0) { ++ Py_DECREF(co); ++ return ERROR; ++ } ++ Py_DECREF(co); ++ ADDOP_I(c, loc, BUILD_TUPLE, 3); ++ ADDOP_I(c, loc, CALL_INTRINSIC_1, INTRINSIC_TYPEALIAS); ++ return SUCCESS; ++} ++ ++static int ++compiler_typealias(struct compiler *c, stmt_ty s) ++{ ++ location loc = LOC(s); ++ asdl_typeparam_seq *typeparams = s->v.TypeAlias.typeparams; ++ int is_generic = asdl_seq_LEN(typeparams) > 0; ++ PyObject *name = s->v.TypeAlias.name->v.Name.id; ++ if (is_generic) { ++ ADDOP(c, loc, PUSH_NULL); ++ PyObject *typeparams_name = PyUnicode_FromFormat("", ++ name); ++ if (!typeparams_name) { ++ return ERROR; ++ } ++ if (compiler_enter_scope(c, typeparams_name, COMPILER_SCOPE_TYPEPARAMS, ++ (void *)typeparams, loc.lineno) == -1) { ++ Py_DECREF(typeparams_name); ++ return ERROR; ++ } ++ Py_DECREF(typeparams_name); ++ RETURN_IF_ERROR_IN_SCOPE( ++ c, compiler_addop_load_const(c->c_const_cache, c->u, loc, name) ++ ); ++ RETURN_IF_ERROR_IN_SCOPE(c, compiler_type_params(c, typeparams)); ++ } ++ else { ++ ADDOP_LOAD_CONST(c, loc, name); ++ ADDOP_LOAD_CONST(c, loc, Py_None); ++ } ++ ++ if (compiler_typealias_body(c, s) < 0) { ++ if (is_generic) { ++ compiler_exit_scope(c); ++ } ++ return ERROR; ++ } ++ ++ if (is_generic) { ++ PyCodeObject *co = optimize_and_assemble(c, 0); ++ compiler_exit_scope(c); ++ if (co == NULL) { ++ return ERROR; ++ } ++ if (compiler_make_closure(c, loc, co, 0) < 0) { ++ Py_DECREF(co); ++ return ERROR; ++ } ++ Py_DECREF(co); ++ ADDOP_I(c, loc, CALL, 0); ++ } ++ RETURN_IF_ERROR(compiler_nameop(c, loc, name, Store)); ++ return SUCCESS; ++} ++ + /* Return false if the expression is a constant value except named singletons. + Return true otherwise. */ + static bool +@@ -2705,7 +3092,7 @@ compiler_return(struct compiler *c, stmt_ty s) + location loc = LOC(s); + int preserve_tos = ((s->v.Return.value != NULL) && + (s->v.Return.value->kind != Constant_kind)); +- if (c->u->u_ste->ste_type != FunctionBlock) { ++ if (!_PyST_IsFunctionLike(c->u->u_ste)) { + return compiler_error(c, loc, "'return' outside function"); + } + if (s->v.Return.value != NULL && +@@ -3519,6 +3906,8 @@ compiler_visit_stmt(struct compiler *c, stmt_ty s) + return compiler_function(c, s, 0); + case ClassDef_kind: + return compiler_class(c, s); ++ case TypeAlias_kind: ++ return compiler_typealias(c, s); + case Return_kind: + return compiler_return(c, s); + case Delete_kind: +@@ -3725,12 +4114,12 @@ compiler_nameop(struct compiler *c, location loc, + optype = OP_DEREF; + break; + case LOCAL: +- if (c->u->u_ste->ste_type == FunctionBlock || ++ if (_PyST_IsFunctionLike(c->u->u_ste) || + (PyDict_GetItem(c->u->u_metadata.u_fasthidden, mangled) == Py_True)) + optype = OP_FAST; + break; + case GLOBAL_IMPLICIT: +- if (c->u->u_ste->ste_type == FunctionBlock) ++ if (_PyST_IsFunctionLike(c->u->u_ste)) + optype = OP_GLOBAL; + break; + case GLOBAL_EXPLICIT: +@@ -3748,7 +4137,24 @@ compiler_nameop(struct compiler *c, location loc, + case OP_DEREF: + switch (ctx) { + case Load: +- op = (c->u->u_ste->ste_type == ClassBlock) ? LOAD_CLASSDEREF : LOAD_DEREF; ++ if (c->u->u_ste->ste_type == ClassBlock) { ++ op = LOAD_FROM_DICT_OR_DEREF; ++ // First load the locals ++ if (codegen_addop_noarg(INSTR_SEQUENCE(c), LOAD_LOCALS, loc) < 0) { ++ return ERROR; ++ } ++ } ++ else if (c->u->u_ste->ste_can_see_class_scope) { ++ op = LOAD_FROM_DICT_OR_DEREF; ++ // First load the classdict ++ if (compiler_addop_o(c->u, loc, LOAD_DEREF, ++ c->u->u_metadata.u_freevars, &_Py_ID(__classdict__)) < 0) { ++ return ERROR; ++ } ++ } ++ else { ++ op = LOAD_DEREF; ++ } + break; + case Store: op = STORE_DEREF; break; + case Del: op = DELETE_DEREF; break; +@@ -3764,7 +4170,18 @@ compiler_nameop(struct compiler *c, location loc, + return SUCCESS; + case OP_GLOBAL: + switch (ctx) { +- case Load: op = LOAD_GLOBAL; break; ++ case Load: ++ if (c->u->u_ste->ste_can_see_class_scope && scope == GLOBAL_IMPLICIT) { ++ op = LOAD_FROM_DICT_OR_GLOBALS; ++ // First load the classdict ++ if (compiler_addop_o(c->u, loc, LOAD_DEREF, ++ c->u->u_metadata.u_freevars, &_Py_ID(__classdict__)) < 0) { ++ return ERROR; ++ } ++ } else { ++ op = LOAD_GLOBAL; ++ } ++ break; + case Store: op = STORE_GLOBAL; break; + case Del: op = DELETE_GLOBAL; break; + } +@@ -5008,7 +5425,7 @@ push_inlined_comprehension_state(struct compiler *c, location loc, + // assignment expression to a nonlocal in the comprehension, these don't + // need handling here since they shouldn't be isolated + if (symbol & DEF_LOCAL && !(symbol & DEF_NONLOCAL)) { +- if (c->u->u_ste->ste_type != FunctionBlock) { ++ if (!_PyST_IsFunctionLike(c->u->u_ste)) { + // non-function scope: override this name to use fast locals + PyObject *orig = PyDict_GetItem(c->u->u_metadata.u_fasthidden, k); + if (orig != Py_True) { +@@ -5604,7 +6021,7 @@ compiler_visit_expr1(struct compiler *c, expr_ty e) + case DictComp_kind: + return compiler_dictcomp(c, e); + case Yield_kind: +- if (c->u->u_ste->ste_type != FunctionBlock) { ++ if (!_PyST_IsFunctionLike(c->u->u_ste)) { + return compiler_error(c, loc, "'yield' outside function"); + } + if (e->v.Yield.value) { +@@ -5616,7 +6033,7 @@ compiler_visit_expr1(struct compiler *c, expr_ty e) + ADDOP_YIELD(c, loc); + break; + case YieldFrom_kind: +- if (c->u->u_ste->ste_type != FunctionBlock) { ++ if (!_PyST_IsFunctionLike(c->u->u_ste)) { + return compiler_error(c, loc, "'yield' outside function"); + } + if (c->u->u_scope_type == COMPILER_SCOPE_ASYNC_FUNCTION) { +@@ -5629,7 +6046,7 @@ compiler_visit_expr1(struct compiler *c, expr_ty e) + break; + case Await_kind: + if (!IS_TOP_LEVEL_AWAIT(c)){ +- if (c->u->u_ste->ste_type != FunctionBlock){ ++ if (!_PyST_IsFunctionLike(c->u->u_ste)) { + return compiler_error(c, loc, "'await' outside function"); + } + +@@ -6916,7 +7333,7 @@ compute_code_flags(struct compiler *c) + { + PySTEntryObject *ste = c->u->u_ste; + int flags = 0; +- if (ste->ste_type == FunctionBlock) { ++ if (_PyST_IsFunctionLike(c->u->u_ste)) { + flags |= CO_NEWLOCALS | CO_OPTIMIZED; + if (ste->ste_nested) + flags |= CO_NESTED; +@@ -7114,7 +7531,7 @@ fix_cell_offsets(_PyCompile_CodeUnitMetadata *umd, basicblock *entryblock, int * + case LOAD_DEREF: + case STORE_DEREF: + case DELETE_DEREF: +- case LOAD_CLASSDEREF: ++ case LOAD_FROM_DICT_OR_DEREF: + assert(oldoffset >= 0); + assert(oldoffset < noffsets); + assert(fixedmap[oldoffset] >= 0); +diff --git a/Python/generated_cases.c.h b/Python/generated_cases.c.h +index 014a69ff7e..fa4ff5ccee 100644 +--- a/Python/generated_cases.c.h ++++ b/Python/generated_cases.c.h +@@ -8,7 +8,7 @@ + } + + TARGET(RESUME) { +- #line 137 "Python/bytecodes.c" ++ #line 138 "Python/bytecodes.c" + assert(tstate->cframe == &cframe); + assert(frame == cframe.current_frame); + /* Possibly combine this with eval breaker */ +@@ -25,7 +25,7 @@ + } + + TARGET(INSTRUMENTED_RESUME) { +- #line 151 "Python/bytecodes.c" ++ #line 152 "Python/bytecodes.c" + /* Possible performance enhancement: + * We need to check the eval breaker anyway, can we + * combine the instrument verison check and the eval breaker test? +@@ -57,7 +57,7 @@ + + TARGET(LOAD_CLOSURE) { + PyObject *value; +- #line 179 "Python/bytecodes.c" ++ #line 180 "Python/bytecodes.c" + /* We keep LOAD_CLOSURE so that the bytecode stays more readable. */ + value = GETLOCAL(oparg); + if (value == NULL) goto unbound_local_error; +@@ -70,7 +70,7 @@ + + TARGET(LOAD_FAST_CHECK) { + PyObject *value; +- #line 186 "Python/bytecodes.c" ++ #line 187 "Python/bytecodes.c" + value = GETLOCAL(oparg); + if (value == NULL) goto unbound_local_error; + Py_INCREF(value); +@@ -82,7 +82,7 @@ + + TARGET(LOAD_FAST) { + PyObject *value; +- #line 192 "Python/bytecodes.c" ++ #line 193 "Python/bytecodes.c" + value = GETLOCAL(oparg); + assert(value != NULL); + Py_INCREF(value); +@@ -94,7 +94,7 @@ + + TARGET(LOAD_FAST_AND_CLEAR) { + PyObject *value; +- #line 198 "Python/bytecodes.c" ++ #line 199 "Python/bytecodes.c" + value = GETLOCAL(oparg); + // do not use SETLOCAL here, it decrefs the old value + GETLOCAL(oparg) = NULL; +@@ -107,7 +107,7 @@ + TARGET(LOAD_CONST) { + PREDICTED(LOAD_CONST); + PyObject *value; +- #line 204 "Python/bytecodes.c" ++ #line 205 "Python/bytecodes.c" + value = GETITEM(frame->f_code->co_consts, oparg); + Py_INCREF(value); + #line 114 "Python/generated_cases.c.h" +@@ -118,7 +118,7 @@ + + TARGET(STORE_FAST) { + PyObject *value = stack_pointer[-1]; +- #line 209 "Python/bytecodes.c" ++ #line 210 "Python/bytecodes.c" + SETLOCAL(oparg, value); + #line 124 "Python/generated_cases.c.h" + STACK_SHRINK(1); +@@ -130,7 +130,7 @@ + PyObject *_tmp_2; + { + PyObject *value; +- #line 192 "Python/bytecodes.c" ++ #line 193 "Python/bytecodes.c" + value = GETLOCAL(oparg); + assert(value != NULL); + Py_INCREF(value); +@@ -140,7 +140,7 @@ + oparg = (next_instr++)->op.arg; + { + PyObject *value; +- #line 192 "Python/bytecodes.c" ++ #line 193 "Python/bytecodes.c" + value = GETLOCAL(oparg); + assert(value != NULL); + Py_INCREF(value); +@@ -158,7 +158,7 @@ + PyObject *_tmp_2; + { + PyObject *value; +- #line 192 "Python/bytecodes.c" ++ #line 193 "Python/bytecodes.c" + value = GETLOCAL(oparg); + assert(value != NULL); + Py_INCREF(value); +@@ -168,7 +168,7 @@ + oparg = (next_instr++)->op.arg; + { + PyObject *value; +- #line 204 "Python/bytecodes.c" ++ #line 205 "Python/bytecodes.c" + value = GETITEM(frame->f_code->co_consts, oparg); + Py_INCREF(value); + #line 175 "Python/generated_cases.c.h" +@@ -184,14 +184,14 @@ + PyObject *_tmp_1 = stack_pointer[-1]; + { + PyObject *value = _tmp_1; +- #line 209 "Python/bytecodes.c" ++ #line 210 "Python/bytecodes.c" + SETLOCAL(oparg, value); + #line 190 "Python/generated_cases.c.h" + } + oparg = (next_instr++)->op.arg; + { + PyObject *value; +- #line 192 "Python/bytecodes.c" ++ #line 193 "Python/bytecodes.c" + value = GETLOCAL(oparg); + assert(value != NULL); + Py_INCREF(value); +@@ -207,14 +207,14 @@ + PyObject *_tmp_2 = stack_pointer[-2]; + { + PyObject *value = _tmp_1; +- #line 209 "Python/bytecodes.c" ++ #line 210 "Python/bytecodes.c" + SETLOCAL(oparg, value); + #line 213 "Python/generated_cases.c.h" + } + oparg = (next_instr++)->op.arg; + { + PyObject *value = _tmp_2; +- #line 209 "Python/bytecodes.c" ++ #line 210 "Python/bytecodes.c" + SETLOCAL(oparg, value); + #line 220 "Python/generated_cases.c.h" + } +@@ -227,7 +227,7 @@ + PyObject *_tmp_2; + { + PyObject *value; +- #line 204 "Python/bytecodes.c" ++ #line 205 "Python/bytecodes.c" + value = GETITEM(frame->f_code->co_consts, oparg); + Py_INCREF(value); + #line 234 "Python/generated_cases.c.h" +@@ -236,7 +236,7 @@ + oparg = (next_instr++)->op.arg; + { + PyObject *value; +- #line 192 "Python/bytecodes.c" ++ #line 193 "Python/bytecodes.c" + value = GETLOCAL(oparg); + assert(value != NULL); + Py_INCREF(value); +@@ -251,7 +251,7 @@ + + TARGET(POP_TOP) { + PyObject *value = stack_pointer[-1]; +- #line 219 "Python/bytecodes.c" ++ #line 220 "Python/bytecodes.c" + #line 256 "Python/generated_cases.c.h" + Py_DECREF(value); + STACK_SHRINK(1); +@@ -260,7 +260,7 @@ + + TARGET(PUSH_NULL) { + PyObject *res; +- #line 223 "Python/bytecodes.c" ++ #line 224 "Python/bytecodes.c" + res = NULL; + #line 266 "Python/generated_cases.c.h" + STACK_GROW(1); +@@ -273,13 +273,13 @@ + PyObject *_tmp_2 = stack_pointer[-2]; + { + PyObject *value = _tmp_1; +- #line 219 "Python/bytecodes.c" ++ #line 220 "Python/bytecodes.c" + #line 278 "Python/generated_cases.c.h" + Py_DECREF(value); + } + { + PyObject *value = _tmp_2; +- #line 219 "Python/bytecodes.c" ++ #line 220 "Python/bytecodes.c" + #line 284 "Python/generated_cases.c.h" + Py_DECREF(value); + } +@@ -290,7 +290,7 @@ + TARGET(INSTRUMENTED_END_FOR) { + PyObject *value = stack_pointer[-1]; + PyObject *receiver = stack_pointer[-2]; +- #line 229 "Python/bytecodes.c" ++ #line 230 "Python/bytecodes.c" + /* Need to create a fake StopIteration error here, + * to conform to PEP 380 */ + if (PyGen_Check(receiver)) { +@@ -310,7 +310,7 @@ + TARGET(END_SEND) { + PyObject *value = stack_pointer[-1]; + PyObject *receiver = stack_pointer[-2]; +- #line 242 "Python/bytecodes.c" ++ #line 243 "Python/bytecodes.c" + Py_DECREF(receiver); + #line 316 "Python/generated_cases.c.h" + STACK_SHRINK(1); +@@ -321,7 +321,7 @@ + TARGET(INSTRUMENTED_END_SEND) { + PyObject *value = stack_pointer[-1]; + PyObject *receiver = stack_pointer[-2]; +- #line 246 "Python/bytecodes.c" ++ #line 247 "Python/bytecodes.c" + if (PyGen_Check(receiver) || PyCoro_CheckExact(receiver)) { + PyErr_SetObject(PyExc_StopIteration, value); + if (monitor_stop_iteration(tstate, frame, next_instr-1)) { +@@ -339,11 +339,11 @@ + TARGET(UNARY_NEGATIVE) { + PyObject *value = stack_pointer[-1]; + PyObject *res; +- #line 257 "Python/bytecodes.c" ++ #line 258 "Python/bytecodes.c" + res = PyNumber_Negative(value); + #line 345 "Python/generated_cases.c.h" + Py_DECREF(value); +- #line 259 "Python/bytecodes.c" ++ #line 260 "Python/bytecodes.c" + if (res == NULL) goto pop_1_error; + #line 349 "Python/generated_cases.c.h" + stack_pointer[-1] = res; +@@ -353,11 +353,11 @@ + TARGET(UNARY_NOT) { + PyObject *value = stack_pointer[-1]; + PyObject *res; +- #line 263 "Python/bytecodes.c" ++ #line 264 "Python/bytecodes.c" + int err = PyObject_IsTrue(value); + #line 359 "Python/generated_cases.c.h" + Py_DECREF(value); +- #line 265 "Python/bytecodes.c" ++ #line 266 "Python/bytecodes.c" + if (err < 0) goto pop_1_error; + if (err == 0) { + res = Py_True; +@@ -374,11 +374,11 @@ + TARGET(UNARY_INVERT) { + PyObject *value = stack_pointer[-1]; + PyObject *res; +- #line 276 "Python/bytecodes.c" ++ #line 277 "Python/bytecodes.c" + res = PyNumber_Invert(value); + #line 380 "Python/generated_cases.c.h" + Py_DECREF(value); +- #line 278 "Python/bytecodes.c" ++ #line 279 "Python/bytecodes.c" + if (res == NULL) goto pop_1_error; + #line 384 "Python/generated_cases.c.h" + stack_pointer[-1] = res; +@@ -389,7 +389,7 @@ + PyObject *right = stack_pointer[-1]; + PyObject *left = stack_pointer[-2]; + PyObject *prod; +- #line 295 "Python/bytecodes.c" ++ #line 296 "Python/bytecodes.c" + DEOPT_IF(!PyLong_CheckExact(left), BINARY_OP); + DEOPT_IF(!PyLong_CheckExact(right), BINARY_OP); + STAT_INC(BINARY_OP, hit); +@@ -408,7 +408,7 @@ + PyObject *right = stack_pointer[-1]; + PyObject *left = stack_pointer[-2]; + PyObject *prod; +- #line 305 "Python/bytecodes.c" ++ #line 306 "Python/bytecodes.c" + DEOPT_IF(!PyFloat_CheckExact(left), BINARY_OP); + DEOPT_IF(!PyFloat_CheckExact(right), BINARY_OP); + STAT_INC(BINARY_OP, hit); +@@ -426,7 +426,7 @@ + PyObject *right = stack_pointer[-1]; + PyObject *left = stack_pointer[-2]; + PyObject *sub; +- #line 314 "Python/bytecodes.c" ++ #line 315 "Python/bytecodes.c" + DEOPT_IF(!PyLong_CheckExact(left), BINARY_OP); + DEOPT_IF(!PyLong_CheckExact(right), BINARY_OP); + STAT_INC(BINARY_OP, hit); +@@ -445,7 +445,7 @@ + PyObject *right = stack_pointer[-1]; + PyObject *left = stack_pointer[-2]; + PyObject *sub; +- #line 324 "Python/bytecodes.c" ++ #line 325 "Python/bytecodes.c" + DEOPT_IF(!PyFloat_CheckExact(left), BINARY_OP); + DEOPT_IF(!PyFloat_CheckExact(right), BINARY_OP); + STAT_INC(BINARY_OP, hit); +@@ -462,7 +462,7 @@ + PyObject *right = stack_pointer[-1]; + PyObject *left = stack_pointer[-2]; + PyObject *res; +- #line 332 "Python/bytecodes.c" ++ #line 333 "Python/bytecodes.c" + DEOPT_IF(!PyUnicode_CheckExact(left), BINARY_OP); + DEOPT_IF(Py_TYPE(right) != Py_TYPE(left), BINARY_OP); + STAT_INC(BINARY_OP, hit); +@@ -480,7 +480,7 @@ + TARGET(BINARY_OP_INPLACE_ADD_UNICODE) { + PyObject *right = stack_pointer[-1]; + PyObject *left = stack_pointer[-2]; +- #line 348 "Python/bytecodes.c" ++ #line 349 "Python/bytecodes.c" + DEOPT_IF(!PyUnicode_CheckExact(left), BINARY_OP); + DEOPT_IF(Py_TYPE(right) != Py_TYPE(left), BINARY_OP); + _Py_CODEUNIT true_next = next_instr[INLINE_CACHE_ENTRIES_BINARY_OP]; +@@ -516,7 +516,7 @@ + PyObject *right = stack_pointer[-1]; + PyObject *left = stack_pointer[-2]; + PyObject *sum; +- #line 377 "Python/bytecodes.c" ++ #line 378 "Python/bytecodes.c" + DEOPT_IF(!PyFloat_CheckExact(left), BINARY_OP); + DEOPT_IF(Py_TYPE(right) != Py_TYPE(left), BINARY_OP); + STAT_INC(BINARY_OP, hit); +@@ -534,7 +534,7 @@ + PyObject *right = stack_pointer[-1]; + PyObject *left = stack_pointer[-2]; + PyObject *sum; +- #line 386 "Python/bytecodes.c" ++ #line 387 "Python/bytecodes.c" + DEOPT_IF(!PyLong_CheckExact(left), BINARY_OP); + DEOPT_IF(Py_TYPE(right) != Py_TYPE(left), BINARY_OP); + STAT_INC(BINARY_OP, hit); +@@ -555,7 +555,7 @@ + PyObject *sub = stack_pointer[-1]; + PyObject *container = stack_pointer[-2]; + PyObject *res; +- #line 404 "Python/bytecodes.c" ++ #line 405 "Python/bytecodes.c" + #if ENABLE_SPECIALIZATION + _PyBinarySubscrCache *cache = (_PyBinarySubscrCache *)next_instr; + if (ADAPTIVE_COUNTER_IS_ZERO(cache->counter)) { +@@ -570,7 +570,7 @@ + #line 571 "Python/generated_cases.c.h" + Py_DECREF(container); + Py_DECREF(sub); +- #line 416 "Python/bytecodes.c" ++ #line 417 "Python/bytecodes.c" + if (res == NULL) goto pop_2_error; + #line 576 "Python/generated_cases.c.h" + STACK_SHRINK(1); +@@ -584,7 +584,7 @@ + PyObject *start = stack_pointer[-2]; + PyObject *container = stack_pointer[-3]; + PyObject *res; +- #line 420 "Python/bytecodes.c" ++ #line 421 "Python/bytecodes.c" + PyObject *slice = _PyBuildSlice_ConsumeRefs(start, stop); + // Can't use ERROR_IF() here, because we haven't + // DECREF'ed container yet, and we still own slice. +@@ -608,7 +608,7 @@ + PyObject *start = stack_pointer[-2]; + PyObject *container = stack_pointer[-3]; + PyObject *v = stack_pointer[-4]; +- #line 435 "Python/bytecodes.c" ++ #line 436 "Python/bytecodes.c" + PyObject *slice = _PyBuildSlice_ConsumeRefs(start, stop); + int err; + if (slice == NULL) { +@@ -630,7 +630,7 @@ + PyObject *sub = stack_pointer[-1]; + PyObject *list = stack_pointer[-2]; + PyObject *res; +- #line 450 "Python/bytecodes.c" ++ #line 451 "Python/bytecodes.c" + DEOPT_IF(!PyLong_CheckExact(sub), BINARY_SUBSCR); + DEOPT_IF(!PyList_CheckExact(list), BINARY_SUBSCR); + +@@ -655,7 +655,7 @@ + PyObject *sub = stack_pointer[-1]; + PyObject *tuple = stack_pointer[-2]; + PyObject *res; +- #line 466 "Python/bytecodes.c" ++ #line 467 "Python/bytecodes.c" + DEOPT_IF(!PyLong_CheckExact(sub), BINARY_SUBSCR); + DEOPT_IF(!PyTuple_CheckExact(tuple), BINARY_SUBSCR); + +@@ -680,7 +680,7 @@ + PyObject *sub = stack_pointer[-1]; + PyObject *dict = stack_pointer[-2]; + PyObject *res; +- #line 482 "Python/bytecodes.c" ++ #line 483 "Python/bytecodes.c" + DEOPT_IF(!PyDict_CheckExact(dict), BINARY_SUBSCR); + STAT_INC(BINARY_SUBSCR, hit); + res = PyDict_GetItemWithError(dict, sub); +@@ -691,7 +691,7 @@ + #line 692 "Python/generated_cases.c.h" + Py_DECREF(dict); + Py_DECREF(sub); +- #line 490 "Python/bytecodes.c" ++ #line 491 "Python/bytecodes.c" + if (true) goto pop_2_error; + } + Py_INCREF(res); // Do this before DECREF'ing dict, sub +@@ -707,7 +707,7 @@ + TARGET(BINARY_SUBSCR_GETITEM) { + PyObject *sub = stack_pointer[-1]; + PyObject *container = stack_pointer[-2]; +- #line 497 "Python/bytecodes.c" ++ #line 498 "Python/bytecodes.c" + DEOPT_IF(tstate->interp->eval_frame, BINARY_SUBSCR); + PyTypeObject *tp = Py_TYPE(container); + DEOPT_IF(!PyType_HasFeature(tp, Py_TPFLAGS_HEAPTYPE), BINARY_SUBSCR); +@@ -736,7 +736,7 @@ + TARGET(LIST_APPEND) { + PyObject *v = stack_pointer[-1]; + PyObject *list = stack_pointer[-(2 + (oparg-1))]; +- #line 522 "Python/bytecodes.c" ++ #line 523 "Python/bytecodes.c" + if (_PyList_AppendTakeRef((PyListObject *)list, v) < 0) goto pop_1_error; + #line 742 "Python/generated_cases.c.h" + STACK_SHRINK(1); +@@ -747,11 +747,11 @@ + TARGET(SET_ADD) { + PyObject *v = stack_pointer[-1]; + PyObject *set = stack_pointer[-(2 + (oparg-1))]; +- #line 527 "Python/bytecodes.c" ++ #line 528 "Python/bytecodes.c" + int err = PySet_Add(set, v); + #line 753 "Python/generated_cases.c.h" + Py_DECREF(v); +- #line 529 "Python/bytecodes.c" ++ #line 530 "Python/bytecodes.c" + if (err) goto pop_1_error; + #line 757 "Python/generated_cases.c.h" + STACK_SHRINK(1); +@@ -766,7 +766,7 @@ + PyObject *container = stack_pointer[-2]; + PyObject *v = stack_pointer[-3]; + uint16_t counter = read_u16(&next_instr[0].cache); +- #line 540 "Python/bytecodes.c" ++ #line 541 "Python/bytecodes.c" + #if ENABLE_SPECIALIZATION + if (ADAPTIVE_COUNTER_IS_ZERO(counter)) { + next_instr--; +@@ -785,7 +785,7 @@ + Py_DECREF(v); + Py_DECREF(container); + Py_DECREF(sub); +- #line 555 "Python/bytecodes.c" ++ #line 556 "Python/bytecodes.c" + if (err) goto pop_3_error; + #line 791 "Python/generated_cases.c.h" + STACK_SHRINK(3); +@@ -797,7 +797,7 @@ + PyObject *sub = stack_pointer[-1]; + PyObject *list = stack_pointer[-2]; + PyObject *value = stack_pointer[-3]; +- #line 559 "Python/bytecodes.c" ++ #line 560 "Python/bytecodes.c" + DEOPT_IF(!PyLong_CheckExact(sub), STORE_SUBSCR); + DEOPT_IF(!PyList_CheckExact(list), STORE_SUBSCR); + +@@ -824,7 +824,7 @@ + PyObject *sub = stack_pointer[-1]; + PyObject *dict = stack_pointer[-2]; + PyObject *value = stack_pointer[-3]; +- #line 578 "Python/bytecodes.c" ++ #line 579 "Python/bytecodes.c" + DEOPT_IF(!PyDict_CheckExact(dict), STORE_SUBSCR); + STAT_INC(STORE_SUBSCR, hit); + int err = _PyDict_SetItem_Take2((PyDictObject *)dict, sub, value); +@@ -839,13 +839,13 @@ + TARGET(DELETE_SUBSCR) { + PyObject *sub = stack_pointer[-1]; + PyObject *container = stack_pointer[-2]; +- #line 586 "Python/bytecodes.c" ++ #line 587 "Python/bytecodes.c" + /* del container[sub] */ + int err = PyObject_DelItem(container, sub); + #line 846 "Python/generated_cases.c.h" + Py_DECREF(container); + Py_DECREF(sub); +- #line 589 "Python/bytecodes.c" ++ #line 590 "Python/bytecodes.c" + if (err) goto pop_2_error; + #line 851 "Python/generated_cases.c.h" + STACK_SHRINK(2); +@@ -855,12 +855,12 @@ + TARGET(CALL_INTRINSIC_1) { + PyObject *value = stack_pointer[-1]; + PyObject *res; +- #line 593 "Python/bytecodes.c" ++ #line 594 "Python/bytecodes.c" + assert(oparg <= MAX_INTRINSIC_1); + res = _PyIntrinsics_UnaryFunctions[oparg](tstate, value); + #line 862 "Python/generated_cases.c.h" + Py_DECREF(value); +- #line 596 "Python/bytecodes.c" ++ #line 597 "Python/bytecodes.c" + if (res == NULL) goto pop_1_error; + #line 866 "Python/generated_cases.c.h" + stack_pointer[-1] = res; +@@ -871,13 +871,13 @@ + PyObject *value1 = stack_pointer[-1]; + PyObject *value2 = stack_pointer[-2]; + PyObject *res; +- #line 600 "Python/bytecodes.c" ++ #line 601 "Python/bytecodes.c" + assert(oparg <= MAX_INTRINSIC_2); + res = _PyIntrinsics_BinaryFunctions[oparg](tstate, value2, value1); + #line 878 "Python/generated_cases.c.h" + Py_DECREF(value2); + Py_DECREF(value1); +- #line 603 "Python/bytecodes.c" ++ #line 604 "Python/bytecodes.c" + if (res == NULL) goto pop_2_error; + #line 883 "Python/generated_cases.c.h" + STACK_SHRINK(1); +@@ -887,7 +887,7 @@ + + TARGET(RAISE_VARARGS) { + PyObject **args = (stack_pointer - oparg); +- #line 607 "Python/bytecodes.c" ++ #line 608 "Python/bytecodes.c" + PyObject *cause = NULL, *exc = NULL; + switch (oparg) { + case 2: +@@ -910,7 +910,7 @@ + + TARGET(INTERPRETER_EXIT) { + PyObject *retval = stack_pointer[-1]; +- #line 627 "Python/bytecodes.c" ++ #line 628 "Python/bytecodes.c" + assert(frame == &entry_frame); + assert(_PyFrame_IsIncomplete(frame)); + STACK_SHRINK(1); // Since we're not going to DISPATCH() +@@ -926,7 +926,7 @@ + + TARGET(RETURN_VALUE) { + PyObject *retval = stack_pointer[-1]; +- #line 640 "Python/bytecodes.c" ++ #line 641 "Python/bytecodes.c" + STACK_SHRINK(1); + assert(EMPTY()); + _PyFrame_SetStackPointer(frame, stack_pointer); +@@ -944,7 +944,7 @@ + + TARGET(INSTRUMENTED_RETURN_VALUE) { + PyObject *retval = stack_pointer[-1]; +- #line 655 "Python/bytecodes.c" ++ #line 656 "Python/bytecodes.c" + int err = _Py_call_instrumentation_arg( + tstate, PY_MONITORING_EVENT_PY_RETURN, + frame, next_instr-1, retval); +@@ -965,7 +965,7 @@ + } + + TARGET(RETURN_CONST) { +- #line 674 "Python/bytecodes.c" ++ #line 675 "Python/bytecodes.c" + PyObject *retval = GETITEM(frame->f_code->co_consts, oparg); + Py_INCREF(retval); + assert(EMPTY()); +@@ -983,7 +983,7 @@ + } + + TARGET(INSTRUMENTED_RETURN_CONST) { +- #line 690 "Python/bytecodes.c" ++ #line 691 "Python/bytecodes.c" + PyObject *retval = GETITEM(frame->f_code->co_consts, oparg); + int err = _Py_call_instrumentation_arg( + tstate, PY_MONITORING_EVENT_PY_RETURN, +@@ -1007,7 +1007,7 @@ + TARGET(GET_AITER) { + PyObject *obj = stack_pointer[-1]; + PyObject *iter; +- #line 710 "Python/bytecodes.c" ++ #line 711 "Python/bytecodes.c" + unaryfunc getter = NULL; + PyTypeObject *type = Py_TYPE(obj); + +@@ -1022,14 +1022,14 @@ + type->tp_name); + #line 1024 "Python/generated_cases.c.h" + Py_DECREF(obj); +- #line 723 "Python/bytecodes.c" ++ #line 724 "Python/bytecodes.c" + if (true) goto pop_1_error; + } + + iter = (*getter)(obj); + #line 1031 "Python/generated_cases.c.h" + Py_DECREF(obj); +- #line 728 "Python/bytecodes.c" ++ #line 729 "Python/bytecodes.c" + if (iter == NULL) goto pop_1_error; + + if (Py_TYPE(iter)->tp_as_async == NULL || +@@ -1050,7 +1050,7 @@ + TARGET(GET_ANEXT) { + PyObject *aiter = stack_pointer[-1]; + PyObject *awaitable; +- #line 743 "Python/bytecodes.c" ++ #line 744 "Python/bytecodes.c" + unaryfunc getter = NULL; + PyObject *next_iter = NULL; + PyTypeObject *type = Py_TYPE(aiter); +@@ -1105,7 +1105,7 @@ + PREDICTED(GET_AWAITABLE); + PyObject *iterable = stack_pointer[-1]; + PyObject *iter; +- #line 790 "Python/bytecodes.c" ++ #line 791 "Python/bytecodes.c" + iter = _PyCoro_GetAwaitableIter(iterable); + + if (iter == NULL) { +@@ -1114,7 +1114,7 @@ + + #line 1116 "Python/generated_cases.c.h" + Py_DECREF(iterable); +- #line 797 "Python/bytecodes.c" ++ #line 798 "Python/bytecodes.c" + + if (iter != NULL && PyCoro_CheckExact(iter)) { + PyObject *yf = _PyGen_yf((PyGenObject*)iter); +@@ -1144,7 +1144,7 @@ + PyObject *v = stack_pointer[-1]; + PyObject *receiver = stack_pointer[-2]; + PyObject *retval; +- #line 823 "Python/bytecodes.c" ++ #line 824 "Python/bytecodes.c" + #if ENABLE_SPECIALIZATION + _PySendCache *cache = (_PySendCache *)next_instr; + if (ADAPTIVE_COUNTER_IS_ZERO(cache->counter)) { +@@ -1200,7 +1200,7 @@ + TARGET(SEND_GEN) { + PyObject *v = stack_pointer[-1]; + PyObject *receiver = stack_pointer[-2]; +- #line 872 "Python/bytecodes.c" ++ #line 873 "Python/bytecodes.c" + DEOPT_IF(tstate->interp->eval_frame, SEND); + PyGenObject *gen = (PyGenObject *)receiver; + DEOPT_IF(Py_TYPE(gen) != &PyGen_Type && +@@ -1221,7 +1221,7 @@ + + TARGET(INSTRUMENTED_YIELD_VALUE) { + PyObject *retval = stack_pointer[-1]; +- #line 890 "Python/bytecodes.c" ++ #line 891 "Python/bytecodes.c" + assert(frame != &entry_frame); + PyGenObject *gen = _PyFrame_GetGenerator(frame); + gen->gi_frame_state = FRAME_SUSPENDED; +@@ -1243,7 +1243,7 @@ + + TARGET(YIELD_VALUE) { + PyObject *retval = stack_pointer[-1]; +- #line 909 "Python/bytecodes.c" ++ #line 910 "Python/bytecodes.c" + // NOTE: It's important that YIELD_VALUE never raises an exception! + // The compiler treats any exception raised here as a failed close() + // or throw() call. +@@ -1264,7 +1264,7 @@ + + TARGET(POP_EXCEPT) { + PyObject *exc_value = stack_pointer[-1]; +- #line 927 "Python/bytecodes.c" ++ #line 928 "Python/bytecodes.c" + _PyErr_StackItem *exc_info = tstate->exc_info; + Py_XSETREF(exc_info->exc_value, exc_value); + #line 1271 "Python/generated_cases.c.h" +@@ -1275,7 +1275,7 @@ + TARGET(RERAISE) { + PyObject *exc = stack_pointer[-1]; + PyObject **values = (stack_pointer - (1 + oparg)); +- #line 932 "Python/bytecodes.c" ++ #line 933 "Python/bytecodes.c" + assert(oparg >= 0 && oparg <= 2); + if (oparg) { + PyObject *lasti = values[0]; +@@ -1299,13 +1299,13 @@ + TARGET(END_ASYNC_FOR) { + PyObject *exc = stack_pointer[-1]; + PyObject *awaitable = stack_pointer[-2]; +- #line 952 "Python/bytecodes.c" ++ #line 953 "Python/bytecodes.c" + assert(exc && PyExceptionInstance_Check(exc)); + if (PyErr_GivenExceptionMatches(exc, PyExc_StopAsyncIteration)) { + #line 1306 "Python/generated_cases.c.h" + Py_DECREF(awaitable); + Py_DECREF(exc); +- #line 955 "Python/bytecodes.c" ++ #line 956 "Python/bytecodes.c" + } + else { + Py_INCREF(exc); +@@ -1323,7 +1323,7 @@ + PyObject *sub_iter = stack_pointer[-3]; + PyObject *none; + PyObject *value; +- #line 964 "Python/bytecodes.c" ++ #line 965 "Python/bytecodes.c" + assert(throwflag); + assert(exc_value && PyExceptionInstance_Check(exc_value)); + if (PyErr_GivenExceptionMatches(exc_value, PyExc_StopIteration)) { +@@ -1332,7 +1332,7 @@ + Py_DECREF(sub_iter); + Py_DECREF(last_sent_val); + Py_DECREF(exc_value); +- #line 969 "Python/bytecodes.c" ++ #line 970 "Python/bytecodes.c" + none = Py_NewRef(Py_None); + } + else { +@@ -1348,7 +1348,7 @@ + + TARGET(LOAD_ASSERTION_ERROR) { + PyObject *value; +- #line 978 "Python/bytecodes.c" ++ #line 979 "Python/bytecodes.c" + value = Py_NewRef(PyExc_AssertionError); + #line 1354 "Python/generated_cases.c.h" + STACK_GROW(1); +@@ -1358,7 +1358,7 @@ + + TARGET(LOAD_BUILD_CLASS) { + PyObject *bc; +- #line 982 "Python/bytecodes.c" ++ #line 983 "Python/bytecodes.c" + if (PyDict_CheckExact(BUILTINS())) { + bc = _PyDict_GetItemWithError(BUILTINS(), + &_Py_ID(__build_class__)); +@@ -1388,7 +1388,7 @@ + + TARGET(STORE_NAME) { + PyObject *v = stack_pointer[-1]; +- #line 1006 "Python/bytecodes.c" ++ #line 1008 "Python/bytecodes.c" + PyObject *name = GETITEM(frame->f_code->co_names, oparg); + PyObject *ns = LOCALS(); + int err; +@@ -1397,7 +1397,7 @@ + "no locals found when storing %R", name); + #line 1399 "Python/generated_cases.c.h" + Py_DECREF(v); +- #line 1013 "Python/bytecodes.c" ++ #line 1015 "Python/bytecodes.c" + if (true) goto pop_1_error; + } + if (PyDict_CheckExact(ns)) +@@ -1406,7 +1406,7 @@ + err = PyObject_SetItem(ns, name, v); + #line 1408 "Python/generated_cases.c.h" + Py_DECREF(v); +- #line 1020 "Python/bytecodes.c" ++ #line 1022 "Python/bytecodes.c" + if (err) goto pop_1_error; + #line 1412 "Python/generated_cases.c.h" + STACK_SHRINK(1); +@@ -1414,7 +1414,7 @@ + } + + TARGET(DELETE_NAME) { +- #line 1024 "Python/bytecodes.c" ++ #line 1026 "Python/bytecodes.c" + PyObject *name = GETITEM(frame->f_code->co_names, oparg); + PyObject *ns = LOCALS(); + int err; +@@ -1439,7 +1439,7 @@ + PREDICTED(UNPACK_SEQUENCE); + static_assert(INLINE_CACHE_ENTRIES_UNPACK_SEQUENCE == 1, "incorrect cache size"); + PyObject *seq = stack_pointer[-1]; +- #line 1050 "Python/bytecodes.c" ++ #line 1052 "Python/bytecodes.c" + #if ENABLE_SPECIALIZATION + _PyUnpackSequenceCache *cache = (_PyUnpackSequenceCache *)next_instr; + if (ADAPTIVE_COUNTER_IS_ZERO(cache->counter)) { +@@ -1454,7 +1454,7 @@ + int res = unpack_iterable(tstate, seq, oparg, -1, top); + #line 1456 "Python/generated_cases.c.h" + Py_DECREF(seq); +- #line 1063 "Python/bytecodes.c" ++ #line 1065 "Python/bytecodes.c" + if (res == 0) goto pop_1_error; + #line 1460 "Python/generated_cases.c.h" + STACK_SHRINK(1); +@@ -1466,7 +1466,7 @@ + TARGET(UNPACK_SEQUENCE_TWO_TUPLE) { + PyObject *seq = stack_pointer[-1]; + PyObject **values = stack_pointer - (1); +- #line 1067 "Python/bytecodes.c" ++ #line 1069 "Python/bytecodes.c" + DEOPT_IF(!PyTuple_CheckExact(seq), UNPACK_SEQUENCE); + DEOPT_IF(PyTuple_GET_SIZE(seq) != 2, UNPACK_SEQUENCE); + assert(oparg == 2); +@@ -1484,7 +1484,7 @@ + TARGET(UNPACK_SEQUENCE_TUPLE) { + PyObject *seq = stack_pointer[-1]; + PyObject **values = stack_pointer - (1); +- #line 1077 "Python/bytecodes.c" ++ #line 1079 "Python/bytecodes.c" + DEOPT_IF(!PyTuple_CheckExact(seq), UNPACK_SEQUENCE); + DEOPT_IF(PyTuple_GET_SIZE(seq) != oparg, UNPACK_SEQUENCE); + STAT_INC(UNPACK_SEQUENCE, hit); +@@ -1503,7 +1503,7 @@ + TARGET(UNPACK_SEQUENCE_LIST) { + PyObject *seq = stack_pointer[-1]; + PyObject **values = stack_pointer - (1); +- #line 1088 "Python/bytecodes.c" ++ #line 1090 "Python/bytecodes.c" + DEOPT_IF(!PyList_CheckExact(seq), UNPACK_SEQUENCE); + DEOPT_IF(PyList_GET_SIZE(seq) != oparg, UNPACK_SEQUENCE); + STAT_INC(UNPACK_SEQUENCE, hit); +@@ -1521,13 +1521,13 @@ + + TARGET(UNPACK_EX) { + PyObject *seq = stack_pointer[-1]; +- #line 1099 "Python/bytecodes.c" ++ #line 1101 "Python/bytecodes.c" + int totalargs = 1 + (oparg & 0xFF) + (oparg >> 8); + PyObject **top = stack_pointer + totalargs - 1; + int res = unpack_iterable(tstate, seq, oparg & 0xFF, oparg >> 8, top); + #line 1529 "Python/generated_cases.c.h" + Py_DECREF(seq); +- #line 1103 "Python/bytecodes.c" ++ #line 1105 "Python/bytecodes.c" + if (res == 0) goto pop_1_error; + #line 1533 "Python/generated_cases.c.h" + STACK_GROW((oparg & 0xFF) + (oparg >> 8)); +@@ -1540,7 +1540,7 @@ + PyObject *owner = stack_pointer[-1]; + PyObject *v = stack_pointer[-2]; + uint16_t counter = read_u16(&next_instr[0].cache); +- #line 1114 "Python/bytecodes.c" ++ #line 1116 "Python/bytecodes.c" + #if ENABLE_SPECIALIZATION + if (ADAPTIVE_COUNTER_IS_ZERO(counter)) { + PyObject *name = GETITEM(frame->f_code->co_names, oparg); +@@ -1559,7 +1559,7 @@ + #line 1560 "Python/generated_cases.c.h" + Py_DECREF(v); + Py_DECREF(owner); +- #line 1130 "Python/bytecodes.c" ++ #line 1132 "Python/bytecodes.c" + if (err) goto pop_2_error; + #line 1565 "Python/generated_cases.c.h" + STACK_SHRINK(2); +@@ -1569,12 +1569,12 @@ + + TARGET(DELETE_ATTR) { + PyObject *owner = stack_pointer[-1]; +- #line 1134 "Python/bytecodes.c" ++ #line 1136 "Python/bytecodes.c" + PyObject *name = GETITEM(frame->f_code->co_names, oparg); + int err = PyObject_SetAttr(owner, name, (PyObject *)NULL); + #line 1576 "Python/generated_cases.c.h" + Py_DECREF(owner); +- #line 1137 "Python/bytecodes.c" ++ #line 1139 "Python/bytecodes.c" + if (err) goto pop_1_error; + #line 1580 "Python/generated_cases.c.h" + STACK_SHRINK(1); +@@ -1583,12 +1583,12 @@ + + TARGET(STORE_GLOBAL) { + PyObject *v = stack_pointer[-1]; +- #line 1141 "Python/bytecodes.c" ++ #line 1143 "Python/bytecodes.c" + PyObject *name = GETITEM(frame->f_code->co_names, oparg); + int err = PyDict_SetItem(GLOBALS(), name, v); + #line 1590 "Python/generated_cases.c.h" + Py_DECREF(v); +- #line 1144 "Python/bytecodes.c" ++ #line 1146 "Python/bytecodes.c" + if (err) goto pop_1_error; + #line 1594 "Python/generated_cases.c.h" + STACK_SHRINK(1); +@@ -1596,7 +1596,7 @@ + } + + TARGET(DELETE_GLOBAL) { +- #line 1148 "Python/bytecodes.c" ++ #line 1150 "Python/bytecodes.c" + PyObject *name = GETITEM(frame->f_code->co_names, oparg); + int err; + err = PyDict_DelItem(GLOBALS(), name); +@@ -1612,70 +1612,175 @@ + DISPATCH(); + } + ++ TARGET(LOAD_LOCALS) { ++ PyObject *_tmp_1; ++ { ++ PyObject *locals; ++ #line 1164 "Python/bytecodes.c" ++ locals = LOCALS(); ++ if (locals == NULL) { ++ _PyErr_SetString(tstate, PyExc_SystemError, ++ "no locals found"); ++ if (true) goto error; ++ } ++ Py_INCREF(locals); ++ #line 1628 "Python/generated_cases.c.h" ++ _tmp_1 = locals; ++ } ++ STACK_GROW(1); ++ stack_pointer[-1] = _tmp_1; ++ DISPATCH(); ++ } ++ + TARGET(LOAD_NAME) { +- PyObject *v; +- #line 1162 "Python/bytecodes.c" +- PyObject *name = GETITEM(frame->f_code->co_names, oparg); +- PyObject *locals = LOCALS(); +- if (locals == NULL) { +- _PyErr_Format(tstate, PyExc_SystemError, +- "no locals when loading %R", name); +- goto error; ++ PyObject *_tmp_1; ++ { ++ PyObject *locals; ++ #line 1164 "Python/bytecodes.c" ++ locals = LOCALS(); ++ if (locals == NULL) { ++ _PyErr_SetString(tstate, PyExc_SystemError, ++ "no locals found"); ++ if (true) goto error; ++ } ++ Py_INCREF(locals); ++ #line 1648 "Python/generated_cases.c.h" ++ _tmp_1 = locals; + } +- if (PyDict_CheckExact(locals)) { +- v = PyDict_GetItemWithError(locals, name); +- if (v != NULL) { +- Py_INCREF(v); ++ { ++ PyObject *mod_or_class_dict = _tmp_1; ++ PyObject *v; ++ #line 1176 "Python/bytecodes.c" ++ PyObject *name = GETITEM(frame->f_code->co_names, oparg); ++ if (PyDict_CheckExact(mod_or_class_dict)) { ++ v = PyDict_GetItemWithError(mod_or_class_dict, name); ++ if (v != NULL) { ++ Py_INCREF(v); ++ } ++ else if (_PyErr_Occurred(tstate)) { ++ Py_DECREF(mod_or_class_dict); ++ goto error; ++ } + } +- else if (_PyErr_Occurred(tstate)) { +- goto error; ++ else { ++ v = PyObject_GetItem(mod_or_class_dict, name); ++ if (v == NULL) { ++ if (!_PyErr_ExceptionMatches(tstate, PyExc_KeyError)) { ++ Py_DECREF(mod_or_class_dict); ++ goto error; ++ } ++ _PyErr_Clear(tstate); ++ } + } +- } +- else { +- v = PyObject_GetItem(locals, name); ++ Py_DECREF(mod_or_class_dict); + if (v == NULL) { +- if (!_PyErr_ExceptionMatches(tstate, PyExc_KeyError)) ++ v = PyDict_GetItemWithError(GLOBALS(), name); ++ if (v != NULL) { ++ Py_INCREF(v); ++ } ++ else if (_PyErr_Occurred(tstate)) { + goto error; +- _PyErr_Clear(tstate); ++ } ++ else { ++ if (PyDict_CheckExact(BUILTINS())) { ++ v = PyDict_GetItemWithError(BUILTINS(), name); ++ if (v == NULL) { ++ if (!_PyErr_Occurred(tstate)) { ++ format_exc_check_arg( ++ tstate, PyExc_NameError, ++ NAME_ERROR_MSG, name); ++ } ++ goto error; ++ } ++ Py_INCREF(v); ++ } ++ else { ++ v = PyObject_GetItem(BUILTINS(), name); ++ if (v == NULL) { ++ if (_PyErr_ExceptionMatches(tstate, PyExc_KeyError)) { ++ format_exc_check_arg( ++ tstate, PyExc_NameError, ++ NAME_ERROR_MSG, name); ++ } ++ goto error; ++ } ++ } ++ } + } ++ #line 1711 "Python/generated_cases.c.h" ++ _tmp_1 = v; + } +- if (v == NULL) { +- v = PyDict_GetItemWithError(GLOBALS(), name); +- if (v != NULL) { +- Py_INCREF(v); +- } +- else if (_PyErr_Occurred(tstate)) { +- goto error; ++ STACK_GROW(1); ++ stack_pointer[-1] = _tmp_1; ++ DISPATCH(); ++ } ++ ++ TARGET(LOAD_FROM_DICT_OR_GLOBALS) { ++ PyObject *_tmp_1 = stack_pointer[-1]; ++ { ++ PyObject *mod_or_class_dict = _tmp_1; ++ PyObject *v; ++ #line 1176 "Python/bytecodes.c" ++ PyObject *name = GETITEM(frame->f_code->co_names, oparg); ++ if (PyDict_CheckExact(mod_or_class_dict)) { ++ v = PyDict_GetItemWithError(mod_or_class_dict, name); ++ if (v != NULL) { ++ Py_INCREF(v); ++ } ++ else if (_PyErr_Occurred(tstate)) { ++ Py_DECREF(mod_or_class_dict); ++ goto error; ++ } + } + else { +- if (PyDict_CheckExact(BUILTINS())) { +- v = PyDict_GetItemWithError(BUILTINS(), name); +- if (v == NULL) { +- if (!_PyErr_Occurred(tstate)) { +- format_exc_check_arg( +- tstate, PyExc_NameError, +- NAME_ERROR_MSG, name); +- } ++ v = PyObject_GetItem(mod_or_class_dict, name); ++ if (v == NULL) { ++ if (!_PyErr_ExceptionMatches(tstate, PyExc_KeyError)) { ++ Py_DECREF(mod_or_class_dict); + goto error; + } ++ _PyErr_Clear(tstate); ++ } ++ } ++ Py_DECREF(mod_or_class_dict); ++ if (v == NULL) { ++ v = PyDict_GetItemWithError(GLOBALS(), name); ++ if (v != NULL) { + Py_INCREF(v); + } ++ else if (_PyErr_Occurred(tstate)) { ++ goto error; ++ } + else { +- v = PyObject_GetItem(BUILTINS(), name); +- if (v == NULL) { +- if (_PyErr_ExceptionMatches(tstate, PyExc_KeyError)) { +- format_exc_check_arg( ++ if (PyDict_CheckExact(BUILTINS())) { ++ v = PyDict_GetItemWithError(BUILTINS(), name); ++ if (v == NULL) { ++ if (!_PyErr_Occurred(tstate)) { ++ format_exc_check_arg( + tstate, PyExc_NameError, + NAME_ERROR_MSG, name); ++ } ++ goto error; ++ } ++ Py_INCREF(v); ++ } ++ else { ++ v = PyObject_GetItem(BUILTINS(), name); ++ if (v == NULL) { ++ if (_PyErr_ExceptionMatches(tstate, PyExc_KeyError)) { ++ format_exc_check_arg( ++ tstate, PyExc_NameError, ++ NAME_ERROR_MSG, name); ++ } ++ goto error; + } +- goto error; + } + } + } ++ #line 1781 "Python/generated_cases.c.h" ++ _tmp_1 = v; + } +- #line 1677 "Python/generated_cases.c.h" +- STACK_GROW(1); +- stack_pointer[-1] = v; ++ stack_pointer[-1] = _tmp_1; + DISPATCH(); + } + +@@ -1684,7 +1789,7 @@ + static_assert(INLINE_CACHE_ENTRIES_LOAD_GLOBAL == 4, "incorrect cache size"); + PyObject *null = NULL; + PyObject *v; +- #line 1229 "Python/bytecodes.c" ++ #line 1245 "Python/bytecodes.c" + #if ENABLE_SPECIALIZATION + _PyLoadGlobalCache *cache = (_PyLoadGlobalCache *)next_instr; + if (ADAPTIVE_COUNTER_IS_ZERO(cache->counter)) { +@@ -1736,7 +1841,7 @@ + } + } + null = NULL; +- #line 1740 "Python/generated_cases.c.h" ++ #line 1845 "Python/generated_cases.c.h" + STACK_GROW(1); + STACK_GROW(((oparg & 1) ? 1 : 0)); + stack_pointer[-1] = v; +@@ -1750,7 +1855,7 @@ + PyObject *res; + uint16_t index = read_u16(&next_instr[1].cache); + uint16_t version = read_u16(&next_instr[2].cache); +- #line 1283 "Python/bytecodes.c" ++ #line 1299 "Python/bytecodes.c" + DEOPT_IF(!PyDict_CheckExact(GLOBALS()), LOAD_GLOBAL); + PyDictObject *dict = (PyDictObject *)GLOBALS(); + DEOPT_IF(dict->ma_keys->dk_version != version, LOAD_GLOBAL); +@@ -1761,7 +1866,7 @@ + Py_INCREF(res); + STAT_INC(LOAD_GLOBAL, hit); + null = NULL; +- #line 1765 "Python/generated_cases.c.h" ++ #line 1870 "Python/generated_cases.c.h" + STACK_GROW(1); + STACK_GROW(((oparg & 1) ? 1 : 0)); + stack_pointer[-1] = res; +@@ -1776,7 +1881,7 @@ + uint16_t index = read_u16(&next_instr[1].cache); + uint16_t mod_version = read_u16(&next_instr[2].cache); + uint16_t bltn_version = read_u16(&next_instr[3].cache); +- #line 1296 "Python/bytecodes.c" ++ #line 1312 "Python/bytecodes.c" + DEOPT_IF(!PyDict_CheckExact(GLOBALS()), LOAD_GLOBAL); + DEOPT_IF(!PyDict_CheckExact(BUILTINS()), LOAD_GLOBAL); + PyDictObject *mdict = (PyDictObject *)GLOBALS(); +@@ -1791,7 +1896,7 @@ + Py_INCREF(res); + STAT_INC(LOAD_GLOBAL, hit); + null = NULL; +- #line 1795 "Python/generated_cases.c.h" ++ #line 1900 "Python/generated_cases.c.h" + STACK_GROW(1); + STACK_GROW(((oparg & 1) ? 1 : 0)); + stack_pointer[-1] = res; +@@ -1801,16 +1906,16 @@ + } + + TARGET(DELETE_FAST) { +- #line 1313 "Python/bytecodes.c" ++ #line 1329 "Python/bytecodes.c" + PyObject *v = GETLOCAL(oparg); + if (v == NULL) goto unbound_local_error; + SETLOCAL(oparg, NULL); +- #line 1809 "Python/generated_cases.c.h" ++ #line 1914 "Python/generated_cases.c.h" + DISPATCH(); + } + + TARGET(MAKE_CELL) { +- #line 1319 "Python/bytecodes.c" ++ #line 1335 "Python/bytecodes.c" + // "initial" is probably NULL but not if it's an arg (or set + // via PyFrame_LocalsToFast() before MAKE_CELL has run). + PyObject *initial = GETLOCAL(oparg); +@@ -1819,12 +1924,12 @@ + goto resume_with_error; + } + SETLOCAL(oparg, cell); +- #line 1823 "Python/generated_cases.c.h" ++ #line 1928 "Python/generated_cases.c.h" + DISPATCH(); + } + + TARGET(DELETE_DEREF) { +- #line 1330 "Python/bytecodes.c" ++ #line 1346 "Python/bytecodes.c" + PyObject *cell = GETLOCAL(oparg); + PyObject *oldobj = PyCell_GET(cell); + // Can't use ERROR_IF here. +@@ -1835,35 +1940,39 @@ + } + PyCell_SET(cell, NULL); + Py_DECREF(oldobj); +- #line 1839 "Python/generated_cases.c.h" ++ #line 1944 "Python/generated_cases.c.h" + DISPATCH(); + } + +- TARGET(LOAD_CLASSDEREF) { ++ TARGET(LOAD_FROM_DICT_OR_DEREF) { ++ PyObject *class_dict = stack_pointer[-1]; + PyObject *value; +- #line 1343 "Python/bytecodes.c" +- PyObject *name, *locals = LOCALS(); +- assert(locals); ++ #line 1359 "Python/bytecodes.c" ++ PyObject *name; ++ assert(class_dict); + assert(oparg >= 0 && oparg < frame->f_code->co_nlocalsplus); + name = PyTuple_GET_ITEM(frame->f_code->co_localsplusnames, oparg); +- if (PyDict_CheckExact(locals)) { +- value = PyDict_GetItemWithError(locals, name); ++ if (PyDict_CheckExact(class_dict)) { ++ value = PyDict_GetItemWithError(class_dict, name); + if (value != NULL) { + Py_INCREF(value); + } + else if (_PyErr_Occurred(tstate)) { ++ Py_DECREF(class_dict); + goto error; + } + } + else { +- value = PyObject_GetItem(locals, name); ++ value = PyObject_GetItem(class_dict, name); + if (value == NULL) { + if (!_PyErr_ExceptionMatches(tstate, PyExc_KeyError)) { ++ Py_DECREF(class_dict); + goto error; + } + _PyErr_Clear(tstate); + } + } ++ Py_DECREF(class_dict); + if (!value) { + PyObject *cell = GETLOCAL(oparg); + value = PyCell_GET(cell); +@@ -1873,15 +1982,14 @@ + } + Py_INCREF(value); + } +- #line 1877 "Python/generated_cases.c.h" +- STACK_GROW(1); ++ #line 1986 "Python/generated_cases.c.h" + stack_pointer[-1] = value; + DISPATCH(); + } + + TARGET(LOAD_DEREF) { + PyObject *value; +- #line 1377 "Python/bytecodes.c" ++ #line 1396 "Python/bytecodes.c" + PyObject *cell = GETLOCAL(oparg); + value = PyCell_GET(cell); + if (value == NULL) { +@@ -1889,7 +1997,7 @@ + if (true) goto error; + } + Py_INCREF(value); +- #line 1893 "Python/generated_cases.c.h" ++ #line 2001 "Python/generated_cases.c.h" + STACK_GROW(1); + stack_pointer[-1] = value; + DISPATCH(); +@@ -1897,18 +2005,18 @@ + + TARGET(STORE_DEREF) { + PyObject *v = stack_pointer[-1]; +- #line 1387 "Python/bytecodes.c" ++ #line 1406 "Python/bytecodes.c" + PyObject *cell = GETLOCAL(oparg); + PyObject *oldobj = PyCell_GET(cell); + PyCell_SET(cell, v); + Py_XDECREF(oldobj); +- #line 1906 "Python/generated_cases.c.h" ++ #line 2014 "Python/generated_cases.c.h" + STACK_SHRINK(1); + DISPATCH(); + } + + TARGET(COPY_FREE_VARS) { +- #line 1394 "Python/bytecodes.c" ++ #line 1413 "Python/bytecodes.c" + /* Copy closure variables to free variables */ + PyCodeObject *co = frame->f_code; + assert(PyFunction_Check(frame->f_funcobj)); +@@ -1919,22 +2027,22 @@ + PyObject *o = PyTuple_GET_ITEM(closure, i); + frame->localsplus[offset + i] = Py_NewRef(o); + } +- #line 1923 "Python/generated_cases.c.h" ++ #line 2031 "Python/generated_cases.c.h" + DISPATCH(); + } + + TARGET(BUILD_STRING) { + PyObject **pieces = (stack_pointer - oparg); + PyObject *str; +- #line 1407 "Python/bytecodes.c" ++ #line 1426 "Python/bytecodes.c" + str = _PyUnicode_JoinArray(&_Py_STR(empty), pieces, oparg); +- #line 1932 "Python/generated_cases.c.h" ++ #line 2040 "Python/generated_cases.c.h" + for (int _i = oparg; --_i >= 0;) { + Py_DECREF(pieces[_i]); + } +- #line 1409 "Python/bytecodes.c" ++ #line 1428 "Python/bytecodes.c" + if (str == NULL) { STACK_SHRINK(oparg); goto error; } +- #line 1938 "Python/generated_cases.c.h" ++ #line 2046 "Python/generated_cases.c.h" + STACK_SHRINK(oparg); + STACK_GROW(1); + stack_pointer[-1] = str; +@@ -1944,10 +2052,10 @@ + TARGET(BUILD_TUPLE) { + PyObject **values = (stack_pointer - oparg); + PyObject *tup; +- #line 1413 "Python/bytecodes.c" ++ #line 1432 "Python/bytecodes.c" + tup = _PyTuple_FromArraySteal(values, oparg); + if (tup == NULL) { STACK_SHRINK(oparg); goto error; } +- #line 1951 "Python/generated_cases.c.h" ++ #line 2059 "Python/generated_cases.c.h" + STACK_SHRINK(oparg); + STACK_GROW(1); + stack_pointer[-1] = tup; +@@ -1957,10 +2065,10 @@ + TARGET(BUILD_LIST) { + PyObject **values = (stack_pointer - oparg); + PyObject *list; +- #line 1418 "Python/bytecodes.c" ++ #line 1437 "Python/bytecodes.c" + list = _PyList_FromArraySteal(values, oparg); + if (list == NULL) { STACK_SHRINK(oparg); goto error; } +- #line 1964 "Python/generated_cases.c.h" ++ #line 2072 "Python/generated_cases.c.h" + STACK_SHRINK(oparg); + STACK_GROW(1); + stack_pointer[-1] = list; +@@ -1970,7 +2078,7 @@ + TARGET(LIST_EXTEND) { + PyObject *iterable = stack_pointer[-1]; + PyObject *list = stack_pointer[-(2 + (oparg-1))]; +- #line 1423 "Python/bytecodes.c" ++ #line 1442 "Python/bytecodes.c" + PyObject *none_val = _PyList_Extend((PyListObject *)list, iterable); + if (none_val == NULL) { + if (_PyErr_ExceptionMatches(tstate, PyExc_TypeError) && +@@ -1981,13 +2089,13 @@ + "Value after * must be an iterable, not %.200s", + Py_TYPE(iterable)->tp_name); + } +- #line 1985 "Python/generated_cases.c.h" ++ #line 2093 "Python/generated_cases.c.h" + Py_DECREF(iterable); +- #line 1434 "Python/bytecodes.c" ++ #line 1453 "Python/bytecodes.c" + if (true) goto pop_1_error; + } + Py_DECREF(none_val); +- #line 1991 "Python/generated_cases.c.h" ++ #line 2099 "Python/generated_cases.c.h" + Py_DECREF(iterable); + STACK_SHRINK(1); + DISPATCH(); +@@ -1996,13 +2104,13 @@ + TARGET(SET_UPDATE) { + PyObject *iterable = stack_pointer[-1]; + PyObject *set = stack_pointer[-(2 + (oparg-1))]; +- #line 1441 "Python/bytecodes.c" ++ #line 1460 "Python/bytecodes.c" + int err = _PySet_Update(set, iterable); +- #line 2002 "Python/generated_cases.c.h" ++ #line 2110 "Python/generated_cases.c.h" + Py_DECREF(iterable); +- #line 1443 "Python/bytecodes.c" ++ #line 1462 "Python/bytecodes.c" + if (err < 0) goto pop_1_error; +- #line 2006 "Python/generated_cases.c.h" ++ #line 2114 "Python/generated_cases.c.h" + STACK_SHRINK(1); + DISPATCH(); + } +@@ -2010,7 +2118,7 @@ + TARGET(BUILD_SET) { + PyObject **values = (stack_pointer - oparg); + PyObject *set; +- #line 1447 "Python/bytecodes.c" ++ #line 1466 "Python/bytecodes.c" + set = PySet_New(NULL); + if (set == NULL) + goto error; +@@ -2025,7 +2133,7 @@ + Py_DECREF(set); + if (true) { STACK_SHRINK(oparg); goto error; } + } +- #line 2029 "Python/generated_cases.c.h" ++ #line 2137 "Python/generated_cases.c.h" + STACK_SHRINK(oparg); + STACK_GROW(1); + stack_pointer[-1] = set; +@@ -2035,7 +2143,7 @@ + TARGET(BUILD_MAP) { + PyObject **values = (stack_pointer - oparg*2); + PyObject *map; +- #line 1464 "Python/bytecodes.c" ++ #line 1483 "Python/bytecodes.c" + map = _PyDict_FromItems( + values, 2, + values+1, 2, +@@ -2043,13 +2151,13 @@ + if (map == NULL) + goto error; + +- #line 2047 "Python/generated_cases.c.h" ++ #line 2155 "Python/generated_cases.c.h" + for (int _i = oparg*2; --_i >= 0;) { + Py_DECREF(values[_i]); + } +- #line 1472 "Python/bytecodes.c" ++ #line 1491 "Python/bytecodes.c" + if (map == NULL) { STACK_SHRINK(oparg*2); goto error; } +- #line 2053 "Python/generated_cases.c.h" ++ #line 2161 "Python/generated_cases.c.h" + STACK_SHRINK(oparg*2); + STACK_GROW(1); + stack_pointer[-1] = map; +@@ -2057,7 +2165,7 @@ + } + + TARGET(SETUP_ANNOTATIONS) { +- #line 1476 "Python/bytecodes.c" ++ #line 1495 "Python/bytecodes.c" + int err; + PyObject *ann_dict; + if (LOCALS() == NULL) { +@@ -2097,7 +2205,7 @@ + Py_DECREF(ann_dict); + } + } +- #line 2101 "Python/generated_cases.c.h" ++ #line 2209 "Python/generated_cases.c.h" + DISPATCH(); + } + +@@ -2105,7 +2213,7 @@ + PyObject *keys = stack_pointer[-1]; + PyObject **values = (stack_pointer - (1 + oparg)); + PyObject *map; +- #line 1518 "Python/bytecodes.c" ++ #line 1537 "Python/bytecodes.c" + if (!PyTuple_CheckExact(keys) || + PyTuple_GET_SIZE(keys) != (Py_ssize_t)oparg) { + _PyErr_SetString(tstate, PyExc_SystemError, +@@ -2115,14 +2223,14 @@ + map = _PyDict_FromItems( + &PyTuple_GET_ITEM(keys, 0), 1, + values, 1, oparg); +- #line 2119 "Python/generated_cases.c.h" ++ #line 2227 "Python/generated_cases.c.h" + for (int _i = oparg; --_i >= 0;) { + Py_DECREF(values[_i]); + } + Py_DECREF(keys); +- #line 1528 "Python/bytecodes.c" ++ #line 1547 "Python/bytecodes.c" + if (map == NULL) { STACK_SHRINK(oparg); goto pop_1_error; } +- #line 2126 "Python/generated_cases.c.h" ++ #line 2234 "Python/generated_cases.c.h" + STACK_SHRINK(oparg); + stack_pointer[-1] = map; + DISPATCH(); +@@ -2130,7 +2238,7 @@ + + TARGET(DICT_UPDATE) { + PyObject *update = stack_pointer[-1]; +- #line 1532 "Python/bytecodes.c" ++ #line 1551 "Python/bytecodes.c" + PyObject *dict = PEEK(oparg + 1); // update is still on the stack + if (PyDict_Update(dict, update) < 0) { + if (_PyErr_ExceptionMatches(tstate, PyExc_AttributeError)) { +@@ -2138,12 +2246,12 @@ + "'%.200s' object is not a mapping", + Py_TYPE(update)->tp_name); + } +- #line 2142 "Python/generated_cases.c.h" ++ #line 2250 "Python/generated_cases.c.h" + Py_DECREF(update); +- #line 1540 "Python/bytecodes.c" ++ #line 1559 "Python/bytecodes.c" + if (true) goto pop_1_error; + } +- #line 2147 "Python/generated_cases.c.h" ++ #line 2255 "Python/generated_cases.c.h" + Py_DECREF(update); + STACK_SHRINK(1); + DISPATCH(); +@@ -2151,17 +2259,17 @@ + + TARGET(DICT_MERGE) { + PyObject *update = stack_pointer[-1]; +- #line 1546 "Python/bytecodes.c" ++ #line 1565 "Python/bytecodes.c" + PyObject *dict = PEEK(oparg + 1); // update is still on the stack + + if (_PyDict_MergeEx(dict, update, 2) < 0) { + format_kwargs_error(tstate, PEEK(3 + oparg), update); +- #line 2160 "Python/generated_cases.c.h" ++ #line 2268 "Python/generated_cases.c.h" + Py_DECREF(update); +- #line 1551 "Python/bytecodes.c" ++ #line 1570 "Python/bytecodes.c" + if (true) goto pop_1_error; + } +- #line 2165 "Python/generated_cases.c.h" ++ #line 2273 "Python/generated_cases.c.h" + Py_DECREF(update); + STACK_SHRINK(1); + PREDICT(CALL_FUNCTION_EX); +@@ -2171,13 +2279,13 @@ + TARGET(MAP_ADD) { + PyObject *value = stack_pointer[-1]; + PyObject *key = stack_pointer[-2]; +- #line 1558 "Python/bytecodes.c" ++ #line 1577 "Python/bytecodes.c" + PyObject *dict = PEEK(oparg + 2); // key, value are still on the stack + assert(PyDict_CheckExact(dict)); + /* dict[key] = value */ + // Do not DECREF INPUTS because the function steals the references + if (_PyDict_SetItem_Take2((PyDictObject *)dict, key, value) != 0) goto pop_2_error; +- #line 2181 "Python/generated_cases.c.h" ++ #line 2289 "Python/generated_cases.c.h" + STACK_SHRINK(2); + PREDICT(JUMP_BACKWARD); + DISPATCH(); +@@ -2191,7 +2299,7 @@ + PyObject *global_super = stack_pointer[-3]; + PyObject *res2 = NULL; + PyObject *res; +- #line 1573 "Python/bytecodes.c" ++ #line 1592 "Python/bytecodes.c" + PyObject *name = GETITEM(frame->f_code->co_names, oparg >> 2); + int load_method = oparg & 1; + #if ENABLE_SPECIALIZATION +@@ -2209,16 +2317,16 @@ + // handle any case whose performance we care about + PyObject *stack[] = {class, self}; + PyObject *super = PyObject_Vectorcall(global_super, stack, oparg & 2, NULL); +- #line 2213 "Python/generated_cases.c.h" ++ #line 2321 "Python/generated_cases.c.h" + Py_DECREF(global_super); + Py_DECREF(class); + Py_DECREF(self); +- #line 1591 "Python/bytecodes.c" ++ #line 1610 "Python/bytecodes.c" + if (super == NULL) goto pop_3_error; + res = PyObject_GetAttr(super, name); + Py_DECREF(super); + if (res == NULL) goto pop_3_error; +- #line 2222 "Python/generated_cases.c.h" ++ #line 2330 "Python/generated_cases.c.h" + STACK_SHRINK(2); + STACK_GROW(((oparg & 1) ? 1 : 0)); + stack_pointer[-1] = res; +@@ -2233,20 +2341,20 @@ + PyObject *global_super = stack_pointer[-3]; + PyObject *res2 = NULL; + PyObject *res; +- #line 1598 "Python/bytecodes.c" ++ #line 1617 "Python/bytecodes.c" + assert(!(oparg & 1)); + DEOPT_IF(global_super != (PyObject *)&PySuper_Type, LOAD_SUPER_ATTR); + DEOPT_IF(!PyType_Check(class), LOAD_SUPER_ATTR); + STAT_INC(LOAD_SUPER_ATTR, hit); + PyObject *name = GETITEM(frame->f_code->co_names, oparg >> 2); + res = _PySuper_Lookup((PyTypeObject *)class, self, name, NULL); +- #line 2244 "Python/generated_cases.c.h" ++ #line 2352 "Python/generated_cases.c.h" + Py_DECREF(global_super); + Py_DECREF(class); + Py_DECREF(self); +- #line 1605 "Python/bytecodes.c" ++ #line 1624 "Python/bytecodes.c" + if (res == NULL) goto pop_3_error; +- #line 2250 "Python/generated_cases.c.h" ++ #line 2358 "Python/generated_cases.c.h" + STACK_SHRINK(2); + STACK_GROW(((oparg & 1) ? 1 : 0)); + stack_pointer[-1] = res; +@@ -2261,7 +2369,7 @@ + PyObject *global_super = stack_pointer[-3]; + PyObject *res2; + PyObject *res; +- #line 1609 "Python/bytecodes.c" ++ #line 1628 "Python/bytecodes.c" + assert(oparg & 1); + DEOPT_IF(global_super != (PyObject *)&PySuper_Type, LOAD_SUPER_ATTR); + DEOPT_IF(!PyType_Check(class), LOAD_SUPER_ATTR); +@@ -2282,7 +2390,7 @@ + res = res2; + res2 = NULL; + } +- #line 2286 "Python/generated_cases.c.h" ++ #line 2394 "Python/generated_cases.c.h" + STACK_SHRINK(1); + stack_pointer[-1] = res; + stack_pointer[-2] = res2; +@@ -2296,7 +2404,7 @@ + PyObject *owner = stack_pointer[-1]; + PyObject *res2 = NULL; + PyObject *res; +- #line 1646 "Python/bytecodes.c" ++ #line 1665 "Python/bytecodes.c" + #if ENABLE_SPECIALIZATION + _PyAttrCache *cache = (_PyAttrCache *)next_instr; + if (ADAPTIVE_COUNTER_IS_ZERO(cache->counter)) { +@@ -2330,9 +2438,9 @@ + + NULL | meth | arg1 | ... | argN + */ +- #line 2334 "Python/generated_cases.c.h" ++ #line 2442 "Python/generated_cases.c.h" + Py_DECREF(owner); +- #line 1680 "Python/bytecodes.c" ++ #line 1699 "Python/bytecodes.c" + if (meth == NULL) goto pop_1_error; + res2 = NULL; + res = meth; +@@ -2341,12 +2449,12 @@ + else { + /* Classic, pushes one value. */ + res = PyObject_GetAttr(owner, name); +- #line 2345 "Python/generated_cases.c.h" ++ #line 2453 "Python/generated_cases.c.h" + Py_DECREF(owner); +- #line 1689 "Python/bytecodes.c" ++ #line 1708 "Python/bytecodes.c" + if (res == NULL) goto pop_1_error; + } +- #line 2350 "Python/generated_cases.c.h" ++ #line 2458 "Python/generated_cases.c.h" + STACK_GROW(((oparg & 1) ? 1 : 0)); + stack_pointer[-1] = res; + if (oparg & 1) { stack_pointer[-(1 + ((oparg & 1) ? 1 : 0))] = res2; } +@@ -2360,7 +2468,7 @@ + PyObject *res; + uint32_t type_version = read_u32(&next_instr[1].cache); + uint16_t index = read_u16(&next_instr[3].cache); +- #line 1694 "Python/bytecodes.c" ++ #line 1713 "Python/bytecodes.c" + PyTypeObject *tp = Py_TYPE(owner); + assert(type_version != 0); + DEOPT_IF(tp->tp_version_tag != type_version, LOAD_ATTR); +@@ -2373,7 +2481,7 @@ + STAT_INC(LOAD_ATTR, hit); + Py_INCREF(res); + res2 = NULL; +- #line 2377 "Python/generated_cases.c.h" ++ #line 2485 "Python/generated_cases.c.h" + Py_DECREF(owner); + STACK_GROW(((oparg & 1) ? 1 : 0)); + stack_pointer[-1] = res; +@@ -2388,7 +2496,7 @@ + PyObject *res; + uint32_t type_version = read_u32(&next_instr[1].cache); + uint16_t index = read_u16(&next_instr[3].cache); +- #line 1710 "Python/bytecodes.c" ++ #line 1729 "Python/bytecodes.c" + DEOPT_IF(!PyModule_CheckExact(owner), LOAD_ATTR); + PyDictObject *dict = (PyDictObject *)((PyModuleObject *)owner)->md_dict; + assert(dict != NULL); +@@ -2401,7 +2509,7 @@ + STAT_INC(LOAD_ATTR, hit); + Py_INCREF(res); + res2 = NULL; +- #line 2405 "Python/generated_cases.c.h" ++ #line 2513 "Python/generated_cases.c.h" + Py_DECREF(owner); + STACK_GROW(((oparg & 1) ? 1 : 0)); + stack_pointer[-1] = res; +@@ -2416,7 +2524,7 @@ + PyObject *res; + uint32_t type_version = read_u32(&next_instr[1].cache); + uint16_t index = read_u16(&next_instr[3].cache); +- #line 1726 "Python/bytecodes.c" ++ #line 1745 "Python/bytecodes.c" + PyTypeObject *tp = Py_TYPE(owner); + assert(type_version != 0); + DEOPT_IF(tp->tp_version_tag != type_version, LOAD_ATTR); +@@ -2443,7 +2551,7 @@ + STAT_INC(LOAD_ATTR, hit); + Py_INCREF(res); + res2 = NULL; +- #line 2447 "Python/generated_cases.c.h" ++ #line 2555 "Python/generated_cases.c.h" + Py_DECREF(owner); + STACK_GROW(((oparg & 1) ? 1 : 0)); + stack_pointer[-1] = res; +@@ -2458,7 +2566,7 @@ + PyObject *res; + uint32_t type_version = read_u32(&next_instr[1].cache); + uint16_t index = read_u16(&next_instr[3].cache); +- #line 1756 "Python/bytecodes.c" ++ #line 1775 "Python/bytecodes.c" + PyTypeObject *tp = Py_TYPE(owner); + assert(type_version != 0); + DEOPT_IF(tp->tp_version_tag != type_version, LOAD_ATTR); +@@ -2468,7 +2576,7 @@ + STAT_INC(LOAD_ATTR, hit); + Py_INCREF(res); + res2 = NULL; +- #line 2472 "Python/generated_cases.c.h" ++ #line 2580 "Python/generated_cases.c.h" + Py_DECREF(owner); + STACK_GROW(((oparg & 1) ? 1 : 0)); + stack_pointer[-1] = res; +@@ -2483,7 +2591,7 @@ + PyObject *res; + uint32_t type_version = read_u32(&next_instr[1].cache); + PyObject *descr = read_obj(&next_instr[5].cache); +- #line 1769 "Python/bytecodes.c" ++ #line 1788 "Python/bytecodes.c" + + DEOPT_IF(!PyType_Check(cls), LOAD_ATTR); + DEOPT_IF(((PyTypeObject *)cls)->tp_version_tag != type_version, +@@ -2495,7 +2603,7 @@ + res = descr; + assert(res != NULL); + Py_INCREF(res); +- #line 2499 "Python/generated_cases.c.h" ++ #line 2607 "Python/generated_cases.c.h" + Py_DECREF(cls); + STACK_GROW(((oparg & 1) ? 1 : 0)); + stack_pointer[-1] = res; +@@ -2509,7 +2617,7 @@ + uint32_t type_version = read_u32(&next_instr[1].cache); + uint32_t func_version = read_u32(&next_instr[3].cache); + PyObject *fget = read_obj(&next_instr[5].cache); +- #line 1784 "Python/bytecodes.c" ++ #line 1803 "Python/bytecodes.c" + DEOPT_IF(tstate->interp->eval_frame, LOAD_ATTR); + + PyTypeObject *cls = Py_TYPE(owner); +@@ -2533,7 +2641,7 @@ + JUMPBY(INLINE_CACHE_ENTRIES_LOAD_ATTR); + frame->return_offset = 0; + DISPATCH_INLINED(new_frame); +- #line 2537 "Python/generated_cases.c.h" ++ #line 2645 "Python/generated_cases.c.h" + } + + TARGET(LOAD_ATTR_GETATTRIBUTE_OVERRIDDEN) { +@@ -2541,7 +2649,7 @@ + uint32_t type_version = read_u32(&next_instr[1].cache); + uint32_t func_version = read_u32(&next_instr[3].cache); + PyObject *getattribute = read_obj(&next_instr[5].cache); +- #line 1810 "Python/bytecodes.c" ++ #line 1829 "Python/bytecodes.c" + DEOPT_IF(tstate->interp->eval_frame, LOAD_ATTR); + PyTypeObject *cls = Py_TYPE(owner); + DEOPT_IF(cls->tp_version_tag != type_version, LOAD_ATTR); +@@ -2567,7 +2675,7 @@ + JUMPBY(INLINE_CACHE_ENTRIES_LOAD_ATTR); + frame->return_offset = 0; + DISPATCH_INLINED(new_frame); +- #line 2571 "Python/generated_cases.c.h" ++ #line 2679 "Python/generated_cases.c.h" + } + + TARGET(STORE_ATTR_INSTANCE_VALUE) { +@@ -2575,7 +2683,7 @@ + PyObject *value = stack_pointer[-2]; + uint32_t type_version = read_u32(&next_instr[1].cache); + uint16_t index = read_u16(&next_instr[3].cache); +- #line 1838 "Python/bytecodes.c" ++ #line 1857 "Python/bytecodes.c" + PyTypeObject *tp = Py_TYPE(owner); + assert(type_version != 0); + DEOPT_IF(tp->tp_version_tag != type_version, STORE_ATTR); +@@ -2593,7 +2701,7 @@ + Py_DECREF(old_value); + } + Py_DECREF(owner); +- #line 2597 "Python/generated_cases.c.h" ++ #line 2705 "Python/generated_cases.c.h" + STACK_SHRINK(2); + next_instr += 4; + DISPATCH(); +@@ -2604,7 +2712,7 @@ + PyObject *value = stack_pointer[-2]; + uint32_t type_version = read_u32(&next_instr[1].cache); + uint16_t hint = read_u16(&next_instr[3].cache); +- #line 1858 "Python/bytecodes.c" ++ #line 1877 "Python/bytecodes.c" + PyTypeObject *tp = Py_TYPE(owner); + assert(type_version != 0); + DEOPT_IF(tp->tp_version_tag != type_version, STORE_ATTR); +@@ -2643,7 +2751,7 @@ + /* PEP 509 */ + dict->ma_version_tag = new_version; + Py_DECREF(owner); +- #line 2647 "Python/generated_cases.c.h" ++ #line 2755 "Python/generated_cases.c.h" + STACK_SHRINK(2); + next_instr += 4; + DISPATCH(); +@@ -2654,7 +2762,7 @@ + PyObject *value = stack_pointer[-2]; + uint32_t type_version = read_u32(&next_instr[1].cache); + uint16_t index = read_u16(&next_instr[3].cache); +- #line 1899 "Python/bytecodes.c" ++ #line 1918 "Python/bytecodes.c" + PyTypeObject *tp = Py_TYPE(owner); + assert(type_version != 0); + DEOPT_IF(tp->tp_version_tag != type_version, STORE_ATTR); +@@ -2664,7 +2772,7 @@ + *(PyObject **)addr = value; + Py_XDECREF(old_value); + Py_DECREF(owner); +- #line 2668 "Python/generated_cases.c.h" ++ #line 2776 "Python/generated_cases.c.h" + STACK_SHRINK(2); + next_instr += 4; + DISPATCH(); +@@ -2676,7 +2784,7 @@ + PyObject *right = stack_pointer[-1]; + PyObject *left = stack_pointer[-2]; + PyObject *res; +- #line 1918 "Python/bytecodes.c" ++ #line 1937 "Python/bytecodes.c" + #if ENABLE_SPECIALIZATION + _PyCompareOpCache *cache = (_PyCompareOpCache *)next_instr; + if (ADAPTIVE_COUNTER_IS_ZERO(cache->counter)) { +@@ -2689,12 +2797,12 @@ + #endif /* ENABLE_SPECIALIZATION */ + assert((oparg >> 4) <= Py_GE); + res = PyObject_RichCompare(left, right, oparg>>4); +- #line 2693 "Python/generated_cases.c.h" ++ #line 2801 "Python/generated_cases.c.h" + Py_DECREF(left); + Py_DECREF(right); +- #line 1931 "Python/bytecodes.c" ++ #line 1950 "Python/bytecodes.c" + if (res == NULL) goto pop_2_error; +- #line 2698 "Python/generated_cases.c.h" ++ #line 2806 "Python/generated_cases.c.h" + STACK_SHRINK(1); + stack_pointer[-1] = res; + next_instr += 1; +@@ -2705,7 +2813,7 @@ + PyObject *right = stack_pointer[-1]; + PyObject *left = stack_pointer[-2]; + PyObject *res; +- #line 1935 "Python/bytecodes.c" ++ #line 1954 "Python/bytecodes.c" + DEOPT_IF(!PyFloat_CheckExact(left), COMPARE_OP); + DEOPT_IF(!PyFloat_CheckExact(right), COMPARE_OP); + STAT_INC(COMPARE_OP, hit); +@@ -2717,7 +2825,7 @@ + _Py_DECREF_SPECIALIZED(right, _PyFloat_ExactDealloc); + res = (sign_ish & oparg) ? Py_True : Py_False; + Py_INCREF(res); +- #line 2721 "Python/generated_cases.c.h" ++ #line 2829 "Python/generated_cases.c.h" + STACK_SHRINK(1); + stack_pointer[-1] = res; + next_instr += 1; +@@ -2728,7 +2836,7 @@ + PyObject *right = stack_pointer[-1]; + PyObject *left = stack_pointer[-2]; + PyObject *res; +- #line 1950 "Python/bytecodes.c" ++ #line 1969 "Python/bytecodes.c" + DEOPT_IF(!PyLong_CheckExact(left), COMPARE_OP); + DEOPT_IF(!PyLong_CheckExact(right), COMPARE_OP); + DEOPT_IF(!_PyLong_IsCompact((PyLongObject *)left), COMPARE_OP); +@@ -2744,7 +2852,7 @@ + _Py_DECREF_SPECIALIZED(right, (destructor)PyObject_Free); + res = (sign_ish & oparg) ? Py_True : Py_False; + Py_INCREF(res); +- #line 2748 "Python/generated_cases.c.h" ++ #line 2856 "Python/generated_cases.c.h" + STACK_SHRINK(1); + stack_pointer[-1] = res; + next_instr += 1; +@@ -2755,7 +2863,7 @@ + PyObject *right = stack_pointer[-1]; + PyObject *left = stack_pointer[-2]; + PyObject *res; +- #line 1969 "Python/bytecodes.c" ++ #line 1988 "Python/bytecodes.c" + DEOPT_IF(!PyUnicode_CheckExact(left), COMPARE_OP); + DEOPT_IF(!PyUnicode_CheckExact(right), COMPARE_OP); + STAT_INC(COMPARE_OP, hit); +@@ -2768,7 +2876,7 @@ + assert(COMPARISON_NOT_EQUALS + 1 == COMPARISON_EQUALS); + res = ((COMPARISON_NOT_EQUALS + eq) & oparg) ? Py_True : Py_False; + Py_INCREF(res); +- #line 2772 "Python/generated_cases.c.h" ++ #line 2880 "Python/generated_cases.c.h" + STACK_SHRINK(1); + stack_pointer[-1] = res; + next_instr += 1; +@@ -2779,14 +2887,14 @@ + PyObject *right = stack_pointer[-1]; + PyObject *left = stack_pointer[-2]; + PyObject *b; +- #line 1984 "Python/bytecodes.c" ++ #line 2003 "Python/bytecodes.c" + int res = Py_Is(left, right) ^ oparg; +- #line 2785 "Python/generated_cases.c.h" ++ #line 2893 "Python/generated_cases.c.h" + Py_DECREF(left); + Py_DECREF(right); +- #line 1986 "Python/bytecodes.c" ++ #line 2005 "Python/bytecodes.c" + b = Py_NewRef(res ? Py_True : Py_False); +- #line 2790 "Python/generated_cases.c.h" ++ #line 2898 "Python/generated_cases.c.h" + STACK_SHRINK(1); + stack_pointer[-1] = b; + DISPATCH(); +@@ -2796,15 +2904,15 @@ + PyObject *right = stack_pointer[-1]; + PyObject *left = stack_pointer[-2]; + PyObject *b; +- #line 1990 "Python/bytecodes.c" ++ #line 2009 "Python/bytecodes.c" + int res = PySequence_Contains(right, left); +- #line 2802 "Python/generated_cases.c.h" ++ #line 2910 "Python/generated_cases.c.h" + Py_DECREF(left); + Py_DECREF(right); +- #line 1992 "Python/bytecodes.c" ++ #line 2011 "Python/bytecodes.c" + if (res < 0) goto pop_2_error; + b = Py_NewRef((res^oparg) ? Py_True : Py_False); +- #line 2808 "Python/generated_cases.c.h" ++ #line 2916 "Python/generated_cases.c.h" + STACK_SHRINK(1); + stack_pointer[-1] = b; + DISPATCH(); +@@ -2815,12 +2923,12 @@ + PyObject *exc_value = stack_pointer[-2]; + PyObject *rest; + PyObject *match; +- #line 1997 "Python/bytecodes.c" ++ #line 2016 "Python/bytecodes.c" + if (check_except_star_type_valid(tstate, match_type) < 0) { +- #line 2821 "Python/generated_cases.c.h" ++ #line 2929 "Python/generated_cases.c.h" + Py_DECREF(exc_value); + Py_DECREF(match_type); +- #line 1999 "Python/bytecodes.c" ++ #line 2018 "Python/bytecodes.c" + if (true) goto pop_2_error; + } + +@@ -2828,10 +2936,10 @@ + rest = NULL; + int res = exception_group_match(exc_value, match_type, + &match, &rest); +- #line 2832 "Python/generated_cases.c.h" ++ #line 2940 "Python/generated_cases.c.h" + Py_DECREF(exc_value); + Py_DECREF(match_type); +- #line 2007 "Python/bytecodes.c" ++ #line 2026 "Python/bytecodes.c" + if (res < 0) goto pop_2_error; + + assert((match == NULL) == (rest == NULL)); +@@ -2840,7 +2948,7 @@ + if (!Py_IsNone(match)) { + PyErr_SetHandledException(match); + } +- #line 2844 "Python/generated_cases.c.h" ++ #line 2952 "Python/generated_cases.c.h" + stack_pointer[-1] = match; + stack_pointer[-2] = rest; + DISPATCH(); +@@ -2850,21 +2958,21 @@ + PyObject *right = stack_pointer[-1]; + PyObject *left = stack_pointer[-2]; + PyObject *b; +- #line 2018 "Python/bytecodes.c" ++ #line 2037 "Python/bytecodes.c" + assert(PyExceptionInstance_Check(left)); + if (check_except_type_valid(tstate, right) < 0) { +- #line 2857 "Python/generated_cases.c.h" ++ #line 2965 "Python/generated_cases.c.h" + Py_DECREF(right); +- #line 2021 "Python/bytecodes.c" ++ #line 2040 "Python/bytecodes.c" + if (true) goto pop_1_error; + } + + int res = PyErr_GivenExceptionMatches(left, right); +- #line 2864 "Python/generated_cases.c.h" ++ #line 2972 "Python/generated_cases.c.h" + Py_DECREF(right); +- #line 2026 "Python/bytecodes.c" ++ #line 2045 "Python/bytecodes.c" + b = Py_NewRef(res ? Py_True : Py_False); +- #line 2868 "Python/generated_cases.c.h" ++ #line 2976 "Python/generated_cases.c.h" + stack_pointer[-1] = b; + DISPATCH(); + } +@@ -2873,15 +2981,15 @@ + PyObject *fromlist = stack_pointer[-1]; + PyObject *level = stack_pointer[-2]; + PyObject *res; +- #line 2030 "Python/bytecodes.c" ++ #line 2049 "Python/bytecodes.c" + PyObject *name = GETITEM(frame->f_code->co_names, oparg); + res = import_name(tstate, frame, name, fromlist, level); +- #line 2880 "Python/generated_cases.c.h" ++ #line 2988 "Python/generated_cases.c.h" + Py_DECREF(level); + Py_DECREF(fromlist); +- #line 2033 "Python/bytecodes.c" ++ #line 2052 "Python/bytecodes.c" + if (res == NULL) goto pop_2_error; +- #line 2885 "Python/generated_cases.c.h" ++ #line 2993 "Python/generated_cases.c.h" + STACK_SHRINK(1); + stack_pointer[-1] = res; + DISPATCH(); +@@ -2890,29 +2998,29 @@ + TARGET(IMPORT_FROM) { + PyObject *from = stack_pointer[-1]; + PyObject *res; +- #line 2037 "Python/bytecodes.c" ++ #line 2056 "Python/bytecodes.c" + PyObject *name = GETITEM(frame->f_code->co_names, oparg); + res = import_from(tstate, from, name); + if (res == NULL) goto error; +- #line 2898 "Python/generated_cases.c.h" ++ #line 3006 "Python/generated_cases.c.h" + STACK_GROW(1); + stack_pointer[-1] = res; + DISPATCH(); + } + + TARGET(JUMP_FORWARD) { +- #line 2043 "Python/bytecodes.c" ++ #line 2062 "Python/bytecodes.c" + JUMPBY(oparg); +- #line 2907 "Python/generated_cases.c.h" ++ #line 3015 "Python/generated_cases.c.h" + DISPATCH(); + } + + TARGET(JUMP_BACKWARD) { + PREDICTED(JUMP_BACKWARD); +- #line 2047 "Python/bytecodes.c" ++ #line 2066 "Python/bytecodes.c" + assert(oparg < INSTR_OFFSET()); + JUMPBY(-oparg); +- #line 2916 "Python/generated_cases.c.h" ++ #line 3024 "Python/generated_cases.c.h" + CHECK_EVAL_BREAKER(); + DISPATCH(); + } +@@ -2920,7 +3028,7 @@ + TARGET(POP_JUMP_IF_FALSE) { + PREDICTED(POP_JUMP_IF_FALSE); + PyObject *cond = stack_pointer[-1]; +- #line 2053 "Python/bytecodes.c" ++ #line 2072 "Python/bytecodes.c" + if (Py_IsTrue(cond)) { + _Py_DECREF_NO_DEALLOC(cond); + } +@@ -2930,9 +3038,9 @@ + } + else { + int err = PyObject_IsTrue(cond); +- #line 2934 "Python/generated_cases.c.h" ++ #line 3042 "Python/generated_cases.c.h" + Py_DECREF(cond); +- #line 2063 "Python/bytecodes.c" ++ #line 2082 "Python/bytecodes.c" + if (err == 0) { + JUMPBY(oparg); + } +@@ -2940,14 +3048,14 @@ + if (err < 0) goto pop_1_error; + } + } +- #line 2944 "Python/generated_cases.c.h" ++ #line 3052 "Python/generated_cases.c.h" + STACK_SHRINK(1); + DISPATCH(); + } + + TARGET(POP_JUMP_IF_TRUE) { + PyObject *cond = stack_pointer[-1]; +- #line 2073 "Python/bytecodes.c" ++ #line 2092 "Python/bytecodes.c" + if (Py_IsFalse(cond)) { + _Py_DECREF_NO_DEALLOC(cond); + } +@@ -2957,9 +3065,9 @@ + } + else { + int err = PyObject_IsTrue(cond); +- #line 2961 "Python/generated_cases.c.h" ++ #line 3069 "Python/generated_cases.c.h" + Py_DECREF(cond); +- #line 2083 "Python/bytecodes.c" ++ #line 2102 "Python/bytecodes.c" + if (err > 0) { + JUMPBY(oparg); + } +@@ -2967,67 +3075,67 @@ + if (err < 0) goto pop_1_error; + } + } +- #line 2971 "Python/generated_cases.c.h" ++ #line 3079 "Python/generated_cases.c.h" + STACK_SHRINK(1); + DISPATCH(); + } + + TARGET(POP_JUMP_IF_NOT_NONE) { + PyObject *value = stack_pointer[-1]; +- #line 2093 "Python/bytecodes.c" ++ #line 2112 "Python/bytecodes.c" + if (!Py_IsNone(value)) { +- #line 2980 "Python/generated_cases.c.h" ++ #line 3088 "Python/generated_cases.c.h" + Py_DECREF(value); +- #line 2095 "Python/bytecodes.c" ++ #line 2114 "Python/bytecodes.c" + JUMPBY(oparg); + } + else { + _Py_DECREF_NO_DEALLOC(value); + } +- #line 2988 "Python/generated_cases.c.h" ++ #line 3096 "Python/generated_cases.c.h" + STACK_SHRINK(1); + DISPATCH(); + } + + TARGET(POP_JUMP_IF_NONE) { + PyObject *value = stack_pointer[-1]; +- #line 2103 "Python/bytecodes.c" ++ #line 2122 "Python/bytecodes.c" + if (Py_IsNone(value)) { + _Py_DECREF_NO_DEALLOC(value); + JUMPBY(oparg); + } + else { +- #line 3001 "Python/generated_cases.c.h" ++ #line 3109 "Python/generated_cases.c.h" + Py_DECREF(value); +- #line 2109 "Python/bytecodes.c" ++ #line 2128 "Python/bytecodes.c" + } +- #line 3005 "Python/generated_cases.c.h" ++ #line 3113 "Python/generated_cases.c.h" + STACK_SHRINK(1); + DISPATCH(); + } + + TARGET(JUMP_BACKWARD_NO_INTERRUPT) { +- #line 2113 "Python/bytecodes.c" ++ #line 2132 "Python/bytecodes.c" + /* This bytecode is used in the `yield from` or `await` loop. + * If there is an interrupt, we want it handled in the innermost + * generator or coroutine, so we deliberately do not check it here. + * (see bpo-30039). + */ + JUMPBY(-oparg); +- #line 3018 "Python/generated_cases.c.h" ++ #line 3126 "Python/generated_cases.c.h" + DISPATCH(); + } + + TARGET(GET_LEN) { + PyObject *obj = stack_pointer[-1]; + PyObject *len_o; +- #line 2122 "Python/bytecodes.c" ++ #line 2141 "Python/bytecodes.c" + // PUSH(len(TOS)) + Py_ssize_t len_i = PyObject_Length(obj); + if (len_i < 0) goto error; + len_o = PyLong_FromSsize_t(len_i); + if (len_o == NULL) goto error; +- #line 3031 "Python/generated_cases.c.h" ++ #line 3139 "Python/generated_cases.c.h" + STACK_GROW(1); + stack_pointer[-1] = len_o; + DISPATCH(); +@@ -3038,16 +3146,16 @@ + PyObject *type = stack_pointer[-2]; + PyObject *subject = stack_pointer[-3]; + PyObject *attrs; +- #line 2130 "Python/bytecodes.c" ++ #line 2149 "Python/bytecodes.c" + // Pop TOS and TOS1. Set TOS to a tuple of attributes on success, or + // None on failure. + assert(PyTuple_CheckExact(names)); + attrs = match_class(tstate, subject, type, oparg, names); +- #line 3047 "Python/generated_cases.c.h" ++ #line 3155 "Python/generated_cases.c.h" + Py_DECREF(subject); + Py_DECREF(type); + Py_DECREF(names); +- #line 2135 "Python/bytecodes.c" ++ #line 2154 "Python/bytecodes.c" + if (attrs) { + assert(PyTuple_CheckExact(attrs)); // Success! + } +@@ -3055,7 +3163,7 @@ + if (_PyErr_Occurred(tstate)) goto pop_3_error; + attrs = Py_NewRef(Py_None); // Failure! + } +- #line 3059 "Python/generated_cases.c.h" ++ #line 3167 "Python/generated_cases.c.h" + STACK_SHRINK(2); + stack_pointer[-1] = attrs; + DISPATCH(); +@@ -3064,10 +3172,10 @@ + TARGET(MATCH_MAPPING) { + PyObject *subject = stack_pointer[-1]; + PyObject *res; +- #line 2145 "Python/bytecodes.c" ++ #line 2164 "Python/bytecodes.c" + int match = Py_TYPE(subject)->tp_flags & Py_TPFLAGS_MAPPING; + res = Py_NewRef(match ? Py_True : Py_False); +- #line 3071 "Python/generated_cases.c.h" ++ #line 3179 "Python/generated_cases.c.h" + STACK_GROW(1); + stack_pointer[-1] = res; + PREDICT(POP_JUMP_IF_FALSE); +@@ -3077,10 +3185,10 @@ + TARGET(MATCH_SEQUENCE) { + PyObject *subject = stack_pointer[-1]; + PyObject *res; +- #line 2151 "Python/bytecodes.c" ++ #line 2170 "Python/bytecodes.c" + int match = Py_TYPE(subject)->tp_flags & Py_TPFLAGS_SEQUENCE; + res = Py_NewRef(match ? Py_True : Py_False); +- #line 3084 "Python/generated_cases.c.h" ++ #line 3192 "Python/generated_cases.c.h" + STACK_GROW(1); + stack_pointer[-1] = res; + PREDICT(POP_JUMP_IF_FALSE); +@@ -3091,11 +3199,11 @@ + PyObject *keys = stack_pointer[-1]; + PyObject *subject = stack_pointer[-2]; + PyObject *values_or_none; +- #line 2157 "Python/bytecodes.c" ++ #line 2176 "Python/bytecodes.c" + // On successful match, PUSH(values). Otherwise, PUSH(None). + values_or_none = match_keys(tstate, subject, keys); + if (values_or_none == NULL) goto error; +- #line 3099 "Python/generated_cases.c.h" ++ #line 3207 "Python/generated_cases.c.h" + STACK_GROW(1); + stack_pointer[-1] = values_or_none; + DISPATCH(); +@@ -3104,14 +3212,14 @@ + TARGET(GET_ITER) { + PyObject *iterable = stack_pointer[-1]; + PyObject *iter; +- #line 2163 "Python/bytecodes.c" ++ #line 2182 "Python/bytecodes.c" + /* before: [obj]; after [getiter(obj)] */ + iter = PyObject_GetIter(iterable); +- #line 3111 "Python/generated_cases.c.h" ++ #line 3219 "Python/generated_cases.c.h" + Py_DECREF(iterable); +- #line 2166 "Python/bytecodes.c" ++ #line 2185 "Python/bytecodes.c" + if (iter == NULL) goto pop_1_error; +- #line 3115 "Python/generated_cases.c.h" ++ #line 3223 "Python/generated_cases.c.h" + stack_pointer[-1] = iter; + DISPATCH(); + } +@@ -3119,7 +3227,7 @@ + TARGET(GET_YIELD_FROM_ITER) { + PyObject *iterable = stack_pointer[-1]; + PyObject *iter; +- #line 2170 "Python/bytecodes.c" ++ #line 2189 "Python/bytecodes.c" + /* before: [obj]; after [getiter(obj)] */ + if (PyCoro_CheckExact(iterable)) { + /* `iterable` is a coroutine */ +@@ -3142,11 +3250,11 @@ + if (iter == NULL) { + goto error; + } +- #line 3146 "Python/generated_cases.c.h" ++ #line 3254 "Python/generated_cases.c.h" + Py_DECREF(iterable); +- #line 2193 "Python/bytecodes.c" ++ #line 2212 "Python/bytecodes.c" + } +- #line 3150 "Python/generated_cases.c.h" ++ #line 3258 "Python/generated_cases.c.h" + stack_pointer[-1] = iter; + PREDICT(LOAD_CONST); + DISPATCH(); +@@ -3157,7 +3265,7 @@ + static_assert(INLINE_CACHE_ENTRIES_FOR_ITER == 1, "incorrect cache size"); + PyObject *iter = stack_pointer[-1]; + PyObject *next; +- #line 2212 "Python/bytecodes.c" ++ #line 2231 "Python/bytecodes.c" + #if ENABLE_SPECIALIZATION + _PyForIterCache *cache = (_PyForIterCache *)next_instr; + if (ADAPTIVE_COUNTER_IS_ZERO(cache->counter)) { +@@ -3188,7 +3296,7 @@ + DISPATCH(); + } + // Common case: no jump, leave it to the code generator +- #line 3192 "Python/generated_cases.c.h" ++ #line 3300 "Python/generated_cases.c.h" + STACK_GROW(1); + stack_pointer[-1] = next; + next_instr += 1; +@@ -3196,7 +3304,7 @@ + } + + TARGET(INSTRUMENTED_FOR_ITER) { +- #line 2245 "Python/bytecodes.c" ++ #line 2264 "Python/bytecodes.c" + _Py_CODEUNIT *here = next_instr-1; + _Py_CODEUNIT *target; + PyObject *iter = TOP(); +@@ -3222,14 +3330,14 @@ + target = next_instr + INLINE_CACHE_ENTRIES_FOR_ITER + oparg + 1; + } + INSTRUMENTED_JUMP(here, target, PY_MONITORING_EVENT_BRANCH); +- #line 3226 "Python/generated_cases.c.h" ++ #line 3334 "Python/generated_cases.c.h" + DISPATCH(); + } + + TARGET(FOR_ITER_LIST) { + PyObject *iter = stack_pointer[-1]; + PyObject *next; +- #line 2273 "Python/bytecodes.c" ++ #line 2292 "Python/bytecodes.c" + DEOPT_IF(Py_TYPE(iter) != &PyListIter_Type, FOR_ITER); + _PyListIterObject *it = (_PyListIterObject *)iter; + STAT_INC(FOR_ITER, hit); +@@ -3249,7 +3357,7 @@ + DISPATCH(); + end_for_iter_list: + // Common case: no jump, leave it to the code generator +- #line 3253 "Python/generated_cases.c.h" ++ #line 3361 "Python/generated_cases.c.h" + STACK_GROW(1); + stack_pointer[-1] = next; + next_instr += 1; +@@ -3259,7 +3367,7 @@ + TARGET(FOR_ITER_TUPLE) { + PyObject *iter = stack_pointer[-1]; + PyObject *next; +- #line 2295 "Python/bytecodes.c" ++ #line 2314 "Python/bytecodes.c" + _PyTupleIterObject *it = (_PyTupleIterObject *)iter; + DEOPT_IF(Py_TYPE(it) != &PyTupleIter_Type, FOR_ITER); + STAT_INC(FOR_ITER, hit); +@@ -3279,7 +3387,7 @@ + DISPATCH(); + end_for_iter_tuple: + // Common case: no jump, leave it to the code generator +- #line 3283 "Python/generated_cases.c.h" ++ #line 3391 "Python/generated_cases.c.h" + STACK_GROW(1); + stack_pointer[-1] = next; + next_instr += 1; +@@ -3289,7 +3397,7 @@ + TARGET(FOR_ITER_RANGE) { + PyObject *iter = stack_pointer[-1]; + PyObject *next; +- #line 2317 "Python/bytecodes.c" ++ #line 2336 "Python/bytecodes.c" + _PyRangeIterObject *r = (_PyRangeIterObject *)iter; + DEOPT_IF(Py_TYPE(r) != &PyRangeIter_Type, FOR_ITER); + STAT_INC(FOR_ITER, hit); +@@ -3307,7 +3415,7 @@ + if (next == NULL) { + goto error; + } +- #line 3311 "Python/generated_cases.c.h" ++ #line 3419 "Python/generated_cases.c.h" + STACK_GROW(1); + stack_pointer[-1] = next; + next_instr += 1; +@@ -3316,7 +3424,7 @@ + + TARGET(FOR_ITER_GEN) { + PyObject *iter = stack_pointer[-1]; +- #line 2337 "Python/bytecodes.c" ++ #line 2356 "Python/bytecodes.c" + DEOPT_IF(tstate->interp->eval_frame, FOR_ITER); + PyGenObject *gen = (PyGenObject *)iter; + DEOPT_IF(Py_TYPE(gen) != &PyGen_Type, FOR_ITER); +@@ -3332,14 +3440,14 @@ + assert(next_instr[oparg].op.code == END_FOR || + next_instr[oparg].op.code == INSTRUMENTED_END_FOR); + DISPATCH_INLINED(gen_frame); +- #line 3336 "Python/generated_cases.c.h" ++ #line 3444 "Python/generated_cases.c.h" + } + + TARGET(BEFORE_ASYNC_WITH) { + PyObject *mgr = stack_pointer[-1]; + PyObject *exit; + PyObject *res; +- #line 2355 "Python/bytecodes.c" ++ #line 2374 "Python/bytecodes.c" + PyObject *enter = _PyObject_LookupSpecial(mgr, &_Py_ID(__aenter__)); + if (enter == NULL) { + if (!_PyErr_Occurred(tstate)) { +@@ -3362,16 +3470,16 @@ + Py_DECREF(enter); + goto error; + } +- #line 3366 "Python/generated_cases.c.h" ++ #line 3474 "Python/generated_cases.c.h" + Py_DECREF(mgr); +- #line 2378 "Python/bytecodes.c" ++ #line 2397 "Python/bytecodes.c" + res = _PyObject_CallNoArgs(enter); + Py_DECREF(enter); + if (res == NULL) { + Py_DECREF(exit); + if (true) goto pop_1_error; + } +- #line 3375 "Python/generated_cases.c.h" ++ #line 3483 "Python/generated_cases.c.h" + STACK_GROW(1); + stack_pointer[-1] = res; + stack_pointer[-2] = exit; +@@ -3383,7 +3491,7 @@ + PyObject *mgr = stack_pointer[-1]; + PyObject *exit; + PyObject *res; +- #line 2388 "Python/bytecodes.c" ++ #line 2407 "Python/bytecodes.c" + /* pop the context manager, push its __exit__ and the + * value returned from calling its __enter__ + */ +@@ -3409,16 +3517,16 @@ + Py_DECREF(enter); + goto error; + } +- #line 3413 "Python/generated_cases.c.h" ++ #line 3521 "Python/generated_cases.c.h" + Py_DECREF(mgr); +- #line 2414 "Python/bytecodes.c" ++ #line 2433 "Python/bytecodes.c" + res = _PyObject_CallNoArgs(enter); + Py_DECREF(enter); + if (res == NULL) { + Py_DECREF(exit); + if (true) goto pop_1_error; + } +- #line 3422 "Python/generated_cases.c.h" ++ #line 3530 "Python/generated_cases.c.h" + STACK_GROW(1); + stack_pointer[-1] = res; + stack_pointer[-2] = exit; +@@ -3430,7 +3538,7 @@ + PyObject *lasti = stack_pointer[-3]; + PyObject *exit_func = stack_pointer[-4]; + PyObject *res; +- #line 2423 "Python/bytecodes.c" ++ #line 2442 "Python/bytecodes.c" + /* At the top of the stack are 4 values: + - val: TOP = exc_info() + - unused: SECOND = previous exception +@@ -3451,7 +3559,7 @@ + res = PyObject_Vectorcall(exit_func, stack + 1, + 3 | PY_VECTORCALL_ARGUMENTS_OFFSET, NULL); + if (res == NULL) goto error; +- #line 3455 "Python/generated_cases.c.h" ++ #line 3563 "Python/generated_cases.c.h" + STACK_GROW(1); + stack_pointer[-1] = res; + DISPATCH(); +@@ -3460,7 +3568,7 @@ + TARGET(PUSH_EXC_INFO) { + PyObject *new_exc = stack_pointer[-1]; + PyObject *prev_exc; +- #line 2446 "Python/bytecodes.c" ++ #line 2465 "Python/bytecodes.c" + _PyErr_StackItem *exc_info = tstate->exc_info; + if (exc_info->exc_value != NULL) { + prev_exc = exc_info->exc_value; +@@ -3470,7 +3578,7 @@ + } + assert(PyExceptionInstance_Check(new_exc)); + exc_info->exc_value = Py_NewRef(new_exc); +- #line 3474 "Python/generated_cases.c.h" ++ #line 3582 "Python/generated_cases.c.h" + STACK_GROW(1); + stack_pointer[-1] = new_exc; + stack_pointer[-2] = prev_exc; +@@ -3484,7 +3592,7 @@ + uint32_t type_version = read_u32(&next_instr[1].cache); + uint32_t keys_version = read_u32(&next_instr[3].cache); + PyObject *descr = read_obj(&next_instr[5].cache); +- #line 2458 "Python/bytecodes.c" ++ #line 2477 "Python/bytecodes.c" + /* Cached method object */ + PyTypeObject *self_cls = Py_TYPE(self); + assert(type_version != 0); +@@ -3501,7 +3609,7 @@ + assert(_PyType_HasFeature(Py_TYPE(res2), Py_TPFLAGS_METHOD_DESCRIPTOR)); + res = self; + assert(oparg & 1); +- #line 3505 "Python/generated_cases.c.h" ++ #line 3613 "Python/generated_cases.c.h" + STACK_GROW(((oparg & 1) ? 1 : 0)); + stack_pointer[-1] = res; + if (oparg & 1) { stack_pointer[-(1 + ((oparg & 1) ? 1 : 0))] = res2; } +@@ -3515,7 +3623,7 @@ + PyObject *res; + uint32_t type_version = read_u32(&next_instr[1].cache); + PyObject *descr = read_obj(&next_instr[5].cache); +- #line 2477 "Python/bytecodes.c" ++ #line 2496 "Python/bytecodes.c" + PyTypeObject *self_cls = Py_TYPE(self); + DEOPT_IF(self_cls->tp_version_tag != type_version, LOAD_ATTR); + assert(self_cls->tp_dictoffset == 0); +@@ -3525,7 +3633,7 @@ + res2 = Py_NewRef(descr); + res = self; + assert(oparg & 1); +- #line 3529 "Python/generated_cases.c.h" ++ #line 3637 "Python/generated_cases.c.h" + STACK_GROW(((oparg & 1) ? 1 : 0)); + stack_pointer[-1] = res; + if (oparg & 1) { stack_pointer[-(1 + ((oparg & 1) ? 1 : 0))] = res2; } +@@ -3539,7 +3647,7 @@ + PyObject *res; + uint32_t type_version = read_u32(&next_instr[1].cache); + PyObject *descr = read_obj(&next_instr[5].cache); +- #line 2489 "Python/bytecodes.c" ++ #line 2508 "Python/bytecodes.c" + PyTypeObject *self_cls = Py_TYPE(self); + DEOPT_IF(self_cls->tp_version_tag != type_version, LOAD_ATTR); + Py_ssize_t dictoffset = self_cls->tp_dictoffset; +@@ -3553,7 +3661,7 @@ + res2 = Py_NewRef(descr); + res = self; + assert(oparg & 1); +- #line 3557 "Python/generated_cases.c.h" ++ #line 3665 "Python/generated_cases.c.h" + STACK_GROW(((oparg & 1) ? 1 : 0)); + stack_pointer[-1] = res; + if (oparg & 1) { stack_pointer[-(1 + ((oparg & 1) ? 1 : 0))] = res2; } +@@ -3562,16 +3670,16 @@ + } + + TARGET(KW_NAMES) { +- #line 2505 "Python/bytecodes.c" ++ #line 2524 "Python/bytecodes.c" + assert(kwnames == NULL); + assert(oparg < PyTuple_GET_SIZE(frame->f_code->co_consts)); + kwnames = GETITEM(frame->f_code->co_consts, oparg); +- #line 3570 "Python/generated_cases.c.h" ++ #line 3678 "Python/generated_cases.c.h" + DISPATCH(); + } + + TARGET(INSTRUMENTED_CALL) { +- #line 2511 "Python/bytecodes.c" ++ #line 2530 "Python/bytecodes.c" + int is_meth = PEEK(oparg+2) != NULL; + int total_args = oparg + is_meth; + PyObject *function = PEEK(total_args + 1); +@@ -3584,7 +3692,7 @@ + _PyCallCache *cache = (_PyCallCache *)next_instr; + INCREMENT_ADAPTIVE_COUNTER(cache->counter); + GO_TO_INSTRUCTION(CALL); +- #line 3588 "Python/generated_cases.c.h" ++ #line 3696 "Python/generated_cases.c.h" + } + + TARGET(CALL) { +@@ -3594,7 +3702,7 @@ + PyObject *callable = stack_pointer[-(1 + oparg)]; + PyObject *method = stack_pointer[-(2 + oparg)]; + PyObject *res; +- #line 2556 "Python/bytecodes.c" ++ #line 2575 "Python/bytecodes.c" + int is_meth = method != NULL; + int total_args = oparg; + if (is_meth) { +@@ -3676,7 +3784,7 @@ + Py_DECREF(args[i]); + } + if (res == NULL) { STACK_SHRINK(oparg); goto pop_2_error; } +- #line 3680 "Python/generated_cases.c.h" ++ #line 3788 "Python/generated_cases.c.h" + STACK_SHRINK(oparg); + STACK_SHRINK(1); + stack_pointer[-1] = res; +@@ -3688,7 +3796,7 @@ + TARGET(CALL_BOUND_METHOD_EXACT_ARGS) { + PyObject *callable = stack_pointer[-(1 + oparg)]; + PyObject *method = stack_pointer[-(2 + oparg)]; +- #line 2644 "Python/bytecodes.c" ++ #line 2663 "Python/bytecodes.c" + DEOPT_IF(method != NULL, CALL); + DEOPT_IF(Py_TYPE(callable) != &PyMethod_Type, CALL); + STAT_INC(CALL, hit); +@@ -3698,7 +3806,7 @@ + PEEK(oparg + 2) = Py_NewRef(meth); // method + Py_DECREF(callable); + GO_TO_INSTRUCTION(CALL_PY_EXACT_ARGS); +- #line 3702 "Python/generated_cases.c.h" ++ #line 3810 "Python/generated_cases.c.h" + } + + TARGET(CALL_PY_EXACT_ARGS) { +@@ -3707,7 +3815,7 @@ + PyObject *callable = stack_pointer[-(1 + oparg)]; + PyObject *method = stack_pointer[-(2 + oparg)]; + uint32_t func_version = read_u32(&next_instr[1].cache); +- #line 2656 "Python/bytecodes.c" ++ #line 2675 "Python/bytecodes.c" + assert(kwnames == NULL); + DEOPT_IF(tstate->interp->eval_frame, CALL); + int is_meth = method != NULL; +@@ -3733,7 +3841,7 @@ + JUMPBY(INLINE_CACHE_ENTRIES_CALL); + frame->return_offset = 0; + DISPATCH_INLINED(new_frame); +- #line 3737 "Python/generated_cases.c.h" ++ #line 3845 "Python/generated_cases.c.h" + } + + TARGET(CALL_PY_WITH_DEFAULTS) { +@@ -3741,7 +3849,7 @@ + PyObject *callable = stack_pointer[-(1 + oparg)]; + PyObject *method = stack_pointer[-(2 + oparg)]; + uint32_t func_version = read_u32(&next_instr[1].cache); +- #line 2684 "Python/bytecodes.c" ++ #line 2703 "Python/bytecodes.c" + assert(kwnames == NULL); + DEOPT_IF(tstate->interp->eval_frame, CALL); + int is_meth = method != NULL; +@@ -3777,7 +3885,7 @@ + JUMPBY(INLINE_CACHE_ENTRIES_CALL); + frame->return_offset = 0; + DISPATCH_INLINED(new_frame); +- #line 3781 "Python/generated_cases.c.h" ++ #line 3889 "Python/generated_cases.c.h" + } + + TARGET(CALL_NO_KW_TYPE_1) { +@@ -3785,7 +3893,7 @@ + PyObject *callable = stack_pointer[-(1 + oparg)]; + PyObject *null = stack_pointer[-(2 + oparg)]; + PyObject *res; +- #line 2722 "Python/bytecodes.c" ++ #line 2741 "Python/bytecodes.c" + assert(kwnames == NULL); + assert(oparg == 1); + DEOPT_IF(null != NULL, CALL); +@@ -3795,7 +3903,7 @@ + res = Py_NewRef(Py_TYPE(obj)); + Py_DECREF(obj); + Py_DECREF(&PyType_Type); // I.e., callable +- #line 3799 "Python/generated_cases.c.h" ++ #line 3907 "Python/generated_cases.c.h" + STACK_SHRINK(oparg); + STACK_SHRINK(1); + stack_pointer[-1] = res; +@@ -3808,7 +3916,7 @@ + PyObject *callable = stack_pointer[-(1 + oparg)]; + PyObject *null = stack_pointer[-(2 + oparg)]; + PyObject *res; +- #line 2734 "Python/bytecodes.c" ++ #line 2753 "Python/bytecodes.c" + assert(kwnames == NULL); + assert(oparg == 1); + DEOPT_IF(null != NULL, CALL); +@@ -3819,7 +3927,7 @@ + Py_DECREF(arg); + Py_DECREF(&PyUnicode_Type); // I.e., callable + if (res == NULL) { STACK_SHRINK(oparg); goto pop_2_error; } +- #line 3823 "Python/generated_cases.c.h" ++ #line 3931 "Python/generated_cases.c.h" + STACK_SHRINK(oparg); + STACK_SHRINK(1); + stack_pointer[-1] = res; +@@ -3833,7 +3941,7 @@ + PyObject *callable = stack_pointer[-(1 + oparg)]; + PyObject *null = stack_pointer[-(2 + oparg)]; + PyObject *res; +- #line 2748 "Python/bytecodes.c" ++ #line 2767 "Python/bytecodes.c" + assert(kwnames == NULL); + assert(oparg == 1); + DEOPT_IF(null != NULL, CALL); +@@ -3844,7 +3952,7 @@ + Py_DECREF(arg); + Py_DECREF(&PyTuple_Type); // I.e., tuple + if (res == NULL) { STACK_SHRINK(oparg); goto pop_2_error; } +- #line 3848 "Python/generated_cases.c.h" ++ #line 3956 "Python/generated_cases.c.h" + STACK_SHRINK(oparg); + STACK_SHRINK(1); + stack_pointer[-1] = res; +@@ -3858,7 +3966,7 @@ + PyObject *callable = stack_pointer[-(1 + oparg)]; + PyObject *method = stack_pointer[-(2 + oparg)]; + PyObject *res; +- #line 2762 "Python/bytecodes.c" ++ #line 2781 "Python/bytecodes.c" + int is_meth = method != NULL; + int total_args = oparg; + if (is_meth) { +@@ -3880,7 +3988,7 @@ + } + Py_DECREF(tp); + if (res == NULL) { STACK_SHRINK(oparg); goto pop_2_error; } +- #line 3884 "Python/generated_cases.c.h" ++ #line 3992 "Python/generated_cases.c.h" + STACK_SHRINK(oparg); + STACK_SHRINK(1); + stack_pointer[-1] = res; +@@ -3894,7 +4002,7 @@ + PyObject *callable = stack_pointer[-(1 + oparg)]; + PyObject *method = stack_pointer[-(2 + oparg)]; + PyObject *res; +- #line 2787 "Python/bytecodes.c" ++ #line 2806 "Python/bytecodes.c" + /* Builtin METH_O functions */ + assert(kwnames == NULL); + int is_meth = method != NULL; +@@ -3922,7 +4030,7 @@ + Py_DECREF(arg); + Py_DECREF(callable); + if (res == NULL) { STACK_SHRINK(oparg); goto pop_2_error; } +- #line 3926 "Python/generated_cases.c.h" ++ #line 4034 "Python/generated_cases.c.h" + STACK_SHRINK(oparg); + STACK_SHRINK(1); + stack_pointer[-1] = res; +@@ -3936,7 +4044,7 @@ + PyObject *callable = stack_pointer[-(1 + oparg)]; + PyObject *method = stack_pointer[-(2 + oparg)]; + PyObject *res; +- #line 2818 "Python/bytecodes.c" ++ #line 2837 "Python/bytecodes.c" + /* Builtin METH_FASTCALL functions, without keywords */ + assert(kwnames == NULL); + int is_meth = method != NULL; +@@ -3968,7 +4076,7 @@ + 'invalid'). In those cases an exception is set, so we must + handle it. + */ +- #line 3972 "Python/generated_cases.c.h" ++ #line 4080 "Python/generated_cases.c.h" + STACK_SHRINK(oparg); + STACK_SHRINK(1); + stack_pointer[-1] = res; +@@ -3982,7 +4090,7 @@ + PyObject *callable = stack_pointer[-(1 + oparg)]; + PyObject *method = stack_pointer[-(2 + oparg)]; + PyObject *res; +- #line 2853 "Python/bytecodes.c" ++ #line 2872 "Python/bytecodes.c" + /* Builtin METH_FASTCALL | METH_KEYWORDS functions */ + int is_meth = method != NULL; + int total_args = oparg; +@@ -4014,7 +4122,7 @@ + } + Py_DECREF(callable); + if (res == NULL) { STACK_SHRINK(oparg); goto pop_2_error; } +- #line 4018 "Python/generated_cases.c.h" ++ #line 4126 "Python/generated_cases.c.h" + STACK_SHRINK(oparg); + STACK_SHRINK(1); + stack_pointer[-1] = res; +@@ -4028,7 +4136,7 @@ + PyObject *callable = stack_pointer[-(1 + oparg)]; + PyObject *method = stack_pointer[-(2 + oparg)]; + PyObject *res; +- #line 2888 "Python/bytecodes.c" ++ #line 2907 "Python/bytecodes.c" + assert(kwnames == NULL); + /* len(o) */ + int is_meth = method != NULL; +@@ -4053,7 +4161,7 @@ + Py_DECREF(callable); + Py_DECREF(arg); + if (res == NULL) { STACK_SHRINK(oparg); goto pop_2_error; } +- #line 4057 "Python/generated_cases.c.h" ++ #line 4165 "Python/generated_cases.c.h" + STACK_SHRINK(oparg); + STACK_SHRINK(1); + stack_pointer[-1] = res; +@@ -4066,7 +4174,7 @@ + PyObject *callable = stack_pointer[-(1 + oparg)]; + PyObject *method = stack_pointer[-(2 + oparg)]; + PyObject *res; +- #line 2915 "Python/bytecodes.c" ++ #line 2934 "Python/bytecodes.c" + assert(kwnames == NULL); + /* isinstance(o, o2) */ + int is_meth = method != NULL; +@@ -4093,7 +4201,7 @@ + Py_DECREF(cls); + Py_DECREF(callable); + if (res == NULL) { STACK_SHRINK(oparg); goto pop_2_error; } +- #line 4097 "Python/generated_cases.c.h" ++ #line 4205 "Python/generated_cases.c.h" + STACK_SHRINK(oparg); + STACK_SHRINK(1); + stack_pointer[-1] = res; +@@ -4105,7 +4213,7 @@ + PyObject **args = (stack_pointer - oparg); + PyObject *self = stack_pointer[-(1 + oparg)]; + PyObject *method = stack_pointer[-(2 + oparg)]; +- #line 2945 "Python/bytecodes.c" ++ #line 2964 "Python/bytecodes.c" + assert(kwnames == NULL); + assert(oparg == 1); + assert(method != NULL); +@@ -4123,14 +4231,14 @@ + JUMPBY(INLINE_CACHE_ENTRIES_CALL + 1); + assert(next_instr[-1].op.code == POP_TOP); + DISPATCH(); +- #line 4127 "Python/generated_cases.c.h" ++ #line 4235 "Python/generated_cases.c.h" + } + + TARGET(CALL_NO_KW_METHOD_DESCRIPTOR_O) { + PyObject **args = (stack_pointer - oparg); + PyObject *method = stack_pointer[-(2 + oparg)]; + PyObject *res; +- #line 2965 "Python/bytecodes.c" ++ #line 2984 "Python/bytecodes.c" + assert(kwnames == NULL); + int is_meth = method != NULL; + int total_args = oparg; +@@ -4161,7 +4269,7 @@ + Py_DECREF(arg); + Py_DECREF(callable); + if (res == NULL) { STACK_SHRINK(oparg); goto pop_2_error; } +- #line 4165 "Python/generated_cases.c.h" ++ #line 4273 "Python/generated_cases.c.h" + STACK_SHRINK(oparg); + STACK_SHRINK(1); + stack_pointer[-1] = res; +@@ -4174,7 +4282,7 @@ + PyObject **args = (stack_pointer - oparg); + PyObject *method = stack_pointer[-(2 + oparg)]; + PyObject *res; +- #line 2999 "Python/bytecodes.c" ++ #line 3018 "Python/bytecodes.c" + int is_meth = method != NULL; + int total_args = oparg; + if (is_meth) { +@@ -4203,7 +4311,7 @@ + } + Py_DECREF(callable); + if (res == NULL) { STACK_SHRINK(oparg); goto pop_2_error; } +- #line 4207 "Python/generated_cases.c.h" ++ #line 4315 "Python/generated_cases.c.h" + STACK_SHRINK(oparg); + STACK_SHRINK(1); + stack_pointer[-1] = res; +@@ -4216,7 +4324,7 @@ + PyObject **args = (stack_pointer - oparg); + PyObject *method = stack_pointer[-(2 + oparg)]; + PyObject *res; +- #line 3031 "Python/bytecodes.c" ++ #line 3050 "Python/bytecodes.c" + assert(kwnames == NULL); + assert(oparg == 0 || oparg == 1); + int is_meth = method != NULL; +@@ -4245,7 +4353,7 @@ + Py_DECREF(self); + Py_DECREF(callable); + if (res == NULL) { STACK_SHRINK(oparg); goto pop_2_error; } +- #line 4249 "Python/generated_cases.c.h" ++ #line 4357 "Python/generated_cases.c.h" + STACK_SHRINK(oparg); + STACK_SHRINK(1); + stack_pointer[-1] = res; +@@ -4258,7 +4366,7 @@ + PyObject **args = (stack_pointer - oparg); + PyObject *method = stack_pointer[-(2 + oparg)]; + PyObject *res; +- #line 3063 "Python/bytecodes.c" ++ #line 3082 "Python/bytecodes.c" + assert(kwnames == NULL); + int is_meth = method != NULL; + int total_args = oparg; +@@ -4286,7 +4394,7 @@ + } + Py_DECREF(callable); + if (res == NULL) { STACK_SHRINK(oparg); goto pop_2_error; } +- #line 4290 "Python/generated_cases.c.h" ++ #line 4398 "Python/generated_cases.c.h" + STACK_SHRINK(oparg); + STACK_SHRINK(1); + stack_pointer[-1] = res; +@@ -4296,9 +4404,9 @@ + } + + TARGET(INSTRUMENTED_CALL_FUNCTION_EX) { +- #line 3094 "Python/bytecodes.c" ++ #line 3113 "Python/bytecodes.c" + GO_TO_INSTRUCTION(CALL_FUNCTION_EX); +- #line 4302 "Python/generated_cases.c.h" ++ #line 4410 "Python/generated_cases.c.h" + } + + TARGET(CALL_FUNCTION_EX) { +@@ -4307,7 +4415,7 @@ + PyObject *callargs = stack_pointer[-(1 + ((oparg & 1) ? 1 : 0))]; + PyObject *func = stack_pointer[-(2 + ((oparg & 1) ? 1 : 0))]; + PyObject *result; +- #line 3098 "Python/bytecodes.c" ++ #line 3117 "Python/bytecodes.c" + // DICT_MERGE is called before this opcode if there are kwargs. + // It converts all dict subtypes in kwargs into regular dicts. + assert(kwargs == NULL || PyDict_CheckExact(kwargs)); +@@ -4369,14 +4477,14 @@ + } + result = PyObject_Call(func, callargs, kwargs); + } +- #line 4373 "Python/generated_cases.c.h" ++ #line 4481 "Python/generated_cases.c.h" + Py_DECREF(func); + Py_DECREF(callargs); + Py_XDECREF(kwargs); +- #line 3160 "Python/bytecodes.c" ++ #line 3179 "Python/bytecodes.c" + assert(PEEK(3 + (oparg & 1)) == NULL); + if (result == NULL) { STACK_SHRINK(((oparg & 1) ? 1 : 0)); goto pop_3_error; } +- #line 4380 "Python/generated_cases.c.h" ++ #line 4488 "Python/generated_cases.c.h" + STACK_SHRINK(((oparg & 1) ? 1 : 0)); + STACK_SHRINK(2); + stack_pointer[-1] = result; +@@ -4391,7 +4499,7 @@ + PyObject *kwdefaults = (oparg & 0x02) ? stack_pointer[-(1 + ((oparg & 0x08) ? 1 : 0) + ((oparg & 0x04) ? 1 : 0) + ((oparg & 0x02) ? 1 : 0))] : NULL; + PyObject *defaults = (oparg & 0x01) ? stack_pointer[-(1 + ((oparg & 0x08) ? 1 : 0) + ((oparg & 0x04) ? 1 : 0) + ((oparg & 0x02) ? 1 : 0) + ((oparg & 0x01) ? 1 : 0))] : NULL; + PyObject *func; +- #line 3170 "Python/bytecodes.c" ++ #line 3189 "Python/bytecodes.c" + + PyFunctionObject *func_obj = (PyFunctionObject *) + PyFunction_New(codeobj, GLOBALS()); +@@ -4420,14 +4528,14 @@ + + func_obj->func_version = ((PyCodeObject *)codeobj)->co_version; + func = (PyObject *)func_obj; +- #line 4424 "Python/generated_cases.c.h" ++ #line 4532 "Python/generated_cases.c.h" + STACK_SHRINK(((oparg & 0x01) ? 1 : 0) + ((oparg & 0x02) ? 1 : 0) + ((oparg & 0x04) ? 1 : 0) + ((oparg & 0x08) ? 1 : 0)); + stack_pointer[-1] = func; + DISPATCH(); + } + + TARGET(RETURN_GENERATOR) { +- #line 3201 "Python/bytecodes.c" ++ #line 3220 "Python/bytecodes.c" + assert(PyFunction_Check(frame->f_funcobj)); + PyFunctionObject *func = (PyFunctionObject *)frame->f_funcobj; + PyGenObject *gen = (PyGenObject *)_Py_MakeCoro(func); +@@ -4448,7 +4556,7 @@ + frame = cframe.current_frame = prev; + _PyFrame_StackPush(frame, (PyObject *)gen); + goto resume_frame; +- #line 4452 "Python/generated_cases.c.h" ++ #line 4560 "Python/generated_cases.c.h" + } + + TARGET(BUILD_SLICE) { +@@ -4456,15 +4564,15 @@ + PyObject *stop = stack_pointer[-(1 + ((oparg == 3) ? 1 : 0))]; + PyObject *start = stack_pointer[-(2 + ((oparg == 3) ? 1 : 0))]; + PyObject *slice; +- #line 3224 "Python/bytecodes.c" ++ #line 3243 "Python/bytecodes.c" + slice = PySlice_New(start, stop, step); +- #line 4462 "Python/generated_cases.c.h" ++ #line 4570 "Python/generated_cases.c.h" + Py_DECREF(start); + Py_DECREF(stop); + Py_XDECREF(step); +- #line 3226 "Python/bytecodes.c" ++ #line 3245 "Python/bytecodes.c" + if (slice == NULL) { STACK_SHRINK(((oparg == 3) ? 1 : 0)); goto pop_2_error; } +- #line 4468 "Python/generated_cases.c.h" ++ #line 4576 "Python/generated_cases.c.h" + STACK_SHRINK(((oparg == 3) ? 1 : 0)); + STACK_SHRINK(1); + stack_pointer[-1] = slice; +@@ -4475,7 +4583,7 @@ + PyObject *fmt_spec = ((oparg & FVS_MASK) == FVS_HAVE_SPEC) ? stack_pointer[-((((oparg & FVS_MASK) == FVS_HAVE_SPEC) ? 1 : 0))] : NULL; + PyObject *value = stack_pointer[-(1 + (((oparg & FVS_MASK) == FVS_HAVE_SPEC) ? 1 : 0))]; + PyObject *result; +- #line 3230 "Python/bytecodes.c" ++ #line 3249 "Python/bytecodes.c" + /* Handles f-string value formatting. */ + PyObject *(*conv_fn)(PyObject *); + int which_conversion = oparg & FVC_MASK; +@@ -4510,7 +4618,7 @@ + Py_DECREF(value); + Py_XDECREF(fmt_spec); + if (result == NULL) { STACK_SHRINK((((oparg & FVS_MASK) == FVS_HAVE_SPEC) ? 1 : 0)); goto pop_1_error; } +- #line 4514 "Python/generated_cases.c.h" ++ #line 4622 "Python/generated_cases.c.h" + STACK_SHRINK((((oparg & FVS_MASK) == FVS_HAVE_SPEC) ? 1 : 0)); + stack_pointer[-1] = result; + DISPATCH(); +@@ -4519,10 +4627,10 @@ + TARGET(COPY) { + PyObject *bottom = stack_pointer[-(1 + (oparg-1))]; + PyObject *top; +- #line 3267 "Python/bytecodes.c" ++ #line 3286 "Python/bytecodes.c" + assert(oparg > 0); + top = Py_NewRef(bottom); +- #line 4526 "Python/generated_cases.c.h" ++ #line 4634 "Python/generated_cases.c.h" + STACK_GROW(1); + stack_pointer[-1] = top; + DISPATCH(); +@@ -4534,7 +4642,7 @@ + PyObject *rhs = stack_pointer[-1]; + PyObject *lhs = stack_pointer[-2]; + PyObject *res; +- #line 3272 "Python/bytecodes.c" ++ #line 3291 "Python/bytecodes.c" + #if ENABLE_SPECIALIZATION + _PyBinaryOpCache *cache = (_PyBinaryOpCache *)next_instr; + if (ADAPTIVE_COUNTER_IS_ZERO(cache->counter)) { +@@ -4549,12 +4657,12 @@ + assert((unsigned)oparg < Py_ARRAY_LENGTH(binary_ops)); + assert(binary_ops[oparg]); + res = binary_ops[oparg](lhs, rhs); +- #line 4553 "Python/generated_cases.c.h" ++ #line 4661 "Python/generated_cases.c.h" + Py_DECREF(lhs); + Py_DECREF(rhs); +- #line 3287 "Python/bytecodes.c" ++ #line 3306 "Python/bytecodes.c" + if (res == NULL) goto pop_2_error; +- #line 4558 "Python/generated_cases.c.h" ++ #line 4666 "Python/generated_cases.c.h" + STACK_SHRINK(1); + stack_pointer[-1] = res; + next_instr += 1; +@@ -4564,16 +4672,16 @@ + TARGET(SWAP) { + PyObject *top = stack_pointer[-1]; + PyObject *bottom = stack_pointer[-(2 + (oparg-2))]; +- #line 3292 "Python/bytecodes.c" ++ #line 3311 "Python/bytecodes.c" + assert(oparg >= 2); +- #line 4570 "Python/generated_cases.c.h" ++ #line 4678 "Python/generated_cases.c.h" + stack_pointer[-1] = bottom; + stack_pointer[-(2 + (oparg-2))] = top; + DISPATCH(); + } + + TARGET(INSTRUMENTED_INSTRUCTION) { +- #line 3296 "Python/bytecodes.c" ++ #line 3315 "Python/bytecodes.c" + int next_opcode = _Py_call_instrumentation_instruction( + tstate, frame, next_instr-1); + if (next_opcode < 0) goto error; +@@ -4585,26 +4693,26 @@ + assert(next_opcode > 0 && next_opcode < 256); + opcode = next_opcode; + DISPATCH_GOTO(); +- #line 4589 "Python/generated_cases.c.h" ++ #line 4697 "Python/generated_cases.c.h" + } + + TARGET(INSTRUMENTED_JUMP_FORWARD) { +- #line 3310 "Python/bytecodes.c" ++ #line 3329 "Python/bytecodes.c" + INSTRUMENTED_JUMP(next_instr-1, next_instr+oparg, PY_MONITORING_EVENT_JUMP); +- #line 4595 "Python/generated_cases.c.h" ++ #line 4703 "Python/generated_cases.c.h" + DISPATCH(); + } + + TARGET(INSTRUMENTED_JUMP_BACKWARD) { +- #line 3314 "Python/bytecodes.c" ++ #line 3333 "Python/bytecodes.c" + INSTRUMENTED_JUMP(next_instr-1, next_instr-oparg, PY_MONITORING_EVENT_JUMP); +- #line 4602 "Python/generated_cases.c.h" ++ #line 4710 "Python/generated_cases.c.h" + CHECK_EVAL_BREAKER(); + DISPATCH(); + } + + TARGET(INSTRUMENTED_POP_JUMP_IF_TRUE) { +- #line 3319 "Python/bytecodes.c" ++ #line 3338 "Python/bytecodes.c" + PyObject *cond = POP(); + int err = PyObject_IsTrue(cond); + Py_DECREF(cond); +@@ -4613,12 +4721,12 @@ + assert(err == 0 || err == 1); + int offset = err*oparg; + INSTRUMENTED_JUMP(here, next_instr + offset, PY_MONITORING_EVENT_BRANCH); +- #line 4617 "Python/generated_cases.c.h" ++ #line 4725 "Python/generated_cases.c.h" + DISPATCH(); + } + + TARGET(INSTRUMENTED_POP_JUMP_IF_FALSE) { +- #line 3330 "Python/bytecodes.c" ++ #line 3349 "Python/bytecodes.c" + PyObject *cond = POP(); + int err = PyObject_IsTrue(cond); + Py_DECREF(cond); +@@ -4627,12 +4735,12 @@ + assert(err == 0 || err == 1); + int offset = (1-err)*oparg; + INSTRUMENTED_JUMP(here, next_instr + offset, PY_MONITORING_EVENT_BRANCH); +- #line 4631 "Python/generated_cases.c.h" ++ #line 4739 "Python/generated_cases.c.h" + DISPATCH(); + } + + TARGET(INSTRUMENTED_POP_JUMP_IF_NONE) { +- #line 3341 "Python/bytecodes.c" ++ #line 3360 "Python/bytecodes.c" + PyObject *value = POP(); + _Py_CODEUNIT *here = next_instr-1; + int offset; +@@ -4645,12 +4753,12 @@ + offset = 0; + } + INSTRUMENTED_JUMP(here, next_instr + offset, PY_MONITORING_EVENT_BRANCH); +- #line 4649 "Python/generated_cases.c.h" ++ #line 4757 "Python/generated_cases.c.h" + DISPATCH(); + } + + TARGET(INSTRUMENTED_POP_JUMP_IF_NOT_NONE) { +- #line 3356 "Python/bytecodes.c" ++ #line 3375 "Python/bytecodes.c" + PyObject *value = POP(); + _Py_CODEUNIT *here = next_instr-1; + int offset; +@@ -4663,30 +4771,30 @@ + offset = oparg; + } + INSTRUMENTED_JUMP(here, next_instr + offset, PY_MONITORING_EVENT_BRANCH); +- #line 4667 "Python/generated_cases.c.h" ++ #line 4775 "Python/generated_cases.c.h" + DISPATCH(); + } + + TARGET(EXTENDED_ARG) { +- #line 3371 "Python/bytecodes.c" ++ #line 3390 "Python/bytecodes.c" + assert(oparg); + opcode = next_instr->op.code; + oparg = oparg << 8 | next_instr->op.arg; + PRE_DISPATCH_GOTO(); + DISPATCH_GOTO(); +- #line 4678 "Python/generated_cases.c.h" ++ #line 4786 "Python/generated_cases.c.h" + } + + TARGET(CACHE) { +- #line 3379 "Python/bytecodes.c" ++ #line 3398 "Python/bytecodes.c" + assert(0 && "Executing a cache."); + Py_UNREACHABLE(); +- #line 4685 "Python/generated_cases.c.h" ++ #line 4793 "Python/generated_cases.c.h" + } + + TARGET(RESERVED) { +- #line 3384 "Python/bytecodes.c" ++ #line 3403 "Python/bytecodes.c" + assert(0 && "Executing RESERVED instruction."); + Py_UNREACHABLE(); +- #line 4692 "Python/generated_cases.c.h" ++ #line 4800 "Python/generated_cases.c.h" + } +diff --git a/Python/intrinsics.c b/Python/intrinsics.c +index cca29d8599..c6f5ac5402 100644 +--- a/Python/intrinsics.c ++++ b/Python/intrinsics.c +@@ -3,10 +3,12 @@ + + #include "Python.h" + #include "pycore_frame.h" ++#include "pycore_function.h" + #include "pycore_runtime.h" + #include "pycore_global_objects.h" + #include "pycore_intrinsics.h" + #include "pycore_pyerrors.h" ++#include "pycore_typevarobject.h" + + + /******** Unary functions ********/ +@@ -199,6 +201,13 @@ list_to_tuple(PyThreadState* unused, PyObject *v) + return _PyTuple_FromArray(((PyListObject *)v)->ob_item, Py_SIZE(v)); + } + ++static PyObject * ++make_typevar(PyThreadState* Py_UNUSED(ignored), PyObject *v) ++{ ++ assert(PyUnicode_Check(v)); ++ return _Py_make_typevar(v, NULL, NULL); ++} ++ + const instrinsic_func1 + _PyIntrinsics_UnaryFunctions[] = { + [0] = no_intrinsic, +@@ -208,6 +217,11 @@ _PyIntrinsics_UnaryFunctions[] = { + [INTRINSIC_ASYNC_GEN_WRAP] = _PyAsyncGenValueWrapperNew, + [INTRINSIC_UNARY_POSITIVE] = unary_pos, + [INTRINSIC_LIST_TO_TUPLE] = list_to_tuple, ++ [INTRINSIC_TYPEVAR] = make_typevar, ++ [INTRINSIC_PARAMSPEC] = _Py_make_paramspec, ++ [INTRINSIC_TYPEVARTUPLE] = _Py_make_typevartuple, ++ [INTRINSIC_SUBSCRIPT_GENERIC] = _Py_subscript_generic, ++ [INTRINSIC_TYPEALIAS] = _Py_make_typealias, + }; + + +@@ -221,8 +235,26 @@ prep_reraise_star(PyThreadState* unused, PyObject *orig, PyObject *excs) + return _PyExc_PrepReraiseStar(orig, excs); + } + ++static PyObject * ++make_typevar_with_bound(PyThreadState* Py_UNUSED(ignored), PyObject *name, ++ PyObject *evaluate_bound) ++{ ++ assert(PyUnicode_Check(name)); ++ return _Py_make_typevar(name, evaluate_bound, NULL); ++} ++ ++static PyObject * ++make_typevar_with_constraints(PyThreadState* Py_UNUSED(ignored), PyObject *name, ++ PyObject *evaluate_constraints) ++{ ++ assert(PyUnicode_Check(name)); ++ return _Py_make_typevar(name, NULL, evaluate_constraints); ++} ++ + const instrinsic_func2 + _PyIntrinsics_BinaryFunctions[] = { + [INTRINSIC_PREP_RERAISE_STAR] = prep_reraise_star, ++ [INTRINSIC_TYPEVAR_WITH_BOUND] = make_typevar_with_bound, ++ [INTRINSIC_TYPEVAR_WITH_CONSTRAINTS] = make_typevar_with_constraints, ++ [INTRINSIC_SET_FUNCTION_TYPE_PARAMS] = _Py_set_function_type_params, + }; +- +diff --git a/Python/opcode_metadata.h b/Python/opcode_metadata.h +index ae68e045a6..601ad3874b 100644 +--- a/Python/opcode_metadata.h ++++ b/Python/opcode_metadata.h +@@ -161,8 +161,12 @@ _PyOpcode_num_popped(int opcode, int oparg, bool jump) { + return 1; + case DELETE_GLOBAL: + return 0; +- case LOAD_NAME: ++ case LOAD_LOCALS: + return 0; ++ case LOAD_NAME: ++ return 0+1; ++ case LOAD_FROM_DICT_OR_GLOBALS: ++ return 1; + case LOAD_GLOBAL: + return 0; + case LOAD_GLOBAL_MODULE: +@@ -175,8 +179,8 @@ _PyOpcode_num_popped(int opcode, int oparg, bool jump) { + return 0; + case DELETE_DEREF: + return 0; +- case LOAD_CLASSDEREF: +- return 0; ++ case LOAD_FROM_DICT_OR_DEREF: ++ return 1; + case LOAD_DEREF: + return 0; + case STORE_DEREF: +@@ -551,7 +555,11 @@ _PyOpcode_num_pushed(int opcode, int oparg, bool jump) { + return 0; + case DELETE_GLOBAL: + return 0; ++ case LOAD_LOCALS: ++ return 1; + case LOAD_NAME: ++ return 1+1; ++ case LOAD_FROM_DICT_OR_GLOBALS: + return 1; + case LOAD_GLOBAL: + return ((oparg & 1) ? 1 : 0) + 1; +@@ -565,7 +573,7 @@ _PyOpcode_num_pushed(int opcode, int oparg, bool jump) { + return 0; + case DELETE_DEREF: + return 0; +- case LOAD_CLASSDEREF: ++ case LOAD_FROM_DICT_OR_DEREF: + return 1; + case LOAD_DEREF: + return 1; +@@ -869,14 +877,16 @@ const struct opcode_metadata _PyOpcode_opcode_metadata[256] = { + [DELETE_ATTR] = { true, INSTR_FMT_IB }, + [STORE_GLOBAL] = { true, INSTR_FMT_IB }, + [DELETE_GLOBAL] = { true, INSTR_FMT_IB }, ++ [LOAD_LOCALS] = { true, INSTR_FMT_IB }, + [LOAD_NAME] = { true, INSTR_FMT_IB }, ++ [LOAD_FROM_DICT_OR_GLOBALS] = { true, INSTR_FMT_IB }, + [LOAD_GLOBAL] = { true, INSTR_FMT_IBC000 }, + [LOAD_GLOBAL_MODULE] = { true, INSTR_FMT_IBC000 }, + [LOAD_GLOBAL_BUILTIN] = { true, INSTR_FMT_IBC000 }, + [DELETE_FAST] = { true, INSTR_FMT_IB }, + [MAKE_CELL] = { true, INSTR_FMT_IB }, + [DELETE_DEREF] = { true, INSTR_FMT_IB }, +- [LOAD_CLASSDEREF] = { true, INSTR_FMT_IB }, ++ [LOAD_FROM_DICT_OR_DEREF] = { true, INSTR_FMT_IB }, + [LOAD_DEREF] = { true, INSTR_FMT_IB }, + [STORE_DEREF] = { true, INSTR_FMT_IB }, + [COPY_FREE_VARS] = { true, INSTR_FMT_IB }, +diff --git a/Python/opcode_targets.h b/Python/opcode_targets.h +index f2742f4ad1..af05a33058 100644 +--- a/Python/opcode_targets.h ++++ b/Python/opcode_targets.h +@@ -86,8 +86,8 @@ static void *opcode_targets[256] = { + &&TARGET_LOAD_CONST__LOAD_FAST, + &&TARGET_SETUP_ANNOTATIONS, + &&TARGET_LOAD_FAST__LOAD_CONST, ++ &&TARGET_LOAD_LOCALS, + &&TARGET_LOAD_FAST__LOAD_FAST, +- &&TARGET_LOAD_GLOBAL_BUILTIN, + &&TARGET_POP_EXCEPT, + &&TARGET_STORE_NAME, + &&TARGET_DELETE_NAME, +@@ -110,9 +110,9 @@ static void *opcode_targets[256] = { + &&TARGET_IMPORT_NAME, + &&TARGET_IMPORT_FROM, + &&TARGET_JUMP_FORWARD, ++ &&TARGET_LOAD_GLOBAL_BUILTIN, + &&TARGET_LOAD_GLOBAL_MODULE, + &&TARGET_STORE_ATTR_INSTANCE_VALUE, +- &&TARGET_STORE_ATTR_SLOT, + &&TARGET_POP_JUMP_IF_FALSE, + &&TARGET_POP_JUMP_IF_TRUE, + &&TARGET_LOAD_GLOBAL, +@@ -147,7 +147,7 @@ static void *opcode_targets[256] = { + &&TARGET_LIST_APPEND, + &&TARGET_SET_ADD, + &&TARGET_MAP_ADD, +- &&TARGET_LOAD_CLASSDEREF, ++ &&TARGET_STORE_ATTR_SLOT, + &&TARGET_COPY_FREE_VARS, + &&TARGET_YIELD_VALUE, + &&TARGET_RESUME, +@@ -174,8 +174,8 @@ static void *opcode_targets[256] = { + &&TARGET_KW_NAMES, + &&TARGET_CALL_INTRINSIC_1, + &&TARGET_CALL_INTRINSIC_2, +- &&_unknown_opcode, +- &&_unknown_opcode, ++ &&TARGET_LOAD_FROM_DICT_OR_GLOBALS, ++ &&TARGET_LOAD_FROM_DICT_OR_DEREF, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, +diff --git a/Python/pylifecycle.c b/Python/pylifecycle.c +index cb87f2c086..740901f53d 100644 +--- a/Python/pylifecycle.c ++++ b/Python/pylifecycle.c +@@ -26,6 +26,7 @@ + #include "pycore_sysmodule.h" // _PySys_ClearAuditHooks() + #include "pycore_traceback.h" // _Py_DumpTracebackThreads() + #include "pycore_typeobject.h" // _PyTypes_InitTypes() ++#include "pycore_typevarobject.h" // _Py_clear_generic_types() + #include "pycore_unicodeobject.h" // _PyUnicode_InitTypes() + #include "opcode.h" + +@@ -1698,6 +1699,7 @@ finalize_interp_clear(PyThreadState *tstate) + int is_main_interp = _Py_IsMainInterpreter(tstate->interp); + + _PyExc_ClearExceptionGroupType(tstate->interp); ++ _Py_clear_generic_types(tstate->interp); + + /* Clear interpreter state and all thread states */ + _PyInterpreterState_Clear(tstate); +diff --git a/Python/symtable.c b/Python/symtable.c +index 2c29f60841..3451f6c7bf 100644 +--- a/Python/symtable.c ++++ b/Python/symtable.c +@@ -47,6 +47,18 @@ + #define ANNOTATION_NOT_ALLOWED \ + "'%s' can not be used within an annotation" + ++#define TYPEVAR_BOUND_NOT_ALLOWED \ ++"'%s' can not be used within a TypeVar bound" ++ ++#define TYPEALIAS_NOT_ALLOWED \ ++"'%s' can not be used within a type alias" ++ ++#define TYPEPARAM_NOT_ALLOWED \ ++"'%s' can not be used within the definition of a generic" ++ ++#define DUPLICATE_TYPE_PARAM \ ++"duplicate type parameter '%U'" ++ + + #define LOCATION(x) \ + (x)->lineno, (x)->col_offset, (x)->end_lineno, (x)->end_col_offset +@@ -95,7 +107,7 @@ ste_new(struct symtable *st, identifier name, _Py_block_ty block, + + if (st->st_cur != NULL && + (st->st_cur->ste_nested || +- st->st_cur->ste_type == FunctionBlock)) ++ _PyST_IsFunctionLike(st->st_cur))) + ste->ste_nested = 1; + ste->ste_child_free = 0; + ste->ste_generator = 0; +@@ -105,7 +117,9 @@ ste_new(struct symtable *st, identifier name, _Py_block_ty block, + ste->ste_needs_class_closure = 0; + ste->ste_comp_inlined = 0; + ste->ste_comp_iter_target = 0; ++ ste->ste_can_see_class_scope = 0; + ste->ste_comp_iter_expr = 0; ++ ste->ste_needs_classdict = 0; + + ste->ste_symbols = PyDict_New(); + ste->ste_varnames = PyList_New(0); +@@ -208,6 +222,7 @@ static int symtable_enter_block(struct symtable *st, identifier name, + static int symtable_exit_block(struct symtable *st); + static int symtable_visit_stmt(struct symtable *st, stmt_ty s); + static int symtable_visit_expr(struct symtable *st, expr_ty s); ++static int symtable_visit_typeparam(struct symtable *st, typeparam_ty s); + static int symtable_visit_genexp(struct symtable *st, expr_ty s); + static int symtable_visit_listcomp(struct symtable *st, expr_ty s); + static int symtable_visit_setcomp(struct symtable *st, expr_ty s); +@@ -403,6 +418,15 @@ _PyST_GetScope(PySTEntryObject *ste, PyObject *name) + return (symbol >> SCOPE_OFFSET) & SCOPE_MASK; + } + ++int ++_PyST_IsFunctionLike(PySTEntryObject *ste) ++{ ++ return ste->ste_type == FunctionBlock ++ || ste->ste_type == TypeVarBoundBlock ++ || ste->ste_type == TypeAliasBlock ++ || ste->ste_type == TypeParamBlock; ++} ++ + static int + error_at_directive(PySTEntryObject *ste, PyObject *name) + { +@@ -495,7 +519,7 @@ error_at_directive(PySTEntryObject *ste, PyObject *name) + static int + analyze_name(PySTEntryObject *ste, PyObject *scopes, PyObject *name, long flags, + PyObject *bound, PyObject *local, PyObject *free, +- PyObject *global) ++ PyObject *global, PyObject *typeparams, PySTEntryObject *class_entry) + { + if (flags & DEF_GLOBAL) { + if (flags & DEF_NONLOCAL) { +@@ -524,6 +548,12 @@ analyze_name(PySTEntryObject *ste, PyObject *scopes, PyObject *name, long flags, + + return error_at_directive(ste, name); + } ++ if (PySet_Contains(typeparams, name)) { ++ PyErr_Format(PyExc_SyntaxError, ++ "nonlocal binding not allowed for type parameter '%U'", ++ name); ++ return error_at_directive(ste, name); ++ } + SET_SCOPE(scopes, name, FREE); + ste->ste_free = 1; + return PySet_Add(free, name) >= 0; +@@ -534,8 +564,34 @@ analyze_name(PySTEntryObject *ste, PyObject *scopes, PyObject *name, long flags, + return 0; + if (PySet_Discard(global, name) < 0) + return 0; ++ if (flags & DEF_TYPE_PARAM) { ++ if (PySet_Add(typeparams, name) < 0) ++ return 0; ++ } ++ else { ++ if (PySet_Discard(typeparams, name) < 0) ++ return 0; ++ } + return 1; + } ++ // If we were passed class_entry (i.e., we're in an ste_can_see_class_scope scope) ++ // and the bound name is in that set, then the name is potentially bound both by ++ // the immediately enclosing class namespace, and also by an outer function namespace. ++ // In that case, we want the runtime name resolution to look at only the class ++ // namespace and the globals (not the namespace providing the bound). ++ // Similarly, if the name is explicitly global in the class namespace (through the ++ // global statement), we want to also treat it as a global in this scope. ++ if (class_entry != NULL) { ++ long class_flags = _PyST_GetSymbol(class_entry, name); ++ if (class_flags & DEF_GLOBAL) { ++ SET_SCOPE(scopes, name, GLOBAL_EXPLICIT); ++ return 1; ++ } ++ else if (class_flags & DEF_BOUND && !(class_flags & DEF_NONLOCAL)) { ++ SET_SCOPE(scopes, name, GLOBAL_IMPLICIT); ++ return 1; ++ } ++ } + /* If an enclosing block has a binding for this name, it + is a free variable rather than a global variable. + Note that having a non-NULL bound implies that the block +@@ -611,7 +667,7 @@ inline_comprehension(PySTEntryObject *ste, PySTEntryObject *comp, + if (PyLong_AsLong(existing) & DEF_BOUND) { + // cell vars in comprehension that are locals in outer scope + // must be promoted to cell so u_cellvars isn't wrong +- if (scope == CELL && ste->ste_type == FunctionBlock) { ++ if (scope == CELL && _PyST_IsFunctionLike(ste)) { + if (PySet_Add(promote_to_cell, k) < 0) { + return 0; + } +@@ -682,6 +738,11 @@ drop_class_free(PySTEntryObject *ste, PyObject *free) + return 0; + if (res) + ste->ste_needs_class_closure = 1; ++ res = PySet_Discard(free, &_Py_ID(__classdict__)); ++ if (res < 0) ++ return 0; ++ if (res) ++ ste->ste_needs_classdict = 1; + return 1; + } + +@@ -799,11 +860,13 @@ update_symbols(PyObject *symbols, PyObject *scopes, + + static int + analyze_child_block(PySTEntryObject *entry, PyObject *bound, PyObject *free, +- PyObject *global, PyObject **child_free); ++ PyObject *global, PyObject *typeparams, ++ PySTEntryObject *class_entry, PyObject **child_free); + + static int + analyze_block(PySTEntryObject *ste, PyObject *bound, PyObject *free, +- PyObject *global) ++ PyObject *global, PyObject *typeparams, ++ PySTEntryObject *class_entry) + { + PyObject *name, *v, *local = NULL, *scopes = NULL, *newbound = NULL; + PyObject *newglobal = NULL, *newfree = NULL, *promote_to_cell = NULL; +@@ -865,14 +928,14 @@ analyze_block(PySTEntryObject *ste, PyObject *bound, PyObject *free, + while (PyDict_Next(ste->ste_symbols, &pos, &name, &v)) { + long flags = PyLong_AS_LONG(v); + if (!analyze_name(ste, scopes, name, flags, +- bound, local, free, global)) ++ bound, local, free, global, typeparams, class_entry)) + goto error; + } + + /* Populate global and bound sets to be passed to children. */ + if (ste->ste_type != ClassBlock) { + /* Add function locals to bound set */ +- if (ste->ste_type == FunctionBlock) { ++ if (_PyST_IsFunctionLike(ste)) { + temp = PyNumber_InPlaceOr(newbound, local); + if (!temp) + goto error; +@@ -892,9 +955,11 @@ analyze_block(PySTEntryObject *ste, PyObject *bound, PyObject *free, + Py_DECREF(temp); + } + else { +- /* Special-case __class__ */ ++ /* Special-case __class__ and __classdict__ */ + if (PySet_Add(newbound, &_Py_ID(__class__)) < 0) + goto error; ++ if (PySet_Add(newbound, &_Py_ID(__classdict__)) < 0) ++ goto error; + } + + /* Recursively call analyze_child_block() on each child block. +@@ -910,13 +975,23 @@ analyze_block(PySTEntryObject *ste, PyObject *bound, PyObject *free, + assert(c && PySTEntry_Check(c)); + entry = (PySTEntryObject*)c; + ++ PySTEntryObject *new_class_entry = NULL; ++ if (entry->ste_can_see_class_scope) { ++ if (ste->ste_type == ClassBlock) { ++ new_class_entry = ste; ++ } ++ else if (class_entry) { ++ new_class_entry = class_entry; ++ } ++ } ++ + // we inline all non-generator-expression comprehensions + int inline_comp = + entry->ste_comprehension && + !entry->ste_generator; + + if (!analyze_child_block(entry, newbound, newfree, newglobal, +- &child_free)) ++ typeparams, new_class_entry, &child_free)) + { + goto error; + } +@@ -952,7 +1027,7 @@ analyze_block(PySTEntryObject *ste, PyObject *bound, PyObject *free, + } + + /* Check if any local variables must be converted to cell variables */ +- if (ste->ste_type == FunctionBlock && !analyze_cells(scopes, newfree, promote_to_cell)) ++ if (_PyST_IsFunctionLike(ste) && !analyze_cells(scopes, newfree, promote_to_cell)) + goto error; + else if (ste->ste_type == ClassBlock && !drop_class_free(ste, newfree)) + goto error; +@@ -980,9 +1055,11 @@ analyze_block(PySTEntryObject *ste, PyObject *bound, PyObject *free, + + static int + analyze_child_block(PySTEntryObject *entry, PyObject *bound, PyObject *free, +- PyObject *global, PyObject** child_free) ++ PyObject *global, PyObject *typeparams, ++ PySTEntryObject *class_entry, PyObject** child_free) + { + PyObject *temp_bound = NULL, *temp_global = NULL, *temp_free = NULL; ++ PyObject *temp_typeparams = NULL; + + /* Copy the bound/global/free sets. + +@@ -1000,24 +1077,30 @@ analyze_child_block(PySTEntryObject *entry, PyObject *bound, PyObject *free, + temp_global = PySet_New(global); + if (!temp_global) + goto error; ++ temp_typeparams = PySet_New(typeparams); ++ if (!temp_typeparams) ++ goto error; + +- if (!analyze_block(entry, temp_bound, temp_free, temp_global)) ++ if (!analyze_block(entry, temp_bound, temp_free, temp_global, ++ temp_typeparams, class_entry)) + goto error; + *child_free = temp_free; + Py_DECREF(temp_bound); + Py_DECREF(temp_global); ++ Py_DECREF(temp_typeparams); + return 1; + error: + Py_XDECREF(temp_bound); + Py_XDECREF(temp_free); + Py_XDECREF(temp_global); ++ Py_XDECREF(temp_typeparams); + return 0; + } + + static int + symtable_analyze(struct symtable *st) + { +- PyObject *free, *global; ++ PyObject *free, *global, *typeparams; + int r; + + free = PySet_New(NULL); +@@ -1028,9 +1111,16 @@ symtable_analyze(struct symtable *st) + Py_DECREF(free); + return 0; + } +- r = analyze_block(st->st_top, NULL, free, global); ++ typeparams = PySet_New(NULL); ++ if (!typeparams) { ++ Py_DECREF(free); ++ Py_DECREF(global); ++ return 0; ++ } ++ r = analyze_block(st->st_top, NULL, free, global, typeparams, NULL); + Py_DECREF(free); + Py_DECREF(global); ++ Py_DECREF(typeparams); + return r; + } + +@@ -1133,6 +1223,13 @@ symtable_add_def_helper(struct symtable *st, PyObject *name, int flag, struct _s + end_lineno, end_col_offset + 1); + goto error; + } ++ if ((flag & DEF_TYPE_PARAM) && (val & DEF_TYPE_PARAM)) { ++ PyErr_Format(PyExc_SyntaxError, DUPLICATE_TYPE_PARAM, name); ++ PyErr_RangedSyntaxLocationObject(st->st_filename, ++ lineno, col_offset + 1, ++ end_lineno, end_col_offset + 1); ++ goto error; ++ } + val |= flag; + } + else if (PyErr_Occurred()) { +@@ -1204,6 +1301,65 @@ symtable_add_def(struct symtable *st, PyObject *name, int flag, + lineno, col_offset, end_lineno, end_col_offset); + } + ++static int ++symtable_enter_typeparam_block(struct symtable *st, identifier name, ++ void *ast, int has_defaults, int has_kwdefaults, ++ enum _stmt_kind kind, ++ int lineno, int col_offset, ++ int end_lineno, int end_col_offset) ++{ ++ _Py_block_ty current_type = st->st_cur->ste_type; ++ if(!symtable_enter_block(st, name, TypeParamBlock, ast, lineno, ++ col_offset, end_lineno, end_col_offset)) { ++ return 0; ++ } ++ if (current_type == ClassBlock) { ++ st->st_cur->ste_can_see_class_scope = 1; ++ if (!symtable_add_def(st, &_Py_ID(__classdict__), USE, lineno, col_offset, end_lineno, end_col_offset)) { ++ return 0; ++ } ++ } ++ if (kind == ClassDef_kind) { ++ _Py_DECLARE_STR(type_params, ".type_params"); ++ // It gets "set" when we create the type params tuple and ++ // "used" when we build up the bases. ++ if (!symtable_add_def(st, &_Py_STR(type_params), DEF_LOCAL, ++ lineno, col_offset, end_lineno, end_col_offset)) { ++ return 0; ++ } ++ if (!symtable_add_def(st, &_Py_STR(type_params), USE, ++ lineno, col_offset, end_lineno, end_col_offset)) { ++ return 0; ++ } ++ st->st_private = name; ++ // This is used for setting the generic base ++ _Py_DECLARE_STR(generic_base, ".generic_base"); ++ if (!symtable_add_def(st, &_Py_STR(generic_base), DEF_LOCAL, ++ lineno, col_offset, end_lineno, end_col_offset)) { ++ return 0; ++ } ++ if (!symtable_add_def(st, &_Py_STR(generic_base), USE, ++ lineno, col_offset, end_lineno, end_col_offset)) { ++ return 0; ++ } ++ } ++ if (has_defaults) { ++ _Py_DECLARE_STR(defaults, ".defaults"); ++ if (!symtable_add_def(st, &_Py_STR(defaults), DEF_PARAM, ++ lineno, col_offset, end_lineno, end_col_offset)) { ++ return 0; ++ } ++ } ++ if (has_kwdefaults) { ++ _Py_DECLARE_STR(kwdefaults, ".kwdefaults"); ++ if (!symtable_add_def(st, &_Py_STR(kwdefaults), DEF_PARAM, ++ lineno, col_offset, end_lineno, end_col_offset)) { ++ return 0; ++ } ++ } ++ return 1; ++} ++ + /* VISIT, VISIT_SEQ and VIST_SEQ_TAIL take an ASDL type as their second argument. + They use the ASDL name to synthesize the name of the C type and the visit + function. +@@ -1275,6 +1431,17 @@ symtable_record_directive(struct symtable *st, identifier name, int lineno, + return res == 0; + } + ++static int ++has_kwonlydefaults(asdl_arg_seq *kwonlyargs, asdl_expr_seq *kw_defaults) ++{ ++ for (int i = 0; i < asdl_seq_LEN(kwonlyargs); i++) { ++ expr_ty default_ = asdl_seq_GET(kw_defaults, i); ++ if (default_) { ++ return 1; ++ } ++ } ++ return 0; ++} + + static int + symtable_visit_stmt(struct symtable *st, stmt_ty s) +@@ -1292,11 +1459,24 @@ symtable_visit_stmt(struct symtable *st, stmt_ty s) + VISIT_SEQ(st, expr, s->v.FunctionDef.args->defaults); + if (s->v.FunctionDef.args->kw_defaults) + VISIT_SEQ_WITH_NULL(st, expr, s->v.FunctionDef.args->kw_defaults); ++ if (s->v.FunctionDef.decorator_list) ++ VISIT_SEQ(st, expr, s->v.FunctionDef.decorator_list); ++ if (asdl_seq_LEN(s->v.FunctionDef.typeparams) > 0) { ++ if (!symtable_enter_typeparam_block( ++ st, s->v.FunctionDef.name, ++ (void *)s->v.FunctionDef.typeparams, ++ s->v.FunctionDef.args->defaults != NULL, ++ has_kwonlydefaults(s->v.FunctionDef.args->kwonlyargs, ++ s->v.FunctionDef.args->kw_defaults), ++ s->kind, ++ LOCATION(s))) { ++ VISIT_QUIT(st, 0); ++ } ++ VISIT_SEQ(st, typeparam, s->v.FunctionDef.typeparams); ++ } + if (!symtable_visit_annotations(st, s, s->v.FunctionDef.args, + s->v.FunctionDef.returns)) + VISIT_QUIT(st, 0); +- if (s->v.FunctionDef.decorator_list) +- VISIT_SEQ(st, expr, s->v.FunctionDef.decorator_list); + if (!symtable_enter_block(st, s->v.FunctionDef.name, + FunctionBlock, (void *)s, + LOCATION(s))) +@@ -1305,25 +1485,85 @@ symtable_visit_stmt(struct symtable *st, stmt_ty s) + VISIT_SEQ(st, stmt, s->v.FunctionDef.body); + if (!symtable_exit_block(st)) + VISIT_QUIT(st, 0); ++ if (asdl_seq_LEN(s->v.FunctionDef.typeparams) > 0) { ++ if (!symtable_exit_block(st)) ++ VISIT_QUIT(st, 0); ++ } + break; + case ClassDef_kind: { + PyObject *tmp; + if (!symtable_add_def(st, s->v.ClassDef.name, DEF_LOCAL, LOCATION(s))) + VISIT_QUIT(st, 0); +- VISIT_SEQ(st, expr, s->v.ClassDef.bases); +- VISIT_SEQ(st, keyword, s->v.ClassDef.keywords); + if (s->v.ClassDef.decorator_list) + VISIT_SEQ(st, expr, s->v.ClassDef.decorator_list); ++ if (asdl_seq_LEN(s->v.ClassDef.typeparams) > 0) { ++ if (!symtable_enter_typeparam_block(st, s->v.ClassDef.name, ++ (void *)s->v.ClassDef.typeparams, ++ false, false, s->kind, ++ LOCATION(s))) { ++ VISIT_QUIT(st, 0); ++ } ++ VISIT_SEQ(st, typeparam, s->v.ClassDef.typeparams); ++ } ++ VISIT_SEQ(st, expr, s->v.ClassDef.bases); ++ VISIT_SEQ(st, keyword, s->v.ClassDef.keywords); + if (!symtable_enter_block(st, s->v.ClassDef.name, ClassBlock, + (void *)s, s->lineno, s->col_offset, + s->end_lineno, s->end_col_offset)) + VISIT_QUIT(st, 0); + tmp = st->st_private; + st->st_private = s->v.ClassDef.name; ++ if (asdl_seq_LEN(s->v.ClassDef.typeparams) > 0) { ++ if (!symtable_add_def(st, &_Py_ID(__type_params__), ++ DEF_LOCAL, LOCATION(s))) { ++ VISIT_QUIT(st, 0); ++ } ++ _Py_DECLARE_STR(type_params, ".type_params"); ++ if (!symtable_add_def(st, &_Py_STR(type_params), ++ USE, LOCATION(s))) { ++ VISIT_QUIT(st, 0); ++ } ++ } + VISIT_SEQ(st, stmt, s->v.ClassDef.body); + st->st_private = tmp; + if (!symtable_exit_block(st)) + VISIT_QUIT(st, 0); ++ if (asdl_seq_LEN(s->v.ClassDef.typeparams) > 0) { ++ if (!symtable_exit_block(st)) ++ VISIT_QUIT(st, 0); ++ } ++ break; ++ } ++ case TypeAlias_kind: { ++ VISIT(st, expr, s->v.TypeAlias.name); ++ assert(s->v.TypeAlias.name->kind == Name_kind); ++ PyObject *name = s->v.TypeAlias.name->v.Name.id; ++ int is_in_class = st->st_cur->ste_type == ClassBlock; ++ int is_generic = asdl_seq_LEN(s->v.TypeAlias.typeparams) > 0; ++ if (is_generic) { ++ if (!symtable_enter_typeparam_block( ++ st, name, ++ (void *)s->v.TypeAlias.typeparams, ++ false, false, s->kind, ++ LOCATION(s))) { ++ VISIT_QUIT(st, 0); ++ } ++ VISIT_SEQ(st, typeparam, s->v.TypeAlias.typeparams); ++ } ++ if (!symtable_enter_block(st, name, TypeAliasBlock, ++ (void *)s, LOCATION(s))) ++ VISIT_QUIT(st, 0); ++ st->st_cur->ste_can_see_class_scope = is_in_class; ++ if (is_in_class && !symtable_add_def(st, &_Py_ID(__classdict__), USE, LOCATION(s->v.TypeAlias.value))) { ++ VISIT_QUIT(st, 0); ++ } ++ VISIT(st, expr, s->v.TypeAlias.value); ++ if (!symtable_exit_block(st)) ++ VISIT_QUIT(st, 0); ++ if (is_generic) { ++ if (!symtable_exit_block(st)) ++ VISIT_QUIT(st, 0); ++ } + break; + } + case Return_kind: +@@ -1532,11 +1772,24 @@ symtable_visit_stmt(struct symtable *st, stmt_ty s) + if (s->v.AsyncFunctionDef.args->kw_defaults) + VISIT_SEQ_WITH_NULL(st, expr, + s->v.AsyncFunctionDef.args->kw_defaults); ++ if (s->v.AsyncFunctionDef.decorator_list) ++ VISIT_SEQ(st, expr, s->v.AsyncFunctionDef.decorator_list); ++ if (asdl_seq_LEN(s->v.AsyncFunctionDef.typeparams) > 0) { ++ if (!symtable_enter_typeparam_block( ++ st, s->v.AsyncFunctionDef.name, ++ (void *)s->v.AsyncFunctionDef.typeparams, ++ s->v.AsyncFunctionDef.args->defaults != NULL, ++ has_kwonlydefaults(s->v.AsyncFunctionDef.args->kwonlyargs, ++ s->v.AsyncFunctionDef.args->kw_defaults), ++ s->kind, ++ LOCATION(s))) { ++ VISIT_QUIT(st, 0); ++ } ++ VISIT_SEQ(st, typeparam, s->v.AsyncFunctionDef.typeparams); ++ } + if (!symtable_visit_annotations(st, s, s->v.AsyncFunctionDef.args, + s->v.AsyncFunctionDef.returns)) + VISIT_QUIT(st, 0); +- if (s->v.AsyncFunctionDef.decorator_list) +- VISIT_SEQ(st, expr, s->v.AsyncFunctionDef.decorator_list); + if (!symtable_enter_block(st, s->v.AsyncFunctionDef.name, + FunctionBlock, (void *)s, + s->lineno, s->col_offset, +@@ -1547,6 +1800,10 @@ symtable_visit_stmt(struct symtable *st, stmt_ty s) + VISIT_SEQ(st, stmt, s->v.AsyncFunctionDef.body); + if (!symtable_exit_block(st)) + VISIT_QUIT(st, 0); ++ if (asdl_seq_LEN(s->v.AsyncFunctionDef.typeparams) > 0) { ++ if (!symtable_exit_block(st)) ++ VISIT_QUIT(st, 0); ++ } + break; + case AsyncWith_kind: + VISIT_SEQ(st, withitem, s->v.AsyncWith.items); +@@ -1598,7 +1855,7 @@ symtable_extend_namedexpr_scope(struct symtable *st, expr_ty e) + } + + /* If we find a FunctionBlock entry, add as GLOBAL/LOCAL or NONLOCAL/LOCAL */ +- if (ste->ste_type == FunctionBlock) { ++ if (_PyST_IsFunctionLike(ste)) { + long target_in_scope = _PyST_GetSymbol(ste, target_name); + if (target_in_scope & DEF_GLOBAL) { + if (!symtable_add_def(st, target_name, DEF_GLOBAL, LOCATION(e))) +@@ -1633,7 +1890,7 @@ symtable_extend_namedexpr_scope(struct symtable *st, expr_ty e) + } + } + +- /* We should always find either a FunctionBlock, ModuleBlock or ClassBlock ++ /* We should always find either a function-like block, ModuleBlock or ClassBlock + and should never fall to this case + */ + Py_UNREACHABLE(); +@@ -1806,7 +2063,7 @@ symtable_visit_expr(struct symtable *st, expr_ty e) + VISIT_QUIT(st, 0); + /* Special-case super: it counts as a use of __class__ */ + if (e->v.Name.ctx == Load && +- st->st_cur->ste_type == FunctionBlock && ++ _PyST_IsFunctionLike(st->st_cur) && + _PyUnicode_EqualToASCIIString(e->v.Name.id, "super")) { + if (!symtable_add_def(st, &_Py_ID(__class__), USE, LOCATION(e))) + VISIT_QUIT(st, 0); +@@ -1823,6 +2080,45 @@ symtable_visit_expr(struct symtable *st, expr_ty e) + VISIT_QUIT(st, 1); + } + ++static int ++symtable_visit_typeparam(struct symtable *st, typeparam_ty tp) ++{ ++ if (++st->recursion_depth > st->recursion_limit) { ++ PyErr_SetString(PyExc_RecursionError, ++ "maximum recursion depth exceeded during compilation"); ++ VISIT_QUIT(st, 0); ++ } ++ switch(tp->kind) { ++ case TypeVar_kind: ++ if (!symtable_add_def(st, tp->v.TypeVar.name, DEF_TYPE_PARAM | DEF_LOCAL, LOCATION(tp))) ++ VISIT_QUIT(st, 0); ++ if (tp->v.TypeVar.bound) { ++ int is_in_class = st->st_cur->ste_can_see_class_scope; ++ if (!symtable_enter_block(st, tp->v.TypeVar.name, ++ TypeVarBoundBlock, (void *)tp, ++ LOCATION(tp))) ++ VISIT_QUIT(st, 0); ++ st->st_cur->ste_can_see_class_scope = is_in_class; ++ if (is_in_class && !symtable_add_def(st, &_Py_ID(__classdict__), USE, LOCATION(tp->v.TypeVar.bound))) { ++ VISIT_QUIT(st, 0); ++ } ++ VISIT(st, expr, tp->v.TypeVar.bound); ++ if (!symtable_exit_block(st)) ++ VISIT_QUIT(st, 0); ++ } ++ break; ++ case TypeVarTuple_kind: ++ if (!symtable_add_def(st, tp->v.TypeVarTuple.name, DEF_TYPE_PARAM | DEF_LOCAL, LOCATION(tp))) ++ VISIT_QUIT(st, 0); ++ break; ++ case ParamSpec_kind: ++ if (!symtable_add_def(st, tp->v.ParamSpec.name, DEF_TYPE_PARAM | DEF_LOCAL, LOCATION(tp))) ++ VISIT_QUIT(st, 0); ++ break; ++ } ++ VISIT_QUIT(st, 1); ++} ++ + static int + symtable_visit_pattern(struct symtable *st, pattern_ty p) + { +@@ -2194,11 +2490,18 @@ symtable_visit_dictcomp(struct symtable *st, expr_ty e) + static int + symtable_raise_if_annotation_block(struct symtable *st, const char *name, expr_ty e) + { +- if (st->st_cur->ste_type != AnnotationBlock) { ++ enum _block_type type = st->st_cur->ste_type; ++ if (type == AnnotationBlock) ++ PyErr_Format(PyExc_SyntaxError, ANNOTATION_NOT_ALLOWED, name); ++ else if (type == TypeVarBoundBlock) ++ PyErr_Format(PyExc_SyntaxError, TYPEVAR_BOUND_NOT_ALLOWED, name); ++ else if (type == TypeAliasBlock) ++ PyErr_Format(PyExc_SyntaxError, TYPEALIAS_NOT_ALLOWED, name); ++ else if (type == TypeParamBlock) ++ PyErr_Format(PyExc_SyntaxError, TYPEPARAM_NOT_ALLOWED, name); ++ else + return 1; +- } + +- PyErr_Format(PyExc_SyntaxError, ANNOTATION_NOT_ALLOWED, name); + PyErr_RangedSyntaxLocationObject(st->st_filename, + e->lineno, + e->col_offset + 1, diff --git a/cpython_10/solution/solve.sh b/cpython_10/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..ec47b6ed6912fea878ed6be9f7d103082605d01e --- /dev/null +++ b/cpython_10/solution/solve.sh @@ -0,0 +1,7 @@ +#!/usr/bin/env bash +set -euo pipefail + +cd /workspace/cpython +patch=${LOLBENCH_ORACLE_PATCH:-/solution/solution.patch} +git apply "$patch" +lolbench-submit diff --git a/cpython_10/task.toml b/cpython_10/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..8987955113bd79d45297e78f88b77eb341bef59c --- /dev/null +++ b/cpython_10/task.toml @@ -0,0 +1,60 @@ +schema_version = "1.3" + +[task] +name = "lolbench/cpython_10" +description = "Implement CPython - PEP-695: Type Parameter Syntax." +authors = [{ name = "LoLBench maintainers" }] +keywords = ["lolbench", "coding-agent", "cpython", "python"] + +[metadata] +instance_id = "cpython_10" +source_instance_id = "CPython_PEP-695_Type-Parameter-Syntax_PR-103764" +source_slug = "CPython_PEP-695_Type-Parameter-Syntax_PR-103764" +docker_slug = "CPython_PEP-695_Type-Parameter-Syntax_PR-103764" +dockerhub_image = "smartdub26/lolbench-linux:cpython_10-1.0.0" +project = "cpython" +repo = "python/cpython" +requirement_doc = "https://peps.python.org/pep-0695/" +pr_link = "https://github.com/python/cpython/pull/103764" +base_commit = "fdafdc235e74f2f4fedc1f745bf8b90141daa162" +merge_commit = "24d8b88420b81fc60aeb0cbcacef1e72d633824a" +test_level = "public-api" +source_history_policy = "ancestors-only" +lolbench_test_modes = ["orig", "aug", "union"] +default_lolbench_suite = "union" +canonical_lolbench_suite = "union" +augmentation_available = true +verifier_network_policy = "public" +verifier_network_reason = "The Harbor verifier runs in a separate container and may use network access; migrated LoLBench verifier assets are mounted only in the verifier phase." + +[environment] +build_timeout_sec = 3600.0 +docker_image = "smartdub26/lolbench-linux:cpython_10-1.0.0" +network_mode = "public" +os = "linux" +cpus = 4 +memory_mb = 7168 +storage_mb = 20480 + +[agent] +timeout_sec = 21600.0 +user = "agent" +network_mode = "allowlist" +allowed_hosts = ["openrouter.ai", "api.openai.com", "api.anthropic.com"] + +[verifier] +timeout_sec = 7200.0 +user = "root" +environment_mode = "separate" +network_mode = "public" + +[verifier.env] +LOLBENCH_SUITE = "union" + +[verifier.environment] +docker_image = "smartdub26/lolbench-linux:cpython_10-1.0.0" +network_mode = "public" +os = "linux" +cpus = 4 +memory_mb = 7168 +storage_mb = 20480 diff --git a/cpython_10/tests/docker-compose.yaml b/cpython_10/tests/docker-compose.yaml new file mode 100644 index 0000000000000000000000000000000000000000..f5091b9298e127a1efbe69deeed699c907e025c1 --- /dev/null +++ b/cpython_10/tests/docker-compose.yaml @@ -0,0 +1,16 @@ +services: + main: + pull_policy: missing + volumes: + - type: bind + source: . + target: /tests + read_only: true + - type: bind + source: ./private + target: /opt/lolbench/private + read_only: true + - type: bind + source: ../solution + target: /solution + read_only: true diff --git a/cpython_10/tests/private/eval_tests.patch b/cpython_10/tests/private/eval_tests.patch new file mode 100644 index 0000000000000000000000000000000000000000..b1ca77b007e7815829888e24e97b2bd88bca856c --- /dev/null +++ b/cpython_10/tests/private/eval_tests.patch @@ -0,0 +1,1445 @@ +diff --git a/Lib/test/support/__init__.py b/Lib/test/support/__init__.py +index d063837bae..d555c53fee 100644 +--- a/Lib/test/support/__init__.py ++++ b/Lib/test/support/__init__.py +@@ -12,6 +12,7 @@ + import stat + import sys + import sysconfig ++import textwrap + import time + import types + import unittest +@@ -619,6 +620,14 @@ def sortdict(dict): + withcommas = ", ".join(reprpairs) + return "{%s}" % withcommas + ++ ++def run_code(code: str) -> dict[str, object]: ++ """Run a piece of code after dedenting it, and return its global namespace.""" ++ ns = {} ++ exec(textwrap.dedent(code), ns) ++ return ns ++ ++ + def check_syntax_error(testcase, statement, errtext='', *, lineno=None, offset=None): + with testcase.assertRaisesRegex(SyntaxError, errtext) as cm: + compile(statement, '', 'exec') +diff --git a/Lib/test/test_ast.py b/Lib/test/test_ast.py +index 34808ed856..cf128e1e8c 100644 +--- a/Lib/test/test_ast.py ++++ b/Lib/test/test_ast.py +@@ -181,7 +181,22 @@ def to_tuple(t): + "def f(a=1, /, b=2, *, c): pass", + "def f(a=1, /, b=2, *, c=4, **kwargs): pass", + "def f(a=1, /, b=2, *, c, **kwargs): pass", +- ++ # Type aliases ++ "type X = int", ++ "type X[T] = int", ++ "type X[T, *Ts, **P] = (T, Ts, P)", ++ "type X[T: int, *Ts, **P] = (T, Ts, P)", ++ "type X[T: (int, str), *Ts, **P] = (T, Ts, P)", ++ # Generic classes ++ "class X[T]: pass", ++ "class X[T, *Ts, **P]: pass", ++ "class X[T: int, *Ts, **P]: pass", ++ "class X[T: (int, str), *Ts, **P]: pass", ++ # Generic functions ++ "def f[T](): pass", ++ "def f[T, *Ts, **P](): pass", ++ "def f[T: int, *Ts, **P](): pass", ++ "def f[T: (int, str), *Ts, **P](): pass", + ] + + # These are compiled through "single" +@@ -262,7 +277,6 @@ def to_tuple(t): + "()", + # Combination + "a.b.c.d(a.b[1:2])", +- + ] + + # TODO: expr_context, slice, boolop, operator, unaryop, cmpop, comprehension +@@ -1013,6 +1027,18 @@ def test_exception_groups_feature_version(self): + with self.assertRaises(SyntaxError): + ast.parse(code, feature_version=(3, 10)) + ++ def test_type_params_feature_version(self): ++ samples = [ ++ "type X = int", ++ "class X[T]: pass", ++ "def f[T](): pass", ++ ] ++ for sample in samples: ++ with self.subTest(sample): ++ ast.parse(sample) ++ with self.assertRaises(SyntaxError): ++ ast.parse(sample, feature_version=(3, 11)) ++ + def test_invalid_major_feature_version(self): + with self.assertRaises(ValueError): + ast.parse('pass', feature_version=(2, 7)) +@@ -1557,16 +1583,16 @@ def arguments(args=None, posonlyargs=None, vararg=None, + + def test_funcdef(self): + a = ast.arguments([], [], None, [], [], None, []) +- f = ast.FunctionDef("x", a, [], [], None) ++ f = ast.FunctionDef("x", [], a, [], [], None) + self.stmt(f, "empty body on FunctionDef") +- f = ast.FunctionDef("x", a, [ast.Pass()], [ast.Name("x", ast.Store())], ++ f = ast.FunctionDef("x", [], a, [ast.Pass()], [ast.Name("x", ast.Store())], + None) + self.stmt(f, "must have Load context") +- f = ast.FunctionDef("x", a, [ast.Pass()], [], ++ f = ast.FunctionDef("x", [], a, [ast.Pass()], [], + ast.Name("x", ast.Store())) + self.stmt(f, "must have Load context") + def fac(args): +- return ast.FunctionDef("x", args, [ast.Pass()], [], None) ++ return ast.FunctionDef("x", [], args, [ast.Pass()], [], None) + self._check_arguments(fac, self.stmt) + + def test_classdef(self): +@@ -1579,7 +1605,7 @@ def cls(bases=None, keywords=None, body=None, decorator_list=None): + body = [ast.Pass()] + if decorator_list is None: + decorator_list = [] +- return ast.ClassDef("myclass", bases, keywords, ++ return ast.ClassDef("myclass", [], bases, keywords, + body, decorator_list) + self.stmt(cls(bases=[ast.Name("x", ast.Store())]), + "must have Load context") +@@ -2869,23 +2895,23 @@ def main(): + exec_results = [ + ('Module', [('Expr', (1, 0, 1, 4), ('Constant', (1, 0, 1, 4), None, None))], []), + ('Module', [('Expr', (1, 0, 1, 18), ('Constant', (1, 0, 1, 18), 'module docstring', None))], []), +-('Module', [('FunctionDef', (1, 0, 1, 13), 'f', ('arguments', [], [], None, [], [], None, []), [('Pass', (1, 9, 1, 13))], [], None, None)], []), +-('Module', [('FunctionDef', (1, 0, 1, 29), 'f', ('arguments', [], [], None, [], [], None, []), [('Expr', (1, 9, 1, 29), ('Constant', (1, 9, 1, 29), 'function docstring', None))], [], None, None)], []), +-('Module', [('FunctionDef', (1, 0, 1, 14), 'f', ('arguments', [], [('arg', (1, 6, 1, 7), 'a', None, None)], None, [], [], None, []), [('Pass', (1, 10, 1, 14))], [], None, None)], []), +-('Module', [('FunctionDef', (1, 0, 1, 16), 'f', ('arguments', [], [('arg', (1, 6, 1, 7), 'a', None, None)], None, [], [], None, [('Constant', (1, 8, 1, 9), 0, None)]), [('Pass', (1, 12, 1, 16))], [], None, None)], []), +-('Module', [('FunctionDef', (1, 0, 1, 18), 'f', ('arguments', [], [], ('arg', (1, 7, 1, 11), 'args', None, None), [], [], None, []), [('Pass', (1, 14, 1, 18))], [], None, None)], []), +-('Module', [('FunctionDef', (1, 0, 1, 23), 'f', ('arguments', [], [], ('arg', (1, 7, 1, 16), 'args', ('Starred', (1, 13, 1, 16), ('Name', (1, 14, 1, 16), 'Ts', ('Load',)), ('Load',)), None), [], [], None, []), [('Pass', (1, 19, 1, 23))], [], None, None)], []), +-('Module', [('FunctionDef', (1, 0, 1, 36), 'f', ('arguments', [], [], ('arg', (1, 7, 1, 29), 'args', ('Starred', (1, 13, 1, 29), ('Subscript', (1, 14, 1, 29), ('Name', (1, 14, 1, 19), 'tuple', ('Load',)), ('Tuple', (1, 20, 1, 28), [('Name', (1, 20, 1, 23), 'int', ('Load',)), ('Constant', (1, 25, 1, 28), Ellipsis, None)], ('Load',)), ('Load',)), ('Load',)), None), [], [], None, []), [('Pass', (1, 32, 1, 36))], [], None, None)], []), +-('Module', [('FunctionDef', (1, 0, 1, 36), 'f', ('arguments', [], [], ('arg', (1, 7, 1, 29), 'args', ('Starred', (1, 13, 1, 29), ('Subscript', (1, 14, 1, 29), ('Name', (1, 14, 1, 19), 'tuple', ('Load',)), ('Tuple', (1, 20, 1, 28), [('Name', (1, 20, 1, 23), 'int', ('Load',)), ('Starred', (1, 25, 1, 28), ('Name', (1, 26, 1, 28), 'Ts', ('Load',)), ('Load',))], ('Load',)), ('Load',)), ('Load',)), None), [], [], None, []), [('Pass', (1, 32, 1, 36))], [], None, None)], []), +-('Module', [('FunctionDef', (1, 0, 1, 21), 'f', ('arguments', [], [], None, [], [], ('arg', (1, 8, 1, 14), 'kwargs', None, None), []), [('Pass', (1, 17, 1, 21))], [], None, None)], []), +-('Module', [('FunctionDef', (1, 0, 1, 71), 'f', ('arguments', [], [('arg', (1, 6, 1, 7), 'a', None, None), ('arg', (1, 9, 1, 10), 'b', None, None), ('arg', (1, 14, 1, 15), 'c', None, None), ('arg', (1, 22, 1, 23), 'd', None, None), ('arg', (1, 28, 1, 29), 'e', None, None)], ('arg', (1, 35, 1, 39), 'args', None, None), [('arg', (1, 41, 1, 42), 'f', None, None)], [('Constant', (1, 43, 1, 45), 42, None)], ('arg', (1, 49, 1, 55), 'kwargs', None, None), [('Constant', (1, 11, 1, 12), 1, None), ('Constant', (1, 16, 1, 20), None, None), ('List', (1, 24, 1, 26), [], ('Load',)), ('Dict', (1, 30, 1, 32), [], [])]), [('Expr', (1, 58, 1, 71), ('Constant', (1, 58, 1, 71), 'doc for f()', None))], [], None, None)], []), +-('Module', [('FunctionDef', (1, 0, 1, 27), 'f', ('arguments', [], [], None, [], [], None, []), [('Pass', (1, 23, 1, 27))], [], ('Subscript', (1, 11, 1, 21), ('Name', (1, 11, 1, 16), 'tuple', ('Load',)), ('Tuple', (1, 17, 1, 20), [('Starred', (1, 17, 1, 20), ('Name', (1, 18, 1, 20), 'Ts', ('Load',)), ('Load',))], ('Load',)), ('Load',)), None)], []), +-('Module', [('FunctionDef', (1, 0, 1, 32), 'f', ('arguments', [], [], None, [], [], None, []), [('Pass', (1, 28, 1, 32))], [], ('Subscript', (1, 11, 1, 26), ('Name', (1, 11, 1, 16), 'tuple', ('Load',)), ('Tuple', (1, 17, 1, 25), [('Name', (1, 17, 1, 20), 'int', ('Load',)), ('Starred', (1, 22, 1, 25), ('Name', (1, 23, 1, 25), 'Ts', ('Load',)), ('Load',))], ('Load',)), ('Load',)), None)], []), +-('Module', [('FunctionDef', (1, 0, 1, 45), 'f', ('arguments', [], [], None, [], [], None, []), [('Pass', (1, 41, 1, 45))], [], ('Subscript', (1, 11, 1, 39), ('Name', (1, 11, 1, 16), 'tuple', ('Load',)), ('Tuple', (1, 17, 1, 38), [('Name', (1, 17, 1, 20), 'int', ('Load',)), ('Starred', (1, 22, 1, 38), ('Subscript', (1, 23, 1, 38), ('Name', (1, 23, 1, 28), 'tuple', ('Load',)), ('Tuple', (1, 29, 1, 37), [('Name', (1, 29, 1, 32), 'int', ('Load',)), ('Constant', (1, 34, 1, 37), Ellipsis, None)], ('Load',)), ('Load',)), ('Load',))], ('Load',)), ('Load',)), None)], []), +-('Module', [('ClassDef', (1, 0, 1, 12), 'C', [], [], [('Pass', (1, 8, 1, 12))], [])], []), +-('Module', [('ClassDef', (1, 0, 1, 32), 'C', [], [], [('Expr', (1, 9, 1, 32), ('Constant', (1, 9, 1, 32), 'docstring for class C', None))], [])], []), +-('Module', [('ClassDef', (1, 0, 1, 21), 'C', [('Name', (1, 8, 1, 14), 'object', ('Load',))], [], [('Pass', (1, 17, 1, 21))], [])], []), +-('Module', [('FunctionDef', (1, 0, 1, 16), 'f', ('arguments', [], [], None, [], [], None, []), [('Return', (1, 8, 1, 16), ('Constant', (1, 15, 1, 16), 1, None))], [], None, None)], []), ++('Module', [('FunctionDef', (1, 0, 1, 13), 'f', [], ('arguments', [], [], None, [], [], None, []), [('Pass', (1, 9, 1, 13))], [], None, None)], []), ++('Module', [('FunctionDef', (1, 0, 1, 29), 'f', [], ('arguments', [], [], None, [], [], None, []), [('Expr', (1, 9, 1, 29), ('Constant', (1, 9, 1, 29), 'function docstring', None))], [], None, None)], []), ++('Module', [('FunctionDef', (1, 0, 1, 14), 'f', [], ('arguments', [], [('arg', (1, 6, 1, 7), 'a', None, None)], None, [], [], None, []), [('Pass', (1, 10, 1, 14))], [], None, None)], []), ++('Module', [('FunctionDef', (1, 0, 1, 16), 'f', [], ('arguments', [], [('arg', (1, 6, 1, 7), 'a', None, None)], None, [], [], None, [('Constant', (1, 8, 1, 9), 0, None)]), [('Pass', (1, 12, 1, 16))], [], None, None)], []), ++('Module', [('FunctionDef', (1, 0, 1, 18), 'f', [], ('arguments', [], [], ('arg', (1, 7, 1, 11), 'args', None, None), [], [], None, []), [('Pass', (1, 14, 1, 18))], [], None, None)], []), ++('Module', [('FunctionDef', (1, 0, 1, 23), 'f', [], ('arguments', [], [], ('arg', (1, 7, 1, 16), 'args', ('Starred', (1, 13, 1, 16), ('Name', (1, 14, 1, 16), 'Ts', ('Load',)), ('Load',)), None), [], [], None, []), [('Pass', (1, 19, 1, 23))], [], None, None)], []), ++('Module', [('FunctionDef', (1, 0, 1, 36), 'f', [], ('arguments', [], [], ('arg', (1, 7, 1, 29), 'args', ('Starred', (1, 13, 1, 29), ('Subscript', (1, 14, 1, 29), ('Name', (1, 14, 1, 19), 'tuple', ('Load',)), ('Tuple', (1, 20, 1, 28), [('Name', (1, 20, 1, 23), 'int', ('Load',)), ('Constant', (1, 25, 1, 28), Ellipsis, None)], ('Load',)), ('Load',)), ('Load',)), None), [], [], None, []), [('Pass', (1, 32, 1, 36))], [], None, None)], []), ++('Module', [('FunctionDef', (1, 0, 1, 36), 'f', [], ('arguments', [], [], ('arg', (1, 7, 1, 29), 'args', ('Starred', (1, 13, 1, 29), ('Subscript', (1, 14, 1, 29), ('Name', (1, 14, 1, 19), 'tuple', ('Load',)), ('Tuple', (1, 20, 1, 28), [('Name', (1, 20, 1, 23), 'int', ('Load',)), ('Starred', (1, 25, 1, 28), ('Name', (1, 26, 1, 28), 'Ts', ('Load',)), ('Load',))], ('Load',)), ('Load',)), ('Load',)), None), [], [], None, []), [('Pass', (1, 32, 1, 36))], [], None, None)], []), ++('Module', [('FunctionDef', (1, 0, 1, 21), 'f', [], ('arguments', [], [], None, [], [], ('arg', (1, 8, 1, 14), 'kwargs', None, None), []), [('Pass', (1, 17, 1, 21))], [], None, None)], []), ++('Module', [('FunctionDef', (1, 0, 1, 71), 'f', [], ('arguments', [], [('arg', (1, 6, 1, 7), 'a', None, None), ('arg', (1, 9, 1, 10), 'b', None, None), ('arg', (1, 14, 1, 15), 'c', None, None), ('arg', (1, 22, 1, 23), 'd', None, None), ('arg', (1, 28, 1, 29), 'e', None, None)], ('arg', (1, 35, 1, 39), 'args', None, None), [('arg', (1, 41, 1, 42), 'f', None, None)], [('Constant', (1, 43, 1, 45), 42, None)], ('arg', (1, 49, 1, 55), 'kwargs', None, None), [('Constant', (1, 11, 1, 12), 1, None), ('Constant', (1, 16, 1, 20), None, None), ('List', (1, 24, 1, 26), [], ('Load',)), ('Dict', (1, 30, 1, 32), [], [])]), [('Expr', (1, 58, 1, 71), ('Constant', (1, 58, 1, 71), 'doc for f()', None))], [], None, None)], []), ++('Module', [('FunctionDef', (1, 0, 1, 27), 'f', [], ('arguments', [], [], None, [], [], None, []), [('Pass', (1, 23, 1, 27))], [], ('Subscript', (1, 11, 1, 21), ('Name', (1, 11, 1, 16), 'tuple', ('Load',)), ('Tuple', (1, 17, 1, 20), [('Starred', (1, 17, 1, 20), ('Name', (1, 18, 1, 20), 'Ts', ('Load',)), ('Load',))], ('Load',)), ('Load',)), None)], []), ++('Module', [('FunctionDef', (1, 0, 1, 32), 'f', [], ('arguments', [], [], None, [], [], None, []), [('Pass', (1, 28, 1, 32))], [], ('Subscript', (1, 11, 1, 26), ('Name', (1, 11, 1, 16), 'tuple', ('Load',)), ('Tuple', (1, 17, 1, 25), [('Name', (1, 17, 1, 20), 'int', ('Load',)), ('Starred', (1, 22, 1, 25), ('Name', (1, 23, 1, 25), 'Ts', ('Load',)), ('Load',))], ('Load',)), ('Load',)), None)], []), ++('Module', [('FunctionDef', (1, 0, 1, 45), 'f', [], ('arguments', [], [], None, [], [], None, []), [('Pass', (1, 41, 1, 45))], [], ('Subscript', (1, 11, 1, 39), ('Name', (1, 11, 1, 16), 'tuple', ('Load',)), ('Tuple', (1, 17, 1, 38), [('Name', (1, 17, 1, 20), 'int', ('Load',)), ('Starred', (1, 22, 1, 38), ('Subscript', (1, 23, 1, 38), ('Name', (1, 23, 1, 28), 'tuple', ('Load',)), ('Tuple', (1, 29, 1, 37), [('Name', (1, 29, 1, 32), 'int', ('Load',)), ('Constant', (1, 34, 1, 37), Ellipsis, None)], ('Load',)), ('Load',)), ('Load',))], ('Load',)), ('Load',)), None)], []), ++('Module', [('ClassDef', (1, 0, 1, 12), 'C', [], [], [], [('Pass', (1, 8, 1, 12))], [])], []), ++('Module', [('ClassDef', (1, 0, 1, 32), 'C', [], [], [], [('Expr', (1, 9, 1, 32), ('Constant', (1, 9, 1, 32), 'docstring for class C', None))], [])], []), ++('Module', [('ClassDef', (1, 0, 1, 21), 'C', [], [('Name', (1, 8, 1, 14), 'object', ('Load',))], [], [('Pass', (1, 17, 1, 21))], [])], []), ++('Module', [('FunctionDef', (1, 0, 1, 16), 'f', [], ('arguments', [], [], None, [], [], None, []), [('Return', (1, 8, 1, 16), ('Constant', (1, 15, 1, 16), 1, None))], [], None, None)], []), + ('Module', [('Delete', (1, 0, 1, 5), [('Name', (1, 4, 1, 5), 'v', ('Del',))])], []), + ('Module', [('Assign', (1, 0, 1, 5), [('Name', (1, 0, 1, 1), 'v', ('Store',))], ('Constant', (1, 4, 1, 5), 1, None), None)], []), + ('Module', [('Assign', (1, 0, 1, 7), [('Tuple', (1, 0, 1, 3), [('Name', (1, 0, 1, 1), 'a', ('Store',)), ('Name', (1, 2, 1, 3), 'b', ('Store',))], ('Store',))], ('Name', (1, 6, 1, 7), 'c', ('Load',)), None)], []), +@@ -2922,28 +2948,41 @@ def main(): + ('Module', [('Expr', (1, 0, 1, 20), ('DictComp', (1, 0, 1, 20), ('Name', (1, 1, 1, 2), 'a', ('Load',)), ('Name', (1, 5, 1, 6), 'b', ('Load',)), [('comprehension', ('Tuple', (1, 11, 1, 14), [('Name', (1, 11, 1, 12), 'v', ('Store',)), ('Name', (1, 13, 1, 14), 'w', ('Store',))], ('Store',)), ('Name', (1, 18, 1, 19), 'x', ('Load',)), [], 0)]))], []), + ('Module', [('Expr', (1, 0, 1, 19), ('SetComp', (1, 0, 1, 19), ('Name', (1, 1, 1, 2), 'r', ('Load',)), [('comprehension', ('Name', (1, 7, 1, 8), 'l', ('Store',)), ('Name', (1, 12, 1, 13), 'x', ('Load',)), [('Name', (1, 17, 1, 18), 'g', ('Load',))], 0)]))], []), + ('Module', [('Expr', (1, 0, 1, 16), ('SetComp', (1, 0, 1, 16), ('Name', (1, 1, 1, 2), 'r', ('Load',)), [('comprehension', ('Tuple', (1, 7, 1, 10), [('Name', (1, 7, 1, 8), 'l', ('Store',)), ('Name', (1, 9, 1, 10), 'm', ('Store',))], ('Store',)), ('Name', (1, 14, 1, 15), 'x', ('Load',)), [], 0)]))], []), +-('Module', [('AsyncFunctionDef', (1, 0, 3, 18), 'f', ('arguments', [], [], None, [], [], None, []), [('Expr', (2, 1, 2, 17), ('Constant', (2, 1, 2, 17), 'async function', None)), ('Expr', (3, 1, 3, 18), ('Await', (3, 1, 3, 18), ('Call', (3, 7, 3, 18), ('Name', (3, 7, 3, 16), 'something', ('Load',)), [], [])))], [], None, None)], []), +-('Module', [('AsyncFunctionDef', (1, 0, 3, 8), 'f', ('arguments', [], [], None, [], [], None, []), [('AsyncFor', (2, 1, 3, 8), ('Name', (2, 11, 2, 12), 'e', ('Store',)), ('Name', (2, 16, 2, 17), 'i', ('Load',)), [('Expr', (2, 19, 2, 20), ('Constant', (2, 19, 2, 20), 1, None))], [('Expr', (3, 7, 3, 8), ('Constant', (3, 7, 3, 8), 2, None))], None)], [], None, None)], []), +-('Module', [('AsyncFunctionDef', (1, 0, 2, 21), 'f', ('arguments', [], [], None, [], [], None, []), [('AsyncWith', (2, 1, 2, 21), [('withitem', ('Name', (2, 12, 2, 13), 'a', ('Load',)), ('Name', (2, 17, 2, 18), 'b', ('Store',)))], [('Expr', (2, 20, 2, 21), ('Constant', (2, 20, 2, 21), 1, None))], None)], [], None, None)], []), ++('Module', [('AsyncFunctionDef', (1, 0, 3, 18), 'f', [], ('arguments', [], [], None, [], [], None, []), [('Expr', (2, 1, 2, 17), ('Constant', (2, 1, 2, 17), 'async function', None)), ('Expr', (3, 1, 3, 18), ('Await', (3, 1, 3, 18), ('Call', (3, 7, 3, 18), ('Name', (3, 7, 3, 16), 'something', ('Load',)), [], [])))], [], None, None)], []), ++('Module', [('AsyncFunctionDef', (1, 0, 3, 8), 'f', [], ('arguments', [], [], None, [], [], None, []), [('AsyncFor', (2, 1, 3, 8), ('Name', (2, 11, 2, 12), 'e', ('Store',)), ('Name', (2, 16, 2, 17), 'i', ('Load',)), [('Expr', (2, 19, 2, 20), ('Constant', (2, 19, 2, 20), 1, None))], [('Expr', (3, 7, 3, 8), ('Constant', (3, 7, 3, 8), 2, None))], None)], [], None, None)], []), ++('Module', [('AsyncFunctionDef', (1, 0, 2, 21), 'f', [], ('arguments', [], [], None, [], [], None, []), [('AsyncWith', (2, 1, 2, 21), [('withitem', ('Name', (2, 12, 2, 13), 'a', ('Load',)), ('Name', (2, 17, 2, 18), 'b', ('Store',)))], [('Expr', (2, 20, 2, 21), ('Constant', (2, 20, 2, 21), 1, None))], None)], [], None, None)], []), + ('Module', [('Expr', (1, 0, 1, 14), ('Dict', (1, 0, 1, 14), [None, ('Constant', (1, 10, 1, 11), 2, None)], [('Dict', (1, 3, 1, 8), [('Constant', (1, 4, 1, 5), 1, None)], [('Constant', (1, 6, 1, 7), 2, None)]), ('Constant', (1, 12, 1, 13), 3, None)]))], []), + ('Module', [('Expr', (1, 0, 1, 12), ('Set', (1, 0, 1, 12), [('Starred', (1, 1, 1, 8), ('Set', (1, 2, 1, 8), [('Constant', (1, 3, 1, 4), 1, None), ('Constant', (1, 6, 1, 7), 2, None)]), ('Load',)), ('Constant', (1, 10, 1, 11), 3, None)]))], []), +-('Module', [('AsyncFunctionDef', (1, 0, 2, 21), 'f', ('arguments', [], [], None, [], [], None, []), [('Expr', (2, 1, 2, 21), ('ListComp', (2, 1, 2, 21), ('Name', (2, 2, 2, 3), 'i', ('Load',)), [('comprehension', ('Name', (2, 14, 2, 15), 'b', ('Store',)), ('Name', (2, 19, 2, 20), 'c', ('Load',)), [], 1)]))], [], None, None)], []), +-('Module', [('FunctionDef', (4, 0, 4, 13), 'f', ('arguments', [], [], None, [], [], None, []), [('Pass', (4, 9, 4, 13))], [('Name', (1, 1, 1, 6), 'deco1', ('Load',)), ('Call', (2, 1, 2, 8), ('Name', (2, 1, 2, 6), 'deco2', ('Load',)), [], []), ('Call', (3, 1, 3, 9), ('Name', (3, 1, 3, 6), 'deco3', ('Load',)), [('Constant', (3, 7, 3, 8), 1, None)], [])], None, None)], []), +-('Module', [('AsyncFunctionDef', (4, 0, 4, 19), 'f', ('arguments', [], [], None, [], [], None, []), [('Pass', (4, 15, 4, 19))], [('Name', (1, 1, 1, 6), 'deco1', ('Load',)), ('Call', (2, 1, 2, 8), ('Name', (2, 1, 2, 6), 'deco2', ('Load',)), [], []), ('Call', (3, 1, 3, 9), ('Name', (3, 1, 3, 6), 'deco3', ('Load',)), [('Constant', (3, 7, 3, 8), 1, None)], [])], None, None)], []), +-('Module', [('ClassDef', (4, 0, 4, 13), 'C', [], [], [('Pass', (4, 9, 4, 13))], [('Name', (1, 1, 1, 6), 'deco1', ('Load',)), ('Call', (2, 1, 2, 8), ('Name', (2, 1, 2, 6), 'deco2', ('Load',)), [], []), ('Call', (3, 1, 3, 9), ('Name', (3, 1, 3, 6), 'deco3', ('Load',)), [('Constant', (3, 7, 3, 8), 1, None)], [])])], []), +-('Module', [('FunctionDef', (2, 0, 2, 13), 'f', ('arguments', [], [], None, [], [], None, []), [('Pass', (2, 9, 2, 13))], [('Call', (1, 1, 1, 19), ('Name', (1, 1, 1, 5), 'deco', ('Load',)), [('GeneratorExp', (1, 5, 1, 19), ('Name', (1, 6, 1, 7), 'a', ('Load',)), [('comprehension', ('Name', (1, 12, 1, 13), 'a', ('Store',)), ('Name', (1, 17, 1, 18), 'b', ('Load',)), [], 0)])], [])], None, None)], []), +-('Module', [('FunctionDef', (2, 0, 2, 13), 'f', ('arguments', [], [], None, [], [], None, []), [('Pass', (2, 9, 2, 13))], [('Attribute', (1, 1, 1, 6), ('Attribute', (1, 1, 1, 4), ('Name', (1, 1, 1, 2), 'a', ('Load',)), 'b', ('Load',)), 'c', ('Load',))], None, None)], []), ++('Module', [('AsyncFunctionDef', (1, 0, 2, 21), 'f', [], ('arguments', [], [], None, [], [], None, []), [('Expr', (2, 1, 2, 21), ('ListComp', (2, 1, 2, 21), ('Name', (2, 2, 2, 3), 'i', ('Load',)), [('comprehension', ('Name', (2, 14, 2, 15), 'b', ('Store',)), ('Name', (2, 19, 2, 20), 'c', ('Load',)), [], 1)]))], [], None, None)], []), ++('Module', [('FunctionDef', (4, 0, 4, 13), 'f', [], ('arguments', [], [], None, [], [], None, []), [('Pass', (4, 9, 4, 13))], [('Name', (1, 1, 1, 6), 'deco1', ('Load',)), ('Call', (2, 1, 2, 8), ('Name', (2, 1, 2, 6), 'deco2', ('Load',)), [], []), ('Call', (3, 1, 3, 9), ('Name', (3, 1, 3, 6), 'deco3', ('Load',)), [('Constant', (3, 7, 3, 8), 1, None)], [])], None, None)], []), ++('Module', [('AsyncFunctionDef', (4, 0, 4, 19), 'f', [], ('arguments', [], [], None, [], [], None, []), [('Pass', (4, 15, 4, 19))], [('Name', (1, 1, 1, 6), 'deco1', ('Load',)), ('Call', (2, 1, 2, 8), ('Name', (2, 1, 2, 6), 'deco2', ('Load',)), [], []), ('Call', (3, 1, 3, 9), ('Name', (3, 1, 3, 6), 'deco3', ('Load',)), [('Constant', (3, 7, 3, 8), 1, None)], [])], None, None)], []), ++('Module', [('ClassDef', (4, 0, 4, 13), 'C', [], [], [], [('Pass', (4, 9, 4, 13))], [('Name', (1, 1, 1, 6), 'deco1', ('Load',)), ('Call', (2, 1, 2, 8), ('Name', (2, 1, 2, 6), 'deco2', ('Load',)), [], []), ('Call', (3, 1, 3, 9), ('Name', (3, 1, 3, 6), 'deco3', ('Load',)), [('Constant', (3, 7, 3, 8), 1, None)], [])])], []), ++('Module', [('FunctionDef', (2, 0, 2, 13), 'f', [], ('arguments', [], [], None, [], [], None, []), [('Pass', (2, 9, 2, 13))], [('Call', (1, 1, 1, 19), ('Name', (1, 1, 1, 5), 'deco', ('Load',)), [('GeneratorExp', (1, 5, 1, 19), ('Name', (1, 6, 1, 7), 'a', ('Load',)), [('comprehension', ('Name', (1, 12, 1, 13), 'a', ('Store',)), ('Name', (1, 17, 1, 18), 'b', ('Load',)), [], 0)])], [])], None, None)], []), ++('Module', [('FunctionDef', (2, 0, 2, 13), 'f', [], ('arguments', [], [], None, [], [], None, []), [('Pass', (2, 9, 2, 13))], [('Attribute', (1, 1, 1, 6), ('Attribute', (1, 1, 1, 4), ('Name', (1, 1, 1, 2), 'a', ('Load',)), 'b', ('Load',)), 'c', ('Load',))], None, None)], []), + ('Module', [('Expr', (1, 0, 1, 8), ('NamedExpr', (1, 1, 1, 7), ('Name', (1, 1, 1, 2), 'a', ('Store',)), ('Constant', (1, 6, 1, 7), 1, None)))], []), +-('Module', [('FunctionDef', (1, 0, 1, 18), 'f', ('arguments', [('arg', (1, 6, 1, 7), 'a', None, None)], [], None, [], [], None, []), [('Pass', (1, 14, 1, 18))], [], None, None)], []), +-('Module', [('FunctionDef', (1, 0, 1, 26), 'f', ('arguments', [('arg', (1, 6, 1, 7), 'a', None, None)], [('arg', (1, 12, 1, 13), 'c', None, None), ('arg', (1, 15, 1, 16), 'd', None, None), ('arg', (1, 18, 1, 19), 'e', None, None)], None, [], [], None, []), [('Pass', (1, 22, 1, 26))], [], None, None)], []), +-('Module', [('FunctionDef', (1, 0, 1, 29), 'f', ('arguments', [('arg', (1, 6, 1, 7), 'a', None, None)], [('arg', (1, 12, 1, 13), 'c', None, None)], None, [('arg', (1, 18, 1, 19), 'd', None, None), ('arg', (1, 21, 1, 22), 'e', None, None)], [None, None], None, []), [('Pass', (1, 25, 1, 29))], [], None, None)], []), +-('Module', [('FunctionDef', (1, 0, 1, 39), 'f', ('arguments', [('arg', (1, 6, 1, 7), 'a', None, None)], [('arg', (1, 12, 1, 13), 'c', None, None)], None, [('arg', (1, 18, 1, 19), 'd', None, None), ('arg', (1, 21, 1, 22), 'e', None, None)], [None, None], ('arg', (1, 26, 1, 32), 'kwargs', None, None), []), [('Pass', (1, 35, 1, 39))], [], None, None)], []), +-('Module', [('FunctionDef', (1, 0, 1, 20), 'f', ('arguments', [('arg', (1, 6, 1, 7), 'a', None, None)], [], None, [], [], None, [('Constant', (1, 8, 1, 9), 1, None)]), [('Pass', (1, 16, 1, 20))], [], None, None)], []), +-('Module', [('FunctionDef', (1, 0, 1, 29), 'f', ('arguments', [('arg', (1, 6, 1, 7), 'a', None, None)], [('arg', (1, 14, 1, 15), 'b', None, None), ('arg', (1, 19, 1, 20), 'c', None, None)], None, [], [], None, [('Constant', (1, 8, 1, 9), 1, None), ('Constant', (1, 16, 1, 17), 2, None), ('Constant', (1, 21, 1, 22), 4, None)]), [('Pass', (1, 25, 1, 29))], [], None, None)], []), +-('Module', [('FunctionDef', (1, 0, 1, 32), 'f', ('arguments', [('arg', (1, 6, 1, 7), 'a', None, None)], [('arg', (1, 14, 1, 15), 'b', None, None)], None, [('arg', (1, 22, 1, 23), 'c', None, None)], [('Constant', (1, 24, 1, 25), 4, None)], None, [('Constant', (1, 8, 1, 9), 1, None), ('Constant', (1, 16, 1, 17), 2, None)]), [('Pass', (1, 28, 1, 32))], [], None, None)], []), +-('Module', [('FunctionDef', (1, 0, 1, 30), 'f', ('arguments', [('arg', (1, 6, 1, 7), 'a', None, None)], [('arg', (1, 14, 1, 15), 'b', None, None)], None, [('arg', (1, 22, 1, 23), 'c', None, None)], [None], None, [('Constant', (1, 8, 1, 9), 1, None), ('Constant', (1, 16, 1, 17), 2, None)]), [('Pass', (1, 26, 1, 30))], [], None, None)], []), +-('Module', [('FunctionDef', (1, 0, 1, 42), 'f', ('arguments', [('arg', (1, 6, 1, 7), 'a', None, None)], [('arg', (1, 14, 1, 15), 'b', None, None)], None, [('arg', (1, 22, 1, 23), 'c', None, None)], [('Constant', (1, 24, 1, 25), 4, None)], ('arg', (1, 29, 1, 35), 'kwargs', None, None), [('Constant', (1, 8, 1, 9), 1, None), ('Constant', (1, 16, 1, 17), 2, None)]), [('Pass', (1, 38, 1, 42))], [], None, None)], []), +-('Module', [('FunctionDef', (1, 0, 1, 40), 'f', ('arguments', [('arg', (1, 6, 1, 7), 'a', None, None)], [('arg', (1, 14, 1, 15), 'b', None, None)], None, [('arg', (1, 22, 1, 23), 'c', None, None)], [None], ('arg', (1, 27, 1, 33), 'kwargs', None, None), [('Constant', (1, 8, 1, 9), 1, None), ('Constant', (1, 16, 1, 17), 2, None)]), [('Pass', (1, 36, 1, 40))], [], None, None)], []), ++('Module', [('FunctionDef', (1, 0, 1, 18), 'f', [], ('arguments', [('arg', (1, 6, 1, 7), 'a', None, None)], [], None, [], [], None, []), [('Pass', (1, 14, 1, 18))], [], None, None)], []), ++('Module', [('FunctionDef', (1, 0, 1, 26), 'f', [], ('arguments', [('arg', (1, 6, 1, 7), 'a', None, None)], [('arg', (1, 12, 1, 13), 'c', None, None), ('arg', (1, 15, 1, 16), 'd', None, None), ('arg', (1, 18, 1, 19), 'e', None, None)], None, [], [], None, []), [('Pass', (1, 22, 1, 26))], [], None, None)], []), ++('Module', [('FunctionDef', (1, 0, 1, 29), 'f', [], ('arguments', [('arg', (1, 6, 1, 7), 'a', None, None)], [('arg', (1, 12, 1, 13), 'c', None, None)], None, [('arg', (1, 18, 1, 19), 'd', None, None), ('arg', (1, 21, 1, 22), 'e', None, None)], [None, None], None, []), [('Pass', (1, 25, 1, 29))], [], None, None)], []), ++('Module', [('FunctionDef', (1, 0, 1, 39), 'f', [], ('arguments', [('arg', (1, 6, 1, 7), 'a', None, None)], [('arg', (1, 12, 1, 13), 'c', None, None)], None, [('arg', (1, 18, 1, 19), 'd', None, None), ('arg', (1, 21, 1, 22), 'e', None, None)], [None, None], ('arg', (1, 26, 1, 32), 'kwargs', None, None), []), [('Pass', (1, 35, 1, 39))], [], None, None)], []), ++('Module', [('FunctionDef', (1, 0, 1, 20), 'f', [], ('arguments', [('arg', (1, 6, 1, 7), 'a', None, None)], [], None, [], [], None, [('Constant', (1, 8, 1, 9), 1, None)]), [('Pass', (1, 16, 1, 20))], [], None, None)], []), ++('Module', [('FunctionDef', (1, 0, 1, 29), 'f', [], ('arguments', [('arg', (1, 6, 1, 7), 'a', None, None)], [('arg', (1, 14, 1, 15), 'b', None, None), ('arg', (1, 19, 1, 20), 'c', None, None)], None, [], [], None, [('Constant', (1, 8, 1, 9), 1, None), ('Constant', (1, 16, 1, 17), 2, None), ('Constant', (1, 21, 1, 22), 4, None)]), [('Pass', (1, 25, 1, 29))], [], None, None)], []), ++('Module', [('FunctionDef', (1, 0, 1, 32), 'f', [], ('arguments', [('arg', (1, 6, 1, 7), 'a', None, None)], [('arg', (1, 14, 1, 15), 'b', None, None)], None, [('arg', (1, 22, 1, 23), 'c', None, None)], [('Constant', (1, 24, 1, 25), 4, None)], None, [('Constant', (1, 8, 1, 9), 1, None), ('Constant', (1, 16, 1, 17), 2, None)]), [('Pass', (1, 28, 1, 32))], [], None, None)], []), ++('Module', [('FunctionDef', (1, 0, 1, 30), 'f', [], ('arguments', [('arg', (1, 6, 1, 7), 'a', None, None)], [('arg', (1, 14, 1, 15), 'b', None, None)], None, [('arg', (1, 22, 1, 23), 'c', None, None)], [None], None, [('Constant', (1, 8, 1, 9), 1, None), ('Constant', (1, 16, 1, 17), 2, None)]), [('Pass', (1, 26, 1, 30))], [], None, None)], []), ++('Module', [('FunctionDef', (1, 0, 1, 42), 'f', [], ('arguments', [('arg', (1, 6, 1, 7), 'a', None, None)], [('arg', (1, 14, 1, 15), 'b', None, None)], None, [('arg', (1, 22, 1, 23), 'c', None, None)], [('Constant', (1, 24, 1, 25), 4, None)], ('arg', (1, 29, 1, 35), 'kwargs', None, None), [('Constant', (1, 8, 1, 9), 1, None), ('Constant', (1, 16, 1, 17), 2, None)]), [('Pass', (1, 38, 1, 42))], [], None, None)], []), ++('Module', [('FunctionDef', (1, 0, 1, 40), 'f', [], ('arguments', [('arg', (1, 6, 1, 7), 'a', None, None)], [('arg', (1, 14, 1, 15), 'b', None, None)], None, [('arg', (1, 22, 1, 23), 'c', None, None)], [None], ('arg', (1, 27, 1, 33), 'kwargs', None, None), [('Constant', (1, 8, 1, 9), 1, None), ('Constant', (1, 16, 1, 17), 2, None)]), [('Pass', (1, 36, 1, 40))], [], None, None)], []), ++('Module', [('TypeAlias', (1, 0, 1, 12), ('Name', (1, 5, 1, 6), 'X', ('Store',)), [], ('Name', (1, 9, 1, 12), 'int', ('Load',)))], []), ++('Module', [('TypeAlias', (1, 0, 1, 15), ('Name', (1, 5, 1, 6), 'X', ('Store',)), [('TypeVar', (1, 7, 1, 8), 'T', None)], ('Name', (1, 12, 1, 15), 'int', ('Load',)))], []), ++('Module', [('TypeAlias', (1, 0, 1, 32), ('Name', (1, 5, 1, 6), 'X', ('Store',)), [('TypeVar', (1, 7, 1, 8), 'T', None), ('TypeVarTuple', (1, 10, 1, 13), 'Ts'), ('ParamSpec', (1, 15, 1, 18), 'P')], ('Tuple', (1, 22, 1, 32), [('Name', (1, 23, 1, 24), 'T', ('Load',)), ('Name', (1, 26, 1, 28), 'Ts', ('Load',)), ('Name', (1, 30, 1, 31), 'P', ('Load',))], ('Load',)))], []), ++('Module', [('TypeAlias', (1, 0, 1, 37), ('Name', (1, 5, 1, 6), 'X', ('Store',)), [('TypeVar', (1, 7, 1, 13), 'T', ('Name', (1, 10, 1, 13), 'int', ('Load',))), ('TypeVarTuple', (1, 15, 1, 18), 'Ts'), ('ParamSpec', (1, 20, 1, 23), 'P')], ('Tuple', (1, 27, 1, 37), [('Name', (1, 28, 1, 29), 'T', ('Load',)), ('Name', (1, 31, 1, 33), 'Ts', ('Load',)), ('Name', (1, 35, 1, 36), 'P', ('Load',))], ('Load',)))], []), ++('Module', [('TypeAlias', (1, 0, 1, 44), ('Name', (1, 5, 1, 6), 'X', ('Store',)), [('TypeVar', (1, 7, 1, 20), 'T', ('Tuple', (1, 10, 1, 20), [('Name', (1, 11, 1, 14), 'int', ('Load',)), ('Name', (1, 16, 1, 19), 'str', ('Load',))], ('Load',))), ('TypeVarTuple', (1, 22, 1, 25), 'Ts'), ('ParamSpec', (1, 27, 1, 30), 'P')], ('Tuple', (1, 34, 1, 44), [('Name', (1, 35, 1, 36), 'T', ('Load',)), ('Name', (1, 38, 1, 40), 'Ts', ('Load',)), ('Name', (1, 42, 1, 43), 'P', ('Load',))], ('Load',)))], []), ++('Module', [('ClassDef', (1, 0, 1, 16), 'X', [('TypeVar', (1, 8, 1, 9), 'T', None)], [], [], [('Pass', (1, 12, 1, 16))], [])], []), ++('Module', [('ClassDef', (1, 0, 1, 26), 'X', [('TypeVar', (1, 8, 1, 9), 'T', None), ('TypeVarTuple', (1, 11, 1, 14), 'Ts'), ('ParamSpec', (1, 16, 1, 19), 'P')], [], [], [('Pass', (1, 22, 1, 26))], [])], []), ++('Module', [('ClassDef', (1, 0, 1, 31), 'X', [('TypeVar', (1, 8, 1, 14), 'T', ('Name', (1, 11, 1, 14), 'int', ('Load',))), ('TypeVarTuple', (1, 16, 1, 19), 'Ts'), ('ParamSpec', (1, 21, 1, 24), 'P')], [], [], [('Pass', (1, 27, 1, 31))], [])], []), ++('Module', [('ClassDef', (1, 0, 1, 38), 'X', [('TypeVar', (1, 8, 1, 21), 'T', ('Tuple', (1, 11, 1, 21), [('Name', (1, 12, 1, 15), 'int', ('Load',)), ('Name', (1, 17, 1, 20), 'str', ('Load',))], ('Load',))), ('TypeVarTuple', (1, 23, 1, 26), 'Ts'), ('ParamSpec', (1, 28, 1, 31), 'P')], [], [], [('Pass', (1, 34, 1, 38))], [])], []), ++('Module', [('FunctionDef', (1, 0, 1, 16), 'f', [('TypeVar', (1, 6, 1, 7), 'T', None)], ('arguments', [], [], None, [], [], None, []), [('Pass', (1, 12, 1, 16))], [], None, None)], []), ++('Module', [('FunctionDef', (1, 0, 1, 26), 'f', [('TypeVar', (1, 6, 1, 7), 'T', None), ('TypeVarTuple', (1, 9, 1, 12), 'Ts'), ('ParamSpec', (1, 14, 1, 17), 'P')], ('arguments', [], [], None, [], [], None, []), [('Pass', (1, 22, 1, 26))], [], None, None)], []), ++('Module', [('FunctionDef', (1, 0, 1, 31), 'f', [('TypeVar', (1, 6, 1, 12), 'T', ('Name', (1, 9, 1, 12), 'int', ('Load',))), ('TypeVarTuple', (1, 14, 1, 17), 'Ts'), ('ParamSpec', (1, 19, 1, 22), 'P')], ('arguments', [], [], None, [], [], None, []), [('Pass', (1, 27, 1, 31))], [], None, None)], []), ++('Module', [('FunctionDef', (1, 0, 1, 38), 'f', [('TypeVar', (1, 6, 1, 19), 'T', ('Tuple', (1, 9, 1, 19), [('Name', (1, 10, 1, 13), 'int', ('Load',)), ('Name', (1, 15, 1, 18), 'str', ('Load',))], ('Load',))), ('TypeVarTuple', (1, 21, 1, 24), 'Ts'), ('ParamSpec', (1, 26, 1, 29), 'P')], ('arguments', [], [], None, [], [], None, []), [('Pass', (1, 34, 1, 38))], [], None, None)], []), + ] + single_results = [ + ('Interactive', [('Expr', (1, 0, 1, 3), ('BinOp', (1, 0, 1, 3), ('Constant', (1, 0, 1, 1), 1, None), ('Add',), ('Constant', (1, 2, 1, 3), 2, None)))]), +diff --git a/Lib/test/test_keyword.py b/Lib/test/test_keyword.py +index f329f88fa0..858e5de3b9 100644 +--- a/Lib/test/test_keyword.py ++++ b/Lib/test/test_keyword.py +@@ -39,7 +39,8 @@ def test_async_and_await_are_keywords(self): + self.assertIn("async", keyword.kwlist) + self.assertIn("await", keyword.kwlist) + +- def test_match_and_case_are_soft_keywords(self): ++ def test_soft_keywords(self): ++ self.assertIn("type", keyword.softkwlist) + self.assertIn("match", keyword.softkwlist) + self.assertIn("case", keyword.softkwlist) + self.assertIn("_", keyword.softkwlist) +diff --git a/Lib/test/test_sys.py b/Lib/test/test_sys.py +index e1db450bf8..d81501f6f1 100644 +--- a/Lib/test/test_sys.py ++++ b/Lib/test/test_sys.py +@@ -1449,7 +1449,7 @@ def func(): + check(x, size('3Pi3c7P2ic??2P')) + # function + def func(): pass +- check(func, size('14Pi')) ++ check(func, size('15Pi')) + class c(): + @staticmethod + def foo(): +diff --git a/Lib/test/test_type_aliases.py b/Lib/test/test_type_aliases.py +new file mode 100644 +index 0000000..efec4db +--- /dev/null ++++ b/Lib/test/test_type_aliases.py +@@ -0,0 +1,204 @@ ++import types ++import unittest ++from test.support import check_syntax_error, run_code ++ ++from typing import Callable, TypeAliasType, TypeVar, get_args ++ ++ ++class TypeParamsInvalidTest(unittest.TestCase): ++ def test_name_collision_01(self): ++ check_syntax_error(self, """type TA1[A, **A] = None""") ++ ++ def test_name_non_collision_02(self): ++ ns = run_code("""type TA1[A] = lambda A: A""") ++ self.assertIsInstance(ns["TA1"], TypeAliasType) ++ self.assertTrue(callable(ns["TA1"].__value__)) ++ self.assertEqual("arg", ns["TA1"].__value__("arg")) ++ ++ def test_name_non_collision_03(self): ++ ns = run_code(""" ++ class Outer[A]: ++ type TA1[A] = None ++ """ ++ ) ++ outer_A, = ns["Outer"].__type_params__ ++ inner_A, = ns["Outer"].TA1.__type_params__ ++ self.assertIsNot(outer_A, inner_A) ++ ++ ++class TypeParamsAccessTest(unittest.TestCase): ++ def test_alias_access_01(self): ++ ns = run_code("type TA1[A, B] = dict[A, B]") ++ alias = ns["TA1"] ++ self.assertIsInstance(alias, TypeAliasType) ++ self.assertEqual(alias.__type_params__, get_args(alias.__value__)) ++ ++ def test_alias_access_02(self): ++ ns = run_code(""" ++ type TA1[A, B] = TA1[A, B] | int ++ """ ++ ) ++ alias = ns["TA1"] ++ self.assertIsInstance(alias, TypeAliasType) ++ A, B = alias.__type_params__ ++ self.assertEqual(alias.__value__, alias[A, B] | int) ++ ++ def test_alias_access_03(self): ++ ns = run_code(""" ++ class Outer[A]: ++ def inner[B](self): ++ type TA1[C] = TA1[A, B] | int ++ return TA1 ++ """ ++ ) ++ cls = ns["Outer"] ++ A, = cls.__type_params__ ++ B, = cls.inner.__type_params__ ++ alias = cls.inner(None) ++ self.assertIsInstance(alias, TypeAliasType) ++ alias2 = cls.inner(None) ++ self.assertIsNot(alias, alias2) ++ self.assertEqual(len(alias.__type_params__), 1) ++ ++ self.assertEqual(alias.__value__, alias[A, B] | int) ++ ++ ++class TypeParamsAliasValueTest(unittest.TestCase): ++ def test_alias_value_01(self): ++ type TA1 = int ++ ++ self.assertIsInstance(TA1, TypeAliasType) ++ self.assertEqual(TA1.__value__, int) ++ self.assertEqual(TA1.__parameters__, ()) ++ self.assertEqual(TA1.__type_params__, ()) ++ ++ type TA2 = TA1 | str ++ ++ self.assertIsInstance(TA2, TypeAliasType) ++ a, b = TA2.__value__.__args__ ++ self.assertEqual(a, TA1) ++ self.assertEqual(b, str) ++ self.assertEqual(TA2.__parameters__, ()) ++ self.assertEqual(TA2.__type_params__, ()) ++ ++ def test_alias_value_02(self): ++ class Parent[A]: ++ type TA1[B] = dict[A, B] ++ ++ self.assertIsInstance(Parent.TA1, TypeAliasType) ++ self.assertEqual(len(Parent.TA1.__parameters__), 1) ++ self.assertEqual(len(Parent.__parameters__), 1) ++ a, = Parent.__parameters__ ++ b, = Parent.TA1.__parameters__ ++ self.assertEqual(Parent.__type_params__, (a,)) ++ self.assertEqual(Parent.TA1.__type_params__, (b,)) ++ self.assertEqual(Parent.TA1.__value__, dict[a, b]) ++ ++ def test_alias_value_03(self): ++ def outer[A](): ++ type TA1[B] = dict[A, B] ++ return TA1 ++ ++ o = outer() ++ self.assertIsInstance(o, TypeAliasType) ++ self.assertEqual(len(o.__parameters__), 1) ++ self.assertEqual(len(outer.__type_params__), 1) ++ b = o.__parameters__[0] ++ self.assertEqual(o.__type_params__, (b,)) ++ ++ def test_alias_value_04(self): ++ def more_generic[T, *Ts, **P](): ++ type TA[T2, *Ts2, **P2] = tuple[Callable[P, tuple[T, *Ts]], Callable[P2, tuple[T2, *Ts2]]] ++ return TA ++ ++ alias = more_generic() ++ self.assertIsInstance(alias, TypeAliasType) ++ T2, Ts2, P2 = alias.__type_params__ ++ self.assertEqual(alias.__parameters__, (T2, *Ts2, P2)) ++ T, Ts, P = more_generic.__type_params__ ++ self.assertEqual(alias.__value__, tuple[Callable[P, tuple[T, *Ts]], Callable[P2, tuple[T2, *Ts2]]]) ++ ++ def test_subscripting(self): ++ type NonGeneric = int ++ type Generic[A] = dict[A, A] ++ type VeryGeneric[T, *Ts, **P] = Callable[P, tuple[T, *Ts]] ++ ++ with self.assertRaises(TypeError): ++ NonGeneric[int] ++ ++ specialized = Generic[int] ++ self.assertIsInstance(specialized, types.GenericAlias) ++ self.assertIs(specialized.__origin__, Generic) ++ self.assertEqual(specialized.__args__, (int,)) ++ ++ specialized2 = VeryGeneric[int, str, float, [bool, range]] ++ self.assertIsInstance(specialized2, types.GenericAlias) ++ self.assertIs(specialized2.__origin__, VeryGeneric) ++ self.assertEqual(specialized2.__args__, (int, str, float, [bool, range])) ++ ++ def test_repr(self): ++ type Simple = int ++ self.assertEqual(repr(Simple), "Simple") ++ ++ def test_recursive_repr(self): ++ type Recursive = Recursive ++ self.assertEqual(repr(Recursive), "Recursive") ++ ++ type X = list[Y] ++ type Y = list[X] ++ self.assertEqual(repr(X), "X") ++ ++ ++class TypeAliasConstructorTest(unittest.TestCase): ++ def test_basic(self): ++ TA = TypeAliasType("TA", int) ++ self.assertEqual(TA.__name__, "TA") ++ self.assertIs(TA.__value__, int) ++ self.assertEqual(TA.__type_params__, ()) ++ ++ def test_generic(self): ++ T = TypeVar("T") ++ TA = TypeAliasType("TA", list[T], type_params=(T,)) ++ self.assertEqual(TA.__name__, "TA") ++ self.assertEqual(TA.__value__, list[T]) ++ self.assertEqual(TA.__type_params__, (T,)) ++ ++ def test_keywords(self): ++ TA = TypeAliasType(name="TA", value=int) ++ self.assertEqual(TA.__name__, "TA") ++ self.assertIs(TA.__value__, int) ++ self.assertEqual(TA.__type_params__, ()) ++ ++ def test_errors(self): ++ with self.assertRaises(TypeError): ++ TypeAliasType() ++ with self.assertRaises(TypeError): ++ TypeAliasType("TA") ++ with self.assertRaises(TypeError): ++ TypeAliasType("TA", list, ()) ++ with self.assertRaises(TypeError): ++ TypeAliasType("TA", list, type_params=42) ++ ++ ++class TypeAliasTypeTest(unittest.TestCase): ++ def test_immutable(self): ++ with self.assertRaises(TypeError): ++ TypeAliasType.whatever = "not allowed" ++ ++ def test_no_subclassing(self): ++ with self.assertRaisesRegex(TypeError, "not an acceptable base type"): ++ class MyAlias(TypeAliasType): ++ pass ++ ++ def test_union(self): ++ type Alias1 = int ++ type Alias2 = str ++ union = Alias1 | Alias2 ++ self.assertIsInstance(union, types.UnionType) ++ self.assertEqual(get_args(union), (Alias1, Alias2)) ++ union2 = Alias1 | list[float] ++ self.assertIsInstance(union2, types.UnionType) ++ self.assertEqual(get_args(union2), (Alias1, list[float])) ++ union3 = list[range] | Alias1 ++ self.assertIsInstance(union3, types.UnionType) ++ self.assertEqual(get_args(union3), (list[range], Alias1)) +diff --git a/Lib/test/test_type_params.py b/Lib/test/test_type_params.py +new file mode 100644 +index 0000000..4ae9841 +--- /dev/null ++++ b/Lib/test/test_type_params.py +@@ -0,0 +1,847 @@ ++import asyncio ++import textwrap ++import types ++import unittest ++from test.support import requires_working_socket, check_syntax_error, run_code ++ ++from typing import Generic, Sequence, TypeVar, TypeVarTuple, ParamSpec, get_args ++ ++ ++class TypeParamsInvalidTest(unittest.TestCase): ++ def test_name_collision_01(self): ++ check_syntax_error(self, """def func[**A, A](): ...""") ++ ++ def test_name_non_collision_02(self): ++ ns = run_code("""def func[A](A): return A""") ++ func = ns["func"] ++ self.assertEqual(func(1), 1) ++ A, = func.__type_params__ ++ self.assertEqual(A.__name__, "A") ++ ++ def test_name_non_collision_03(self): ++ ns = run_code("""def func[A](*A): return A""") ++ func = ns["func"] ++ self.assertEqual(func(1), (1,)) ++ A, = func.__type_params__ ++ self.assertEqual(A.__name__, "A") ++ ++ def test_name_non_collision_04(self): ++ # Mangled names should not cause a conflict. ++ ns = run_code(""" ++ class ClassA: ++ def func[__A](self, __A): return __A ++ """ ++ ) ++ cls = ns["ClassA"] ++ self.assertEqual(cls().func(1), 1) ++ A, = cls.func.__type_params__ ++ self.assertEqual(A.__name__, "__A") ++ ++ def test_name_non_collision_05(self): ++ ns = run_code(""" ++ class ClassA: ++ def func[_ClassA__A](self, __A): return __A ++ """ ++ ) ++ cls = ns["ClassA"] ++ self.assertEqual(cls().func(1), 1) ++ A, = cls.func.__type_params__ ++ self.assertEqual(A.__name__, "_ClassA__A") ++ ++ def test_name_non_collision_06(self): ++ ns = run_code(""" ++ class ClassA[X]: ++ def func(self, X): return X ++ """ ++ ) ++ cls = ns["ClassA"] ++ self.assertEqual(cls().func(1), 1) ++ X, = cls.__type_params__ ++ self.assertEqual(X.__name__, "X") ++ ++ def test_name_non_collision_07(self): ++ ns = run_code(""" ++ class ClassA[X]: ++ def func(self): ++ X = 1 ++ return X ++ """ ++ ) ++ cls = ns["ClassA"] ++ self.assertEqual(cls().func(), 1) ++ X, = cls.__type_params__ ++ self.assertEqual(X.__name__, "X") ++ ++ def test_name_non_collision_08(self): ++ ns = run_code(""" ++ class ClassA[X]: ++ def func(self): ++ return [X for X in [1, 2]] ++ """ ++ ) ++ cls = ns["ClassA"] ++ self.assertEqual(cls().func(), [1, 2]) ++ X, = cls.__type_params__ ++ self.assertEqual(X.__name__, "X") ++ ++ def test_name_non_collision_9(self): ++ ns = run_code(""" ++ class ClassA[X]: ++ def func[X](self): ++ ... ++ """ ++ ) ++ cls = ns["ClassA"] ++ outer_X, = cls.__type_params__ ++ inner_X, = cls.func.__type_params__ ++ self.assertEqual(outer_X.__name__, "X") ++ self.assertEqual(inner_X.__name__, "X") ++ self.assertIsNot(outer_X, inner_X) ++ ++ def test_name_non_collision_10(self): ++ ns = run_code(""" ++ class ClassA[X]: ++ X: int ++ """ ++ ) ++ cls = ns["ClassA"] ++ X, = cls.__type_params__ ++ self.assertEqual(X.__name__, "X") ++ self.assertIs(cls.__annotations__["X"], int) ++ ++ def test_name_non_collision_13(self): ++ ns = run_code(""" ++ X = 1 ++ def outer(): ++ def inner[X](): ++ global X ++ X = 2 ++ return inner ++ """ ++ ) ++ self.assertEqual(ns["X"], 1) ++ outer = ns["outer"] ++ outer()() ++ self.assertEqual(ns["X"], 2) ++ ++ def test_disallowed_expressions(self): ++ check_syntax_error(self, "type X = (yield)") ++ check_syntax_error(self, "type X = (yield from x)") ++ check_syntax_error(self, "type X = (await 42)") ++ check_syntax_error(self, "async def f(): type X = (yield)") ++ check_syntax_error(self, "type X = (y := 3)") ++ check_syntax_error(self, "class X[T: (yield)]: pass") ++ check_syntax_error(self, "class X[T: (yield from x)]: pass") ++ check_syntax_error(self, "class X[T: (await 42)]: pass") ++ check_syntax_error(self, "class X[T: (y := 3)]: pass") ++ check_syntax_error(self, "class X[T](y := Sequence[T]): pass") ++ check_syntax_error(self, "def f[T](y: (x := Sequence[T])): pass") ++ ++ ++class TypeParamsNonlocalTest(unittest.TestCase): ++ def test_nonlocal_disallowed_01(self): ++ code = """ ++ def outer(): ++ X = 1 ++ def inner[X](): ++ nonlocal X ++ return X ++ """ ++ check_syntax_error(self, code) ++ ++ def test_nonlocal_disallowed_02(self): ++ code = """ ++ def outer2[T](): ++ def inner1(): ++ nonlocal T ++ """ ++ check_syntax_error(self, textwrap.dedent(code)) ++ ++ def test_nonlocal_disallowed_03(self): ++ code = """ ++ class Cls[T]: ++ nonlocal T ++ """ ++ check_syntax_error(self, textwrap.dedent(code)) ++ ++ def test_nonlocal_allowed(self): ++ code = """ ++ def func[T](): ++ T = "func" ++ def inner(): ++ nonlocal T ++ T = "inner" ++ inner() ++ assert T == "inner" ++ """ ++ ns = run_code(code) ++ func = ns["func"] ++ T, = func.__type_params__ ++ self.assertEqual(T.__name__, "T") ++ ++ ++class TypeParamsAccessTest(unittest.TestCase): ++ def test_class_access_01(self): ++ ns = run_code(""" ++ class ClassA[A, B](dict[A, B]): ++ ... ++ """ ++ ) ++ cls = ns["ClassA"] ++ A, B = cls.__type_params__ ++ self.assertEqual(types.get_original_bases(cls), (dict[A, B], Generic[A, B])) ++ ++ def test_class_access_02(self): ++ ns = run_code(""" ++ class MyMeta[A, B](type): ... ++ class ClassA[A, B](metaclass=MyMeta[A, B]): ++ ... ++ """ ++ ) ++ meta = ns["MyMeta"] ++ cls = ns["ClassA"] ++ A1, B1 = meta.__type_params__ ++ A2, B2 = cls.__type_params__ ++ self.assertIsNot(A1, A2) ++ self.assertIsNot(B1, B2) ++ self.assertIs(type(cls), meta) ++ ++ def test_class_access_03(self): ++ code = """ ++ def my_decorator(a): ++ ... ++ @my_decorator(A) ++ class ClassA[A, B](): ++ ... ++ """ ++ ++ with self.assertRaisesRegex(NameError, "name 'A' is not defined"): ++ run_code(code) ++ ++ def test_function_access_01(self): ++ ns = run_code(""" ++ def func[A, B](a: dict[A, B]): ++ ... ++ """ ++ ) ++ func = ns["func"] ++ A, B = func.__type_params__ ++ self.assertEqual(func.__annotations__["a"], dict[A, B]) ++ ++ def test_function_access_02(self): ++ code = """ ++ def func[A](a = list[A]()): ++ ... ++ """ ++ ++ with self.assertRaisesRegex(NameError, "name 'A' is not defined"): ++ run_code(code) ++ ++ def test_function_access_03(self): ++ code = """ ++ def my_decorator(a): ++ ... ++ @my_decorator(A) ++ def func[A](): ++ ... ++ """ ++ ++ with self.assertRaisesRegex(NameError, "name 'A' is not defined"): ++ run_code(code) ++ ++ def test_method_access_01(self): ++ ns = run_code(""" ++ class ClassA: ++ x = int ++ def func[T](self, a: x, b: T): ++ ... ++ """ ++ ) ++ cls = ns["ClassA"] ++ self.assertIs(cls.func.__annotations__["a"], int) ++ T, = cls.func.__type_params__ ++ self.assertIs(cls.func.__annotations__["b"], T) ++ ++ def test_nested_access_01(self): ++ ns = run_code(""" ++ class ClassA[A]: ++ def funcB[B](self): ++ class ClassC[C]: ++ def funcD[D](self): ++ return lambda: (A, B, C, D) ++ return ClassC ++ """ ++ ) ++ cls = ns["ClassA"] ++ A, = cls.__type_params__ ++ B, = cls.funcB.__type_params__ ++ classC = cls().funcB() ++ C, = classC.__type_params__ ++ D, = classC.funcD.__type_params__ ++ self.assertEqual(classC().funcD()(), (A, B, C, D)) ++ ++ def test_out_of_scope_01(self): ++ code = """ ++ class ClassA[T]: ... ++ x = T ++ """ ++ ++ with self.assertRaisesRegex(NameError, "name 'T' is not defined"): ++ run_code(code) ++ ++ def test_out_of_scope_02(self): ++ code = """ ++ class ClassA[A]: ++ def funcB[B](self): ... ++ ++ x = B ++ """ ++ ++ with self.assertRaisesRegex(NameError, "name 'B' is not defined"): ++ run_code(code) ++ ++ def test_class_scope_interaction_01(self): ++ ns = run_code(""" ++ class C: ++ x = 1 ++ def method[T](self, arg: x): pass ++ """) ++ cls = ns["C"] ++ self.assertEqual(cls.method.__annotations__["arg"], 1) ++ ++ def test_class_scope_interaction_02(self): ++ ns = run_code(""" ++ class C: ++ class Base: pass ++ class Child[T](Base): pass ++ """) ++ cls = ns["C"] ++ self.assertEqual(cls.Child.__bases__, (cls.Base, Generic)) ++ T, = cls.Child.__type_params__ ++ self.assertEqual(types.get_original_bases(cls.Child), (cls.Base, Generic[T])) ++ ++ def test_class_deref(self): ++ ns = run_code(""" ++ class C[T]: ++ T = "class" ++ type Alias = T ++ """) ++ cls = ns["C"] ++ self.assertEqual(cls.Alias.__value__, "class") ++ ++ def test_shadowing_nonlocal(self): ++ ns = run_code(""" ++ def outer[T](): ++ T = "outer" ++ def inner(): ++ nonlocal T ++ T = "inner" ++ return T ++ return lambda: T, inner ++ """) ++ outer = ns["outer"] ++ T, = outer.__type_params__ ++ self.assertEqual(T.__name__, "T") ++ getter, inner = outer() ++ self.assertEqual(getter(), "outer") ++ self.assertEqual(inner(), "inner") ++ self.assertEqual(getter(), "inner") ++ ++ def test_reference_previous_typevar(self): ++ def func[S, T: Sequence[S]](): ++ pass ++ ++ S, T = func.__type_params__ ++ self.assertEqual(T.__bound__, Sequence[S]) ++ ++ def test_super(self): ++ class Base: ++ def meth(self): ++ return "base" ++ ++ class Child(Base): ++ # Having int in the annotation ensures the class gets cells for both ++ # __class__ and __classdict__ ++ def meth[T](self, arg: int) -> T: ++ return super().meth() + "child" ++ ++ c = Child() ++ self.assertEqual(c.meth(1), "basechild") ++ ++ def test_type_alias_containing_lambda(self): ++ type Alias[T] = lambda: T ++ T, = Alias.__type_params__ ++ self.assertIs(Alias.__value__(), T) ++ ++ def test_class_base_containing_lambda(self): ++ # Test that scopes nested inside hidden functions work correctly ++ outer_var = "outer" ++ class Base[T]: ... ++ class Child[T](Base[lambda: (int, outer_var, T)]): ... ++ base, _ = types.get_original_bases(Child) ++ func, = get_args(base) ++ T, = Child.__type_params__ ++ self.assertEqual(func(), (int, "outer", T)) ++ ++ def test_comprehension_01(self): ++ type Alias[T: ([T for T in (T, [1])[1]], T)] = [T for T in T.__name__] ++ self.assertEqual(Alias.__value__, ["T"]) ++ T, = Alias.__type_params__ ++ self.assertEqual(T.__constraints__, ([1], T)) ++ ++ def test_comprehension_02(self): ++ type Alias[T: [lambda: T for T in (T, [1])[1]]] = [lambda: T for T in T.__name__] ++ func, = Alias.__value__ ++ self.assertEqual(func(), "T") ++ T, = Alias.__type_params__ ++ func, = T.__bound__ ++ self.assertEqual(func(), 1) ++ ++ ++def global_generic_func[T](): ++ pass ++ ++class GlobalGenericClass[T]: ++ pass ++ ++ ++class TypeParamsLazyEvaluationTest(unittest.TestCase): ++ def test_qualname(self): ++ class Foo[T]: ++ pass ++ ++ def func[T](): ++ pass ++ ++ self.assertEqual(Foo.__qualname__, "TypeParamsLazyEvaluationTest.test_qualname..Foo") ++ self.assertEqual(func.__qualname__, "TypeParamsLazyEvaluationTest.test_qualname..func") ++ self.assertEqual(global_generic_func.__qualname__, "global_generic_func") ++ self.assertEqual(GlobalGenericClass.__qualname__, "GlobalGenericClass") ++ ++ def test_recursive_class(self): ++ class Foo[T: Foo, U: (Foo, Foo)]: ++ pass ++ ++ type_params = Foo.__type_params__ ++ self.assertEqual(len(type_params), 2) ++ self.assertEqual(type_params[0].__name__, "T") ++ self.assertEqual(type_params[0].__bound__, Foo) ++ self.assertEqual(type_params[0].__constraints__, None) ++ ++ self.assertEqual(type_params[1].__name__, "U") ++ self.assertEqual(type_params[1].__bound__, None) ++ self.assertEqual(type_params[1].__constraints__, (Foo, Foo)) ++ ++ def test_evaluation_error(self): ++ class Foo[T: Undefined, U: (Undefined,)]: ++ pass ++ ++ type_params = Foo.__type_params__ ++ with self.assertRaises(NameError): ++ type_params[0].__bound__ ++ self.assertEqual(type_params[0].__constraints__, None) ++ self.assertEqual(type_params[1].__bound__, None) ++ with self.assertRaises(NameError): ++ type_params[1].__constraints__ ++ ++ Undefined = "defined" ++ self.assertEqual(type_params[0].__bound__, "defined") ++ self.assertEqual(type_params[0].__constraints__, None) ++ ++ self.assertEqual(type_params[1].__bound__, None) ++ self.assertEqual(type_params[1].__constraints__, ("defined",)) ++ ++ ++class TypeParamsClassScopeTest(unittest.TestCase): ++ def test_alias(self): ++ class X: ++ T = int ++ type U = T ++ self.assertIs(X.U.__value__, int) ++ ++ ns = run_code(""" ++ glb = "global" ++ class X: ++ cls = "class" ++ type U = (glb, cls) ++ """) ++ cls = ns["X"] ++ self.assertEqual(cls.U.__value__, ("global", "class")) ++ ++ def test_bound(self): ++ class X: ++ T = int ++ def foo[U: T](self): ... ++ self.assertIs(X.foo.__type_params__[0].__bound__, int) ++ ++ ns = run_code(""" ++ glb = "global" ++ class X: ++ cls = "class" ++ def foo[T: glb, U: cls](self): ... ++ """) ++ cls = ns["X"] ++ T, U = cls.foo.__type_params__ ++ self.assertEqual(T.__bound__, "global") ++ self.assertEqual(U.__bound__, "class") ++ ++ def test_modified_later(self): ++ class X: ++ T = int ++ def foo[U: T](self): ... ++ type Alias = T ++ X.T = float ++ self.assertIs(X.foo.__type_params__[0].__bound__, float) ++ self.assertIs(X.Alias.__value__, float) ++ ++ def test_binding_uses_global(self): ++ ns = run_code(""" ++ x = "global" ++ def outer(): ++ x = "nonlocal" ++ class Cls: ++ type Alias = x ++ val = Alias.__value__ ++ def meth[T: x](self, arg: x): ... ++ bound = meth.__type_params__[0].__bound__ ++ annotation = meth.__annotations__["arg"] ++ x = "class" ++ return Cls ++ """) ++ cls = ns["outer"]() ++ self.assertEqual(cls.val, "global") ++ self.assertEqual(cls.bound, "global") ++ self.assertEqual(cls.annotation, "global") ++ ++ def test_no_binding_uses_nonlocal(self): ++ ns = run_code(""" ++ x = "global" ++ def outer(): ++ x = "nonlocal" ++ class Cls: ++ type Alias = x ++ val = Alias.__value__ ++ def meth[T: x](self, arg: x): ... ++ bound = meth.__type_params__[0].__bound__ ++ return Cls ++ """) ++ cls = ns["outer"]() ++ self.assertEqual(cls.val, "nonlocal") ++ self.assertEqual(cls.bound, "nonlocal") ++ self.assertEqual(cls.meth.__annotations__["arg"], "nonlocal") ++ ++ def test_explicit_global(self): ++ ns = run_code(""" ++ x = "global" ++ def outer(): ++ x = "nonlocal" ++ class Cls: ++ global x ++ type Alias = x ++ Cls.x = "class" ++ return Cls ++ """) ++ cls = ns["outer"]() ++ self.assertEqual(cls.Alias.__value__, "global") ++ ++ def test_explicit_global_with_no_static_bound(self): ++ ns = run_code(""" ++ def outer(): ++ class Cls: ++ global x ++ type Alias = x ++ Cls.x = "class" ++ return Cls ++ """) ++ ns["x"] = "global" ++ cls = ns["outer"]() ++ self.assertEqual(cls.Alias.__value__, "global") ++ ++ def test_explicit_global_with_assignment(self): ++ ns = run_code(""" ++ x = "global" ++ def outer(): ++ x = "nonlocal" ++ class Cls: ++ global x ++ type Alias = x ++ x = "global from class" ++ Cls.x = "class" ++ return Cls ++ """) ++ cls = ns["outer"]() ++ self.assertEqual(cls.Alias.__value__, "global from class") ++ ++ def test_explicit_nonlocal(self): ++ ns = run_code(""" ++ x = "global" ++ def outer(): ++ x = "nonlocal" ++ class Cls: ++ nonlocal x ++ type Alias = x ++ x = "class" ++ return Cls ++ """) ++ cls = ns["outer"]() ++ self.assertEqual(cls.Alias.__value__, "class") ++ ++ ++class TypeParamsManglingTest(unittest.TestCase): ++ def test_mangling(self): ++ class Foo[__T]: ++ param = __T ++ def meth[__U](self, arg: __T, arg2: __U): ++ return (__T, __U) ++ type Alias[__V] = (__T, __V) ++ ++ T = Foo.__type_params__[0] ++ self.assertEqual(T.__name__, "__T") ++ U = Foo.meth.__type_params__[0] ++ self.assertEqual(U.__name__, "__U") ++ V = Foo.Alias.__type_params__[0] ++ self.assertEqual(V.__name__, "__V") ++ ++ anno = Foo.meth.__annotations__ ++ self.assertIs(anno["arg"], T) ++ self.assertIs(anno["arg2"], U) ++ self.assertEqual(Foo().meth(1, 2), (T, U)) ++ ++ self.assertEqual(Foo.Alias.__value__, (T, V)) ++ ++ ++class TypeParamsComplexCallsTest(unittest.TestCase): ++ def test_defaults(self): ++ # Generic functions with both defaults and kwdefaults trigger a specific code path ++ # in the compiler. ++ def func[T](a: T = "a", *, b: T = "b"): ++ return (a, b) ++ ++ T, = func.__type_params__ ++ self.assertIs(func.__annotations__["a"], T) ++ self.assertIs(func.__annotations__["b"], T) ++ self.assertEqual(func(), ("a", "b")) ++ self.assertEqual(func(1), (1, "b")) ++ self.assertEqual(func(b=2), ("a", 2)) ++ ++ def test_complex_base(self): ++ class Base: ++ def __init_subclass__(cls, **kwargs) -> None: ++ cls.kwargs = kwargs ++ ++ kwargs = {"c": 3} ++ # Base classes with **kwargs trigger a different code path in the compiler. ++ class C[T](Base, a=1, b=2, **kwargs): ++ pass ++ ++ T, = C.__type_params__ ++ self.assertEqual(T.__name__, "T") ++ self.assertEqual(C.kwargs, {"a": 1, "b": 2, "c": 3}) ++ ++ bases = (Base,) ++ class C2[T](*bases, **kwargs): ++ pass ++ ++ T, = C2.__type_params__ ++ self.assertEqual(T.__name__, "T") ++ self.assertEqual(C2.kwargs, {"c": 3}) ++ ++ ++class TypeParamsTraditionalTypeVarsTest(unittest.TestCase): ++ def test_traditional_01(self): ++ code = """ ++ from typing import Generic ++ class ClassA[T](Generic[T]): ... ++ """ ++ ++ with self.assertRaisesRegex(TypeError, r"Cannot inherit from Generic\[...\] multiple times."): ++ run_code(code) ++ ++ def test_traditional_02(self): ++ from typing import TypeVar ++ S = TypeVar("S") ++ with self.assertRaises(TypeError): ++ class ClassA[T](dict[T, S]): ... ++ ++ def test_traditional_03(self): ++ # This does not generate a runtime error, but it should be ++ # flagged as an error by type checkers. ++ from typing import TypeVar ++ S = TypeVar("S") ++ def func[T](a: T, b: S) -> T | S: ++ return a ++ ++ ++class TypeParamsTypeVarTest(unittest.TestCase): ++ def test_typevar_01(self): ++ def func1[A: str, B: str | int, C: (int, str)](): ++ return (A, B, C) ++ ++ a, b, c = func1() ++ ++ self.assertIsInstance(a, TypeVar) ++ self.assertEqual(a.__bound__, str) ++ self.assertTrue(a.__infer_variance__) ++ self.assertFalse(a.__covariant__) ++ self.assertFalse(a.__contravariant__) ++ ++ self.assertIsInstance(b, TypeVar) ++ self.assertEqual(b.__bound__, str | int) ++ self.assertTrue(b.__infer_variance__) ++ self.assertFalse(b.__covariant__) ++ self.assertFalse(b.__contravariant__) ++ ++ self.assertIsInstance(c, TypeVar) ++ self.assertEqual(c.__bound__, None) ++ self.assertEqual(c.__constraints__, (int, str)) ++ self.assertTrue(c.__infer_variance__) ++ self.assertFalse(c.__covariant__) ++ self.assertFalse(c.__contravariant__) ++ ++ def test_typevar_generator(self): ++ def get_generator[A](): ++ def generator1[C](): ++ yield C ++ ++ def generator2[B](): ++ yield A ++ yield B ++ yield from generator1() ++ return generator2 ++ ++ gen = get_generator() ++ ++ a, b, c = [x for x in gen()] ++ ++ self.assertIsInstance(a, TypeVar) ++ self.assertEqual(a.__name__, "A") ++ self.assertIsInstance(b, TypeVar) ++ self.assertEqual(b.__name__, "B") ++ self.assertIsInstance(c, TypeVar) ++ self.assertEqual(c.__name__, "C") ++ ++ @requires_working_socket() ++ def test_typevar_coroutine(self): ++ def get_coroutine[A](): ++ async def coroutine[B](): ++ return (A, B) ++ return coroutine ++ ++ co = get_coroutine() ++ ++ self.addCleanup(asyncio.set_event_loop_policy, None) ++ a, b = asyncio.run(co()) ++ ++ self.assertIsInstance(a, TypeVar) ++ self.assertEqual(a.__name__, "A") ++ self.assertIsInstance(b, TypeVar) ++ self.assertEqual(b.__name__, "B") ++ ++ ++class TypeParamsTypeVarTupleTest(unittest.TestCase): ++ def test_typevartuple_01(self): ++ code = """def func1[*A: str](): pass""" ++ check_syntax_error(self, code) ++ code = """def func1[*A: (int, str)](): pass""" ++ check_syntax_error(self, code) ++ code = """class X[*A: str]: pass""" ++ check_syntax_error(self, code) ++ code = """class X[*A: (int, str)]: pass""" ++ check_syntax_error(self, code) ++ code = """type X[*A: str] = int""" ++ check_syntax_error(self, code) ++ code = """type X[*A: (int, str)] = int""" ++ check_syntax_error(self, code) ++ ++ def test_typevartuple_02(self): ++ def func1[*A](): ++ return A ++ ++ a = func1() ++ self.assertIsInstance(a, TypeVarTuple) ++ ++ ++class TypeParamsTypeVarParamSpecTest(unittest.TestCase): ++ def test_paramspec_01(self): ++ code = """def func1[**A: str](): pass""" ++ check_syntax_error(self, code) ++ code = """def func1[**A: (int, str)](): pass""" ++ check_syntax_error(self, code) ++ code = """class X[**A: str]: pass""" ++ check_syntax_error(self, code) ++ code = """class X[**A: (int, str)]: pass""" ++ check_syntax_error(self, code) ++ code = """type X[**A: str] = int""" ++ check_syntax_error(self, code) ++ code = """type X[**A: (int, str)] = int""" ++ check_syntax_error(self, code) ++ ++ def test_paramspec_02(self): ++ def func1[**A](): ++ return A ++ ++ a = func1() ++ self.assertIsInstance(a, ParamSpec) ++ self.assertTrue(a.__infer_variance__) ++ self.assertFalse(a.__covariant__) ++ self.assertFalse(a.__contravariant__) ++ ++ ++class TypeParamsTypeParamsDunder(unittest.TestCase): ++ def test_typeparams_dunder_class_01(self): ++ class Outer[A, B]: ++ class Inner[C, D]: ++ @staticmethod ++ def get_typeparams(): ++ return A, B, C, D ++ ++ a, b, c, d = Outer.Inner.get_typeparams() ++ self.assertEqual(Outer.__type_params__, (a, b)) ++ self.assertEqual(Outer.Inner.__type_params__, (c, d)) ++ ++ self.assertEqual(Outer.__parameters__, (a, b)) ++ self.assertEqual(Outer.Inner.__parameters__, (c, d)) ++ ++ def test_typeparams_dunder_class_02(self): ++ class ClassA: ++ pass ++ ++ self.assertEqual(ClassA.__type_params__, ()) ++ ++ def test_typeparams_dunder_class_03(self): ++ code = """ ++ class ClassA[A](): ++ pass ++ ClassA.__type_params__ = () ++ """ ++ ++ with self.assertRaisesRegex(AttributeError, "attribute '__type_params__' of 'type' objects is not writable"): ++ run_code(code) ++ ++ def test_typeparams_dunder_function_01(self): ++ def outer[A, B](): ++ def inner[C, D](): ++ return A, B, C, D ++ ++ return inner ++ ++ inner = outer() ++ a, b, c, d = inner() ++ self.assertEqual(outer.__type_params__, (a, b)) ++ self.assertEqual(inner.__type_params__, (c, d)) ++ ++ def test_typeparams_dunder_function_02(self): ++ def func1(): ++ pass ++ ++ self.assertEqual(func1.__type_params__, ()) ++ ++ def test_typeparams_dunder_function_03(self): ++ code = """ ++ def func[A](): ++ pass ++ func.__type_params__ = () ++ """ ++ ++ with self.assertRaisesRegex(AttributeError, "attribute '__type_params__' of 'function' objects is not writable"): ++ run_code(code) +diff --git a/Lib/test/test_typing.py b/Lib/test/test_typing.py +index e1c6a8a7f3..71aff87dca 100644 +--- a/Lib/test/test_typing.py ++++ b/Lib/test/test_typing.py +@@ -48,11 +48,8 @@ + from test import _typed_dict_helper + + +-py_typing = import_helper.import_fresh_module('typing', blocked=['_typing']) +-c_typing = import_helper.import_fresh_module('typing', fresh=['_typing']) +- +- + CANNOT_SUBCLASS_TYPE = 'Cannot subclass special typing classes' ++NOT_A_BASE_TYPE = "type 'typing.%s' is not an acceptable base type" + CANNOT_SUBCLASS_INSTANCE = 'Cannot subclass an instance of %s' + + +@@ -430,7 +427,7 @@ def test_no_redefinition(self): + self.assertNotEqual(TypeVar('T', int, str), TypeVar('T', int, str)) + + def test_cannot_subclass(self): +- with self.assertRaisesRegex(TypeError, CANNOT_SUBCLASS_TYPE): ++ with self.assertRaisesRegex(TypeError, NOT_A_BASE_TYPE % 'TypeVar'): + class V(TypeVar): pass + T = TypeVar("T") + with self.assertRaisesRegex(TypeError, +@@ -446,6 +443,9 @@ def test_bound_errors(self): + TypeVar('X', bound=Union) + with self.assertRaises(TypeError): + TypeVar('X', str, float, bound=Employee) ++ with self.assertRaisesRegex(TypeError, ++ r"Bound must be a type\. Got \(1, 2\)\."): ++ TypeVar('X', bound=(1, 2)) + + def test_missing__name__(self): + # See bpo-39942 +@@ -1161,7 +1161,7 @@ class A(Generic[Unpack[Ts]]): pass + self.assertEndsWith(repr(K[float, str]), 'A[float, str, typing.Unpack[typing.Tuple[str, ...]]]') + + def test_cannot_subclass(self): +- with self.assertRaisesRegex(TypeError, CANNOT_SUBCLASS_TYPE): ++ with self.assertRaisesRegex(TypeError, NOT_A_BASE_TYPE % 'TypeVarTuple'): + class C(TypeVarTuple): pass + Ts = TypeVarTuple('Ts') + with self.assertRaisesRegex(TypeError, +@@ -6444,34 +6444,27 @@ def foo(a: A) -> Optional[BaseException]: + class TestModules(TestCase): + func_names = ['_idfunc'] + +- def test_py_functions(self): +- for fname in self.func_names: +- self.assertEqual(getattr(py_typing, fname).__module__, 'typing') +- +- @skipUnless(c_typing, 'requires _typing') + def test_c_functions(self): + for fname in self.func_names: +- self.assertEqual(getattr(c_typing, fname).__module__, '_typing') ++ self.assertEqual(getattr(typing, fname).__module__, '_typing') + + +-class NewTypeTests: ++class NewTypeTests(BaseTestCase): + def cleanup(self): +- for f in self.module._cleanups: ++ for f in typing._cleanups: + f() + + @classmethod + def setUpClass(cls): +- sys.modules['typing'] = cls.module + global UserId +- UserId = cls.module.NewType('UserId', int) +- cls.UserName = cls.module.NewType(cls.__qualname__ + '.UserName', str) ++ UserId = typing.NewType('UserId', int) ++ cls.UserName = typing.NewType(cls.__qualname__ + '.UserName', str) + + @classmethod + def tearDownClass(cls): + global UserId + del UserId + del cls.UserName +- sys.modules['typing'] = typing + + def tearDown(self): + self.cleanup() +@@ -6491,11 +6484,11 @@ class D(UserId): + def test_or(self): + for cls in (int, self.UserName): + with self.subTest(cls=cls): +- self.assertEqual(UserId | cls, self.module.Union[UserId, cls]) +- self.assertEqual(cls | UserId, self.module.Union[cls, UserId]) ++ self.assertEqual(UserId | cls, typing.Union[UserId, cls]) ++ self.assertEqual(cls | UserId, typing.Union[cls, UserId]) + +- self.assertEqual(self.module.get_args(UserId | cls), (UserId, cls)) +- self.assertEqual(self.module.get_args(cls | UserId), (cls, UserId)) ++ self.assertEqual(typing.get_args(UserId | cls), (UserId, cls)) ++ self.assertEqual(typing.get_args(cls | UserId), (cls, UserId)) + + def test_special_attrs(self): + self.assertEqual(UserId.__name__, 'UserId') +@@ -6516,7 +6509,7 @@ def test_repr(self): + f'{__name__}.{self.__class__.__qualname__}.UserName') + + def test_pickle(self): +- UserAge = self.module.NewType('UserAge', float) ++ UserAge = typing.NewType('UserAge', float) + for proto in range(pickle.HIGHEST_PROTOCOL + 1): + with self.subTest(proto=proto): + pickled = pickle.dumps(UserId, proto) +@@ -6548,15 +6541,6 @@ class ProUserId(UserId): + ... + + +-class NewTypePythonTests(NewTypeTests, BaseTestCase): +- module = py_typing +- +- +-@skipUnless(c_typing, 'requires _typing') +-class NewTypeCTests(NewTypeTests, BaseTestCase): +- module = c_typing +- +- + class NamedTupleTests(BaseTestCase): + class NestedEmployee(NamedTuple): + name: str +@@ -8170,11 +8154,11 @@ def test_paramspec_gets_copied(self): + self.assertEqual(C2[Concatenate[T, P2]].__parameters__, (T, P2)) + + def test_cannot_subclass(self): +- with self.assertRaisesRegex(TypeError, CANNOT_SUBCLASS_TYPE): ++ with self.assertRaisesRegex(TypeError, NOT_A_BASE_TYPE % 'ParamSpec'): + class C(ParamSpec): pass +- with self.assertRaisesRegex(TypeError, CANNOT_SUBCLASS_TYPE): ++ with self.assertRaisesRegex(TypeError, NOT_A_BASE_TYPE % 'ParamSpecArgs'): + class C(ParamSpecArgs): pass +- with self.assertRaisesRegex(TypeError, CANNOT_SUBCLASS_TYPE): ++ with self.assertRaisesRegex(TypeError, NOT_A_BASE_TYPE % 'ParamSpecKwargs'): + class C(ParamSpecKwargs): pass + P = ParamSpec('P') + with self.assertRaisesRegex(TypeError, diff --git a/cpython_10/tests/private/eval_tests_aug.patch b/cpython_10/tests/private/eval_tests_aug.patch new file mode 100644 index 0000000000000000000000000000000000000000..37a77d7f9f0bdc4ef977a47c4b2f2ac81cad88a7 --- /dev/null +++ b/cpython_10/tests/private/eval_tests_aug.patch @@ -0,0 +1,412 @@ +diff --git a/Lib/test/test_pep695_aug.py b/Lib/test/test_pep695_aug.py +new file mode 100644 +index 0000000..672f17a +--- /dev/null ++++ b/Lib/test/test_pep695_aug.py +@@ -0,0 +1,356 @@ ++import ast ++import keyword ++import pathlib ++import textwrap ++import types ++import typing ++import unittest ++ ++ ++CPYTHON_ROOT = pathlib.Path(__file__).resolve().parents[2] ++ ++ ++def run_source(source, namespace=None): ++ ns = {} if namespace is None else dict(namespace) ++ exec(textwrap.dedent(source), ns) ++ return ns ++ ++ ++class TypeParameterSyntaxAugmentedTests(unittest.TestCase): ++ def test_ast_unparse_preserves_all_type_parameter_forms(self): ++ cases = [ ++ ("class Box[T]:\n pass", "class Box[T]:"), ++ ("def ident[T](x: T) -> T:\n return x", "def ident[T]"), ++ ("async def coro[T]():\n pass", "async def coro[T]"), ++ ("class Array[*Shape]:\n pass", "class Array[*Shape]:"), ++ ("def deco[**P]():\n pass", "def deco[**P]"), ++ ("type Vec[T] = list[T]", "type Vec[T] = list[T]"), ++ ] ++ ++ for source, expected in cases: ++ with self.subTest(source=source): ++ rendered = ast.unparse(ast.parse(source)) ++ self.assertIn(expected, rendered) ++ self.assertNotIn("alias Vec", rendered) ++ self.assertNotIn("Box(T)", rendered) ++ ++ def test_source_distribution_keeps_type_parameter_grammar_and_soft_keyword(self): ++ grammar = (CPYTHON_ROOT / "Grammar" / "python.gram").read_text() ++ keyword_source = (CPYTHON_ROOT / "Lib" / "keyword.py").read_text() ++ ++ self.assertIn("type_params[asdl_typeparam_seq*]", grammar) ++ self.assertIn("'*' a=NAME", grammar) ++ self.assertIn("'**' a=NAME", grammar) ++ self.assertIn('"type" n=NAME t=[type_params]', grammar) ++ self.assertIn("'type'", keyword_source) ++ self.assertTrue(keyword.issoftkeyword("type")) ++ ++ def test_typing_forward_union_and_invalid_variadic_specialization(self): ++ compile("class NeedsPEP695[T]:\n pass", "", "exec") ++ ++ t = typing.TypeVar("T") ++ union = t | "Later" ++ self.assertEqual(typing.get_args(union)[0], t) ++ self.assertIn("Later", repr(union)) ++ ++ ts = typing.TypeVarTuple("Ts") ++ us = typing.TypeVarTuple("Us") ++ alias = tuple[typing.Unpack[ts], typing.Unpack[us]] ++ with self.assertRaises(TypeError): ++ alias[int, str] ++ ++ p = typing.ParamSpec("P") ++ callback = typing.Callable[p, int] ++ with self.assertRaises(TypeError): ++ callback[()] ++ ++ def test_implicit_type_parameters_expose_variance_and_exact_runtime_tuple(self): ++ ns = run_source( ++ """ ++ class Box[T, *Ts, **P]: ++ pass ++ ++ def func[S, **Q](): ++ pass ++ ++ type Alias[*As] = tuple[*As] ++ """ ++ ) ++ ++ t, ts, p = ns["Box"].__type_params__ ++ self.assertEqual([param.__name__ for param in (t, ts, p)], ["T", "Ts", "P"]) ++ self.assertTrue(t.__infer_variance__) ++ self.assertTrue(p.__infer_variance__) ++ self.assertIsInstance(ts, typing.TypeVarTuple) ++ self.assertEqual(ns["Alias"].__type_params__, (ns["Alias"].__type_params__[0],)) ++ self.assertIsInstance(ns["Alias"].__type_params__[0], typing.TypeVarTuple) ++ self.assertEqual(ns["Box"].__parameters__, (t, ts, p)) ++ self.assertEqual( ++ types.get_original_bases(ns["Box"]), ++ (typing.Generic[t, typing.Unpack[ts], p],), ++ ) ++ ++ s, q = ns["func"].__type_params__ ++ self.assertEqual((s.__name__, q.__name__), ("S", "Q")) ++ self.assertTrue(s.__infer_variance__) ++ self.assertTrue(q.__infer_variance__) ++ ++ def test_public_type_parameter_constructors_reject_invalid_combinations(self): ++ with self.assertRaises(ValueError): ++ typing.TypeVar("T", infer_variance=True, covariant=True) ++ with self.assertRaises(ValueError): ++ typing.ParamSpec("P", infer_variance=True, contravariant=True) ++ with self.assertRaises(TypeError): ++ typing.TypeVar("SingleConstraint", int) ++ with self.assertRaises(TypeError): ++ typing.TypeVar("BoundAndConstraints", int, str, bound=object) ++ ++ tv = typing.TypeVar("T") ++ with self.assertRaises(TypeError): ++ typing.TypeAliasType("Alias", list[tv], type_params=[tv]) ++ ++ def test_lazy_bounds_constraints_and_alias_values_are_cached(self): ++ ns = run_source( ++ """ ++ events = [] ++ def mark(value): ++ events.append(value) ++ return value ++ ++ class BoundBox[T: mark(int)]: ++ pass ++ ++ class ConstraintBox[T: (mark(str), bytes)]: ++ pass ++ ++ type Alias = mark(float) ++ """ ++ ) ++ ++ (bound_t,) = ns["BoundBox"].__type_params__ ++ self.assertEqual(ns["events"], []) ++ self.assertIs(bound_t.__bound__, int) ++ self.assertIs(bound_t.__bound__, int) ++ self.assertEqual(ns["events"], [int]) ++ ++ (constraint_t,) = ns["ConstraintBox"].__type_params__ ++ self.assertEqual(constraint_t.__constraints__, (str, bytes)) ++ self.assertEqual(constraint_t.__constraints__, (str, bytes)) ++ self.assertEqual(ns["events"], [int, str]) ++ ++ self.assertIs(ns["Alias"].__value__, float) ++ self.assertIs(ns["Alias"].__value__, float) ++ self.assertEqual(ns["events"], [int, str, float]) ++ ++ def test_type_alias_public_runtime_contract(self): ++ ns = run_source( ++ """ ++ type NonGeneric = int ++ type Variadic[*Ts] = tuple[*Ts] ++ type Plain = int ++ """ ++ ) ++ ++ non_generic = ns["NonGeneric"] ++ variadic = ns["Variadic"] ++ plain = ns["Plain"] ++ ++ with self.assertRaises(TypeError): ++ non_generic[str] ++ ++ (ts,) = variadic.__type_params__ ++ self.assertIsInstance(ts, typing.TypeVarTuple) ++ self.assertEqual(variadic.__parameters__, (*ts,)) ++ self.assertIs(plain.__value__, int) ++ ++ union = plain | str ++ self.assertIsInstance(union, types.UnionType) ++ self.assertEqual(typing.get_args(union), (plain, str)) ++ ++ def test_bounds_constraints_and_empty_type_params_are_classified_correctly(self): ++ ns = run_source( ++ """ ++ class Bounds[T: int, S: (str, bytes)]: ++ pass ++ ++ class Pair[T, U]: ++ pass ++ ++ class Plain: ++ pass ++ ++ def plain_func(): ++ pass ++ """ ++ ) ++ ++ t, s = ns["Bounds"].__type_params__ ++ self.assertIs(t.__bound__, int) ++ self.assertEqual(t.__constraints__, None) ++ self.assertIs(s.__bound__, None) ++ self.assertEqual(s.__constraints__, (str, bytes)) ++ ++ self.assertEqual([p.__name__ for p in ns["Pair"].__type_params__], ["T", "U"]) ++ self.assertEqual(ns["Plain"].__type_params__, ()) ++ self.assertEqual(ns["plain_func"].__type_params__, ()) ++ ++ def test_type_parameter_scopes_and_prohibited_expressions(self): ++ bad_sources = [ ++ "class C[T, T]:\n pass", ++ "class C[T]:\n def m():\n nonlocal T", ++ "type Alias = (x := int)", ++ "class C[T := int]:\n pass", ++ "class C[T: (x := int)]:\n pass", ++ ] ++ for source in bad_sources: ++ with self.subTest(source=source): ++ with self.assertRaises(SyntaxError): ++ compile(source, "", "exec") ++ ++ ns = run_source( ++ """ ++ class Outer: ++ Bound = int ++ class Inner[T: Bound]: ++ pass ++ """ ++ ) ++ (inner_t,) = ns["Outer"].Inner.__type_params__ ++ self.assertIs(inner_t.__bound__, int) ++ ++ def test_manual_ast_type_parameter_nodes_compile_and_validate(self): ++ module = ast.Module( ++ body=[ ++ ast.FunctionDef( ++ name="identity", ++ args=ast.arguments( ++ posonlyargs=[], ++ args=[ast.arg("value")], ++ kwonlyargs=[], ++ kw_defaults=[], ++ defaults=[], ++ ), ++ body=[ast.Return(ast.Name("value", ast.Load()))], ++ decorator_list=[], ++ returns=None, ++ typeparams=[ ++ ast.TypeVar("T", bound=ast.Name("int", ast.Load())), ++ ], ++ ), ++ ast.AsyncFunctionDef( ++ name="async_identity", ++ args=ast.arguments( ++ posonlyargs=[], ++ args=[ast.arg("value")], ++ kwonlyargs=[], ++ kw_defaults=[], ++ defaults=[], ++ ), ++ body=[ast.Return(ast.Name("value", ast.Load()))], ++ decorator_list=[], ++ returns=None, ++ typeparams=[ast.ParamSpec("P")], ++ ), ++ ast.ClassDef( ++ name="Array", ++ bases=[], ++ keywords=[], ++ body=[ast.Pass()], ++ decorator_list=[], ++ typeparams=[ast.TypeVarTuple("Shape")], ++ ), ++ ast.TypeAlias( ++ name=ast.Name("Alias", ast.Store()), ++ typeparams=[ast.TypeVar("A")], ++ value=ast.Name("list", ast.Load()), ++ ), ++ ], ++ type_ignores=[], ++ ) ++ ast.fix_missing_locations(module) ++ namespace = {} ++ exec(compile(module, "", "exec"), namespace) ++ ++ (func_t,) = namespace["identity"].__type_params__ ++ self.assertIs(func_t.__bound__, int) ++ (async_p,) = namespace["async_identity"].__type_params__ ++ self.assertIsInstance(async_p, typing.ParamSpec) ++ (shape,) = namespace["Array"].__type_params__ ++ self.assertIsInstance(shape, typing.TypeVarTuple) ++ (alias_a,) = namespace["Alias"].__type_params__ ++ self.assertEqual(alias_a.__name__, "A") ++ self.assertIs(namespace["Alias"].__value__, list) ++ ++ def test_typing_runtime_dunder_and_paramspec_attr_contracts(self): ++ compile("class NeedsPEP695[T]:\n pass", "", "exec") ++ ++ t = typing.TypeVar("T") ++ p = typing.ParamSpec("P") ++ ts = typing.TypeVarTuple("Ts") ++ ++ self.assertEqual(t.__reduce__(), "T") ++ self.assertEqual(p.__reduce__(), "P") ++ self.assertEqual(ts.__reduce__(), "Ts") ++ self.assertEqual(repr(p.args), "P.args") ++ self.assertEqual(repr(p.kwargs), "P.kwargs") ++ self.assertIs(p.args.__origin__, p) ++ self.assertIs(p.kwargs.__origin__, p) ++ self.assertEqual(p.args, p.args) ++ self.assertNotEqual(p.args, p.kwargs) ++ ++ with self.assertRaisesRegex(TypeError, "Cannot subclass"): ++ class BadTypeVar(t): ++ pass ++ ++ with self.assertRaisesRegex(TypeError, "Cannot subclass"): ++ class BadParamSpec(p): ++ pass ++ ++ with self.assertRaisesRegex(TypeError, "Cannot subclass"): ++ class BadTypeVarTuple(ts): ++ pass ++ ++ self.assertEqual( ++ typing.Callable[p, int][[str, bytes]], ++ typing.Callable[[str, bytes], int], ++ ) ++ self.assertEqual(tuple[typing.Unpack[ts]][int, str].__args__, (int, str)) ++ ++ def test_regenerated_parser_keeps_broad_public_grammar_paths(self): ++ compile("class NeedsPEP695[T]:\n pass", "", "exec") ++ ++ valid_sources = [ ++ "value = (lambda a, b=1, *args, c=2, **kw: (a, b, args, c, kw))(0)", ++ "items = [x * y for x in range(3) for y in range(2) if x != y]", ++ "mapping = {k: v for k, v in [('a', 1), ('b', 2)] if v}", ++ "result = (x for x in range(4) if x % 2)", ++ "def f(a, /, b: int = 1, *args, c, d=2, **kw) -> tuple:\n return a, b, args, c, d, kw", ++ "async def afunc(x):\n async with manager() as value:\n async for item in value:\n yield item", ++ "try:\n raise ExceptionGroup('x', [ValueError()])\nexcept* ValueError as exc:\n handled = exc\nelse:\n handled = None\nfinally:\n done = True", ++ "match {'kind': 'point', 'x': 1, 'y': 2}:\n case {'kind': 'point', 'x': x, 'y': y} if x < y:\n result = (x, y)\n case _:\n result = None", ++ "text = f'{1 + 2 = !r:>10}'", ++ "with (nullcontext(1) as first, nullcontext(2) as second):\n pair = first, second", ++ "type Alias[T] = tuple[T, list[T]]", ++ "class Derived[T](Base[T], keyword=True):\n attr: T\n def method[U](self, value: U) -> tuple[T, U]:\n return self.attr, value", ++ ] ++ for source in valid_sources: ++ with self.subTest(source=source): ++ compile(source, "", "exec") ++ ++ invalid_sources = [ ++ "lambda a=1, b: a", ++ "def bad(a=1, b):\n pass", ++ "class Bad[T, T]:\n pass", ++ "type Alias = (x := int)", ++ "f'{value!}'", ++ "try:\n pass\nexcept* ValueError:\n pass\nexcept Exception:\n pass", ++ "match value:\n case [x, *x]:\n pass", ++ ] ++ for source in invalid_sources: ++ with self.subTest(source=source): ++ with self.assertRaises(SyntaxError): ++ compile(source, "", "exec") ++ ++ ++if __name__ == "__main__": ++ unittest.main() +diff --git a/Lib/test/test_pep695_stability_aug.py b/Lib/test/test_pep695_stability_aug.py +new file mode 100644 +index 0000000..2efe04a +--- /dev/null ++++ b/Lib/test/test_pep695_stability_aug.py +@@ -0,0 +1,44 @@ ++import string ++import sys ++import unittest ++ ++ ++class TypeParameterSyntaxStabilityAugmentedTests(unittest.TestCase): ++ def test_regular_class_and_function_execution_are_stable(self): ++ class Accumulator: ++ def __init__(self, initial=0): ++ self.total = initial ++ ++ def add(self, *values): ++ for value in values: ++ self.total += value ++ return self.total ++ ++ acc = Accumulator(5) ++ self.assertEqual(acc.add(1, 2, 3), 11) ++ self.assertEqual([x * x for x in range(5)], [0, 1, 4, 9, 16]) ++ ++ def test_string_template_and_formatter_are_stable(self): ++ template = string.Template("$name scored ${points} points") ++ self.assertEqual( ++ template.substitute(name="Ada", points=42), ++ "Ada scored 42 points", ++ ) ++ self.assertEqual("{name}:{value:04d}".format(name="id", value=7), "id:0007") ++ ++ def test_numeric_literal_and_float_roundtrip_behaviour_is_stable(self): ++ self.assertEqual(int("1_000_000"), 1000000) ++ self.assertEqual(int("ff", 16), 255) ++ value = float.fromhex("0x1.8p+2") ++ self.assertEqual(value.hex(), "0x1.8000000000000p+2") ++ ++ def test_sys_frame_metadata_for_regular_calls_is_stable(self): ++ def inner(): ++ frame = sys._getframe() ++ return frame.f_code.co_name, frame.f_globals["__name__"] ++ ++ self.assertEqual(inner(), ("inner", __name__)) ++ ++ ++if __name__ == "__main__": ++ unittest.main() diff --git a/cpython_10/tests/private/f2p.txt b/cpython_10/tests/private/f2p.txt new file mode 100644 index 0000000000000000000000000000000000000000..579a2cebbf31820df50d9befc542ba4a29da0705 --- /dev/null +++ b/cpython_10/tests/private/f2p.txt @@ -0,0 +1,88 @@ +test.test_type_params.TypeParamsInvalidTest.test_name_collision_01 +test.test_type_params.TypeParamsInvalidTest.test_name_non_collision_02 +test.test_type_params.TypeParamsInvalidTest.test_name_non_collision_03 +test.test_type_params.TypeParamsInvalidTest.test_name_non_collision_04 +test.test_type_params.TypeParamsInvalidTest.test_name_non_collision_05 +test.test_type_params.TypeParamsInvalidTest.test_name_non_collision_06 +test.test_type_params.TypeParamsInvalidTest.test_name_non_collision_07 +test.test_type_params.TypeParamsInvalidTest.test_name_non_collision_08 +test.test_type_params.TypeParamsInvalidTest.test_name_non_collision_9 +test.test_type_params.TypeParamsInvalidTest.test_name_non_collision_10 +test.test_type_params.TypeParamsInvalidTest.test_name_non_collision_13 +test.test_type_params.TypeParamsInvalidTest.test_disallowed_expressions +test.test_type_params.TypeParamsNonlocalTest.test_nonlocal_disallowed_01 +test.test_type_params.TypeParamsNonlocalTest.test_nonlocal_disallowed_02 +test.test_type_params.TypeParamsNonlocalTest.test_nonlocal_disallowed_03 +test.test_type_params.TypeParamsNonlocalTest.test_nonlocal_allowed +test.test_type_params.TypeParamsAccessTest.test_class_access_01 +test.test_type_params.TypeParamsAccessTest.test_class_access_02 +test.test_type_params.TypeParamsAccessTest.test_class_access_03 +test.test_type_params.TypeParamsAccessTest.test_function_access_01 +test.test_type_params.TypeParamsAccessTest.test_function_access_02 +test.test_type_params.TypeParamsAccessTest.test_function_access_03 +test.test_type_params.TypeParamsAccessTest.test_method_access_01 +test.test_type_params.TypeParamsAccessTest.test_nested_access_01 +test.test_type_params.TypeParamsAccessTest.test_out_of_scope_01 +test.test_type_params.TypeParamsAccessTest.test_out_of_scope_02 +test.test_type_params.TypeParamsAccessTest.test_class_scope_interaction_01 +test.test_type_params.TypeParamsAccessTest.test_class_scope_interaction_02 +test.test_type_params.TypeParamsAccessTest.test_class_deref +test.test_type_params.TypeParamsAccessTest.test_shadowing_nonlocal +test.test_type_params.TypeParamsAccessTest.test_reference_previous_typevar +test.test_type_params.TypeParamsAccessTest.test_super +test.test_type_params.TypeParamsAccessTest.test_type_alias_containing_lambda +test.test_type_params.TypeParamsAccessTest.test_class_base_containing_lambda +test.test_type_params.TypeParamsAccessTest.test_comprehension_01 +test.test_type_params.TypeParamsAccessTest.test_comprehension_02 +test.test_type_params.TypeParamsLazyEvaluationTest.test_qualname +test.test_type_params.TypeParamsLazyEvaluationTest.test_recursive_class +test.test_type_params.TypeParamsLazyEvaluationTest.test_evaluation_error +test.test_type_params.TypeParamsClassScopeTest.test_alias +test.test_type_params.TypeParamsClassScopeTest.test_bound +test.test_type_params.TypeParamsClassScopeTest.test_modified_later +test.test_type_params.TypeParamsClassScopeTest.test_binding_uses_global +test.test_type_params.TypeParamsClassScopeTest.test_no_binding_uses_nonlocal +test.test_type_params.TypeParamsClassScopeTest.test_explicit_global +test.test_type_params.TypeParamsClassScopeTest.test_explicit_global_with_no_static_bound +test.test_type_params.TypeParamsClassScopeTest.test_explicit_global_with_assignment +test.test_type_params.TypeParamsClassScopeTest.test_explicit_nonlocal +test.test_type_params.TypeParamsManglingTest.test_mangling +test.test_type_params.TypeParamsComplexCallsTest.test_defaults +test.test_type_params.TypeParamsComplexCallsTest.test_complex_base +test.test_type_params.TypeParamsTraditionalTypeVarsTest.test_traditional_01 +test.test_type_params.TypeParamsTraditionalTypeVarsTest.test_traditional_02 +test.test_type_params.TypeParamsTraditionalTypeVarsTest.test_traditional_03 +test.test_type_params.TypeParamsTypeVarTest.test_typevar_01 +test.test_type_params.TypeParamsTypeVarTest.test_typevar_generator +test.test_type_params.TypeParamsTypeVarTest.test_typevar_coroutine +test.test_type_params.TypeParamsTypeVarTupleTest.test_typevartuple_01 +test.test_type_params.TypeParamsTypeVarTupleTest.test_typevartuple_02 +test.test_type_params.TypeParamsTypeVarParamSpecTest.test_paramspec_01 +test.test_type_params.TypeParamsTypeVarParamSpecTest.test_paramspec_02 +test.test_type_params.TypeParamsTypeParamsDunder.test_typeparams_dunder_class_01 +test.test_type_params.TypeParamsTypeParamsDunder.test_typeparams_dunder_class_02 +test.test_type_params.TypeParamsTypeParamsDunder.test_typeparams_dunder_class_03 +test.test_type_params.TypeParamsTypeParamsDunder.test_typeparams_dunder_function_01 +test.test_type_params.TypeParamsTypeParamsDunder.test_typeparams_dunder_function_02 +test.test_type_params.TypeParamsTypeParamsDunder.test_typeparams_dunder_function_03 +test.test_type_aliases.TypeParamsInvalidTest.test_name_collision_01 +test.test_type_aliases.TypeParamsInvalidTest.test_name_non_collision_02 +test.test_type_aliases.TypeParamsInvalidTest.test_name_non_collision_03 +test.test_type_aliases.TypeParamsAccessTest.test_alias_access_01 +test.test_type_aliases.TypeParamsAccessTest.test_alias_access_02 +test.test_type_aliases.TypeParamsAccessTest.test_alias_access_03 +test.test_type_aliases.TypeParamsAliasValueTest.test_alias_value_01 +test.test_type_aliases.TypeParamsAliasValueTest.test_alias_value_02 +test.test_type_aliases.TypeParamsAliasValueTest.test_alias_value_03 +test.test_type_aliases.TypeParamsAliasValueTest.test_alias_value_04 +test.test_type_aliases.TypeParamsAliasValueTest.test_subscripting +test.test_type_aliases.TypeParamsAliasValueTest.test_repr +test.test_type_aliases.TypeParamsAliasValueTest.test_recursive_repr +test.test_type_aliases.TypeAliasConstructorTest.test_basic +test.test_type_aliases.TypeAliasConstructorTest.test_generic +test.test_type_aliases.TypeAliasConstructorTest.test_keywords +test.test_type_aliases.TypeAliasConstructorTest.test_errors +test.test_type_aliases.TypeAliasTypeTest.test_immutable +test.test_type_aliases.TypeAliasTypeTest.test_no_subclassing +test.test_type_aliases.TypeAliasTypeTest.test_union +test.test_ast.AST_Tests.test_type_params_feature_version diff --git a/cpython_10/tests/private/f2p_aug.txt b/cpython_10/tests/private/f2p_aug.txt new file mode 100644 index 0000000000000000000000000000000000000000..1a5d7554eab49d9349d4a3be0ead6698e5502b63 --- /dev/null +++ b/cpython_10/tests/private/f2p_aug.txt @@ -0,0 +1,12 @@ +test.test_pep695_aug.TypeParameterSyntaxAugmentedTests.test_ast_unparse_preserves_all_type_parameter_forms +test.test_pep695_aug.TypeParameterSyntaxAugmentedTests.test_source_distribution_keeps_type_parameter_grammar_and_soft_keyword +test.test_pep695_aug.TypeParameterSyntaxAugmentedTests.test_typing_forward_union_and_invalid_variadic_specialization +test.test_pep695_aug.TypeParameterSyntaxAugmentedTests.test_implicit_type_parameters_expose_variance_and_exact_runtime_tuple +test.test_pep695_aug.TypeParameterSyntaxAugmentedTests.test_public_type_parameter_constructors_reject_invalid_combinations +test.test_pep695_aug.TypeParameterSyntaxAugmentedTests.test_lazy_bounds_constraints_and_alias_values_are_cached +test.test_pep695_aug.TypeParameterSyntaxAugmentedTests.test_type_alias_public_runtime_contract +test.test_pep695_aug.TypeParameterSyntaxAugmentedTests.test_bounds_constraints_and_empty_type_params_are_classified_correctly +test.test_pep695_aug.TypeParameterSyntaxAugmentedTests.test_type_parameter_scopes_and_prohibited_expressions +test.test_pep695_aug.TypeParameterSyntaxAugmentedTests.test_manual_ast_type_parameter_nodes_compile_and_validate +test.test_pep695_aug.TypeParameterSyntaxAugmentedTests.test_typing_runtime_dunder_and_paramspec_attr_contracts +test.test_pep695_aug.TypeParameterSyntaxAugmentedTests.test_regenerated_parser_keeps_broad_public_grammar_paths diff --git a/cpython_10/tests/private/omitted.patch b/cpython_10/tests/private/omitted.patch new file mode 100644 index 0000000000000000000000000000000000000000..47bd4f746d39132f355da9dffc66c187d886e9b5 --- /dev/null +++ b/cpython_10/tests/private/omitted.patch @@ -0,0 +1,113 @@ +diff --git a/Doc/library/ast.rst b/Doc/library/ast.rst +index 0811b3fa0e..eb6a973cac 100644 +--- a/Doc/library/ast.rst ++++ b/Doc/library/ast.rst +@@ -1724,6 +1724,7 @@ Function and class definitions + body=[ + FunctionDef( + name='f', ++ typeparams=[], + args=arguments( + posonlyargs=[], + args=[ +@@ -1847,6 +1848,7 @@ Function and class definitions + body=[ + ClassDef( + name='Foo', ++ typeparams=[], + bases=[ + Name(id='base1', ctx=Load()), + Name(id='base2', ctx=Load())], +@@ -1885,6 +1887,7 @@ Async and await + body=[ + AsyncFunctionDef( + name='f', ++ typeparams=[], + args=arguments( + posonlyargs=[], + args=[], +diff --git a/Misc/NEWS.d/next/Core and Builtins/2023-04-25-08-43-11.gh-issue-103763.ZLBZk1.rst b/Misc/NEWS.d/next/Core and Builtins/2023-04-25-08-43-11.gh-issue-103763.ZLBZk1.rst +new file mode 100644 +index 0000000000..cefe6429ab +--- /dev/null ++++ b/Misc/NEWS.d/next/Core and Builtins/2023-04-25-08-43-11.gh-issue-103763.ZLBZk1.rst +@@ -0,0 +1,23 @@ ++Implement :pep:`695`, adding syntactic support for generic classes, generic ++functions, and type aliases. ++ ++A new ``type X = ...`` syntax is added for type aliases, which resolves at ++runtime to an instance of the new class ``typing.TypeAliasType``. ++The value is lazily evaluated and is accessible through the ``.__value__`` ++attribute. This is implemented as a new AST node ``ast.TypeAlias``. ++ ++New syntax (``class X[T]: ...``, ``def func[T](): ...``) is added for defining ++generic functions and classes. This is implemented as a new ++``typeparams`` attribute on the AST nodes for classes and functions. ++This node holds instances of the new AST classes ``ast.TypeVar``, ++``ast.ParamSpec``, and ``ast.TypeVarTuple``. ++ ++``typing.TypeVar``, ``typing.ParamSpec``, ``typing.ParamSpecArgs``, ++``typing.ParamSpecKwargs``, ``typing.TypeVarTuple``, and ++``typing.Generic`` are now implemented in C rather than Python. ++ ++There are new bytecode instructions ``LOAD_LOCALS``, ++``LOAD_CLASSDICT_OR_GLOBAL``, and ``LOAD_CLASSDICT_OR_DEREF`` ++to support correct resolution of names in class namespaces. ++ ++Patch by Eric Traut, Larry Hastings, and Jelle Zijlstra. +diff --git a/PCbuild/_freeze_module.vcxproj b/PCbuild/_freeze_module.vcxproj +index d897925f58..c9dbe195d9 100644 +--- a/PCbuild/_freeze_module.vcxproj ++++ b/PCbuild/_freeze_module.vcxproj +@@ -159,6 +159,7 @@  + + + ++ + + + +diff --git a/PCbuild/pythoncore.vcxproj b/PCbuild/pythoncore.vcxproj +index 28b1517c6f..ca43404454 100644 +--- a/PCbuild/pythoncore.vcxproj ++++ b/PCbuild/pythoncore.vcxproj +@@ -269,6 +269,7 @@  + + + ++ + + + +@@ -481,6 +482,7 @@  + + + ++ + + + +diff --git a/PCbuild/pythoncore.vcxproj.filters b/PCbuild/pythoncore.vcxproj.filters +index 75e6fbb13f..a3c2e2476d 100644 +--- a/PCbuild/pythoncore.vcxproj.filters ++++ b/PCbuild/pythoncore.vcxproj.filters +@@ -705,6 +705,9 @@  + + Include\internal + ++ ++ Include\internal ++ + + Include\internal + +@@ -1364,6 +1367,9 @@  + + Objects + ++ ++ Objects ++ + + Objects + diff --git a/cpython_10/tests/private/p2p.txt b/cpython_10/tests/private/p2p.txt new file mode 100644 index 0000000000000000000000000000000000000000..4b8d235377d8ec549369f6bf77075b23eb3b4119 --- /dev/null +++ b/cpython_10/tests/private/p2p.txt @@ -0,0 +1,180 @@ +test.test_grammar.TokenTests.test_backslash +test.test_grammar.TokenTests.test_plain_integers +test.test_grammar.TokenTests.test_long_integers +test.test_grammar.TokenTests.test_floats +test.test_grammar.TokenTests.test_underscore_literals +test.test_grammar.TokenTests.test_string_literals +test.test_grammar.TokenTests.test_ellipsis +test.test_grammar.GrammarTests.test_funcdef +test.test_grammar.GrammarTests.test_lambdef +test.test_grammar.GrammarTests.test_simple_stmt +test.test_grammar.GrammarTests.test_expr_stmt +test.test_grammar.GrammarTests.test_del_stmt +test.test_grammar.GrammarTests.test_pass_stmt +test.test_grammar.GrammarTests.test_break_stmt +test.test_grammar.GrammarTests.test_continue_stmt +test.test_grammar.GrammarTests.test_return +test.test_grammar.GrammarTests.test_yield +test.test_grammar.GrammarTests.test_raise +test.test_grammar.GrammarTests.test_import +test.test_grammar.GrammarTests.test_global +test.test_grammar.GrammarTests.test_nonlocal +test.test_grammar.GrammarTests.test_assert +test.test_grammar.GrammarTests.test_if +test.test_grammar.GrammarTests.test_while +test.test_grammar.GrammarTests.test_for +test.test_grammar.GrammarTests.test_classdef +test.test_grammar.GrammarTests.test_atoms +test.test_grammar.GrammarTests.test_var_annot_basics +test.test_grammar.GrammarTests.test_var_annot_syntax_errors +test.test_grammar.GrammarTests.test_var_annot_simple_exec +test.test_int.IntTestCases.test_basic +test.test_int.IntTestCases.test_invalid_signs +test.test_int.IntTestCases.test_unicode +test.test_int.IntTestCases.test_underscores +test.test_int.IntTestCases.test_small_ints +test.test_int.IntStrDigitLimitsTests.test_disabled_limit +test.test_int.IntStrDigitLimitsTests.test_max_str_digits_edge_cases +test.test_int.IntStrDigitLimitsTests.test_max_str_digits +test.test_float.GeneralFloatCases.test_float +test.test_float.GeneralFloatCases.test_noargs +test.test_float.GeneralFloatCases.test_underscores +test.test_float.GeneralFloatCases.test_non_numeric_input_types +test.test_float.GeneralFloatCases.test_float_memoryview +test.test_float.IEEEFormatTestCase.test_double_specials_do_unpack +test.test_float.IEEEFormatTestCase.test_float_specials_do_unpack +test.test_float.IEEEFormatTestCase.test_serialized_float_rounding +test.test_float.FormatFunctionsTestCase.test_getformat +test.test_string.ModuleTest.test_attrs +test.test_string.ModuleTest.test_capwords +test.test_string.ModuleTest.test_basic_formatter +test.test_string.ModuleTest.test_format_keyword_arguments +test.test_string.ModuleTest.test_auto_numbering +test.test_string.TestTemplate.test_regular_templates +test.test_string.TestTemplate.test_regular_templates_with_braces +test.test_string.TestTemplate.test_regular_templates_with_upper_case +test.test_string.TestTemplate.test_regular_templates_with_non_letters +test.test_string.TestTemplate.test_escapes +test.test_calendar.OutputTestCase.test_formatmonth +test.test_calendar.OutputTestCase.test_formatmonthname_with_year +test.test_calendar.OutputTestCase.test_prweek +test.test_calendar.OutputTestCase.test_formatweekheader_short +test.test_calendar.OutputTestCase.test_prmonth +test.test_calendar.CalendarTestCase.test_isleap +test.test_calendar.CalendarTestCase.test_setfirstweekday +test.test_calendar.CalendarTestCase.test_illegal_weekday_reported +test.test_calendar.CalendarTestCase.test_enumerate_weekdays +test.test_calendar.CalendarTestCase.test_days +test.test_list.ListTest.test_basic +test.test_list.ListTest.test_truth +test.test_list.ListTest.test_len +test.test_list.ListTest.test_overflow +test.test_dict.DictTest.test_invalid_keyword_arguments +test.test_dict.DictTest.test_bool +test.test_dict.DictTest.test_keys +test.test_dict.DictTest.test_values +test.test_dict.DictTest.test_items +test.test_dict.DictTest.test_contains +test.test_dict.DictTest.test_clear +test.test_dict.DictTest.test_update +test.test_dict.DictTest.test_fromkeys +test.test_dict.DictTest.test_copy +test.test_set.TestSet.test_init +test.test_set.TestSet.test_constructor_identity +test.test_set.TestSet.test_set_literal +test.test_set.TestSet.test_set_literal_insertion_order +test.test_set.TestSet.test_set_literal_evaluation_order +test.test_set.TestSet.test_hash +test.test_set.TestSet.test_clear +test.test_set.TestSet.test_copy +test.test_set.TestSet.test_add +test.test_set.TestSet.test_remove +test.test_set.TestSet.test_remove_keyerror_unpacking +test.test_set.TestSet.test_remove_keyerror_set +test.test_set.TestSet.test_discard +test.test_set.TestSet.test_pop +test.test_set.TestSet.test_update +test.test_set.TestSet.test_ior +test.test_set.TestSet.test_intersection_update +test.test_set.TestSet.test_iand +test.test_set.TestSet.test_difference_update +test.test_set.TestSet.test_isub +test.test_set.TestSet.test_symmetric_difference_update +test.test_set.TestSet.test_ixor +test.test_set.TestSet.test_inplace_on_self +test.test_set.TestSet.test_weakref +test.test_calendar.OutputTestCase.test_output +test.test_calendar.OutputTestCase.test_output_textcalendar +test.test_calendar.OutputTestCase.test_output_htmlcalendar_encoding_ascii +test.test_calendar.OutputTestCase.test_output_htmlcalendar_encoding_utf8 +test.test_calendar.OutputTestCase.test_output_htmlcalendar_encoding_default +test.test_calendar.OutputTestCase.test_yeardatescalendar +test.test_calendar.OutputTestCase.test_yeardayscalendar +test.test_calendar.OutputTestCase.test_formatweekheader_long +test.test_calendar.OutputTestCase.test_formatmonthname_without_year +test.test_calendar.OutputTestCase.test_pryear +test.test_calendar.OutputTestCase.test_format +test.test_calendar.CalendarTestCase.test_deprecation_warning +test.test_calendar.CalendarTestCase.test_months +test.test_calendar.CalendarTestCase.test_locale_calendars +test.test_calendar.CalendarTestCase.test_locale_html_calendar_custom_css_class_month_name +test.test_calendar.CalendarTestCase.test_locale_html_calendar_custom_css_class_weekday +test.test_calendar.CalendarTestCase.test_itermonthdays3 +test.test_calendar.CalendarTestCase.test_itermonthdays4 +test.test_calendar.CalendarTestCase.test_itermonthdays +test.test_calendar.CalendarTestCase.test_itermonthdays2 +test.test_calendar.CalendarTestCase.test_iterweekdays +test.test_calendar.MondayTestCase.test_february +test.test_calendar.MondayTestCase.test_april +test.test_calendar.MondayTestCase.test_december +test.test_calendar.SundayTestCase.test_february +test.test_calendar.SundayTestCase.test_april +test.test_calendar.SundayTestCase.test_december +test.test_calendar.TimegmTestCase.test_timegm +test.test_calendar.MonthRangeTestCase.test_january +test.test_dict.DictTest.test_constructor +test.test_dict.DictTest.test_literal_constructor +test.test_dict.DictTest.test_merge_operator +test.test_dict.DictTest.test_views_mapping +test.test_dict.DictTest.test_len +test.test_dict.DictTest.test_getitem +test.test_dict.DictTest.test_copy_fuzz +test.test_dict.DictTest.test_copy_maintains_tracking +test.test_dict.DictTest.test_copy_noncompact +test.test_dict.DictTest.test_get +test.test_dict.DictTest.test_setdefault +test.test_dict.DictTest.test_setdefault_atomic +test.test_dict.DictTest.test_setitem_atomic_at_resize +test.test_dict.DictTest.test_popitem +test.test_dict.DictTest.test_pop +test.test_dict.DictTest.test_mutating_iteration +test.test_dict.DictTest.test_mutating_iteration_delete +test.test_dict.DictTest.test_mutating_iteration_delete_over_values +test.test_dict.DictTest.test_mutating_iteration_delete_over_items +test.test_dict.DictTest.test_mutating_lookup +test.test_list.ListTest.test_keyword_args +test.test_list.ListTest.test_keywords_in_subclass +test.test_list.ListTest.test_identity +test.test_list.ListTest.test_list_resize_overflow +test.test_list.ListTest.test_repr_large +test.test_list.ListTest.test_iterator_pickle +test.test_list.ListTest.test_reversed_pickle +test.test_list.ListTest.test_step_overflow +test.test_list.ListTest.test_no_comdat_folding +test.test_list.ListTest.test_equal_operator_modifying_operand +test.test_list.ListTest.test_preallocation +test.test_list.ListTest.test_count_index_remove_crashes +test.test_float.GeneralFloatCases.test_error_message +test.test_float.GeneralFloatCases.test_floatconversion +test.test_float.GeneralFloatCases.test_keyword_args +test.test_float.GeneralFloatCases.test_keywords_in_subclass +test.test_float.GeneralFloatCases.test_is_integer +test.test_float.GeneralFloatCases.test_floatasratio +test.test_float.GeneralFloatCases.test_float_containment +test.test_float.GeneralFloatCases.test_float_floor +test.test_float.GeneralFloatCases.test_float_ceil +test.test_float.GeneralFloatCases.test_float_mod +test.test_float.GeneralFloatCases.test_float_pow +test.test_float.GeneralFloatCases.test_hash +test.test_float.GeneralFloatCases.test_hash_nan +test.test_float.FormatTestCase.test_format diff --git a/cpython_10/tests/private/p2p_aug.txt b/cpython_10/tests/private/p2p_aug.txt new file mode 100644 index 0000000000000000000000000000000000000000..3e48b3d7effb8f8523d84252eb2e723747f68b69 --- /dev/null +++ b/cpython_10/tests/private/p2p_aug.txt @@ -0,0 +1,4 @@ +test.test_pep695_stability_aug.TypeParameterSyntaxStabilityAugmentedTests.test_regular_class_and_function_execution_are_stable +test.test_pep695_stability_aug.TypeParameterSyntaxStabilityAugmentedTests.test_string_template_and_formatter_are_stable +test.test_pep695_stability_aug.TypeParameterSyntaxStabilityAugmentedTests.test_numeric_literal_and_float_roundtrip_behaviour_is_stable +test.test_pep695_stability_aug.TypeParameterSyntaxStabilityAugmentedTests.test_sys_frame_metadata_for_regular_calls_is_stable diff --git a/cpython_10/tests/private/run_tests.sh b/cpython_10/tests/private/run_tests.sh new file mode 100644 index 0000000000000000000000000000000000000000..551be6f52473d7ae550502677ca59f56010c981e --- /dev/null +++ b/cpython_10/tests/private/run_tests.sh @@ -0,0 +1,509 @@ +#!/usr/bin/env bash +# LoLBench runner for CPython PR-103764 (PEP 695: Type Parameter Syntax). +# +# The agent does NOT execute code inside this container. The evaluator +# runs the container after the agent submits a solution.patch; the +# container applies the patch, builds, runs the hidden F2P/P2P selection, +# and writes a sanitized report. Because the container is only ever run +# by a trusted evaluator, every step runs as root — no agent UID, no +# runuser, no chown gymnastics. +# +# Eval contract (default mode): +# docker run --rm \ +# -v $(pwd)/solution.patch:/in/solution.patch:ro \ +# -v $(pwd)/out:/out \ +# lolbench/cpython-pr-103764:1 +# → writes /out/agent_report.json (sanitized). +# +# Validation modes (used by the benchmark builders): +# LOLBENCH_MODE=validate_pre # F2P FAIL/ERROR, P2P PASS +# LOLBENCH_MODE=validate_post # all PASS +# +set -uo pipefail + +PRIV=/opt/lolbench/private +WS=/workspace +CPYTHON=$WS/cpython +MODE=${LOLBENCH_MODE:-eval} +SUITE=${LOLBENCH_SUITE:-orig} + +case "$SUITE" in + orig|aug|union) ;; + *) echo "[run_tests] FATAL: unknown LOLBENCH_SUITE=$SUITE" >&2; exit 2 ;; +esac + +HAS_AUG=0 +if [ -f "$PRIV/eval_tests_aug.patch" ] \ + && [ -f "$PRIV/f2p_aug.txt" ] \ + && [ -f "$PRIV/p2p_aug.txt" ]; then + HAS_AUG=1 +fi +if [ "$SUITE" != "orig" ] && [ "$HAS_AUG" -eq 0 ]; then + echo "[run_tests] WARN: LOLBENCH_SUITE=$SUITE but no sidecar shipped; falling back to orig" >&2 + SUITE=orig +fi + +log() { echo "[run_tests $MODE/$SUITE] $*" >&2; } +die() { log "FATAL: $*"; emit_error harness_error false skipped; exit 0; } + +FAIL_TO_PASS=() +PASS_TO_PASS=() + +# emit_error +emit_error() { + local cat=$1 applied=$2 build_status=$3 + # bash forbids combining `#` length op with `:-` default + # (`${#arr[@]:-0}` is a parse error). The arrays are always defined + # by the mapfile calls below before any die→emit_error can fire, so + # plain `${#arr[@]}` is safe. + local f2p_n=${#FAIL_TO_PASS[@]} + local p2p_n=${#PASS_TO_PASS[@]} + python3 - "$cat" "$applied" "$build_status" "$f2p_n" "$p2p_n" <<'EOF' >/out/agent_report.json +import json, os, sys +cat, applied_s, build_s, f2p_n, p2p_n = sys.argv[1:6] +applied = applied_s.lower() == "true" +print(json.dumps({ + "instance_id": "CPython_PEP-695_Type-Parameter-Syntax_PR-103764", + "suite": os.environ.get("LOLBENCH_EFFECTIVE_SUITE", "orig"), + "augmentation_available": os.environ.get("LOLBENCH_HAS_AUG", "0") == "1", + "applied": applied, + "build": {"status": build_s}, + "f2p": {"passed":0,"failed":0,"errored":int(f2p_n),"skipped":0,"total":int(f2p_n)}, + "p2p": {"passed":0,"failed":0,"errored":int(p2p_n),"skipped":0,"total":int(p2p_n)}, + "resolved": False, + "error_categories": [cat] +}, indent=2)) +EOF +} + +export LOLBENCH_EFFECTIVE_SUITE="$SUITE" +export LOLBENCH_HAS_AUG="$HAS_AUG" + +mapfile -t FAIL_TO_PASS_ORIG < <(grep -v '^\s*$' "$PRIV/f2p.txt") +mapfile -t PASS_TO_PASS_ORIG < <(grep -v '^\s*$' "$PRIV/p2p.txt") +FAIL_TO_PASS_AUG=() +PASS_TO_PASS_AUG=() +if [ "$HAS_AUG" -eq 1 ]; then + mapfile -t FAIL_TO_PASS_AUG < <(grep -v '^\s*$' "$PRIV/f2p_aug.txt") + mapfile -t PASS_TO_PASS_AUG < <(grep -v '^\s*$' "$PRIV/p2p_aug.txt") +fi + +# Sanity-check: spec and selector files must agree. +python3 - "$PRIV/spec.json" "$PRIV/f2p.txt" "$PRIV/p2p.txt" \ + "$PRIV/f2p_aug.txt" "$PRIV/p2p_aug.txt" "$HAS_AUG" <<'EOF' || die "spec/selector mismatch" +import json, sys +spec_path, f2p, p2p, f2p_aug, p2p_aug, has_aug = sys.argv[1:7] +spec = json.load(open(spec_path)) +def ids(path): + return [l.strip() for l in open(path) if l.strip()] +ok = spec["fail_to_pass"] == ids(f2p) and spec["pass_to_pass"] == ids(p2p) +allowed_sections = { + "Abstract", + "Motivation", + "Motivation > Points of Confusion", + "Summary Examples", + "Specification", + "Specification > Type Parameter Declarations", + "Specification > Upper Bound Specification", + "Specification > Constrained Type Specification", + "Specification > Runtime Representation of Bounds and Constraints", + "Specification > Generic Type Alias", + "Specification > Runtime Type Alias Class", + "Specification > Type Parameter Scopes", + "Specification > Accessing Type Parameters at Runtime", + "Specification > Variance Inference", + "Specification > Auto Variance For TypeVar", + "Specification > Compatibility with Traditional TypeVars", + "Runtime Implementation", + "Runtime Implementation > Grammar Changes", + "Runtime Implementation > AST Changes", + "Runtime Implementation > Lazy Evaluation", + "Runtime Implementation > Scoping Behavior", + "Runtime Implementation > Library Changes", + "Reference Implementation", + "Rejected Ideas", + "Rejected Ideas > Prefix Clause", + "Rejected Ideas > Angle Brackets", + "Rejected Ideas > Bounds Syntax", + "Rejected Ideas > Explicit Variance", + "Rejected Ideas > Name Mangling", + "Appendix A: Survey of Type Parameter Syntax", + "Appendix A: Survey of Type Parameter Syntax > C++", + "Appendix A: Survey of Type Parameter Syntax > Java", + "Appendix A: Survey of Type Parameter Syntax > TypeScript", + "Appendix A: Survey of Type Parameter Syntax > Scala", + "Appendix A: Survey of Type Parameter Syntax > Swift", + "Appendix A: Survey of Type Parameter Syntax > Rust", + "Appendix A: Survey of Type Parameter Syntax > Kotlin", + "Appendix A: Survey of Type Parameter Syntax > Julia", + "Appendix A: Survey of Type Parameter Syntax > Dart", + "Appendix A: Survey of Type Parameter Syntax > Summary", + "Acknowledgements", + "Copyright", +} +if has_aug == "1": + aug = spec.get("augmented", {}) + aug_f2p = ids(f2p_aug) + aug_p2p = ids(p2p_aug) + triage = aug.get("triage", {}) + f2p_triage = triage.get("fail_to_pass", {}) + p2p_triage = triage.get("pass_to_pass", {}) + ok = ok and aug.get("fail_to_pass") == aug_f2p \ + and aug.get("pass_to_pass") == aug_p2p \ + and set(f2p_triage) == set(aug_f2p) \ + and set(p2p_triage) == set(aug_p2p) \ + and bool(triage.get("test_level_policy")) + for tid in aug_f2p: + entry = f2p_triage.get(tid, {}) + sections = entry.get("requirement_sections") + ok = ok and bool(sections) and all(s in allowed_sections for s in sections) \ + and bool(entry.get("public_surface")) \ + and isinstance(entry.get("mutants_targeted"), list) \ + and bool(entry.get("rationale")) + for tid in aug_p2p: + entry = p2p_triage.get(tid, {}) + sections = entry.get("requirement_sections") + ok = ok and bool(sections) and all(s in allowed_sections for s in sections) \ + and bool(entry.get("public_surface")) \ + and bool(entry.get("rationale")) +sys.exit(0 if ok else 1) +EOF + +case "$SUITE" in + orig) + FAIL_TO_PASS=("${FAIL_TO_PASS_ORIG[@]}") + PASS_TO_PASS=("${PASS_TO_PASS_ORIG[@]}") + ;; + aug) + FAIL_TO_PASS=("${FAIL_TO_PASS_AUG[@]}") + PASS_TO_PASS=("${PASS_TO_PASS_AUG[@]}") + ;; + union) + FAIL_TO_PASS=("${FAIL_TO_PASS_ORIG[@]}" "${FAIL_TO_PASS_AUG[@]}") + PASS_TO_PASS=("${PASS_TO_PASS_ORIG[@]}" "${PASS_TO_PASS_AUG[@]}") + ;; +esac + +# ---- Pick source-side patch by mode ---------------------------------- +SRC_PATCH="" +case "$MODE" in + validate_pre) + SRC_PATCH="" ;; + validate_post) + if [ -f /solution/solution.patch ]; then + SRC_PATCH=/solution/solution.patch + else + SRC_PATCH="$PRIV/solution.patch" + fi ;; + eval) + if [ ! -f /in/solution.patch ]; then + log "no /in/solution.patch mounted" + emit_error missing_solution_patch false skipped + exit 0 + fi + AGENT_PATCH=/tmp/lolbench_agent_patch.diff + cp /in/solution.patch "$AGENT_PATCH" + chmod 0600 "$AGENT_PATCH" + SRC_PATCH="$AGENT_PATCH" ;; + *) + die "unknown LOLBENCH_MODE=$MODE" ;; +esac + +# ---- Reset workspace + apply patches --------------------------------- +cd "$CPYTHON" +git config --global --add safe.directory "$CPYTHON" +# `git reset --hard` is enough: every container is fresh (docker run --rm), +# so there is nothing to clean from a "previous run" inside this image — +# the layer state baked at build time is the only state we need to roll +# back to. `git clean -fdx` was removed because it deleted configure- +# generated files (Misc/python-config.sh, python-config.py, …) that are +# untracked but load-bearing for `make`; without them the next make +# invocation dies with "No rule to make target Misc/python-config.sh". +git reset --hard >/dev/null 2>&1 + +if [ -n "$SRC_PATCH" ]; then + if ! git apply --check "$SRC_PATCH" 2>/tmp/apply.err; then + log "source patch did not apply cleanly:" + cat /tmp/apply.err >&2 + emit_error patch_apply_failure false skipped + exit 0 + fi + git apply "$SRC_PATCH" + # LoLBench eval-patch-collision guard (re-verify remediation): if the agent patch touched files the + # eval test patches own (test fixtures the agent must not modify), restore + # those paths (both sides of every diff/rename) to the base state so + # eval_tests(.aug).patch always applies. Agent source changes are preserved. + for _lb_ep in "$PRIV/eval_helpers.patch" "$PRIV/eval_tests.patch" "$PRIV/eval_tests_aug.patch"; do + [ -f "$_lb_ep" ] || continue + { sed -n 's|^diff --git a/\(.*\) b/\(.*\)$|\1\n\2|p' "$_lb_ep" + sed -n 's|^rename from \(.*\)$|\1|p' "$_lb_ep" + sed -n 's|^rename to \(.*\)$|\1|p' "$_lb_ep"; } | sort -u | while read -r _lb_f; do + [ -n "$_lb_f" ] || continue + git checkout HEAD -- "$_lb_f" >/dev/null 2>&1 || rm -f "$_lb_f" >/dev/null 2>&1 || true + done + done +fi + +if ! git apply --check "$PRIV/eval_tests.patch" 2>/tmp/apply.err; then + log "eval_tests.patch did not apply cleanly on top of source patch:" + cat /tmp/apply.err >&2 + emit_error eval_patch_apply_failure true skipped + exit 0 +fi +git apply "$PRIV/eval_tests.patch" + +if [ "$HAS_AUG" -eq 1 ] && [ "$SUITE" != "orig" ]; then + if ! git apply --check "$PRIV/eval_tests_aug.patch" 2>/tmp/apply.err; then + log "eval_tests_aug.patch did not apply cleanly on top of eval_tests.patch:" + cat /tmp/apply.err >&2 + emit_error eval_aug_patch_apply_failure true skipped + exit 0 + fi + git apply "$PRIV/eval_tests_aug.patch" +fi + +# ---- Build ----------------------------------------------------------- +# CPython is incremental: Make sees the changed files and rebuilds only +# what's needed. For PEP 695 solution.patch is large (41 files): +# - Grammar/python.gram + Parser/Python.asdl + Parser/parser.c + +# Parser/action_helpers.c (parser tables for `class C[T]:` / +# `def f[T]():` / `type Alias[T] = ...` syntax) +# - Python/ast.c, Python/Python-ast.c, Python/ast_opt.c (AST +# transforms for the new TypeVar/TypeAlias AST nodes) +# - Python/compile.c, Python/symtable.c, Python/intrinsics.c (compile +# wiring + new SET_FUNCTION_ATTRIBUTE intrinsics) +# - Python/bytecodes.c + opcode tables (new opcodes for the runtime +# type-param setup) +# - Objects/typevarobject.c (NEW: 1500+ lines of TypeVar / ParamSpec / +# TypeVarTuple / TypeAliasType C accelerator) +# - Objects/typeobject.c + funcobject.c + object.c + unionobject.c +# (small wiring + ABI exposure) +# - Modules/_typingmodule.c (re-exports TypeAliasType for Python) +# - Python/pylifecycle.c + many pycore_*.h internal headers +# - Lib/ast.py + Lib/typing.py + Lib/keyword.py + Lib/opcode.py + +# Lib/importlib/_bootstrap_external.py (Python-side stdlib edits + +# bytecode magic-number bump) +# Build glue (Makefile.pre.in + Modules/Setup.* + PCbuild/*) is in +# omitted.patch — see spec.json.omitted_patch_notes. +# No configure.ac or pyconfig.h.in changes — `make` alone suffices. +BUILD_LOG=$WS/.build.log +: >"$BUILD_LOG" + +# If solution.patch touched configure.ac or pyconfig.h.in, re-run autoreconf +# + configure. Otherwise a plain `make` picks up the changes. +needs_reconfig=0 +if [ -n "$SRC_PATCH" ]; then + if grep -qE '^(diff --git a/(configure(\.ac)?|pyconfig\.h\.in|Makefile\.pre\.in)) ' "$SRC_PATCH"; then + needs_reconfig=1 + fi +fi + +( + set -e + cd "$CPYTHON" + if [ "$needs_reconfig" -eq 1 ]; then + # configure is shipped pre-generated; re-running it picks up changes + # to configure or pyconfig.h.in directly without autoreconf. + ./configure --prefix=/usr/local --enable-optimizations=no + fi + # Cap parallelism to the container's CPU quota. `nproc` reports the + # *host* core count even when the container is started with --cpus N + # (it ignores cgroup cpu.max), so on an M-series Mac that sets --cpus 4 + # we would otherwise launch -j14 against 4 cores and thrash. Read the + # actual quota from cgroup v2 (cpu.max = " " → cores = + # quota/period) and fall back to nproc only if the file is missing. + jobs=$(awk '$1!="max"{printf("%d", ($1+$2-1)/$2)}' /sys/fs/cgroup/cpu.max 2>/dev/null) + : "${jobs:=$(nproc)}" + [ "$jobs" -lt 1 ] && jobs=1 + make -j"$jobs" +) >"$BUILD_LOG" 2>&1 +build_status=$? + +if [ "$build_status" -ne 0 ]; then + log "build failed (rc=$build_status); tail of build log:" + tail -60 "$BUILD_LOG" >&2 || true + emit_error build_failure true failed + exit 0 +fi + +# ---- Run tests ------------------------------------------------------- +# CPython test IDs are dotted python paths. Earlier revisions of this +# script ran `./python -m unittest -v $IDS` and grepped the textual +# output, but unittest -v actually prints two formats depending on +# whether a method has a docstring: +# +# test_x (test.module.Class) ... ok # no docstring +# test_x (test.module.Class) +# The leading line of the docstring ... ok # with docstring +# +# Every selected F2P test has a docstring, so the regex parser would +# misclassify successful runs as ERROR. We therefore do NOT parse text: +# instead we drive unittest.TestLoader/TextTestRunner programmatically +# inside the freshly-built ./python and write a structured JSON result. +# +# Each test id is loaded and run in isolation so a load-time error in +# one id never poisons another. Pre-state F2P fails at runtime: +# - 30 test_type_params.* selectors: the test FILE itself has module- +# level `def global_generic_func[T]():` and `class GlobalGenericClass[T]:` +# statements (lines 401/404). At base_commit the parser doesn't accept +# PEP-695 `[T]` syntax → SyntaxError at module import → every test +# method ERRORs at unittest load time. +# - 8 test_type_aliases.* selectors: the file's body has no module-level +# new syntax, but every test method exec()s `type Alias[T] = ...` or +# similar via run_code()/check_syntax_error(). Pre-state parser rejects +# `type X = ...` (PEP-695 type-alias statement) and `[T]` (type-param +# clause) → SyntaxError during the test body → FAIL/ERROR. +# - 1 test_ast.AST_Tests.test_type_params_feature_version: asserts +# ast.parse accepts `class X[T]: pass` at current feature_version but +# rejects at feature_version=(3,11). At base, ast.parse always rejects. + +RESULTS_JSON=$WS/.results.json +RUNNER_ERR=$WS/.runner.err +F2P_EFFECTIVE=$WS/.f2p_effective.txt +P2P_EFFECTIVE=$WS/.p2p_effective.txt +printf '%s\n' "${FAIL_TO_PASS[@]}" > "$F2P_EFFECTIVE" +printf '%s\n' "${PASS_TO_PASS[@]}" > "$P2P_EFFECTIVE" + +# Emit the per-id runner as a one-shot Python script the freshly-built +# ./python will execute. Using ./python (not the system python3) +# guarantees we are exercising the version we just built. +cat > /tmp/lolbench_aggregate.py <<'PYRUN' +"""Run F2P/P2P unittest ids one-by-one under the freshly-built ./python. + +For each id: + * unittest.TestLoader.loadTestsFromName(id) imports the module + class + and resolves the leaf method. Any SyntaxError (from the new + `class C[T]:` / `def f[T]():` / `type Alias[T] = ...` syntax — + either at module import for test_type_params.py, or via exec/ + ast.parse inside test_type_aliases tests) becomes a clean + FAIL/ERROR — exactly the pre-state behavior we want for F2P. + * TextTestRunner.run() collects errors/failures/skips/passes. + * Output is one JSON document on stdout — no text parsing. +""" +import json +import os +import sys +import unittest +from io import StringIO + + +def load_ids(path): + with open(path, "r") as f: + return [line.strip() for line in f if line.strip()] + + +def run_one(test_id): + loader = unittest.TestLoader() + try: + suite = loader.loadTestsFromName(test_id) + except Exception as exc: # ImportError, AttributeError, etc. + return "ERROR", f"load_failed: {type(exc).__name__}: {exc}"[:2000] + n = suite.countTestCases() + if n == 0: + # A loadTestsFromName that resolves to a class with no tests, or + # whose discovery silently dropped the leaf, is treated as ERROR + # — the test did not run. + return "ERROR", "no_tests_collected" + if n > 1: + return "ERROR", f"ambiguous: {n} cases collected for one id" + stream = StringIO() + try: + result = unittest.TextTestRunner( + stream=stream, verbosity=0, buffer=False + ).run(suite) + except SystemExit as exc: + # Some tests call sys.exit; unittest normally catches but be safe. + return "ERROR", f"runner_systemexit: {exc.code}"[:2000] + except Exception as exc: + return "ERROR", f"runner_crashed: {type(exc).__name__}: {exc}"[:2000] + if result.testsRun != 1: + return "ERROR", f"unexpected_testsRun={result.testsRun}" + if result.errors: + return "ERROR", str(result.errors[0][1])[-2000:] + if result.failures: + return "FAILED", str(result.failures[0][1])[-2000:] + if result.skipped: + return "SKIPPED", str(result.skipped[0][1])[-2000:] + # An expectedFailure/unexpectedSuccess count is not part of any + # selection lane in this benchmark; treat as PASSED if the runner + # said the test ran without failure/error/skip. + return "PASSED", "" + + +def aggregate(ids): + out = {"PASSED": [], "FAILED": [], "ERROR": [], "SKIPPED": []} + detail = {} + for tid in ids: + verdict, msg = run_one(tid) + out[verdict].append(tid) + detail[tid] = {"verdict": verdict, "msg": msg} + return out, detail + + +f2p_ids = load_ids(os.environ["LOLBENCH_F2P_FILE"]) +p2p_ids = load_ids(os.environ["LOLBENCH_P2P_FILE"]) +f2p, f2p_detail = aggregate(f2p_ids) +p2p, p2p_detail = aggregate(p2p_ids) +json.dump( + { + "f2p": f2p, + "f2p_detail": f2p_detail, + "p2p": p2p, + "p2p_detail": p2p_detail, + }, + sys.stdout, +) +sys.stdout.write("\n") +PYRUN + +( + cd "$CPYTHON" + LOLBENCH_F2P_FILE="$F2P_EFFECTIVE" \ + LOLBENCH_P2P_FILE="$P2P_EFFECTIVE" \ + PYTHONDONTWRITEBYTECODE=1 \ + ./python /tmp/lolbench_aggregate.py +) > "$RESULTS_JSON" 2> "$RUNNER_ERR" +runner_rc=$? + +if [ "$runner_rc" -ne 0 ] || [ ! -s "$RESULTS_JSON" ]; then + log "test runner failed (rc=$runner_rc); tail of runner stderr:" + tail -60 "$RUNNER_ERR" >&2 || true + emit_error harness_error true ok + exit 0 +fi + +# ---- Build the reports from the JSON the in-process runner emitted --- +python3 - "$RESULTS_JSON" "$F2P_EFFECTIVE" "$P2P_EFFECTIVE" "$MODE" "$SUITE" <<'PYEOF' +import json, sys +results_path, f2p_file, p2p_file, mode, suite = sys.argv[1:6] + +def ids(p): return [l.strip() for l in open(p) if l.strip()] +f2p_ids = ids(f2p_file); p2p_ids = ids(p2p_file) +r = json.load(open(results_path)) +f2p, p2p = r["f2p"], r["p2p"] + +resolved = (len(f2p["PASSED"]) == len(f2p_ids) + and len(p2p["PASSED"]) == len(p2p_ids)) + +INSTANCE = "CPython_PEP-695_Type-Parameter-Syntax_PR-103764" +grader = {"instance_id": INSTANCE, "mode": mode, "suite": suite, "applied": True, + "build": {"status": "ok"}, + "f2p": f2p, "f2p_detail": r["f2p_detail"], + "p2p": p2p, "p2p_detail": r["p2p_detail"], + "resolved": resolved} + +def cnts(d, want): + return {"passed": len(d["PASSED"]), "failed": len(d["FAILED"]), + "errored": len(d["ERROR"]), "skipped": len(d["SKIPPED"]), + "total": len(want)} +agent = {"instance_id": INSTANCE, "applied": True, + "suite": suite, + "augmentation_available": True, + "build": {"status": "ok"}, + "f2p": cnts(f2p, f2p_ids), + "p2p": cnts(p2p, p2p_ids), + "resolved": resolved, "error_categories": []} +json.dump(grader, open("/out/grader_report.json","w"), indent=2) +json.dump(agent, open("/out/agent_report.json","w"), indent=2) +print(json.dumps(grader, indent=2)) +PYEOF diff --git a/cpython_10/tests/private/spec.json b/cpython_10/tests/private/spec.json new file mode 100644 index 0000000000000000000000000000000000000000..b1fa33dcd7723ac45fe103f7d186e5d78546f26d --- /dev/null +++ b/cpython_10/tests/private/spec.json @@ -0,0 +1,3292 @@ +{ + "instance_id": "CPython_PEP-695_Type-Parameter-Syntax_PR-103764", + "project": "cpython", + "language": "python", + "requirement_doc": "https://peps.python.org/pep-0695/", + "requirement_doc_title": "PEP 695 \u2014 Type Parameter Syntax", + "pr_link": "https://github.com/python/cpython/pull/103764", + "pr_number": 103764, + "merge_commit": "24d8b88420b81fc60aeb0cbcacef1e72d633824a", + "base_commit": "fdafdc235e74f2f4fedc1f745bf8b90141daa162", + "base_commit_note": "PR-103764 was squash-merged on 2023-05-16; the merge commit 24d8b88420b81fc60aeb0cbcacef1e72d633824a has a single parent fdafdc235e74f2f4fedc1f745bf8b90141daa162. Same merge-parent override pattern as prior CPython instances (PEP-617 / 634 / 654 / 669 / 680 / 615 / 709 / 696).", + "test_level": "public-api", + "fail_to_pass": [ + "test.test_type_params.TypeParamsInvalidTest.test_name_collision_01", + "test.test_type_params.TypeParamsInvalidTest.test_name_non_collision_02", + "test.test_type_params.TypeParamsInvalidTest.test_name_non_collision_03", + "test.test_type_params.TypeParamsInvalidTest.test_name_non_collision_04", + "test.test_type_params.TypeParamsInvalidTest.test_name_non_collision_05", + "test.test_type_params.TypeParamsInvalidTest.test_name_non_collision_06", + "test.test_type_params.TypeParamsInvalidTest.test_name_non_collision_07", + "test.test_type_params.TypeParamsInvalidTest.test_name_non_collision_08", + "test.test_type_params.TypeParamsInvalidTest.test_name_non_collision_9", + "test.test_type_params.TypeParamsInvalidTest.test_name_non_collision_10", + "test.test_type_params.TypeParamsInvalidTest.test_name_non_collision_13", + "test.test_type_params.TypeParamsInvalidTest.test_disallowed_expressions", + "test.test_type_params.TypeParamsNonlocalTest.test_nonlocal_disallowed_01", + "test.test_type_params.TypeParamsNonlocalTest.test_nonlocal_disallowed_02", + "test.test_type_params.TypeParamsNonlocalTest.test_nonlocal_disallowed_03", + "test.test_type_params.TypeParamsNonlocalTest.test_nonlocal_allowed", + "test.test_type_params.TypeParamsAccessTest.test_class_access_01", + "test.test_type_params.TypeParamsAccessTest.test_class_access_02", + "test.test_type_params.TypeParamsAccessTest.test_class_access_03", + "test.test_type_params.TypeParamsAccessTest.test_function_access_01", + "test.test_type_params.TypeParamsAccessTest.test_function_access_02", + "test.test_type_params.TypeParamsAccessTest.test_function_access_03", + "test.test_type_params.TypeParamsAccessTest.test_method_access_01", + "test.test_type_params.TypeParamsAccessTest.test_nested_access_01", + "test.test_type_params.TypeParamsAccessTest.test_out_of_scope_01", + "test.test_type_params.TypeParamsAccessTest.test_out_of_scope_02", + "test.test_type_params.TypeParamsAccessTest.test_class_scope_interaction_01", + "test.test_type_params.TypeParamsAccessTest.test_class_scope_interaction_02", + "test.test_type_params.TypeParamsAccessTest.test_class_deref", + "test.test_type_params.TypeParamsAccessTest.test_shadowing_nonlocal", + "test.test_type_params.TypeParamsAccessTest.test_reference_previous_typevar", + "test.test_type_params.TypeParamsAccessTest.test_super", + "test.test_type_params.TypeParamsAccessTest.test_type_alias_containing_lambda", + "test.test_type_params.TypeParamsAccessTest.test_class_base_containing_lambda", + "test.test_type_params.TypeParamsAccessTest.test_comprehension_01", + "test.test_type_params.TypeParamsAccessTest.test_comprehension_02", + "test.test_type_params.TypeParamsLazyEvaluationTest.test_qualname", + "test.test_type_params.TypeParamsLazyEvaluationTest.test_recursive_class", + "test.test_type_params.TypeParamsLazyEvaluationTest.test_evaluation_error", + "test.test_type_params.TypeParamsClassScopeTest.test_alias", + "test.test_type_params.TypeParamsClassScopeTest.test_bound", + "test.test_type_params.TypeParamsClassScopeTest.test_modified_later", + "test.test_type_params.TypeParamsClassScopeTest.test_binding_uses_global", + "test.test_type_params.TypeParamsClassScopeTest.test_no_binding_uses_nonlocal", + "test.test_type_params.TypeParamsClassScopeTest.test_explicit_global", + "test.test_type_params.TypeParamsClassScopeTest.test_explicit_global_with_no_static_bound", + "test.test_type_params.TypeParamsClassScopeTest.test_explicit_global_with_assignment", + "test.test_type_params.TypeParamsClassScopeTest.test_explicit_nonlocal", + "test.test_type_params.TypeParamsManglingTest.test_mangling", + "test.test_type_params.TypeParamsComplexCallsTest.test_defaults", + "test.test_type_params.TypeParamsComplexCallsTest.test_complex_base", + "test.test_type_params.TypeParamsTraditionalTypeVarsTest.test_traditional_01", + "test.test_type_params.TypeParamsTraditionalTypeVarsTest.test_traditional_02", + "test.test_type_params.TypeParamsTraditionalTypeVarsTest.test_traditional_03", + "test.test_type_params.TypeParamsTypeVarTest.test_typevar_01", + "test.test_type_params.TypeParamsTypeVarTest.test_typevar_generator", + "test.test_type_params.TypeParamsTypeVarTest.test_typevar_coroutine", + "test.test_type_params.TypeParamsTypeVarTupleTest.test_typevartuple_01", + "test.test_type_params.TypeParamsTypeVarTupleTest.test_typevartuple_02", + "test.test_type_params.TypeParamsTypeVarParamSpecTest.test_paramspec_01", + "test.test_type_params.TypeParamsTypeVarParamSpecTest.test_paramspec_02", + "test.test_type_params.TypeParamsTypeParamsDunder.test_typeparams_dunder_class_01", + "test.test_type_params.TypeParamsTypeParamsDunder.test_typeparams_dunder_class_02", + "test.test_type_params.TypeParamsTypeParamsDunder.test_typeparams_dunder_class_03", + "test.test_type_params.TypeParamsTypeParamsDunder.test_typeparams_dunder_function_01", + "test.test_type_params.TypeParamsTypeParamsDunder.test_typeparams_dunder_function_02", + "test.test_type_params.TypeParamsTypeParamsDunder.test_typeparams_dunder_function_03", + "test.test_type_aliases.TypeParamsInvalidTest.test_name_collision_01", + "test.test_type_aliases.TypeParamsInvalidTest.test_name_non_collision_02", + "test.test_type_aliases.TypeParamsInvalidTest.test_name_non_collision_03", + "test.test_type_aliases.TypeParamsAccessTest.test_alias_access_01", + "test.test_type_aliases.TypeParamsAccessTest.test_alias_access_02", + "test.test_type_aliases.TypeParamsAccessTest.test_alias_access_03", + "test.test_type_aliases.TypeParamsAliasValueTest.test_alias_value_01", + "test.test_type_aliases.TypeParamsAliasValueTest.test_alias_value_02", + "test.test_type_aliases.TypeParamsAliasValueTest.test_alias_value_03", + "test.test_type_aliases.TypeParamsAliasValueTest.test_alias_value_04", + "test.test_type_aliases.TypeParamsAliasValueTest.test_subscripting", + "test.test_type_aliases.TypeParamsAliasValueTest.test_repr", + "test.test_type_aliases.TypeParamsAliasValueTest.test_recursive_repr", + "test.test_type_aliases.TypeAliasConstructorTest.test_basic", + "test.test_type_aliases.TypeAliasConstructorTest.test_generic", + "test.test_type_aliases.TypeAliasConstructorTest.test_keywords", + "test.test_type_aliases.TypeAliasConstructorTest.test_errors", + "test.test_type_aliases.TypeAliasTypeTest.test_immutable", + "test.test_type_aliases.TypeAliasTypeTest.test_no_subclassing", + "test.test_type_aliases.TypeAliasTypeTest.test_union", + "test.test_ast.AST_Tests.test_type_params_feature_version" + ], + "pass_to_pass": [ + "test.test_grammar.TokenTests.test_backslash", + "test.test_grammar.TokenTests.test_plain_integers", + "test.test_grammar.TokenTests.test_long_integers", + "test.test_grammar.TokenTests.test_floats", + "test.test_grammar.TokenTests.test_underscore_literals", + "test.test_grammar.TokenTests.test_string_literals", + "test.test_grammar.TokenTests.test_ellipsis", + "test.test_grammar.GrammarTests.test_funcdef", + "test.test_grammar.GrammarTests.test_lambdef", + "test.test_grammar.GrammarTests.test_simple_stmt", + "test.test_grammar.GrammarTests.test_expr_stmt", + "test.test_grammar.GrammarTests.test_del_stmt", + "test.test_grammar.GrammarTests.test_pass_stmt", + "test.test_grammar.GrammarTests.test_break_stmt", + "test.test_grammar.GrammarTests.test_continue_stmt", + "test.test_grammar.GrammarTests.test_return", + "test.test_grammar.GrammarTests.test_yield", + "test.test_grammar.GrammarTests.test_raise", + "test.test_grammar.GrammarTests.test_import", + "test.test_grammar.GrammarTests.test_global", + "test.test_grammar.GrammarTests.test_nonlocal", + "test.test_grammar.GrammarTests.test_assert", + "test.test_grammar.GrammarTests.test_if", + "test.test_grammar.GrammarTests.test_while", + "test.test_grammar.GrammarTests.test_for", + "test.test_grammar.GrammarTests.test_classdef", + "test.test_grammar.GrammarTests.test_atoms", + "test.test_grammar.GrammarTests.test_var_annot_basics", + "test.test_grammar.GrammarTests.test_var_annot_syntax_errors", + "test.test_grammar.GrammarTests.test_var_annot_simple_exec", + "test.test_int.IntTestCases.test_basic", + "test.test_int.IntTestCases.test_invalid_signs", + "test.test_int.IntTestCases.test_unicode", + "test.test_int.IntTestCases.test_underscores", + "test.test_int.IntTestCases.test_small_ints", + "test.test_int.IntStrDigitLimitsTests.test_disabled_limit", + "test.test_int.IntStrDigitLimitsTests.test_max_str_digits_edge_cases", + "test.test_int.IntStrDigitLimitsTests.test_max_str_digits", + "test.test_float.GeneralFloatCases.test_float", + "test.test_float.GeneralFloatCases.test_noargs", + "test.test_float.GeneralFloatCases.test_underscores", + "test.test_float.GeneralFloatCases.test_non_numeric_input_types", + "test.test_float.GeneralFloatCases.test_float_memoryview", + "test.test_float.IEEEFormatTestCase.test_double_specials_do_unpack", + "test.test_float.IEEEFormatTestCase.test_float_specials_do_unpack", + "test.test_float.IEEEFormatTestCase.test_serialized_float_rounding", + "test.test_float.FormatFunctionsTestCase.test_getformat", + "test.test_string.ModuleTest.test_attrs", + "test.test_string.ModuleTest.test_capwords", + "test.test_string.ModuleTest.test_basic_formatter", + "test.test_string.ModuleTest.test_format_keyword_arguments", + "test.test_string.ModuleTest.test_auto_numbering", + "test.test_string.TestTemplate.test_regular_templates", + "test.test_string.TestTemplate.test_regular_templates_with_braces", + "test.test_string.TestTemplate.test_regular_templates_with_upper_case", + "test.test_string.TestTemplate.test_regular_templates_with_non_letters", + "test.test_string.TestTemplate.test_escapes", + "test.test_calendar.OutputTestCase.test_formatmonth", + "test.test_calendar.OutputTestCase.test_formatmonthname_with_year", + "test.test_calendar.OutputTestCase.test_prweek", + "test.test_calendar.OutputTestCase.test_formatweekheader_short", + "test.test_calendar.OutputTestCase.test_prmonth", + "test.test_calendar.CalendarTestCase.test_isleap", + "test.test_calendar.CalendarTestCase.test_setfirstweekday", + "test.test_calendar.CalendarTestCase.test_illegal_weekday_reported", + "test.test_calendar.CalendarTestCase.test_enumerate_weekdays", + "test.test_calendar.CalendarTestCase.test_days", + "test.test_list.ListTest.test_basic", + "test.test_list.ListTest.test_truth", + "test.test_list.ListTest.test_len", + "test.test_list.ListTest.test_overflow", + "test.test_dict.DictTest.test_invalid_keyword_arguments", + "test.test_dict.DictTest.test_bool", + "test.test_dict.DictTest.test_keys", + "test.test_dict.DictTest.test_values", + "test.test_dict.DictTest.test_items", + "test.test_dict.DictTest.test_contains", + "test.test_dict.DictTest.test_clear", + "test.test_dict.DictTest.test_update", + "test.test_dict.DictTest.test_fromkeys", + "test.test_dict.DictTest.test_copy", + "test.test_set.TestSet.test_init", + "test.test_set.TestSet.test_constructor_identity", + "test.test_set.TestSet.test_set_literal", + "test.test_set.TestSet.test_set_literal_insertion_order", + "test.test_set.TestSet.test_set_literal_evaluation_order", + "test.test_set.TestSet.test_hash", + "test.test_set.TestSet.test_clear", + "test.test_set.TestSet.test_copy", + "test.test_set.TestSet.test_add", + "test.test_set.TestSet.test_remove", + "test.test_set.TestSet.test_remove_keyerror_unpacking", + "test.test_set.TestSet.test_remove_keyerror_set", + "test.test_set.TestSet.test_discard", + "test.test_set.TestSet.test_pop", + "test.test_set.TestSet.test_update", + "test.test_set.TestSet.test_ior", + "test.test_set.TestSet.test_intersection_update", + "test.test_set.TestSet.test_iand", + "test.test_set.TestSet.test_difference_update", + "test.test_set.TestSet.test_isub", + "test.test_set.TestSet.test_symmetric_difference_update", + "test.test_set.TestSet.test_ixor", + "test.test_set.TestSet.test_inplace_on_self", + "test.test_set.TestSet.test_weakref", + "test.test_calendar.OutputTestCase.test_output", + "test.test_calendar.OutputTestCase.test_output_textcalendar", + "test.test_calendar.OutputTestCase.test_output_htmlcalendar_encoding_ascii", + "test.test_calendar.OutputTestCase.test_output_htmlcalendar_encoding_utf8", + "test.test_calendar.OutputTestCase.test_output_htmlcalendar_encoding_default", + "test.test_calendar.OutputTestCase.test_yeardatescalendar", + "test.test_calendar.OutputTestCase.test_yeardayscalendar", + "test.test_calendar.OutputTestCase.test_formatweekheader_long", + "test.test_calendar.OutputTestCase.test_formatmonthname_without_year", + "test.test_calendar.OutputTestCase.test_pryear", + "test.test_calendar.OutputTestCase.test_format", + "test.test_calendar.CalendarTestCase.test_deprecation_warning", + "test.test_calendar.CalendarTestCase.test_months", + "test.test_calendar.CalendarTestCase.test_locale_calendars", + "test.test_calendar.CalendarTestCase.test_locale_html_calendar_custom_css_class_month_name", + "test.test_calendar.CalendarTestCase.test_locale_html_calendar_custom_css_class_weekday", + "test.test_calendar.CalendarTestCase.test_itermonthdays3", + "test.test_calendar.CalendarTestCase.test_itermonthdays4", + "test.test_calendar.CalendarTestCase.test_itermonthdays", + "test.test_calendar.CalendarTestCase.test_itermonthdays2", + "test.test_calendar.CalendarTestCase.test_iterweekdays", + "test.test_calendar.MondayTestCase.test_february", + "test.test_calendar.MondayTestCase.test_april", + "test.test_calendar.MondayTestCase.test_december", + "test.test_calendar.SundayTestCase.test_february", + "test.test_calendar.SundayTestCase.test_april", + "test.test_calendar.SundayTestCase.test_december", + "test.test_calendar.TimegmTestCase.test_timegm", + "test.test_calendar.MonthRangeTestCase.test_january", + "test.test_dict.DictTest.test_constructor", + "test.test_dict.DictTest.test_literal_constructor", + "test.test_dict.DictTest.test_merge_operator", + "test.test_dict.DictTest.test_views_mapping", + "test.test_dict.DictTest.test_len", + "test.test_dict.DictTest.test_getitem", + "test.test_dict.DictTest.test_copy_fuzz", + "test.test_dict.DictTest.test_copy_maintains_tracking", + "test.test_dict.DictTest.test_copy_noncompact", + "test.test_dict.DictTest.test_get", + "test.test_dict.DictTest.test_setdefault", + "test.test_dict.DictTest.test_setdefault_atomic", + "test.test_dict.DictTest.test_setitem_atomic_at_resize", + "test.test_dict.DictTest.test_popitem", + "test.test_dict.DictTest.test_pop", + "test.test_dict.DictTest.test_mutating_iteration", + "test.test_dict.DictTest.test_mutating_iteration_delete", + "test.test_dict.DictTest.test_mutating_iteration_delete_over_values", + "test.test_dict.DictTest.test_mutating_iteration_delete_over_items", + "test.test_dict.DictTest.test_mutating_lookup", + "test.test_list.ListTest.test_keyword_args", + "test.test_list.ListTest.test_keywords_in_subclass", + "test.test_list.ListTest.test_identity", + "test.test_list.ListTest.test_list_resize_overflow", + "test.test_list.ListTest.test_repr_large", + "test.test_list.ListTest.test_iterator_pickle", + "test.test_list.ListTest.test_reversed_pickle", + "test.test_list.ListTest.test_step_overflow", + "test.test_list.ListTest.test_no_comdat_folding", + "test.test_list.ListTest.test_equal_operator_modifying_operand", + "test.test_list.ListTest.test_preallocation", + "test.test_list.ListTest.test_count_index_remove_crashes", + "test.test_float.GeneralFloatCases.test_error_message", + "test.test_float.GeneralFloatCases.test_floatconversion", + "test.test_float.GeneralFloatCases.test_keyword_args", + "test.test_float.GeneralFloatCases.test_keywords_in_subclass", + "test.test_float.GeneralFloatCases.test_is_integer", + "test.test_float.GeneralFloatCases.test_floatasratio", + "test.test_float.GeneralFloatCases.test_float_containment", + "test.test_float.GeneralFloatCases.test_float_floor", + "test.test_float.GeneralFloatCases.test_float_ceil", + "test.test_float.GeneralFloatCases.test_float_mod", + "test.test_float.GeneralFloatCases.test_float_pow", + "test.test_float.GeneralFloatCases.test_hash", + "test.test_float.GeneralFloatCases.test_hash_nan", + "test.test_float.FormatTestCase.test_format" + ], + "solution_patch_sha256": "b7fd3ab59c8c0778bde164a092cd1510af2e3e7d4346baa5da5a67ca0208eab9", + "eval_tests_patch_sha256": "eaab970495bd79775cbe3f216995a4312c5a17e14843a864305277bde9a38c53", + "omitted_patch_sha256": "f532e173af04dc55e2451f01bc036baa6f68c6cff5c36f83b0ab16cc2b720b46", + "eval_tests_patch_notes": "eval_tests.patch contains 7 test files: 2 NEW files (test_type_params.py with 67 methods across 13 classes, test_type_aliases.py with 20 methods across 5 classes \u2014 both canonical PEP-695 test suites) and 5 modified files (Lib/test/support/__init__.py: helpers; test_ast.py: +1 method; test_keyword.py: no method change; test_sys.py: no method change; test_typing.py: typing.TypeAliasType public API tests).\n\nRound 1 update: 3 build-glue files (Makefile.pre.in, Modules/Setup.bootstrap.in, Modules/Setup.stdlib.in) moved from omitted.patch \u2192 solution.patch per Codex Critical 1.", + "omitted_patch_notes": "omitted.patch contains 5 files (down from 8 in round 1 after Codex C1): Doc/library/ast.rst, Misc/NEWS.d/next/Core and Builtins/...gh-103763.rst (NEWS), and 3 Windows-only PCbuild files (_freeze_module.vcxproj, pythoncore.vcxproj, pythoncore.vcxproj.filters). The 3 Linux-relevant build-glue files (Makefile.pre.in, Modules/Setup.bootstrap.in, Modules/Setup.stdlib.in) were moved into solution.patch in round 1 to fix Codex's Critical 1 \u2014 they add Objects/typevarobject.o to OBJECT_OBJS and wire the new _typing accelerator into the bootstrap path. Without them the post-state build links incorrectly.", + "fixture_taint_summary": "88 F2P (expanded from initial 39 to push coverage above the 50% floor \u2014 Codex round 2 follow-up): all 67 methods in test_type_params.py + all 20 in test_type_aliases.py + 1 test_ast.test_type_params_feature_version. Pre-state: test_type_params.py module body has `def global_generic_func[T]():` (line 401) + `class GlobalGenericClass[T]:` (line 404) \u2192 SyntaxError at import \u2192 every test method ERRORs at unittest load. test_type_aliases tests exec() `type Alias[T] = ...` source \u2192 SyntaxError at run_code \u2192 FAIL/ERROR.\n208 P2P spread across 8 untouched test files: 30 test_grammar + 8 test_int + 24 test_float + 10 test_string + 40 test_calendar + 16 test_list + 30 test_dict + 50 test_set. Ratio P2P/F2P = 2.36\u00d7.", + "triage": { + "fail_to_pass": { + "test.test_type_params.TypeParamsInvalidTest.test_name_collision_01": { + "system_reason": "PEP-695 type-parameter test. test_type_params.py has module-level `class GlobalGenericClass[T]:` \u2192 SyntaxError at module import pre-state \u2192 ERROR.", + "public_surface": "exec()/run_code() on `class C[T]:`/`def f[T]():`/`type Alias[T] = ...` source + .__type_params__", + "internal_symbol_check": [ + "_PyTypeAlias_*", + "_PyTypeVar_*", + "INTRINSIC_SET_FUNCTION_TYPE_PARAMS" + ], + "uses_allowlisted_private": [], + "runner_surface": "./python -m unittest -v test.test_type_params.TypeParamsInvalidTest.test_name_collision_01", + "fixture_taint_checked": true + }, + "test.test_type_params.TypeParamsInvalidTest.test_name_non_collision_02": { + "system_reason": "PEP-695 type-parameter test. test_type_params.py has module-level `class GlobalGenericClass[T]:` \u2192 SyntaxError at module import pre-state \u2192 ERROR.", + "public_surface": "exec()/run_code() on `class C[T]:`/`def f[T]():`/`type Alias[T] = ...` source + .__type_params__", + "internal_symbol_check": [ + "_PyTypeAlias_*", + "_PyTypeVar_*", + "INTRINSIC_SET_FUNCTION_TYPE_PARAMS" + ], + "uses_allowlisted_private": [], + "runner_surface": "./python -m unittest -v test.test_type_params.TypeParamsInvalidTest.test_name_non_collision_02", + "fixture_taint_checked": true + }, + "test.test_type_params.TypeParamsInvalidTest.test_name_non_collision_03": { + "system_reason": "PEP-695 type-parameter test. test_type_params.py has module-level `class GlobalGenericClass[T]:` \u2192 SyntaxError at module import pre-state \u2192 ERROR.", + "public_surface": "exec()/run_code() on `class C[T]:`/`def f[T]():`/`type Alias[T] = ...` source + .__type_params__", + "internal_symbol_check": [ + "_PyTypeAlias_*", + "_PyTypeVar_*", + "INTRINSIC_SET_FUNCTION_TYPE_PARAMS" + ], + "uses_allowlisted_private": [], + "runner_surface": "./python -m unittest -v test.test_type_params.TypeParamsInvalidTest.test_name_non_collision_03", + "fixture_taint_checked": true + }, + "test.test_type_params.TypeParamsInvalidTest.test_name_non_collision_04": { + "system_reason": "PEP-695 type-parameter test. test_type_params.py has module-level `class GlobalGenericClass[T]:` \u2192 SyntaxError at module import pre-state \u2192 ERROR.", + "public_surface": "exec()/run_code() on `class C[T]:`/`def f[T]():`/`type Alias[T] = ...` source + .__type_params__", + "internal_symbol_check": [ + "_PyTypeAlias_*", + "_PyTypeVar_*", + "INTRINSIC_SET_FUNCTION_TYPE_PARAMS" + ], + "uses_allowlisted_private": [], + "runner_surface": "./python -m unittest -v test.test_type_params.TypeParamsInvalidTest.test_name_non_collision_04", + "fixture_taint_checked": true + }, + "test.test_type_params.TypeParamsInvalidTest.test_name_non_collision_05": { + "system_reason": "PEP-695 type-parameter test. test_type_params.py has module-level `class GlobalGenericClass[T]:` \u2192 SyntaxError at module import pre-state \u2192 ERROR.", + "public_surface": "exec()/run_code() on `class C[T]:`/`def f[T]():`/`type Alias[T] = ...` source + .__type_params__", + "internal_symbol_check": [ + "_PyTypeAlias_*", + "_PyTypeVar_*", + "INTRINSIC_SET_FUNCTION_TYPE_PARAMS" + ], + "uses_allowlisted_private": [], + "runner_surface": "./python -m unittest -v test.test_type_params.TypeParamsInvalidTest.test_name_non_collision_05", + "fixture_taint_checked": true + }, + "test.test_type_params.TypeParamsInvalidTest.test_name_non_collision_06": { + "system_reason": "PEP-695 type-parameter test. test_type_params.py has module-level `class GlobalGenericClass[T]:` \u2192 SyntaxError at module import pre-state \u2192 ERROR.", + "public_surface": "exec()/run_code() on `class C[T]:`/`def f[T]():`/`type Alias[T] = ...` source + .__type_params__", + "internal_symbol_check": [ + "_PyTypeAlias_*", + "_PyTypeVar_*", + "INTRINSIC_SET_FUNCTION_TYPE_PARAMS" + ], + "uses_allowlisted_private": [], + "runner_surface": "./python -m unittest -v test.test_type_params.TypeParamsInvalidTest.test_name_non_collision_06", + "fixture_taint_checked": true + }, + "test.test_type_params.TypeParamsInvalidTest.test_name_non_collision_07": { + "system_reason": "PEP-695 type-parameter test. test_type_params.py has module-level `class GlobalGenericClass[T]:` \u2192 SyntaxError at module import pre-state \u2192 ERROR.", + "public_surface": "exec()/run_code() on `class C[T]:`/`def f[T]():`/`type Alias[T] = ...` source + .__type_params__", + "internal_symbol_check": [ + "_PyTypeAlias_*", + "_PyTypeVar_*", + "INTRINSIC_SET_FUNCTION_TYPE_PARAMS" + ], + "uses_allowlisted_private": [], + "runner_surface": "./python -m unittest -v test.test_type_params.TypeParamsInvalidTest.test_name_non_collision_07", + "fixture_taint_checked": true + }, + "test.test_type_params.TypeParamsInvalidTest.test_name_non_collision_08": { + "system_reason": "PEP-695 type-parameter test. test_type_params.py has module-level `class GlobalGenericClass[T]:` \u2192 SyntaxError at module import pre-state \u2192 ERROR.", + "public_surface": "exec()/run_code() on `class C[T]:`/`def f[T]():`/`type Alias[T] = ...` source + .__type_params__", + "internal_symbol_check": [ + "_PyTypeAlias_*", + "_PyTypeVar_*", + "INTRINSIC_SET_FUNCTION_TYPE_PARAMS" + ], + "uses_allowlisted_private": [], + "runner_surface": "./python -m unittest -v test.test_type_params.TypeParamsInvalidTest.test_name_non_collision_08", + "fixture_taint_checked": true + }, + "test.test_type_params.TypeParamsInvalidTest.test_name_non_collision_9": { + "system_reason": "PEP-695 type-parameter test. test_type_params.py has module-level `class GlobalGenericClass[T]:` \u2192 SyntaxError at module import pre-state \u2192 ERROR.", + "public_surface": "exec()/run_code() on `class C[T]:`/`def f[T]():`/`type Alias[T] = ...` source + .__type_params__", + "internal_symbol_check": [ + "_PyTypeAlias_*", + "_PyTypeVar_*", + "INTRINSIC_SET_FUNCTION_TYPE_PARAMS" + ], + "uses_allowlisted_private": [], + "runner_surface": "./python -m unittest -v test.test_type_params.TypeParamsInvalidTest.test_name_non_collision_9", + "fixture_taint_checked": true + }, + "test.test_type_params.TypeParamsInvalidTest.test_name_non_collision_10": { + "system_reason": "PEP-695 type-parameter test. test_type_params.py has module-level `class GlobalGenericClass[T]:` \u2192 SyntaxError at module import pre-state \u2192 ERROR.", + "public_surface": "exec()/run_code() on `class C[T]:`/`def f[T]():`/`type Alias[T] = ...` source + .__type_params__", + "internal_symbol_check": [ + "_PyTypeAlias_*", + "_PyTypeVar_*", + "INTRINSIC_SET_FUNCTION_TYPE_PARAMS" + ], + "uses_allowlisted_private": [], + "runner_surface": "./python -m unittest -v test.test_type_params.TypeParamsInvalidTest.test_name_non_collision_10", + "fixture_taint_checked": true + }, + "test.test_type_params.TypeParamsInvalidTest.test_name_non_collision_13": { + "system_reason": "PEP-695 type-parameter test. test_type_params.py has module-level `class GlobalGenericClass[T]:` \u2192 SyntaxError at module import pre-state \u2192 ERROR.", + "public_surface": "exec()/run_code() on `class C[T]:`/`def f[T]():`/`type Alias[T] = ...` source + .__type_params__", + "internal_symbol_check": [ + "_PyTypeAlias_*", + "_PyTypeVar_*", + "INTRINSIC_SET_FUNCTION_TYPE_PARAMS" + ], + "uses_allowlisted_private": [], + "runner_surface": "./python -m unittest -v test.test_type_params.TypeParamsInvalidTest.test_name_non_collision_13", + "fixture_taint_checked": true + }, + "test.test_type_params.TypeParamsInvalidTest.test_disallowed_expressions": { + "system_reason": "PEP-695 type-parameter test. test_type_params.py has module-level `class GlobalGenericClass[T]:` \u2192 SyntaxError at module import pre-state \u2192 ERROR.", + "public_surface": "exec()/run_code() on `class C[T]:`/`def f[T]():`/`type Alias[T] = ...` source + .__type_params__", + "internal_symbol_check": [ + "_PyTypeAlias_*", + "_PyTypeVar_*", + "INTRINSIC_SET_FUNCTION_TYPE_PARAMS" + ], + "uses_allowlisted_private": [], + "runner_surface": "./python -m unittest -v test.test_type_params.TypeParamsInvalidTest.test_disallowed_expressions", + "fixture_taint_checked": true + }, + "test.test_type_params.TypeParamsNonlocalTest.test_nonlocal_disallowed_01": { + "system_reason": "PEP-695 type-parameter test. test_type_params.py has module-level `class GlobalGenericClass[T]:` \u2192 SyntaxError at module import pre-state \u2192 ERROR.", + "public_surface": "exec()/run_code() on `class C[T]:`/`def f[T]():`/`type Alias[T] = ...` source + .__type_params__", + "internal_symbol_check": [ + "_PyTypeAlias_*", + "_PyTypeVar_*", + "INTRINSIC_SET_FUNCTION_TYPE_PARAMS" + ], + "uses_allowlisted_private": [], + "runner_surface": "./python -m unittest -v test.test_type_params.TypeParamsNonlocalTest.test_nonlocal_disallowed_01", + "fixture_taint_checked": true + }, + "test.test_type_params.TypeParamsNonlocalTest.test_nonlocal_disallowed_02": { + "system_reason": "PEP-695 type-parameter test. test_type_params.py has module-level `class GlobalGenericClass[T]:` \u2192 SyntaxError at module import pre-state \u2192 ERROR.", + "public_surface": "exec()/run_code() on `class C[T]:`/`def f[T]():`/`type Alias[T] = ...` source + .__type_params__", + "internal_symbol_check": [ + "_PyTypeAlias_*", + "_PyTypeVar_*", + "INTRINSIC_SET_FUNCTION_TYPE_PARAMS" + ], + "uses_allowlisted_private": [], + "runner_surface": "./python -m unittest -v test.test_type_params.TypeParamsNonlocalTest.test_nonlocal_disallowed_02", + "fixture_taint_checked": true + }, + "test.test_type_params.TypeParamsNonlocalTest.test_nonlocal_disallowed_03": { + "system_reason": "PEP-695 type-parameter test. test_type_params.py has module-level `class GlobalGenericClass[T]:` \u2192 SyntaxError at module import pre-state \u2192 ERROR.", + "public_surface": "exec()/run_code() on `class C[T]:`/`def f[T]():`/`type Alias[T] = ...` source + .__type_params__", + "internal_symbol_check": [ + "_PyTypeAlias_*", + "_PyTypeVar_*", + "INTRINSIC_SET_FUNCTION_TYPE_PARAMS" + ], + "uses_allowlisted_private": [], + "runner_surface": "./python -m unittest -v test.test_type_params.TypeParamsNonlocalTest.test_nonlocal_disallowed_03", + "fixture_taint_checked": true + }, + "test.test_type_params.TypeParamsNonlocalTest.test_nonlocal_allowed": { + "system_reason": "PEP-695 type-parameter test. test_type_params.py has module-level `class GlobalGenericClass[T]:` \u2192 SyntaxError at module import pre-state \u2192 ERROR.", + "public_surface": "exec()/run_code() on `class C[T]:`/`def f[T]():`/`type Alias[T] = ...` source + .__type_params__", + "internal_symbol_check": [ + "_PyTypeAlias_*", + "_PyTypeVar_*", + "INTRINSIC_SET_FUNCTION_TYPE_PARAMS" + ], + "uses_allowlisted_private": [], + "runner_surface": "./python -m unittest -v test.test_type_params.TypeParamsNonlocalTest.test_nonlocal_allowed", + "fixture_taint_checked": true + }, + "test.test_type_params.TypeParamsAccessTest.test_class_access_01": { + "system_reason": "PEP-695 type-parameter test. test_type_params.py has module-level `class GlobalGenericClass[T]:` \u2192 SyntaxError at module import pre-state \u2192 ERROR.", + "public_surface": "exec()/run_code() on `class C[T]:`/`def f[T]():`/`type Alias[T] = ...` source + .__type_params__", + "internal_symbol_check": [ + "_PyTypeAlias_*", + "_PyTypeVar_*", + "INTRINSIC_SET_FUNCTION_TYPE_PARAMS" + ], + "uses_allowlisted_private": [], + "runner_surface": "./python -m unittest -v test.test_type_params.TypeParamsAccessTest.test_class_access_01", + "fixture_taint_checked": true + }, + "test.test_type_params.TypeParamsAccessTest.test_class_access_02": { + "system_reason": "PEP-695 type-parameter test. test_type_params.py has module-level `class GlobalGenericClass[T]:` \u2192 SyntaxError at module import pre-state \u2192 ERROR.", + "public_surface": "exec()/run_code() on `class C[T]:`/`def f[T]():`/`type Alias[T] = ...` source + .__type_params__", + "internal_symbol_check": [ + "_PyTypeAlias_*", + "_PyTypeVar_*", + "INTRINSIC_SET_FUNCTION_TYPE_PARAMS" + ], + "uses_allowlisted_private": [], + "runner_surface": "./python -m unittest -v test.test_type_params.TypeParamsAccessTest.test_class_access_02", + "fixture_taint_checked": true + }, + "test.test_type_params.TypeParamsAccessTest.test_class_access_03": { + "system_reason": "PEP-695 type-parameter test. test_type_params.py has module-level `class GlobalGenericClass[T]:` \u2192 SyntaxError at module import pre-state \u2192 ERROR.", + "public_surface": "exec()/run_code() on `class C[T]:`/`def f[T]():`/`type Alias[T] = ...` source + .__type_params__", + "internal_symbol_check": [ + "_PyTypeAlias_*", + "_PyTypeVar_*", + "INTRINSIC_SET_FUNCTION_TYPE_PARAMS" + ], + "uses_allowlisted_private": [], + "runner_surface": "./python -m unittest -v test.test_type_params.TypeParamsAccessTest.test_class_access_03", + "fixture_taint_checked": true + }, + "test.test_type_params.TypeParamsAccessTest.test_function_access_01": { + "system_reason": "PEP-695 type-parameter test. test_type_params.py has module-level `class GlobalGenericClass[T]:` \u2192 SyntaxError at module import pre-state \u2192 ERROR.", + "public_surface": "exec()/run_code() on `class C[T]:`/`def f[T]():`/`type Alias[T] = ...` source + .__type_params__", + "internal_symbol_check": [ + "_PyTypeAlias_*", + "_PyTypeVar_*", + "INTRINSIC_SET_FUNCTION_TYPE_PARAMS" + ], + "uses_allowlisted_private": [], + "runner_surface": "./python -m unittest -v test.test_type_params.TypeParamsAccessTest.test_function_access_01", + "fixture_taint_checked": true + }, + "test.test_type_params.TypeParamsAccessTest.test_function_access_02": { + "system_reason": "PEP-695 type-parameter test. test_type_params.py has module-level `class GlobalGenericClass[T]:` \u2192 SyntaxError at module import pre-state \u2192 ERROR.", + "public_surface": "exec()/run_code() on `class C[T]:`/`def f[T]():`/`type Alias[T] = ...` source + .__type_params__", + "internal_symbol_check": [ + "_PyTypeAlias_*", + "_PyTypeVar_*", + "INTRINSIC_SET_FUNCTION_TYPE_PARAMS" + ], + "uses_allowlisted_private": [], + "runner_surface": "./python -m unittest -v test.test_type_params.TypeParamsAccessTest.test_function_access_02", + "fixture_taint_checked": true + }, + "test.test_type_params.TypeParamsAccessTest.test_function_access_03": { + "system_reason": "PEP-695 type-parameter test. test_type_params.py has module-level `class GlobalGenericClass[T]:` \u2192 SyntaxError at module import pre-state \u2192 ERROR.", + "public_surface": "exec()/run_code() on `class C[T]:`/`def f[T]():`/`type Alias[T] = ...` source + .__type_params__", + "internal_symbol_check": [ + "_PyTypeAlias_*", + "_PyTypeVar_*", + "INTRINSIC_SET_FUNCTION_TYPE_PARAMS" + ], + "uses_allowlisted_private": [], + "runner_surface": "./python -m unittest -v test.test_type_params.TypeParamsAccessTest.test_function_access_03", + "fixture_taint_checked": true + }, + "test.test_type_params.TypeParamsAccessTest.test_method_access_01": { + "system_reason": "PEP-695 type-parameter test. test_type_params.py has module-level `class GlobalGenericClass[T]:` \u2192 SyntaxError at module import pre-state \u2192 ERROR.", + "public_surface": "exec()/run_code() on `class C[T]:`/`def f[T]():`/`type Alias[T] = ...` source + .__type_params__", + "internal_symbol_check": [ + "_PyTypeAlias_*", + "_PyTypeVar_*", + "INTRINSIC_SET_FUNCTION_TYPE_PARAMS" + ], + "uses_allowlisted_private": [], + "runner_surface": "./python -m unittest -v test.test_type_params.TypeParamsAccessTest.test_method_access_01", + "fixture_taint_checked": true + }, + "test.test_type_params.TypeParamsAccessTest.test_nested_access_01": { + "system_reason": "PEP-695 type-parameter test. test_type_params.py has module-level `class GlobalGenericClass[T]:` \u2192 SyntaxError at module import pre-state \u2192 ERROR.", + "public_surface": "exec()/run_code() on `class C[T]:`/`def f[T]():`/`type Alias[T] = ...` source + .__type_params__", + "internal_symbol_check": [ + "_PyTypeAlias_*", + "_PyTypeVar_*", + "INTRINSIC_SET_FUNCTION_TYPE_PARAMS" + ], + "uses_allowlisted_private": [], + "runner_surface": "./python -m unittest -v test.test_type_params.TypeParamsAccessTest.test_nested_access_01", + "fixture_taint_checked": true + }, + "test.test_type_params.TypeParamsAccessTest.test_out_of_scope_01": { + "system_reason": "PEP-695 type-parameter test. test_type_params.py has module-level `class GlobalGenericClass[T]:` \u2192 SyntaxError at module import pre-state \u2192 ERROR.", + "public_surface": "exec()/run_code() on `class C[T]:`/`def f[T]():`/`type Alias[T] = ...` source + .__type_params__", + "internal_symbol_check": [ + "_PyTypeAlias_*", + "_PyTypeVar_*", + "INTRINSIC_SET_FUNCTION_TYPE_PARAMS" + ], + "uses_allowlisted_private": [], + "runner_surface": "./python -m unittest -v test.test_type_params.TypeParamsAccessTest.test_out_of_scope_01", + "fixture_taint_checked": true + }, + "test.test_type_params.TypeParamsAccessTest.test_out_of_scope_02": { + "system_reason": "PEP-695 type-parameter test. test_type_params.py has module-level `class GlobalGenericClass[T]:` \u2192 SyntaxError at module import pre-state \u2192 ERROR.", + "public_surface": "exec()/run_code() on `class C[T]:`/`def f[T]():`/`type Alias[T] = ...` source + .__type_params__", + "internal_symbol_check": [ + "_PyTypeAlias_*", + "_PyTypeVar_*", + "INTRINSIC_SET_FUNCTION_TYPE_PARAMS" + ], + "uses_allowlisted_private": [], + "runner_surface": "./python -m unittest -v test.test_type_params.TypeParamsAccessTest.test_out_of_scope_02", + "fixture_taint_checked": true + }, + "test.test_type_params.TypeParamsAccessTest.test_class_scope_interaction_01": { + "system_reason": "PEP-695 type-parameter test. test_type_params.py has module-level `class GlobalGenericClass[T]:` \u2192 SyntaxError at module import pre-state \u2192 ERROR.", + "public_surface": "exec()/run_code() on `class C[T]:`/`def f[T]():`/`type Alias[T] = ...` source + .__type_params__", + "internal_symbol_check": [ + "_PyTypeAlias_*", + "_PyTypeVar_*", + "INTRINSIC_SET_FUNCTION_TYPE_PARAMS" + ], + "uses_allowlisted_private": [], + "runner_surface": "./python -m unittest -v test.test_type_params.TypeParamsAccessTest.test_class_scope_interaction_01", + "fixture_taint_checked": true + }, + "test.test_type_params.TypeParamsAccessTest.test_class_scope_interaction_02": { + "system_reason": "PEP-695 type-parameter test. test_type_params.py has module-level `class GlobalGenericClass[T]:` \u2192 SyntaxError at module import pre-state \u2192 ERROR.", + "public_surface": "exec()/run_code() on `class C[T]:`/`def f[T]():`/`type Alias[T] = ...` source + .__type_params__", + "internal_symbol_check": [ + "_PyTypeAlias_*", + "_PyTypeVar_*", + "INTRINSIC_SET_FUNCTION_TYPE_PARAMS" + ], + "uses_allowlisted_private": [], + "runner_surface": "./python -m unittest -v test.test_type_params.TypeParamsAccessTest.test_class_scope_interaction_02", + "fixture_taint_checked": true + }, + "test.test_type_params.TypeParamsAccessTest.test_class_deref": { + "system_reason": "PEP-695 type-parameter test. test_type_params.py has module-level `class GlobalGenericClass[T]:` \u2192 SyntaxError at module import pre-state \u2192 ERROR.", + "public_surface": "exec()/run_code() on `class C[T]:`/`def f[T]():`/`type Alias[T] = ...` source + .__type_params__", + "internal_symbol_check": [ + "_PyTypeAlias_*", + "_PyTypeVar_*", + "INTRINSIC_SET_FUNCTION_TYPE_PARAMS" + ], + "uses_allowlisted_private": [], + "runner_surface": "./python -m unittest -v test.test_type_params.TypeParamsAccessTest.test_class_deref", + "fixture_taint_checked": true + }, + "test.test_type_params.TypeParamsAccessTest.test_shadowing_nonlocal": { + "system_reason": "PEP-695 type-parameter test. test_type_params.py has module-level `class GlobalGenericClass[T]:` \u2192 SyntaxError at module import pre-state \u2192 ERROR.", + "public_surface": "exec()/run_code() on `class C[T]:`/`def f[T]():`/`type Alias[T] = ...` source + .__type_params__", + "internal_symbol_check": [ + "_PyTypeAlias_*", + "_PyTypeVar_*", + "INTRINSIC_SET_FUNCTION_TYPE_PARAMS" + ], + "uses_allowlisted_private": [], + "runner_surface": "./python -m unittest -v test.test_type_params.TypeParamsAccessTest.test_shadowing_nonlocal", + "fixture_taint_checked": true + }, + "test.test_type_params.TypeParamsAccessTest.test_reference_previous_typevar": { + "system_reason": "PEP-695 type-parameter test. test_type_params.py has module-level `class GlobalGenericClass[T]:` \u2192 SyntaxError at module import pre-state \u2192 ERROR.", + "public_surface": "exec()/run_code() on `class C[T]:`/`def f[T]():`/`type Alias[T] = ...` source + .__type_params__", + "internal_symbol_check": [ + "_PyTypeAlias_*", + "_PyTypeVar_*", + "INTRINSIC_SET_FUNCTION_TYPE_PARAMS" + ], + "uses_allowlisted_private": [], + "runner_surface": "./python -m unittest -v test.test_type_params.TypeParamsAccessTest.test_reference_previous_typevar", + "fixture_taint_checked": true + }, + "test.test_type_params.TypeParamsAccessTest.test_super": { + "system_reason": "PEP-695 type-parameter test. test_type_params.py has module-level `class GlobalGenericClass[T]:` \u2192 SyntaxError at module import pre-state \u2192 ERROR.", + "public_surface": "exec()/run_code() on `class C[T]:`/`def f[T]():`/`type Alias[T] = ...` source + .__type_params__", + "internal_symbol_check": [ + "_PyTypeAlias_*", + "_PyTypeVar_*", + "INTRINSIC_SET_FUNCTION_TYPE_PARAMS" + ], + "uses_allowlisted_private": [], + "runner_surface": "./python -m unittest -v test.test_type_params.TypeParamsAccessTest.test_super", + "fixture_taint_checked": true + }, + "test.test_type_params.TypeParamsAccessTest.test_type_alias_containing_lambda": { + "system_reason": "PEP-695 type-parameter test. test_type_params.py has module-level `class GlobalGenericClass[T]:` \u2192 SyntaxError at module import pre-state \u2192 ERROR.", + "public_surface": "exec()/run_code() on `class C[T]:`/`def f[T]():`/`type Alias[T] = ...` source + .__type_params__", + "internal_symbol_check": [ + "_PyTypeAlias_*", + "_PyTypeVar_*", + "INTRINSIC_SET_FUNCTION_TYPE_PARAMS" + ], + "uses_allowlisted_private": [], + "runner_surface": "./python -m unittest -v test.test_type_params.TypeParamsAccessTest.test_type_alias_containing_lambda", + "fixture_taint_checked": true + }, + "test.test_type_params.TypeParamsAccessTest.test_class_base_containing_lambda": { + "system_reason": "PEP-695 type-parameter test. test_type_params.py has module-level `class GlobalGenericClass[T]:` \u2192 SyntaxError at module import pre-state \u2192 ERROR.", + "public_surface": "exec()/run_code() on `class C[T]:`/`def f[T]():`/`type Alias[T] = ...` source + .__type_params__", + "internal_symbol_check": [ + "_PyTypeAlias_*", + "_PyTypeVar_*", + "INTRINSIC_SET_FUNCTION_TYPE_PARAMS" + ], + "uses_allowlisted_private": [], + "runner_surface": "./python -m unittest -v test.test_type_params.TypeParamsAccessTest.test_class_base_containing_lambda", + "fixture_taint_checked": true + }, + "test.test_type_params.TypeParamsAccessTest.test_comprehension_01": { + "system_reason": "PEP-695 type-parameter test. test_type_params.py has module-level `class GlobalGenericClass[T]:` \u2192 SyntaxError at module import pre-state \u2192 ERROR.", + "public_surface": "exec()/run_code() on `class C[T]:`/`def f[T]():`/`type Alias[T] = ...` source + .__type_params__", + "internal_symbol_check": [ + "_PyTypeAlias_*", + "_PyTypeVar_*", + "INTRINSIC_SET_FUNCTION_TYPE_PARAMS" + ], + "uses_allowlisted_private": [], + "runner_surface": "./python -m unittest -v test.test_type_params.TypeParamsAccessTest.test_comprehension_01", + "fixture_taint_checked": true + }, + "test.test_type_params.TypeParamsAccessTest.test_comprehension_02": { + "system_reason": "PEP-695 type-parameter test. test_type_params.py has module-level `class GlobalGenericClass[T]:` \u2192 SyntaxError at module import pre-state \u2192 ERROR.", + "public_surface": "exec()/run_code() on `class C[T]:`/`def f[T]():`/`type Alias[T] = ...` source + .__type_params__", + "internal_symbol_check": [ + "_PyTypeAlias_*", + "_PyTypeVar_*", + "INTRINSIC_SET_FUNCTION_TYPE_PARAMS" + ], + "uses_allowlisted_private": [], + "runner_surface": "./python -m unittest -v test.test_type_params.TypeParamsAccessTest.test_comprehension_02", + "fixture_taint_checked": true + }, + "test.test_type_params.TypeParamsLazyEvaluationTest.test_qualname": { + "system_reason": "PEP-695 type-parameter test. test_type_params.py has module-level `class GlobalGenericClass[T]:` \u2192 SyntaxError at module import pre-state \u2192 ERROR.", + "public_surface": "exec()/run_code() on `class C[T]:`/`def f[T]():`/`type Alias[T] = ...` source + .__type_params__", + "internal_symbol_check": [ + "_PyTypeAlias_*", + "_PyTypeVar_*", + "INTRINSIC_SET_FUNCTION_TYPE_PARAMS" + ], + "uses_allowlisted_private": [], + "runner_surface": "./python -m unittest -v test.test_type_params.TypeParamsLazyEvaluationTest.test_qualname", + "fixture_taint_checked": true + }, + "test.test_type_params.TypeParamsLazyEvaluationTest.test_recursive_class": { + "system_reason": "PEP-695 type-parameter test. test_type_params.py has module-level `class GlobalGenericClass[T]:` \u2192 SyntaxError at module import pre-state \u2192 ERROR.", + "public_surface": "exec()/run_code() on `class C[T]:`/`def f[T]():`/`type Alias[T] = ...` source + .__type_params__", + "internal_symbol_check": [ + "_PyTypeAlias_*", + "_PyTypeVar_*", + "INTRINSIC_SET_FUNCTION_TYPE_PARAMS" + ], + "uses_allowlisted_private": [], + "runner_surface": "./python -m unittest -v test.test_type_params.TypeParamsLazyEvaluationTest.test_recursive_class", + "fixture_taint_checked": true + }, + "test.test_type_params.TypeParamsLazyEvaluationTest.test_evaluation_error": { + "system_reason": "PEP-695 type-parameter test. test_type_params.py has module-level `class GlobalGenericClass[T]:` \u2192 SyntaxError at module import pre-state \u2192 ERROR.", + "public_surface": "exec()/run_code() on `class C[T]:`/`def f[T]():`/`type Alias[T] = ...` source + .__type_params__", + "internal_symbol_check": [ + "_PyTypeAlias_*", + "_PyTypeVar_*", + "INTRINSIC_SET_FUNCTION_TYPE_PARAMS" + ], + "uses_allowlisted_private": [], + "runner_surface": "./python -m unittest -v test.test_type_params.TypeParamsLazyEvaluationTest.test_evaluation_error", + "fixture_taint_checked": true + }, + "test.test_type_params.TypeParamsClassScopeTest.test_alias": { + "system_reason": "PEP-695 type-parameter test. test_type_params.py has module-level `class GlobalGenericClass[T]:` \u2192 SyntaxError at module import pre-state \u2192 ERROR.", + "public_surface": "exec()/run_code() on `class C[T]:`/`def f[T]():`/`type Alias[T] = ...` source + .__type_params__", + "internal_symbol_check": [ + "_PyTypeAlias_*", + "_PyTypeVar_*", + "INTRINSIC_SET_FUNCTION_TYPE_PARAMS" + ], + "uses_allowlisted_private": [], + "runner_surface": "./python -m unittest -v test.test_type_params.TypeParamsClassScopeTest.test_alias", + "fixture_taint_checked": true + }, + "test.test_type_params.TypeParamsClassScopeTest.test_bound": { + "system_reason": "PEP-695 type-parameter test. test_type_params.py has module-level `class GlobalGenericClass[T]:` \u2192 SyntaxError at module import pre-state \u2192 ERROR.", + "public_surface": "exec()/run_code() on `class C[T]:`/`def f[T]():`/`type Alias[T] = ...` source + .__type_params__", + "internal_symbol_check": [ + "_PyTypeAlias_*", + "_PyTypeVar_*", + "INTRINSIC_SET_FUNCTION_TYPE_PARAMS" + ], + "uses_allowlisted_private": [], + "runner_surface": "./python -m unittest -v test.test_type_params.TypeParamsClassScopeTest.test_bound", + "fixture_taint_checked": true + }, + "test.test_type_params.TypeParamsClassScopeTest.test_modified_later": { + "system_reason": "PEP-695 type-parameter test. test_type_params.py has module-level `class GlobalGenericClass[T]:` \u2192 SyntaxError at module import pre-state \u2192 ERROR.", + "public_surface": "exec()/run_code() on `class C[T]:`/`def f[T]():`/`type Alias[T] = ...` source + .__type_params__", + "internal_symbol_check": [ + "_PyTypeAlias_*", + "_PyTypeVar_*", + "INTRINSIC_SET_FUNCTION_TYPE_PARAMS" + ], + "uses_allowlisted_private": [], + "runner_surface": "./python -m unittest -v test.test_type_params.TypeParamsClassScopeTest.test_modified_later", + "fixture_taint_checked": true + }, + "test.test_type_params.TypeParamsClassScopeTest.test_binding_uses_global": { + "system_reason": "PEP-695 type-parameter test. test_type_params.py has module-level `class GlobalGenericClass[T]:` \u2192 SyntaxError at module import pre-state \u2192 ERROR.", + "public_surface": "exec()/run_code() on `class C[T]:`/`def f[T]():`/`type Alias[T] = ...` source + .__type_params__", + "internal_symbol_check": [ + "_PyTypeAlias_*", + "_PyTypeVar_*", + "INTRINSIC_SET_FUNCTION_TYPE_PARAMS" + ], + "uses_allowlisted_private": [], + "runner_surface": "./python -m unittest -v test.test_type_params.TypeParamsClassScopeTest.test_binding_uses_global", + "fixture_taint_checked": true + }, + "test.test_type_params.TypeParamsClassScopeTest.test_no_binding_uses_nonlocal": { + "system_reason": "PEP-695 type-parameter test. test_type_params.py has module-level `class GlobalGenericClass[T]:` \u2192 SyntaxError at module import pre-state \u2192 ERROR.", + "public_surface": "exec()/run_code() on `class C[T]:`/`def f[T]():`/`type Alias[T] = ...` source + .__type_params__", + "internal_symbol_check": [ + "_PyTypeAlias_*", + "_PyTypeVar_*", + "INTRINSIC_SET_FUNCTION_TYPE_PARAMS" + ], + "uses_allowlisted_private": [], + "runner_surface": "./python -m unittest -v test.test_type_params.TypeParamsClassScopeTest.test_no_binding_uses_nonlocal", + "fixture_taint_checked": true + }, + "test.test_type_params.TypeParamsClassScopeTest.test_explicit_global": { + "system_reason": "PEP-695 type-parameter test. test_type_params.py has module-level `class GlobalGenericClass[T]:` \u2192 SyntaxError at module import pre-state \u2192 ERROR.", + "public_surface": "exec()/run_code() on `class C[T]:`/`def f[T]():`/`type Alias[T] = ...` source + .__type_params__", + "internal_symbol_check": [ + "_PyTypeAlias_*", + "_PyTypeVar_*", + "INTRINSIC_SET_FUNCTION_TYPE_PARAMS" + ], + "uses_allowlisted_private": [], + "runner_surface": "./python -m unittest -v test.test_type_params.TypeParamsClassScopeTest.test_explicit_global", + "fixture_taint_checked": true + }, + "test.test_type_params.TypeParamsClassScopeTest.test_explicit_global_with_no_static_bound": { + "system_reason": "PEP-695 type-parameter test. test_type_params.py has module-level `class GlobalGenericClass[T]:` \u2192 SyntaxError at module import pre-state \u2192 ERROR.", + "public_surface": "exec()/run_code() on `class C[T]:`/`def f[T]():`/`type Alias[T] = ...` source + .__type_params__", + "internal_symbol_check": [ + "_PyTypeAlias_*", + "_PyTypeVar_*", + "INTRINSIC_SET_FUNCTION_TYPE_PARAMS" + ], + "uses_allowlisted_private": [], + "runner_surface": "./python -m unittest -v test.test_type_params.TypeParamsClassScopeTest.test_explicit_global_with_no_static_bound", + "fixture_taint_checked": true + }, + "test.test_type_params.TypeParamsClassScopeTest.test_explicit_global_with_assignment": { + "system_reason": "PEP-695 type-parameter test. test_type_params.py has module-level `class GlobalGenericClass[T]:` \u2192 SyntaxError at module import pre-state \u2192 ERROR.", + "public_surface": "exec()/run_code() on `class C[T]:`/`def f[T]():`/`type Alias[T] = ...` source + .__type_params__", + "internal_symbol_check": [ + "_PyTypeAlias_*", + "_PyTypeVar_*", + "INTRINSIC_SET_FUNCTION_TYPE_PARAMS" + ], + "uses_allowlisted_private": [], + "runner_surface": "./python -m unittest -v test.test_type_params.TypeParamsClassScopeTest.test_explicit_global_with_assignment", + "fixture_taint_checked": true + }, + "test.test_type_params.TypeParamsClassScopeTest.test_explicit_nonlocal": { + "system_reason": "PEP-695 type-parameter test. test_type_params.py has module-level `class GlobalGenericClass[T]:` \u2192 SyntaxError at module import pre-state \u2192 ERROR.", + "public_surface": "exec()/run_code() on `class C[T]:`/`def f[T]():`/`type Alias[T] = ...` source + .__type_params__", + "internal_symbol_check": [ + "_PyTypeAlias_*", + "_PyTypeVar_*", + "INTRINSIC_SET_FUNCTION_TYPE_PARAMS" + ], + "uses_allowlisted_private": [], + "runner_surface": "./python -m unittest -v test.test_type_params.TypeParamsClassScopeTest.test_explicit_nonlocal", + "fixture_taint_checked": true + }, + "test.test_type_params.TypeParamsManglingTest.test_mangling": { + "system_reason": "PEP-695 type-parameter test. test_type_params.py has module-level `class GlobalGenericClass[T]:` \u2192 SyntaxError at module import pre-state \u2192 ERROR.", + "public_surface": "exec()/run_code() on `class C[T]:`/`def f[T]():`/`type Alias[T] = ...` source + .__type_params__", + "internal_symbol_check": [ + "_PyTypeAlias_*", + "_PyTypeVar_*", + "INTRINSIC_SET_FUNCTION_TYPE_PARAMS" + ], + "uses_allowlisted_private": [], + "runner_surface": "./python -m unittest -v test.test_type_params.TypeParamsManglingTest.test_mangling", + "fixture_taint_checked": true + }, + "test.test_type_params.TypeParamsComplexCallsTest.test_defaults": { + "system_reason": "PEP-695 type-parameter test. test_type_params.py has module-level `class GlobalGenericClass[T]:` \u2192 SyntaxError at module import pre-state \u2192 ERROR.", + "public_surface": "exec()/run_code() on `class C[T]:`/`def f[T]():`/`type Alias[T] = ...` source + .__type_params__", + "internal_symbol_check": [ + "_PyTypeAlias_*", + "_PyTypeVar_*", + "INTRINSIC_SET_FUNCTION_TYPE_PARAMS" + ], + "uses_allowlisted_private": [], + "runner_surface": "./python -m unittest -v test.test_type_params.TypeParamsComplexCallsTest.test_defaults", + "fixture_taint_checked": true + }, + "test.test_type_params.TypeParamsComplexCallsTest.test_complex_base": { + "system_reason": "PEP-695 type-parameter test. test_type_params.py has module-level `class GlobalGenericClass[T]:` \u2192 SyntaxError at module import pre-state \u2192 ERROR.", + "public_surface": "exec()/run_code() on `class C[T]:`/`def f[T]():`/`type Alias[T] = ...` source + .__type_params__", + "internal_symbol_check": [ + "_PyTypeAlias_*", + "_PyTypeVar_*", + "INTRINSIC_SET_FUNCTION_TYPE_PARAMS" + ], + "uses_allowlisted_private": [], + "runner_surface": "./python -m unittest -v test.test_type_params.TypeParamsComplexCallsTest.test_complex_base", + "fixture_taint_checked": true + }, + "test.test_type_params.TypeParamsTraditionalTypeVarsTest.test_traditional_01": { + "system_reason": "PEP-695 type-parameter test. test_type_params.py has module-level `class GlobalGenericClass[T]:` \u2192 SyntaxError at module import pre-state \u2192 ERROR.", + "public_surface": "exec()/run_code() on `class C[T]:`/`def f[T]():`/`type Alias[T] = ...` source + .__type_params__", + "internal_symbol_check": [ + "_PyTypeAlias_*", + "_PyTypeVar_*", + "INTRINSIC_SET_FUNCTION_TYPE_PARAMS" + ], + "uses_allowlisted_private": [], + "runner_surface": "./python -m unittest -v test.test_type_params.TypeParamsTraditionalTypeVarsTest.test_traditional_01", + "fixture_taint_checked": true + }, + "test.test_type_params.TypeParamsTraditionalTypeVarsTest.test_traditional_02": { + "system_reason": "PEP-695 type-parameter test. test_type_params.py has module-level `class GlobalGenericClass[T]:` \u2192 SyntaxError at module import pre-state \u2192 ERROR.", + "public_surface": "exec()/run_code() on `class C[T]:`/`def f[T]():`/`type Alias[T] = ...` source + .__type_params__", + "internal_symbol_check": [ + "_PyTypeAlias_*", + "_PyTypeVar_*", + "INTRINSIC_SET_FUNCTION_TYPE_PARAMS" + ], + "uses_allowlisted_private": [], + "runner_surface": "./python -m unittest -v test.test_type_params.TypeParamsTraditionalTypeVarsTest.test_traditional_02", + "fixture_taint_checked": true + }, + "test.test_type_params.TypeParamsTraditionalTypeVarsTest.test_traditional_03": { + "system_reason": "PEP-695 type-parameter test. test_type_params.py has module-level `class GlobalGenericClass[T]:` \u2192 SyntaxError at module import pre-state \u2192 ERROR.", + "public_surface": "exec()/run_code() on `class C[T]:`/`def f[T]():`/`type Alias[T] = ...` source + .__type_params__", + "internal_symbol_check": [ + "_PyTypeAlias_*", + "_PyTypeVar_*", + "INTRINSIC_SET_FUNCTION_TYPE_PARAMS" + ], + "uses_allowlisted_private": [], + "runner_surface": "./python -m unittest -v test.test_type_params.TypeParamsTraditionalTypeVarsTest.test_traditional_03", + "fixture_taint_checked": true + }, + "test.test_type_params.TypeParamsTypeVarTest.test_typevar_01": { + "system_reason": "PEP-695 type-parameter test. test_type_params.py has module-level `class GlobalGenericClass[T]:` \u2192 SyntaxError at module import pre-state \u2192 ERROR.", + "public_surface": "exec()/run_code() on `class C[T]:`/`def f[T]():`/`type Alias[T] = ...` source + .__type_params__", + "internal_symbol_check": [ + "_PyTypeAlias_*", + "_PyTypeVar_*", + "INTRINSIC_SET_FUNCTION_TYPE_PARAMS" + ], + "uses_allowlisted_private": [], + "runner_surface": "./python -m unittest -v test.test_type_params.TypeParamsTypeVarTest.test_typevar_01", + "fixture_taint_checked": true + }, + "test.test_type_params.TypeParamsTypeVarTest.test_typevar_generator": { + "system_reason": "PEP-695 type-parameter test. test_type_params.py has module-level `class GlobalGenericClass[T]:` \u2192 SyntaxError at module import pre-state \u2192 ERROR.", + "public_surface": "exec()/run_code() on `class C[T]:`/`def f[T]():`/`type Alias[T] = ...` source + .__type_params__", + "internal_symbol_check": [ + "_PyTypeAlias_*", + "_PyTypeVar_*", + "INTRINSIC_SET_FUNCTION_TYPE_PARAMS" + ], + "uses_allowlisted_private": [], + "runner_surface": "./python -m unittest -v test.test_type_params.TypeParamsTypeVarTest.test_typevar_generator", + "fixture_taint_checked": true + }, + "test.test_type_params.TypeParamsTypeVarTest.test_typevar_coroutine": { + "system_reason": "PEP-695 type-parameter test. test_type_params.py has module-level `class GlobalGenericClass[T]:` \u2192 SyntaxError at module import pre-state \u2192 ERROR.", + "public_surface": "exec()/run_code() on `class C[T]:`/`def f[T]():`/`type Alias[T] = ...` source + .__type_params__", + "internal_symbol_check": [ + "_PyTypeAlias_*", + "_PyTypeVar_*", + "INTRINSIC_SET_FUNCTION_TYPE_PARAMS" + ], + "uses_allowlisted_private": [], + "runner_surface": "./python -m unittest -v test.test_type_params.TypeParamsTypeVarTest.test_typevar_coroutine", + "fixture_taint_checked": true + }, + "test.test_type_params.TypeParamsTypeVarTupleTest.test_typevartuple_01": { + "system_reason": "PEP-695 type-parameter test. test_type_params.py has module-level `class GlobalGenericClass[T]:` \u2192 SyntaxError at module import pre-state \u2192 ERROR.", + "public_surface": "exec()/run_code() on `class C[T]:`/`def f[T]():`/`type Alias[T] = ...` source + .__type_params__", + "internal_symbol_check": [ + "_PyTypeAlias_*", + "_PyTypeVar_*", + "INTRINSIC_SET_FUNCTION_TYPE_PARAMS" + ], + "uses_allowlisted_private": [], + "runner_surface": "./python -m unittest -v test.test_type_params.TypeParamsTypeVarTupleTest.test_typevartuple_01", + "fixture_taint_checked": true + }, + "test.test_type_params.TypeParamsTypeVarTupleTest.test_typevartuple_02": { + "system_reason": "PEP-695 type-parameter test. test_type_params.py has module-level `class GlobalGenericClass[T]:` \u2192 SyntaxError at module import pre-state \u2192 ERROR.", + "public_surface": "exec()/run_code() on `class C[T]:`/`def f[T]():`/`type Alias[T] = ...` source + .__type_params__", + "internal_symbol_check": [ + "_PyTypeAlias_*", + "_PyTypeVar_*", + "INTRINSIC_SET_FUNCTION_TYPE_PARAMS" + ], + "uses_allowlisted_private": [], + "runner_surface": "./python -m unittest -v test.test_type_params.TypeParamsTypeVarTupleTest.test_typevartuple_02", + "fixture_taint_checked": true + }, + "test.test_type_params.TypeParamsTypeVarParamSpecTest.test_paramspec_01": { + "system_reason": "PEP-695 type-parameter test. test_type_params.py has module-level `class GlobalGenericClass[T]:` \u2192 SyntaxError at module import pre-state \u2192 ERROR.", + "public_surface": "exec()/run_code() on `class C[T]:`/`def f[T]():`/`type Alias[T] = ...` source + .__type_params__", + "internal_symbol_check": [ + "_PyTypeAlias_*", + "_PyTypeVar_*", + "INTRINSIC_SET_FUNCTION_TYPE_PARAMS" + ], + "uses_allowlisted_private": [], + "runner_surface": "./python -m unittest -v test.test_type_params.TypeParamsTypeVarParamSpecTest.test_paramspec_01", + "fixture_taint_checked": true + }, + "test.test_type_params.TypeParamsTypeVarParamSpecTest.test_paramspec_02": { + "system_reason": "PEP-695 type-parameter test. test_type_params.py has module-level `class GlobalGenericClass[T]:` \u2192 SyntaxError at module import pre-state \u2192 ERROR.", + "public_surface": "exec()/run_code() on `class C[T]:`/`def f[T]():`/`type Alias[T] = ...` source + .__type_params__", + "internal_symbol_check": [ + "_PyTypeAlias_*", + "_PyTypeVar_*", + "INTRINSIC_SET_FUNCTION_TYPE_PARAMS" + ], + "uses_allowlisted_private": [], + "runner_surface": "./python -m unittest -v test.test_type_params.TypeParamsTypeVarParamSpecTest.test_paramspec_02", + "fixture_taint_checked": true + }, + "test.test_type_params.TypeParamsTypeParamsDunder.test_typeparams_dunder_class_01": { + "system_reason": "PEP-695 type-parameter test. test_type_params.py has module-level `class GlobalGenericClass[T]:` \u2192 SyntaxError at module import pre-state \u2192 ERROR.", + "public_surface": "exec()/run_code() on `class C[T]:`/`def f[T]():`/`type Alias[T] = ...` source + .__type_params__", + "internal_symbol_check": [ + "_PyTypeAlias_*", + "_PyTypeVar_*", + "INTRINSIC_SET_FUNCTION_TYPE_PARAMS" + ], + "uses_allowlisted_private": [], + "runner_surface": "./python -m unittest -v test.test_type_params.TypeParamsTypeParamsDunder.test_typeparams_dunder_class_01", + "fixture_taint_checked": true + }, + "test.test_type_params.TypeParamsTypeParamsDunder.test_typeparams_dunder_class_02": { + "system_reason": "PEP-695 type-parameter test. test_type_params.py has module-level `class GlobalGenericClass[T]:` \u2192 SyntaxError at module import pre-state \u2192 ERROR.", + "public_surface": "exec()/run_code() on `class C[T]:`/`def f[T]():`/`type Alias[T] = ...` source + .__type_params__", + "internal_symbol_check": [ + "_PyTypeAlias_*", + "_PyTypeVar_*", + "INTRINSIC_SET_FUNCTION_TYPE_PARAMS" + ], + "uses_allowlisted_private": [], + "runner_surface": "./python -m unittest -v test.test_type_params.TypeParamsTypeParamsDunder.test_typeparams_dunder_class_02", + "fixture_taint_checked": true + }, + "test.test_type_params.TypeParamsTypeParamsDunder.test_typeparams_dunder_class_03": { + "system_reason": "PEP-695 type-parameter test. test_type_params.py has module-level `class GlobalGenericClass[T]:` \u2192 SyntaxError at module import pre-state \u2192 ERROR.", + "public_surface": "exec()/run_code() on `class C[T]:`/`def f[T]():`/`type Alias[T] = ...` source + .__type_params__", + "internal_symbol_check": [ + "_PyTypeAlias_*", + "_PyTypeVar_*", + "INTRINSIC_SET_FUNCTION_TYPE_PARAMS" + ], + "uses_allowlisted_private": [], + "runner_surface": "./python -m unittest -v test.test_type_params.TypeParamsTypeParamsDunder.test_typeparams_dunder_class_03", + "fixture_taint_checked": true + }, + "test.test_type_params.TypeParamsTypeParamsDunder.test_typeparams_dunder_function_01": { + "system_reason": "PEP-695 type-parameter test. test_type_params.py has module-level `class GlobalGenericClass[T]:` \u2192 SyntaxError at module import pre-state \u2192 ERROR.", + "public_surface": "exec()/run_code() on `class C[T]:`/`def f[T]():`/`type Alias[T] = ...` source + .__type_params__", + "internal_symbol_check": [ + "_PyTypeAlias_*", + "_PyTypeVar_*", + "INTRINSIC_SET_FUNCTION_TYPE_PARAMS" + ], + "uses_allowlisted_private": [], + "runner_surface": "./python -m unittest -v test.test_type_params.TypeParamsTypeParamsDunder.test_typeparams_dunder_function_01", + "fixture_taint_checked": true + }, + "test.test_type_params.TypeParamsTypeParamsDunder.test_typeparams_dunder_function_02": { + "system_reason": "PEP-695 type-parameter test. test_type_params.py has module-level `class GlobalGenericClass[T]:` \u2192 SyntaxError at module import pre-state \u2192 ERROR.", + "public_surface": "exec()/run_code() on `class C[T]:`/`def f[T]():`/`type Alias[T] = ...` source + .__type_params__", + "internal_symbol_check": [ + "_PyTypeAlias_*", + "_PyTypeVar_*", + "INTRINSIC_SET_FUNCTION_TYPE_PARAMS" + ], + "uses_allowlisted_private": [], + "runner_surface": "./python -m unittest -v test.test_type_params.TypeParamsTypeParamsDunder.test_typeparams_dunder_function_02", + "fixture_taint_checked": true + }, + "test.test_type_params.TypeParamsTypeParamsDunder.test_typeparams_dunder_function_03": { + "system_reason": "PEP-695 type-parameter test. test_type_params.py has module-level `class GlobalGenericClass[T]:` \u2192 SyntaxError at module import pre-state \u2192 ERROR.", + "public_surface": "exec()/run_code() on `class C[T]:`/`def f[T]():`/`type Alias[T] = ...` source + .__type_params__", + "internal_symbol_check": [ + "_PyTypeAlias_*", + "_PyTypeVar_*", + "INTRINSIC_SET_FUNCTION_TYPE_PARAMS" + ], + "uses_allowlisted_private": [], + "runner_surface": "./python -m unittest -v test.test_type_params.TypeParamsTypeParamsDunder.test_typeparams_dunder_function_03", + "fixture_taint_checked": true + }, + "test.test_type_aliases.TypeParamsInvalidTest.test_name_collision_01": { + "system_reason": "PEP-695 type-alias test. exec()s `type Alias[T] = ...` source \u2192 pre-state SyntaxError.", + "public_surface": "exec()/run_code() on `type Alias[T] = ...` source + typing.TypeAliasType public API", + "internal_symbol_check": [ + "_PyTypeAlias_*", + "_PyTypeVar_*", + "INTRINSIC_SET_FUNCTION_TYPE_PARAMS" + ], + "uses_allowlisted_private": [], + "runner_surface": "./python -m unittest -v test.test_type_aliases.TypeParamsInvalidTest.test_name_collision_01", + "fixture_taint_checked": true + }, + "test.test_type_aliases.TypeParamsInvalidTest.test_name_non_collision_02": { + "system_reason": "PEP-695 type-alias test. exec()s `type Alias[T] = ...` source \u2192 pre-state SyntaxError.", + "public_surface": "exec()/run_code() on `type Alias[T] = ...` source + typing.TypeAliasType public API", + "internal_symbol_check": [ + "_PyTypeAlias_*", + "_PyTypeVar_*", + "INTRINSIC_SET_FUNCTION_TYPE_PARAMS" + ], + "uses_allowlisted_private": [], + "runner_surface": "./python -m unittest -v test.test_type_aliases.TypeParamsInvalidTest.test_name_non_collision_02", + "fixture_taint_checked": true + }, + "test.test_type_aliases.TypeParamsInvalidTest.test_name_non_collision_03": { + "system_reason": "PEP-695 type-alias test. exec()s `type Alias[T] = ...` source \u2192 pre-state SyntaxError.", + "public_surface": "exec()/run_code() on `type Alias[T] = ...` source + typing.TypeAliasType public API", + "internal_symbol_check": [ + "_PyTypeAlias_*", + "_PyTypeVar_*", + "INTRINSIC_SET_FUNCTION_TYPE_PARAMS" + ], + "uses_allowlisted_private": [], + "runner_surface": "./python -m unittest -v test.test_type_aliases.TypeParamsInvalidTest.test_name_non_collision_03", + "fixture_taint_checked": true + }, + "test.test_type_aliases.TypeParamsAccessTest.test_alias_access_01": { + "system_reason": "PEP-695 type-alias test. exec()s `type Alias[T] = ...` source \u2192 pre-state SyntaxError.", + "public_surface": "exec()/run_code() on `type Alias[T] = ...` source + typing.TypeAliasType public API", + "internal_symbol_check": [ + "_PyTypeAlias_*", + "_PyTypeVar_*", + "INTRINSIC_SET_FUNCTION_TYPE_PARAMS" + ], + "uses_allowlisted_private": [], + "runner_surface": "./python -m unittest -v test.test_type_aliases.TypeParamsAccessTest.test_alias_access_01", + "fixture_taint_checked": true + }, + "test.test_type_aliases.TypeParamsAccessTest.test_alias_access_02": { + "system_reason": "PEP-695 type-alias test. exec()s `type Alias[T] = ...` source \u2192 pre-state SyntaxError.", + "public_surface": "exec()/run_code() on `type Alias[T] = ...` source + typing.TypeAliasType public API", + "internal_symbol_check": [ + "_PyTypeAlias_*", + "_PyTypeVar_*", + "INTRINSIC_SET_FUNCTION_TYPE_PARAMS" + ], + "uses_allowlisted_private": [], + "runner_surface": "./python -m unittest -v test.test_type_aliases.TypeParamsAccessTest.test_alias_access_02", + "fixture_taint_checked": true + }, + "test.test_type_aliases.TypeParamsAccessTest.test_alias_access_03": { + "system_reason": "PEP-695 type-alias test. exec()s `type Alias[T] = ...` source \u2192 pre-state SyntaxError.", + "public_surface": "exec()/run_code() on `type Alias[T] = ...` source + typing.TypeAliasType public API", + "internal_symbol_check": [ + "_PyTypeAlias_*", + "_PyTypeVar_*", + "INTRINSIC_SET_FUNCTION_TYPE_PARAMS" + ], + "uses_allowlisted_private": [], + "runner_surface": "./python -m unittest -v test.test_type_aliases.TypeParamsAccessTest.test_alias_access_03", + "fixture_taint_checked": true + }, + "test.test_type_aliases.TypeParamsAliasValueTest.test_alias_value_01": { + "system_reason": "PEP-695 type-alias test. exec()s `type Alias[T] = ...` source \u2192 pre-state SyntaxError.", + "public_surface": "exec()/run_code() on `type Alias[T] = ...` source + typing.TypeAliasType public API", + "internal_symbol_check": [ + "_PyTypeAlias_*", + "_PyTypeVar_*", + "INTRINSIC_SET_FUNCTION_TYPE_PARAMS" + ], + "uses_allowlisted_private": [], + "runner_surface": "./python -m unittest -v test.test_type_aliases.TypeParamsAliasValueTest.test_alias_value_01", + "fixture_taint_checked": true + }, + "test.test_type_aliases.TypeParamsAliasValueTest.test_alias_value_02": { + "system_reason": "PEP-695 type-alias test. exec()s `type Alias[T] = ...` source \u2192 pre-state SyntaxError.", + "public_surface": "exec()/run_code() on `type Alias[T] = ...` source + typing.TypeAliasType public API", + "internal_symbol_check": [ + "_PyTypeAlias_*", + "_PyTypeVar_*", + "INTRINSIC_SET_FUNCTION_TYPE_PARAMS" + ], + "uses_allowlisted_private": [], + "runner_surface": "./python -m unittest -v test.test_type_aliases.TypeParamsAliasValueTest.test_alias_value_02", + "fixture_taint_checked": true + }, + "test.test_type_aliases.TypeParamsAliasValueTest.test_alias_value_03": { + "system_reason": "PEP-695 type-alias test. exec()s `type Alias[T] = ...` source \u2192 pre-state SyntaxError.", + "public_surface": "exec()/run_code() on `type Alias[T] = ...` source + typing.TypeAliasType public API", + "internal_symbol_check": [ + "_PyTypeAlias_*", + "_PyTypeVar_*", + "INTRINSIC_SET_FUNCTION_TYPE_PARAMS" + ], + "uses_allowlisted_private": [], + "runner_surface": "./python -m unittest -v test.test_type_aliases.TypeParamsAliasValueTest.test_alias_value_03", + "fixture_taint_checked": true + }, + "test.test_type_aliases.TypeParamsAliasValueTest.test_alias_value_04": { + "system_reason": "PEP-695 type-alias test. exec()s `type Alias[T] = ...` source \u2192 pre-state SyntaxError.", + "public_surface": "exec()/run_code() on `type Alias[T] = ...` source + typing.TypeAliasType public API", + "internal_symbol_check": [ + "_PyTypeAlias_*", + "_PyTypeVar_*", + "INTRINSIC_SET_FUNCTION_TYPE_PARAMS" + ], + "uses_allowlisted_private": [], + "runner_surface": "./python -m unittest -v test.test_type_aliases.TypeParamsAliasValueTest.test_alias_value_04", + "fixture_taint_checked": true + }, + "test.test_type_aliases.TypeParamsAliasValueTest.test_subscripting": { + "system_reason": "PEP-695 type-alias test. exec()s `type Alias[T] = ...` source \u2192 pre-state SyntaxError.", + "public_surface": "exec()/run_code() on `type Alias[T] = ...` source + typing.TypeAliasType public API", + "internal_symbol_check": [ + "_PyTypeAlias_*", + "_PyTypeVar_*", + "INTRINSIC_SET_FUNCTION_TYPE_PARAMS" + ], + "uses_allowlisted_private": [], + "runner_surface": "./python -m unittest -v test.test_type_aliases.TypeParamsAliasValueTest.test_subscripting", + "fixture_taint_checked": true + }, + "test.test_type_aliases.TypeParamsAliasValueTest.test_repr": { + "system_reason": "PEP-695 type-alias test. exec()s `type Alias[T] = ...` source \u2192 pre-state SyntaxError.", + "public_surface": "exec()/run_code() on `type Alias[T] = ...` source + typing.TypeAliasType public API", + "internal_symbol_check": [ + "_PyTypeAlias_*", + "_PyTypeVar_*", + "INTRINSIC_SET_FUNCTION_TYPE_PARAMS" + ], + "uses_allowlisted_private": [], + "runner_surface": "./python -m unittest -v test.test_type_aliases.TypeParamsAliasValueTest.test_repr", + "fixture_taint_checked": true + }, + "test.test_type_aliases.TypeParamsAliasValueTest.test_recursive_repr": { + "system_reason": "PEP-695 type-alias test. exec()s `type Alias[T] = ...` source \u2192 pre-state SyntaxError.", + "public_surface": "exec()/run_code() on `type Alias[T] = ...` source + typing.TypeAliasType public API", + "internal_symbol_check": [ + "_PyTypeAlias_*", + "_PyTypeVar_*", + "INTRINSIC_SET_FUNCTION_TYPE_PARAMS" + ], + "uses_allowlisted_private": [], + "runner_surface": "./python -m unittest -v test.test_type_aliases.TypeParamsAliasValueTest.test_recursive_repr", + "fixture_taint_checked": true + }, + "test.test_type_aliases.TypeAliasConstructorTest.test_basic": { + "system_reason": "PEP-695 type-alias test. exec()s `type Alias[T] = ...` source \u2192 pre-state SyntaxError.", + "public_surface": "exec()/run_code() on `type Alias[T] = ...` source + typing.TypeAliasType public API", + "internal_symbol_check": [ + "_PyTypeAlias_*", + "_PyTypeVar_*", + "INTRINSIC_SET_FUNCTION_TYPE_PARAMS" + ], + "uses_allowlisted_private": [], + "runner_surface": "./python -m unittest -v test.test_type_aliases.TypeAliasConstructorTest.test_basic", + "fixture_taint_checked": true + }, + "test.test_type_aliases.TypeAliasConstructorTest.test_generic": { + "system_reason": "PEP-695 type-alias test. exec()s `type Alias[T] = ...` source \u2192 pre-state SyntaxError.", + "public_surface": "exec()/run_code() on `type Alias[T] = ...` source + typing.TypeAliasType public API", + "internal_symbol_check": [ + "_PyTypeAlias_*", + "_PyTypeVar_*", + "INTRINSIC_SET_FUNCTION_TYPE_PARAMS" + ], + "uses_allowlisted_private": [], + "runner_surface": "./python -m unittest -v test.test_type_aliases.TypeAliasConstructorTest.test_generic", + "fixture_taint_checked": true + }, + "test.test_type_aliases.TypeAliasConstructorTest.test_keywords": { + "system_reason": "PEP-695 type-alias test. exec()s `type Alias[T] = ...` source \u2192 pre-state SyntaxError.", + "public_surface": "exec()/run_code() on `type Alias[T] = ...` source + typing.TypeAliasType public API", + "internal_symbol_check": [ + "_PyTypeAlias_*", + "_PyTypeVar_*", + "INTRINSIC_SET_FUNCTION_TYPE_PARAMS" + ], + "uses_allowlisted_private": [], + "runner_surface": "./python -m unittest -v test.test_type_aliases.TypeAliasConstructorTest.test_keywords", + "fixture_taint_checked": true + }, + "test.test_type_aliases.TypeAliasConstructorTest.test_errors": { + "system_reason": "PEP-695 type-alias test. exec()s `type Alias[T] = ...` source \u2192 pre-state SyntaxError.", + "public_surface": "exec()/run_code() on `type Alias[T] = ...` source + typing.TypeAliasType public API", + "internal_symbol_check": [ + "_PyTypeAlias_*", + "_PyTypeVar_*", + "INTRINSIC_SET_FUNCTION_TYPE_PARAMS" + ], + "uses_allowlisted_private": [], + "runner_surface": "./python -m unittest -v test.test_type_aliases.TypeAliasConstructorTest.test_errors", + "fixture_taint_checked": true + }, + "test.test_type_aliases.TypeAliasTypeTest.test_immutable": { + "system_reason": "PEP-695 type-alias test. exec()s `type Alias[T] = ...` source \u2192 pre-state SyntaxError.", + "public_surface": "exec()/run_code() on `type Alias[T] = ...` source + typing.TypeAliasType public API", + "internal_symbol_check": [ + "_PyTypeAlias_*", + "_PyTypeVar_*", + "INTRINSIC_SET_FUNCTION_TYPE_PARAMS" + ], + "uses_allowlisted_private": [], + "runner_surface": "./python -m unittest -v test.test_type_aliases.TypeAliasTypeTest.test_immutable", + "fixture_taint_checked": true + }, + "test.test_type_aliases.TypeAliasTypeTest.test_no_subclassing": { + "system_reason": "PEP-695 type-alias test. exec()s `type Alias[T] = ...` source \u2192 pre-state SyntaxError.", + "public_surface": "exec()/run_code() on `type Alias[T] = ...` source + typing.TypeAliasType public API", + "internal_symbol_check": [ + "_PyTypeAlias_*", + "_PyTypeVar_*", + "INTRINSIC_SET_FUNCTION_TYPE_PARAMS" + ], + "uses_allowlisted_private": [], + "runner_surface": "./python -m unittest -v test.test_type_aliases.TypeAliasTypeTest.test_no_subclassing", + "fixture_taint_checked": true + }, + "test.test_type_aliases.TypeAliasTypeTest.test_union": { + "system_reason": "PEP-695 type-alias test. exec()s `type Alias[T] = ...` source \u2192 pre-state SyntaxError.", + "public_surface": "exec()/run_code() on `type Alias[T] = ...` source + typing.TypeAliasType public API", + "internal_symbol_check": [ + "_PyTypeAlias_*", + "_PyTypeVar_*", + "INTRINSIC_SET_FUNCTION_TYPE_PARAMS" + ], + "uses_allowlisted_private": [], + "runner_surface": "./python -m unittest -v test.test_type_aliases.TypeAliasTypeTest.test_union", + "fixture_taint_checked": true + }, + "test.test_ast.AST_Tests.test_type_params_feature_version": { + "system_reason": "ast.parse feature_version gating of `class X[T]:` syntax.", + "public_surface": "ast.parse(source, feature_version=...)", + "internal_symbol_check": [ + "_PyTypeAlias_*", + "_PyTypeVar_*", + "INTRINSIC_SET_FUNCTION_TYPE_PARAMS" + ], + "uses_allowlisted_private": [], + "runner_surface": "./python -m unittest -v test.test_ast.AST_Tests.test_type_params_feature_version", + "fixture_taint_checked": true + } + }, + "pass_to_pass": { + "test.test_grammar.TokenTests.test_backslash": { + "system_reason": "Pre-existing grammar test. test_grammar.py is NOT modified by this PR.", + "public_surface": "compile()/exec() on source", + "internal_symbol_check": [], + "uses_allowlisted_private": [], + "runner_surface": "./python -m unittest -v test.test_grammar.TokenTests.test_backslash", + "fixture_taint_checked": true + }, + "test.test_grammar.TokenTests.test_plain_integers": { + "system_reason": "Pre-existing grammar test. test_grammar.py is NOT modified by this PR.", + "public_surface": "compile()/exec() on source", + "internal_symbol_check": [], + "uses_allowlisted_private": [], + "runner_surface": "./python -m unittest -v test.test_grammar.TokenTests.test_plain_integers", + "fixture_taint_checked": true + }, + "test.test_grammar.TokenTests.test_long_integers": { + "system_reason": "Pre-existing grammar test. test_grammar.py is NOT modified by this PR.", + "public_surface": "compile()/exec() on source", + "internal_symbol_check": [], + "uses_allowlisted_private": [], + "runner_surface": "./python -m unittest -v test.test_grammar.TokenTests.test_long_integers", + "fixture_taint_checked": true + }, + "test.test_grammar.TokenTests.test_floats": { + "system_reason": "Pre-existing grammar test. test_grammar.py is NOT modified by this PR.", + "public_surface": "compile()/exec() on source", + "internal_symbol_check": [], + "uses_allowlisted_private": [], + "runner_surface": "./python -m unittest -v test.test_grammar.TokenTests.test_floats", + "fixture_taint_checked": true + }, + "test.test_grammar.TokenTests.test_underscore_literals": { + "system_reason": "Pre-existing grammar test. test_grammar.py is NOT modified by this PR.", + "public_surface": "compile()/exec() on source", + "internal_symbol_check": [], + "uses_allowlisted_private": [], + "runner_surface": "./python -m unittest -v test.test_grammar.TokenTests.test_underscore_literals", + "fixture_taint_checked": true + }, + "test.test_grammar.TokenTests.test_string_literals": { + "system_reason": "Pre-existing grammar test. test_grammar.py is NOT modified by this PR.", + "public_surface": "compile()/exec() on source", + "internal_symbol_check": [], + "uses_allowlisted_private": [], + "runner_surface": "./python -m unittest -v test.test_grammar.TokenTests.test_string_literals", + "fixture_taint_checked": true + }, + "test.test_grammar.TokenTests.test_ellipsis": { + "system_reason": "Pre-existing grammar test. test_grammar.py is NOT modified by this PR.", + "public_surface": "compile()/exec() on source", + "internal_symbol_check": [], + "uses_allowlisted_private": [], + "runner_surface": "./python -m unittest -v test.test_grammar.TokenTests.test_ellipsis", + "fixture_taint_checked": true + }, + "test.test_grammar.GrammarTests.test_funcdef": { + "system_reason": "Pre-existing grammar test. test_grammar.py is NOT modified by this PR.", + "public_surface": "compile()/exec() on source", + "internal_symbol_check": [], + "uses_allowlisted_private": [], + "runner_surface": "./python -m unittest -v test.test_grammar.GrammarTests.test_funcdef", + "fixture_taint_checked": true + }, + "test.test_grammar.GrammarTests.test_lambdef": { + "system_reason": "Pre-existing grammar test. test_grammar.py is NOT modified by this PR.", + "public_surface": "compile()/exec() on source", + "internal_symbol_check": [], + "uses_allowlisted_private": [], + "runner_surface": "./python -m unittest -v test.test_grammar.GrammarTests.test_lambdef", + "fixture_taint_checked": true + }, + "test.test_grammar.GrammarTests.test_simple_stmt": { + "system_reason": "Pre-existing grammar test. test_grammar.py is NOT modified by this PR.", + "public_surface": "compile()/exec() on source", + "internal_symbol_check": [], + "uses_allowlisted_private": [], + "runner_surface": "./python -m unittest -v test.test_grammar.GrammarTests.test_simple_stmt", + "fixture_taint_checked": true + }, + "test.test_grammar.GrammarTests.test_expr_stmt": { + "system_reason": "Pre-existing grammar test. test_grammar.py is NOT modified by this PR.", + "public_surface": "compile()/exec() on source", + "internal_symbol_check": [], + "uses_allowlisted_private": [], + "runner_surface": "./python -m unittest -v test.test_grammar.GrammarTests.test_expr_stmt", + "fixture_taint_checked": true + }, + "test.test_grammar.GrammarTests.test_del_stmt": { + "system_reason": "Pre-existing grammar test. test_grammar.py is NOT modified by this PR.", + "public_surface": "compile()/exec() on source", + "internal_symbol_check": [], + "uses_allowlisted_private": [], + "runner_surface": "./python -m unittest -v test.test_grammar.GrammarTests.test_del_stmt", + "fixture_taint_checked": true + }, + "test.test_grammar.GrammarTests.test_pass_stmt": { + "system_reason": "Pre-existing grammar test. test_grammar.py is NOT modified by this PR.", + "public_surface": "compile()/exec() on source", + "internal_symbol_check": [], + "uses_allowlisted_private": [], + "runner_surface": "./python -m unittest -v test.test_grammar.GrammarTests.test_pass_stmt", + "fixture_taint_checked": true + }, + "test.test_grammar.GrammarTests.test_break_stmt": { + "system_reason": "Pre-existing grammar test. test_grammar.py is NOT modified by this PR.", + "public_surface": "compile()/exec() on source", + "internal_symbol_check": [], + "uses_allowlisted_private": [], + "runner_surface": "./python -m unittest -v test.test_grammar.GrammarTests.test_break_stmt", + "fixture_taint_checked": true + }, + "test.test_grammar.GrammarTests.test_continue_stmt": { + "system_reason": "Pre-existing grammar test. test_grammar.py is NOT modified by this PR.", + "public_surface": "compile()/exec() on source", + "internal_symbol_check": [], + "uses_allowlisted_private": [], + "runner_surface": "./python -m unittest -v test.test_grammar.GrammarTests.test_continue_stmt", + "fixture_taint_checked": true + }, + "test.test_grammar.GrammarTests.test_return": { + "system_reason": "Pre-existing grammar test. test_grammar.py is NOT modified by this PR.", + "public_surface": "compile()/exec() on source", + "internal_symbol_check": [], + "uses_allowlisted_private": [], + "runner_surface": "./python -m unittest -v test.test_grammar.GrammarTests.test_return", + "fixture_taint_checked": true + }, + "test.test_grammar.GrammarTests.test_yield": { + "system_reason": "Pre-existing grammar test. test_grammar.py is NOT modified by this PR.", + "public_surface": "compile()/exec() on source", + "internal_symbol_check": [], + "uses_allowlisted_private": [], + "runner_surface": "./python -m unittest -v test.test_grammar.GrammarTests.test_yield", + "fixture_taint_checked": true + }, + "test.test_grammar.GrammarTests.test_raise": { + "system_reason": "Pre-existing grammar test. test_grammar.py is NOT modified by this PR.", + "public_surface": "compile()/exec() on source", + "internal_symbol_check": [], + "uses_allowlisted_private": [], + "runner_surface": "./python -m unittest -v test.test_grammar.GrammarTests.test_raise", + "fixture_taint_checked": true + }, + "test.test_grammar.GrammarTests.test_import": { + "system_reason": "Pre-existing grammar test. test_grammar.py is NOT modified by this PR.", + "public_surface": "compile()/exec() on source", + "internal_symbol_check": [], + "uses_allowlisted_private": [], + "runner_surface": "./python -m unittest -v test.test_grammar.GrammarTests.test_import", + "fixture_taint_checked": true + }, + "test.test_grammar.GrammarTests.test_global": { + "system_reason": "Pre-existing grammar test. test_grammar.py is NOT modified by this PR.", + "public_surface": "compile()/exec() on source", + "internal_symbol_check": [], + "uses_allowlisted_private": [], + "runner_surface": "./python -m unittest -v test.test_grammar.GrammarTests.test_global", + "fixture_taint_checked": true + }, + "test.test_grammar.GrammarTests.test_nonlocal": { + "system_reason": "Pre-existing grammar test. test_grammar.py is NOT modified by this PR.", + "public_surface": "compile()/exec() on source", + "internal_symbol_check": [], + "uses_allowlisted_private": [], + "runner_surface": "./python -m unittest -v test.test_grammar.GrammarTests.test_nonlocal", + "fixture_taint_checked": true + }, + "test.test_grammar.GrammarTests.test_assert": { + "system_reason": "Pre-existing grammar test. test_grammar.py is NOT modified by this PR.", + "public_surface": "compile()/exec() on source", + "internal_symbol_check": [], + "uses_allowlisted_private": [], + "runner_surface": "./python -m unittest -v test.test_grammar.GrammarTests.test_assert", + "fixture_taint_checked": true + }, + "test.test_grammar.GrammarTests.test_if": { + "system_reason": "Pre-existing grammar test. test_grammar.py is NOT modified by this PR.", + "public_surface": "compile()/exec() on source", + "internal_symbol_check": [], + "uses_allowlisted_private": [], + "runner_surface": "./python -m unittest -v test.test_grammar.GrammarTests.test_if", + "fixture_taint_checked": true + }, + "test.test_grammar.GrammarTests.test_while": { + "system_reason": "Pre-existing grammar test. test_grammar.py is NOT modified by this PR.", + "public_surface": "compile()/exec() on source", + "internal_symbol_check": [], + "uses_allowlisted_private": [], + "runner_surface": "./python -m unittest -v test.test_grammar.GrammarTests.test_while", + "fixture_taint_checked": true + }, + "test.test_grammar.GrammarTests.test_for": { + "system_reason": "Pre-existing grammar test. test_grammar.py is NOT modified by this PR.", + "public_surface": "compile()/exec() on source", + "internal_symbol_check": [], + "uses_allowlisted_private": [], + "runner_surface": "./python -m unittest -v test.test_grammar.GrammarTests.test_for", + "fixture_taint_checked": true + }, + "test.test_grammar.GrammarTests.test_classdef": { + "system_reason": "Pre-existing grammar test. test_grammar.py is NOT modified by this PR.", + "public_surface": "compile()/exec() on source", + "internal_symbol_check": [], + "uses_allowlisted_private": [], + "runner_surface": "./python -m unittest -v test.test_grammar.GrammarTests.test_classdef", + "fixture_taint_checked": true + }, + "test.test_grammar.GrammarTests.test_atoms": { + "system_reason": "Pre-existing grammar test. test_grammar.py is NOT modified by this PR.", + "public_surface": "compile()/exec() on source", + "internal_symbol_check": [], + "uses_allowlisted_private": [], + "runner_surface": "./python -m unittest -v test.test_grammar.GrammarTests.test_atoms", + "fixture_taint_checked": true + }, + "test.test_grammar.GrammarTests.test_var_annot_basics": { + "system_reason": "Pre-existing grammar test. test_grammar.py is NOT modified by this PR.", + "public_surface": "compile()/exec() on source", + "internal_symbol_check": [], + "uses_allowlisted_private": [], + "runner_surface": "./python -m unittest -v test.test_grammar.GrammarTests.test_var_annot_basics", + "fixture_taint_checked": true + }, + "test.test_grammar.GrammarTests.test_var_annot_syntax_errors": { + "system_reason": "Pre-existing grammar test. test_grammar.py is NOT modified by this PR.", + "public_surface": "compile()/exec() on source", + "internal_symbol_check": [], + "uses_allowlisted_private": [], + "runner_surface": "./python -m unittest -v test.test_grammar.GrammarTests.test_var_annot_syntax_errors", + "fixture_taint_checked": true + }, + "test.test_grammar.GrammarTests.test_var_annot_simple_exec": { + "system_reason": "Pre-existing grammar test. test_grammar.py is NOT modified by this PR.", + "public_surface": "compile()/exec() on source", + "internal_symbol_check": [], + "uses_allowlisted_private": [], + "runner_surface": "./python -m unittest -v test.test_grammar.GrammarTests.test_var_annot_simple_exec", + "fixture_taint_checked": true + }, + "test.test_int.IntTestCases.test_basic": { + "system_reason": "Pre-existing int test. test_int.py is NOT modified by this PR.", + "public_surface": "int() public API", + "internal_symbol_check": [], + "uses_allowlisted_private": [], + "runner_surface": "./python -m unittest -v test.test_int.IntTestCases.test_basic", + "fixture_taint_checked": true + }, + "test.test_int.IntTestCases.test_invalid_signs": { + "system_reason": "Pre-existing int test. test_int.py is NOT modified by this PR.", + "public_surface": "int() public API", + "internal_symbol_check": [], + "uses_allowlisted_private": [], + "runner_surface": "./python -m unittest -v test.test_int.IntTestCases.test_invalid_signs", + "fixture_taint_checked": true + }, + "test.test_int.IntTestCases.test_unicode": { + "system_reason": "Pre-existing int test. test_int.py is NOT modified by this PR.", + "public_surface": "int() public API", + "internal_symbol_check": [], + "uses_allowlisted_private": [], + "runner_surface": "./python -m unittest -v test.test_int.IntTestCases.test_unicode", + "fixture_taint_checked": true + }, + "test.test_int.IntTestCases.test_underscores": { + "system_reason": "Pre-existing int test. test_int.py is NOT modified by this PR.", + "public_surface": "int() public API", + "internal_symbol_check": [], + "uses_allowlisted_private": [], + "runner_surface": "./python -m unittest -v test.test_int.IntTestCases.test_underscores", + "fixture_taint_checked": true + }, + "test.test_int.IntTestCases.test_small_ints": { + "system_reason": "Pre-existing int test. test_int.py is NOT modified by this PR.", + "public_surface": "int() public API", + "internal_symbol_check": [], + "uses_allowlisted_private": [], + "runner_surface": "./python -m unittest -v test.test_int.IntTestCases.test_small_ints", + "fixture_taint_checked": true + }, + "test.test_int.IntStrDigitLimitsTests.test_disabled_limit": { + "system_reason": "Pre-existing int test. test_int.py is NOT modified by this PR.", + "public_surface": "int() public API", + "internal_symbol_check": [], + "uses_allowlisted_private": [], + "runner_surface": "./python -m unittest -v test.test_int.IntStrDigitLimitsTests.test_disabled_limit", + "fixture_taint_checked": true + }, + "test.test_int.IntStrDigitLimitsTests.test_max_str_digits_edge_cases": { + "system_reason": "Pre-existing int test. test_int.py is NOT modified by this PR.", + "public_surface": "int() public API", + "internal_symbol_check": [], + "uses_allowlisted_private": [], + "runner_surface": "./python -m unittest -v test.test_int.IntStrDigitLimitsTests.test_max_str_digits_edge_cases", + "fixture_taint_checked": true + }, + "test.test_int.IntStrDigitLimitsTests.test_max_str_digits": { + "system_reason": "Pre-existing int test. test_int.py is NOT modified by this PR.", + "public_surface": "int() public API", + "internal_symbol_check": [], + "uses_allowlisted_private": [], + "runner_surface": "./python -m unittest -v test.test_int.IntStrDigitLimitsTests.test_max_str_digits", + "fixture_taint_checked": true + }, + "test.test_float.GeneralFloatCases.test_float": { + "system_reason": "Pre-existing float test. test_float.py is NOT modified by this PR.", + "public_surface": "float() public API", + "internal_symbol_check": [], + "uses_allowlisted_private": [], + "runner_surface": "./python -m unittest -v test.test_float.GeneralFloatCases.test_float", + "fixture_taint_checked": true + }, + "test.test_float.GeneralFloatCases.test_noargs": { + "system_reason": "Pre-existing float test. test_float.py is NOT modified by this PR.", + "public_surface": "float() public API", + "internal_symbol_check": [], + "uses_allowlisted_private": [], + "runner_surface": "./python -m unittest -v test.test_float.GeneralFloatCases.test_noargs", + "fixture_taint_checked": true + }, + "test.test_float.GeneralFloatCases.test_underscores": { + "system_reason": "Pre-existing float test. test_float.py is NOT modified by this PR.", + "public_surface": "float() public API", + "internal_symbol_check": [], + "uses_allowlisted_private": [], + "runner_surface": "./python -m unittest -v test.test_float.GeneralFloatCases.test_underscores", + "fixture_taint_checked": true + }, + "test.test_float.GeneralFloatCases.test_non_numeric_input_types": { + "system_reason": "Pre-existing float test. test_float.py is NOT modified by this PR.", + "public_surface": "float() public API", + "internal_symbol_check": [], + "uses_allowlisted_private": [], + "runner_surface": "./python -m unittest -v test.test_float.GeneralFloatCases.test_non_numeric_input_types", + "fixture_taint_checked": true + }, + "test.test_float.GeneralFloatCases.test_float_memoryview": { + "system_reason": "Pre-existing float test. test_float.py is NOT modified by this PR.", + "public_surface": "float() public API", + "internal_symbol_check": [], + "uses_allowlisted_private": [], + "runner_surface": "./python -m unittest -v test.test_float.GeneralFloatCases.test_float_memoryview", + "fixture_taint_checked": true + }, + "test.test_float.IEEEFormatTestCase.test_double_specials_do_unpack": { + "system_reason": "Pre-existing float test. test_float.py is NOT modified by this PR.", + "public_surface": "float() public API", + "internal_symbol_check": [], + "uses_allowlisted_private": [], + "runner_surface": "./python -m unittest -v test.test_float.IEEEFormatTestCase.test_double_specials_do_unpack", + "fixture_taint_checked": true + }, + "test.test_float.IEEEFormatTestCase.test_float_specials_do_unpack": { + "system_reason": "Pre-existing float test. test_float.py is NOT modified by this PR.", + "public_surface": "float() public API", + "internal_symbol_check": [], + "uses_allowlisted_private": [], + "runner_surface": "./python -m unittest -v test.test_float.IEEEFormatTestCase.test_float_specials_do_unpack", + "fixture_taint_checked": true + }, + "test.test_float.IEEEFormatTestCase.test_serialized_float_rounding": { + "system_reason": "Pre-existing float test. test_float.py is NOT modified by this PR.", + "public_surface": "float() public API", + "internal_symbol_check": [], + "uses_allowlisted_private": [], + "runner_surface": "./python -m unittest -v test.test_float.IEEEFormatTestCase.test_serialized_float_rounding", + "fixture_taint_checked": true + }, + "test.test_float.FormatFunctionsTestCase.test_getformat": { + "system_reason": "Pre-existing float test. test_float.py is NOT modified by this PR.", + "public_surface": "float() public API", + "internal_symbol_check": [], + "uses_allowlisted_private": [], + "runner_surface": "./python -m unittest -v test.test_float.FormatFunctionsTestCase.test_getformat", + "fixture_taint_checked": true + }, + "test.test_string.ModuleTest.test_attrs": { + "system_reason": "Pre-existing string test. test_string.py is NOT modified by this PR.", + "public_surface": "string module public API", + "internal_symbol_check": [], + "uses_allowlisted_private": [], + "runner_surface": "./python -m unittest -v test.test_string.ModuleTest.test_attrs", + "fixture_taint_checked": true + }, + "test.test_string.ModuleTest.test_capwords": { + "system_reason": "Pre-existing string test. test_string.py is NOT modified by this PR.", + "public_surface": "string module public API", + "internal_symbol_check": [], + "uses_allowlisted_private": [], + "runner_surface": "./python -m unittest -v test.test_string.ModuleTest.test_capwords", + "fixture_taint_checked": true + }, + "test.test_string.ModuleTest.test_basic_formatter": { + "system_reason": "Pre-existing string test. test_string.py is NOT modified by this PR.", + "public_surface": "string module public API", + "internal_symbol_check": [], + "uses_allowlisted_private": [], + "runner_surface": "./python -m unittest -v test.test_string.ModuleTest.test_basic_formatter", + "fixture_taint_checked": true + }, + "test.test_string.ModuleTest.test_format_keyword_arguments": { + "system_reason": "Pre-existing string test. test_string.py is NOT modified by this PR.", + "public_surface": "string module public API", + "internal_symbol_check": [], + "uses_allowlisted_private": [], + "runner_surface": "./python -m unittest -v test.test_string.ModuleTest.test_format_keyword_arguments", + "fixture_taint_checked": true + }, + "test.test_string.ModuleTest.test_auto_numbering": { + "system_reason": "Pre-existing string test. test_string.py is NOT modified by this PR.", + "public_surface": "string module public API", + "internal_symbol_check": [], + "uses_allowlisted_private": [], + "runner_surface": "./python -m unittest -v test.test_string.ModuleTest.test_auto_numbering", + "fixture_taint_checked": true + }, + "test.test_string.TestTemplate.test_regular_templates": { + "system_reason": "Pre-existing string test. test_string.py is NOT modified by this PR.", + "public_surface": "string module public API", + "internal_symbol_check": [], + "uses_allowlisted_private": [], + "runner_surface": "./python -m unittest -v test.test_string.TestTemplate.test_regular_templates", + "fixture_taint_checked": true + }, + "test.test_string.TestTemplate.test_regular_templates_with_braces": { + "system_reason": "Pre-existing string test. test_string.py is NOT modified by this PR.", + "public_surface": "string module public API", + "internal_symbol_check": [], + "uses_allowlisted_private": [], + "runner_surface": "./python -m unittest -v test.test_string.TestTemplate.test_regular_templates_with_braces", + "fixture_taint_checked": true + }, + "test.test_string.TestTemplate.test_regular_templates_with_upper_case": { + "system_reason": "Pre-existing string test. test_string.py is NOT modified by this PR.", + "public_surface": "string module public API", + "internal_symbol_check": [], + "uses_allowlisted_private": [], + "runner_surface": "./python -m unittest -v test.test_string.TestTemplate.test_regular_templates_with_upper_case", + "fixture_taint_checked": true + }, + "test.test_string.TestTemplate.test_regular_templates_with_non_letters": { + "system_reason": "Pre-existing string test. test_string.py is NOT modified by this PR.", + "public_surface": "string module public API", + "internal_symbol_check": [], + "uses_allowlisted_private": [], + "runner_surface": "./python -m unittest -v test.test_string.TestTemplate.test_regular_templates_with_non_letters", + "fixture_taint_checked": true + }, + "test.test_string.TestTemplate.test_escapes": { + "system_reason": "Pre-existing string test. test_string.py is NOT modified by this PR.", + "public_surface": "string module public API", + "internal_symbol_check": [], + "uses_allowlisted_private": [], + "runner_surface": "./python -m unittest -v test.test_string.TestTemplate.test_escapes", + "fixture_taint_checked": true + }, + "test.test_calendar.OutputTestCase.test_formatmonth": { + "system_reason": "Pre-existing calendar test. test_calendar.py is NOT modified by this PR.", + "public_surface": "calendar public API", + "internal_symbol_check": [], + "uses_allowlisted_private": [], + "runner_surface": "./python -m unittest -v test.test_calendar.OutputTestCase.test_formatmonth", + "fixture_taint_checked": true + }, + "test.test_calendar.OutputTestCase.test_formatmonthname_with_year": { + "system_reason": "Pre-existing calendar test. test_calendar.py is NOT modified by this PR.", + "public_surface": "calendar public API", + "internal_symbol_check": [], + "uses_allowlisted_private": [], + "runner_surface": "./python -m unittest -v test.test_calendar.OutputTestCase.test_formatmonthname_with_year", + "fixture_taint_checked": true + }, + "test.test_calendar.OutputTestCase.test_prweek": { + "system_reason": "Pre-existing calendar test. test_calendar.py is NOT modified by this PR.", + "public_surface": "calendar public API", + "internal_symbol_check": [], + "uses_allowlisted_private": [], + "runner_surface": "./python -m unittest -v test.test_calendar.OutputTestCase.test_prweek", + "fixture_taint_checked": true + }, + "test.test_calendar.OutputTestCase.test_formatweekheader_short": { + "system_reason": "Pre-existing calendar test. test_calendar.py is NOT modified by this PR.", + "public_surface": "calendar public API", + "internal_symbol_check": [], + "uses_allowlisted_private": [], + "runner_surface": "./python -m unittest -v test.test_calendar.OutputTestCase.test_formatweekheader_short", + "fixture_taint_checked": true + }, + "test.test_calendar.OutputTestCase.test_prmonth": { + "system_reason": "Pre-existing calendar test. test_calendar.py is NOT modified by this PR.", + "public_surface": "calendar public API", + "internal_symbol_check": [], + "uses_allowlisted_private": [], + "runner_surface": "./python -m unittest -v test.test_calendar.OutputTestCase.test_prmonth", + "fixture_taint_checked": true + }, + "test.test_calendar.CalendarTestCase.test_isleap": { + "system_reason": "Pre-existing calendar test. test_calendar.py is NOT modified by this PR.", + "public_surface": "calendar public API", + "internal_symbol_check": [], + "uses_allowlisted_private": [], + "runner_surface": "./python -m unittest -v test.test_calendar.CalendarTestCase.test_isleap", + "fixture_taint_checked": true + }, + "test.test_calendar.CalendarTestCase.test_setfirstweekday": { + "system_reason": "Pre-existing calendar test. test_calendar.py is NOT modified by this PR.", + "public_surface": "calendar public API", + "internal_symbol_check": [], + "uses_allowlisted_private": [], + "runner_surface": "./python -m unittest -v test.test_calendar.CalendarTestCase.test_setfirstweekday", + "fixture_taint_checked": true + }, + "test.test_calendar.CalendarTestCase.test_illegal_weekday_reported": { + "system_reason": "Pre-existing calendar test. test_calendar.py is NOT modified by this PR.", + "public_surface": "calendar public API", + "internal_symbol_check": [], + "uses_allowlisted_private": [], + "runner_surface": "./python -m unittest -v test.test_calendar.CalendarTestCase.test_illegal_weekday_reported", + "fixture_taint_checked": true + }, + "test.test_calendar.CalendarTestCase.test_enumerate_weekdays": { + "system_reason": "Pre-existing calendar test. test_calendar.py is NOT modified by this PR.", + "public_surface": "calendar public API", + "internal_symbol_check": [], + "uses_allowlisted_private": [], + "runner_surface": "./python -m unittest -v test.test_calendar.CalendarTestCase.test_enumerate_weekdays", + "fixture_taint_checked": true + }, + "test.test_calendar.CalendarTestCase.test_days": { + "system_reason": "Pre-existing calendar test. test_calendar.py is NOT modified by this PR.", + "public_surface": "calendar public API", + "internal_symbol_check": [], + "uses_allowlisted_private": [], + "runner_surface": "./python -m unittest -v test.test_calendar.CalendarTestCase.test_days", + "fixture_taint_checked": true + }, + "test.test_list.ListTest.test_basic": { + "system_reason": "Pre-existing list test. test_list.py is NOT modified by this PR.", + "public_surface": "list builtin", + "internal_symbol_check": [], + "uses_allowlisted_private": [], + "runner_surface": "./python -m unittest -v test.test_list.ListTest.test_basic", + "fixture_taint_checked": true + }, + "test.test_list.ListTest.test_truth": { + "system_reason": "Pre-existing list test. test_list.py is NOT modified by this PR.", + "public_surface": "list builtin", + "internal_symbol_check": [], + "uses_allowlisted_private": [], + "runner_surface": "./python -m unittest -v test.test_list.ListTest.test_truth", + "fixture_taint_checked": true + }, + "test.test_list.ListTest.test_len": { + "system_reason": "Pre-existing list test. test_list.py is NOT modified by this PR.", + "public_surface": "list builtin", + "internal_symbol_check": [], + "uses_allowlisted_private": [], + "runner_surface": "./python -m unittest -v test.test_list.ListTest.test_len", + "fixture_taint_checked": true + }, + "test.test_list.ListTest.test_overflow": { + "system_reason": "Pre-existing list test. test_list.py is NOT modified by this PR.", + "public_surface": "list builtin", + "internal_symbol_check": [], + "uses_allowlisted_private": [], + "runner_surface": "./python -m unittest -v test.test_list.ListTest.test_overflow", + "fixture_taint_checked": true + }, + "test.test_dict.DictTest.test_invalid_keyword_arguments": { + "system_reason": "Pre-existing dict test. test_dict.py is NOT modified by this PR.", + "public_surface": "dict builtin", + "internal_symbol_check": [], + "uses_allowlisted_private": [], + "runner_surface": "./python -m unittest -v test.test_dict.DictTest.test_invalid_keyword_arguments", + "fixture_taint_checked": true + }, + "test.test_dict.DictTest.test_bool": { + "system_reason": "Pre-existing dict test. test_dict.py is NOT modified by this PR.", + "public_surface": "dict builtin", + "internal_symbol_check": [], + "uses_allowlisted_private": [], + "runner_surface": "./python -m unittest -v test.test_dict.DictTest.test_bool", + "fixture_taint_checked": true + }, + "test.test_dict.DictTest.test_keys": { + "system_reason": "Pre-existing dict test. test_dict.py is NOT modified by this PR.", + "public_surface": "dict builtin", + "internal_symbol_check": [], + "uses_allowlisted_private": [], + "runner_surface": "./python -m unittest -v test.test_dict.DictTest.test_keys", + "fixture_taint_checked": true + }, + "test.test_dict.DictTest.test_values": { + "system_reason": "Pre-existing dict test. test_dict.py is NOT modified by this PR.", + "public_surface": "dict builtin", + "internal_symbol_check": [], + "uses_allowlisted_private": [], + "runner_surface": "./python -m unittest -v test.test_dict.DictTest.test_values", + "fixture_taint_checked": true + }, + "test.test_dict.DictTest.test_items": { + "system_reason": "Pre-existing dict test. test_dict.py is NOT modified by this PR.", + "public_surface": "dict builtin", + "internal_symbol_check": [], + "uses_allowlisted_private": [], + "runner_surface": "./python -m unittest -v test.test_dict.DictTest.test_items", + "fixture_taint_checked": true + }, + "test.test_dict.DictTest.test_contains": { + "system_reason": "Pre-existing dict test. test_dict.py is NOT modified by this PR.", + "public_surface": "dict builtin", + "internal_symbol_check": [], + "uses_allowlisted_private": [], + "runner_surface": "./python -m unittest -v test.test_dict.DictTest.test_contains", + "fixture_taint_checked": true + }, + "test.test_dict.DictTest.test_clear": { + "system_reason": "Pre-existing dict test. test_dict.py is NOT modified by this PR.", + "public_surface": "dict builtin", + "internal_symbol_check": [], + "uses_allowlisted_private": [], + "runner_surface": "./python -m unittest -v test.test_dict.DictTest.test_clear", + "fixture_taint_checked": true + }, + "test.test_dict.DictTest.test_update": { + "system_reason": "Pre-existing dict test. test_dict.py is NOT modified by this PR.", + "public_surface": "dict builtin", + "internal_symbol_check": [], + "uses_allowlisted_private": [], + "runner_surface": "./python -m unittest -v test.test_dict.DictTest.test_update", + "fixture_taint_checked": true + }, + "test.test_dict.DictTest.test_fromkeys": { + "system_reason": "Pre-existing dict test. test_dict.py is NOT modified by this PR.", + "public_surface": "dict builtin", + "internal_symbol_check": [], + "uses_allowlisted_private": [], + "runner_surface": "./python -m unittest -v test.test_dict.DictTest.test_fromkeys", + "fixture_taint_checked": true + }, + "test.test_dict.DictTest.test_copy": { + "system_reason": "Pre-existing dict test. test_dict.py is NOT modified by this PR.", + "public_surface": "dict builtin", + "internal_symbol_check": [], + "uses_allowlisted_private": [], + "runner_surface": "./python -m unittest -v test.test_dict.DictTest.test_copy", + "fixture_taint_checked": true + }, + "test.test_set.TestSet.test_init": { + "system_reason": "Pre-existing set test. test_set.py is NOT modified by this PR.", + "public_surface": "set/frozenset builtins", + "internal_symbol_check": [], + "uses_allowlisted_private": [], + "runner_surface": "./python -m unittest -v test.test_set.TestSet.test_init", + "fixture_taint_checked": true + }, + "test.test_set.TestSet.test_constructor_identity": { + "system_reason": "Pre-existing set test. test_set.py is NOT modified by this PR.", + "public_surface": "set/frozenset builtins", + "internal_symbol_check": [], + "uses_allowlisted_private": [], + "runner_surface": "./python -m unittest -v test.test_set.TestSet.test_constructor_identity", + "fixture_taint_checked": true + }, + "test.test_set.TestSet.test_set_literal": { + "system_reason": "Pre-existing set test. test_set.py is NOT modified by this PR.", + "public_surface": "set/frozenset builtins", + "internal_symbol_check": [], + "uses_allowlisted_private": [], + "runner_surface": "./python -m unittest -v test.test_set.TestSet.test_set_literal", + "fixture_taint_checked": true + }, + "test.test_set.TestSet.test_set_literal_insertion_order": { + "system_reason": "Pre-existing set test. test_set.py is NOT modified by this PR.", + "public_surface": "set/frozenset builtins", + "internal_symbol_check": [], + "uses_allowlisted_private": [], + "runner_surface": "./python -m unittest -v test.test_set.TestSet.test_set_literal_insertion_order", + "fixture_taint_checked": true + }, + "test.test_set.TestSet.test_set_literal_evaluation_order": { + "system_reason": "Pre-existing set test. test_set.py is NOT modified by this PR.", + "public_surface": "set/frozenset builtins", + "internal_symbol_check": [], + "uses_allowlisted_private": [], + "runner_surface": "./python -m unittest -v test.test_set.TestSet.test_set_literal_evaluation_order", + "fixture_taint_checked": true + }, + "test.test_set.TestSet.test_hash": { + "system_reason": "Pre-existing set test. test_set.py is NOT modified by this PR.", + "public_surface": "set/frozenset builtins", + "internal_symbol_check": [], + "uses_allowlisted_private": [], + "runner_surface": "./python -m unittest -v test.test_set.TestSet.test_hash", + "fixture_taint_checked": true + }, + "test.test_set.TestSet.test_clear": { + "system_reason": "Pre-existing set test. test_set.py is NOT modified by this PR.", + "public_surface": "set/frozenset builtins", + "internal_symbol_check": [], + "uses_allowlisted_private": [], + "runner_surface": "./python -m unittest -v test.test_set.TestSet.test_clear", + "fixture_taint_checked": true + }, + "test.test_set.TestSet.test_copy": { + "system_reason": "Pre-existing set test. test_set.py is NOT modified by this PR.", + "public_surface": "set/frozenset builtins", + "internal_symbol_check": [], + "uses_allowlisted_private": [], + "runner_surface": "./python -m unittest -v test.test_set.TestSet.test_copy", + "fixture_taint_checked": true + }, + "test.test_set.TestSet.test_add": { + "system_reason": "Pre-existing set test. test_set.py is NOT modified by this PR.", + "public_surface": "set/frozenset builtins", + "internal_symbol_check": [], + "uses_allowlisted_private": [], + "runner_surface": "./python -m unittest -v test.test_set.TestSet.test_add", + "fixture_taint_checked": true + }, + "test.test_set.TestSet.test_remove": { + "system_reason": "Pre-existing set test. test_set.py is NOT modified by this PR.", + "public_surface": "set/frozenset builtins", + "internal_symbol_check": [], + "uses_allowlisted_private": [], + "runner_surface": "./python -m unittest -v test.test_set.TestSet.test_remove", + "fixture_taint_checked": true + }, + "test.test_set.TestSet.test_remove_keyerror_unpacking": { + "system_reason": "Pre-existing set test. test_set.py is NOT modified by this PR.", + "public_surface": "set/frozenset builtins", + "internal_symbol_check": [], + "uses_allowlisted_private": [], + "runner_surface": "./python -m unittest -v test.test_set.TestSet.test_remove_keyerror_unpacking", + "fixture_taint_checked": true + }, + "test.test_set.TestSet.test_remove_keyerror_set": { + "system_reason": "Pre-existing set test. test_set.py is NOT modified by this PR.", + "public_surface": "set/frozenset builtins", + "internal_symbol_check": [], + "uses_allowlisted_private": [], + "runner_surface": "./python -m unittest -v test.test_set.TestSet.test_remove_keyerror_set", + "fixture_taint_checked": true + }, + "test.test_set.TestSet.test_discard": { + "system_reason": "Pre-existing set test. test_set.py is NOT modified by this PR.", + "public_surface": "set/frozenset builtins", + "internal_symbol_check": [], + "uses_allowlisted_private": [], + "runner_surface": "./python -m unittest -v test.test_set.TestSet.test_discard", + "fixture_taint_checked": true + }, + "test.test_set.TestSet.test_pop": { + "system_reason": "Pre-existing set test. test_set.py is NOT modified by this PR.", + "public_surface": "set/frozenset builtins", + "internal_symbol_check": [], + "uses_allowlisted_private": [], + "runner_surface": "./python -m unittest -v test.test_set.TestSet.test_pop", + "fixture_taint_checked": true + }, + "test.test_set.TestSet.test_update": { + "system_reason": "Pre-existing set test. test_set.py is NOT modified by this PR.", + "public_surface": "set/frozenset builtins", + "internal_symbol_check": [], + "uses_allowlisted_private": [], + "runner_surface": "./python -m unittest -v test.test_set.TestSet.test_update", + "fixture_taint_checked": true + }, + "test.test_set.TestSet.test_ior": { + "system_reason": "Pre-existing set test. test_set.py is NOT modified by this PR.", + "public_surface": "set/frozenset builtins", + "internal_symbol_check": [], + "uses_allowlisted_private": [], + "runner_surface": "./python -m unittest -v test.test_set.TestSet.test_ior", + "fixture_taint_checked": true + }, + "test.test_set.TestSet.test_intersection_update": { + "system_reason": "Pre-existing set test. test_set.py is NOT modified by this PR.", + "public_surface": "set/frozenset builtins", + "internal_symbol_check": [], + "uses_allowlisted_private": [], + "runner_surface": "./python -m unittest -v test.test_set.TestSet.test_intersection_update", + "fixture_taint_checked": true + }, + "test.test_set.TestSet.test_iand": { + "system_reason": "Pre-existing set test. test_set.py is NOT modified by this PR.", + "public_surface": "set/frozenset builtins", + "internal_symbol_check": [], + "uses_allowlisted_private": [], + "runner_surface": "./python -m unittest -v test.test_set.TestSet.test_iand", + "fixture_taint_checked": true + }, + "test.test_set.TestSet.test_difference_update": { + "system_reason": "Pre-existing set test. test_set.py is NOT modified by this PR.", + "public_surface": "set/frozenset builtins", + "internal_symbol_check": [], + "uses_allowlisted_private": [], + "runner_surface": "./python -m unittest -v test.test_set.TestSet.test_difference_update", + "fixture_taint_checked": true + }, + "test.test_set.TestSet.test_isub": { + "system_reason": "Pre-existing set test. test_set.py is NOT modified by this PR.", + "public_surface": "set/frozenset builtins", + "internal_symbol_check": [], + "uses_allowlisted_private": [], + "runner_surface": "./python -m unittest -v test.test_set.TestSet.test_isub", + "fixture_taint_checked": true + }, + "test.test_set.TestSet.test_symmetric_difference_update": { + "system_reason": "Pre-existing set test. test_set.py is NOT modified by this PR.", + "public_surface": "set/frozenset builtins", + "internal_symbol_check": [], + "uses_allowlisted_private": [], + "runner_surface": "./python -m unittest -v test.test_set.TestSet.test_symmetric_difference_update", + "fixture_taint_checked": true + }, + "test.test_set.TestSet.test_ixor": { + "system_reason": "Pre-existing set test. test_set.py is NOT modified by this PR.", + "public_surface": "set/frozenset builtins", + "internal_symbol_check": [], + "uses_allowlisted_private": [], + "runner_surface": "./python -m unittest -v test.test_set.TestSet.test_ixor", + "fixture_taint_checked": true + }, + "test.test_set.TestSet.test_inplace_on_self": { + "system_reason": "Pre-existing set test. test_set.py is NOT modified by this PR.", + "public_surface": "set/frozenset builtins", + "internal_symbol_check": [], + "uses_allowlisted_private": [], + "runner_surface": "./python -m unittest -v test.test_set.TestSet.test_inplace_on_self", + "fixture_taint_checked": true + }, + "test.test_set.TestSet.test_weakref": { + "system_reason": "Pre-existing set test. test_set.py is NOT modified by this PR.", + "public_surface": "set/frozenset builtins", + "internal_symbol_check": [], + "uses_allowlisted_private": [], + "runner_surface": "./python -m unittest -v test.test_set.TestSet.test_weakref", + "fixture_taint_checked": true + }, + "test.test_calendar.OutputTestCase.test_output": { + "system_reason": "Pre-existing calendar test. test_calendar.py is NOT modified by this PR.", + "public_surface": "calendar public API", + "internal_symbol_check": [], + "uses_allowlisted_private": [], + "runner_surface": "./python -m unittest -v test.test_calendar.OutputTestCase.test_output", + "fixture_taint_checked": true + }, + "test.test_calendar.OutputTestCase.test_output_textcalendar": { + "system_reason": "Pre-existing calendar test. test_calendar.py is NOT modified by this PR.", + "public_surface": "calendar public API", + "internal_symbol_check": [], + "uses_allowlisted_private": [], + "runner_surface": "./python -m unittest -v test.test_calendar.OutputTestCase.test_output_textcalendar", + "fixture_taint_checked": true + }, + "test.test_calendar.OutputTestCase.test_output_htmlcalendar_encoding_ascii": { + "system_reason": "Pre-existing calendar test. test_calendar.py is NOT modified by this PR.", + "public_surface": "calendar public API", + "internal_symbol_check": [], + "uses_allowlisted_private": [], + "runner_surface": "./python -m unittest -v test.test_calendar.OutputTestCase.test_output_htmlcalendar_encoding_ascii", + "fixture_taint_checked": true + }, + "test.test_calendar.OutputTestCase.test_output_htmlcalendar_encoding_utf8": { + "system_reason": "Pre-existing calendar test. test_calendar.py is NOT modified by this PR.", + "public_surface": "calendar public API", + "internal_symbol_check": [], + "uses_allowlisted_private": [], + "runner_surface": "./python -m unittest -v test.test_calendar.OutputTestCase.test_output_htmlcalendar_encoding_utf8", + "fixture_taint_checked": true + }, + "test.test_calendar.OutputTestCase.test_output_htmlcalendar_encoding_default": { + "system_reason": "Pre-existing calendar test. test_calendar.py is NOT modified by this PR.", + "public_surface": "calendar public API", + "internal_symbol_check": [], + "uses_allowlisted_private": [], + "runner_surface": "./python -m unittest -v test.test_calendar.OutputTestCase.test_output_htmlcalendar_encoding_default", + "fixture_taint_checked": true + }, + "test.test_calendar.OutputTestCase.test_yeardatescalendar": { + "system_reason": "Pre-existing calendar test. test_calendar.py is NOT modified by this PR.", + "public_surface": "calendar public API", + "internal_symbol_check": [], + "uses_allowlisted_private": [], + "runner_surface": "./python -m unittest -v test.test_calendar.OutputTestCase.test_yeardatescalendar", + "fixture_taint_checked": true + }, + "test.test_calendar.OutputTestCase.test_yeardayscalendar": { + "system_reason": "Pre-existing calendar test. test_calendar.py is NOT modified by this PR.", + "public_surface": "calendar public API", + "internal_symbol_check": [], + "uses_allowlisted_private": [], + "runner_surface": "./python -m unittest -v test.test_calendar.OutputTestCase.test_yeardayscalendar", + "fixture_taint_checked": true + }, + "test.test_calendar.OutputTestCase.test_formatweekheader_long": { + "system_reason": "Pre-existing calendar test. test_calendar.py is NOT modified by this PR.", + "public_surface": "calendar public API", + "internal_symbol_check": [], + "uses_allowlisted_private": [], + "runner_surface": "./python -m unittest -v test.test_calendar.OutputTestCase.test_formatweekheader_long", + "fixture_taint_checked": true + }, + "test.test_calendar.OutputTestCase.test_formatmonthname_without_year": { + "system_reason": "Pre-existing calendar test. test_calendar.py is NOT modified by this PR.", + "public_surface": "calendar public API", + "internal_symbol_check": [], + "uses_allowlisted_private": [], + "runner_surface": "./python -m unittest -v test.test_calendar.OutputTestCase.test_formatmonthname_without_year", + "fixture_taint_checked": true + }, + "test.test_calendar.OutputTestCase.test_pryear": { + "system_reason": "Pre-existing calendar test. test_calendar.py is NOT modified by this PR.", + "public_surface": "calendar public API", + "internal_symbol_check": [], + "uses_allowlisted_private": [], + "runner_surface": "./python -m unittest -v test.test_calendar.OutputTestCase.test_pryear", + "fixture_taint_checked": true + }, + "test.test_calendar.OutputTestCase.test_format": { + "system_reason": "Pre-existing calendar test. test_calendar.py is NOT modified by this PR.", + "public_surface": "calendar public API", + "internal_symbol_check": [], + "uses_allowlisted_private": [], + "runner_surface": "./python -m unittest -v test.test_calendar.OutputTestCase.test_format", + "fixture_taint_checked": true + }, + "test.test_calendar.CalendarTestCase.test_deprecation_warning": { + "system_reason": "Pre-existing calendar test. test_calendar.py is NOT modified by this PR.", + "public_surface": "calendar public API", + "internal_symbol_check": [], + "uses_allowlisted_private": [], + "runner_surface": "./python -m unittest -v test.test_calendar.CalendarTestCase.test_deprecation_warning", + "fixture_taint_checked": true + }, + "test.test_calendar.CalendarTestCase.test_months": { + "system_reason": "Pre-existing calendar test. test_calendar.py is NOT modified by this PR.", + "public_surface": "calendar public API", + "internal_symbol_check": [], + "uses_allowlisted_private": [], + "runner_surface": "./python -m unittest -v test.test_calendar.CalendarTestCase.test_months", + "fixture_taint_checked": true + }, + "test.test_calendar.CalendarTestCase.test_locale_calendars": { + "system_reason": "Pre-existing calendar test. test_calendar.py is NOT modified by this PR.", + "public_surface": "calendar public API", + "internal_symbol_check": [], + "uses_allowlisted_private": [], + "runner_surface": "./python -m unittest -v test.test_calendar.CalendarTestCase.test_locale_calendars", + "fixture_taint_checked": true + }, + "test.test_calendar.CalendarTestCase.test_locale_html_calendar_custom_css_class_month_name": { + "system_reason": "Pre-existing calendar test. test_calendar.py is NOT modified by this PR.", + "public_surface": "calendar public API", + "internal_symbol_check": [], + "uses_allowlisted_private": [], + "runner_surface": "./python -m unittest -v test.test_calendar.CalendarTestCase.test_locale_html_calendar_custom_css_class_month_name", + "fixture_taint_checked": true + }, + "test.test_calendar.CalendarTestCase.test_locale_html_calendar_custom_css_class_weekday": { + "system_reason": "Pre-existing calendar test. test_calendar.py is NOT modified by this PR.", + "public_surface": "calendar public API", + "internal_symbol_check": [], + "uses_allowlisted_private": [], + "runner_surface": "./python -m unittest -v test.test_calendar.CalendarTestCase.test_locale_html_calendar_custom_css_class_weekday", + "fixture_taint_checked": true + }, + "test.test_calendar.CalendarTestCase.test_itermonthdays3": { + "system_reason": "Pre-existing calendar test. test_calendar.py is NOT modified by this PR.", + "public_surface": "calendar public API", + "internal_symbol_check": [], + "uses_allowlisted_private": [], + "runner_surface": "./python -m unittest -v test.test_calendar.CalendarTestCase.test_itermonthdays3", + "fixture_taint_checked": true + }, + "test.test_calendar.CalendarTestCase.test_itermonthdays4": { + "system_reason": "Pre-existing calendar test. test_calendar.py is NOT modified by this PR.", + "public_surface": "calendar public API", + "internal_symbol_check": [], + "uses_allowlisted_private": [], + "runner_surface": "./python -m unittest -v test.test_calendar.CalendarTestCase.test_itermonthdays4", + "fixture_taint_checked": true + }, + "test.test_calendar.CalendarTestCase.test_itermonthdays": { + "system_reason": "Pre-existing calendar test. test_calendar.py is NOT modified by this PR.", + "public_surface": "calendar public API", + "internal_symbol_check": [], + "uses_allowlisted_private": [], + "runner_surface": "./python -m unittest -v test.test_calendar.CalendarTestCase.test_itermonthdays", + "fixture_taint_checked": true + }, + "test.test_calendar.CalendarTestCase.test_itermonthdays2": { + "system_reason": "Pre-existing calendar test. test_calendar.py is NOT modified by this PR.", + "public_surface": "calendar public API", + "internal_symbol_check": [], + "uses_allowlisted_private": [], + "runner_surface": "./python -m unittest -v test.test_calendar.CalendarTestCase.test_itermonthdays2", + "fixture_taint_checked": true + }, + "test.test_calendar.CalendarTestCase.test_iterweekdays": { + "system_reason": "Pre-existing calendar test. test_calendar.py is NOT modified by this PR.", + "public_surface": "calendar public API", + "internal_symbol_check": [], + "uses_allowlisted_private": [], + "runner_surface": "./python -m unittest -v test.test_calendar.CalendarTestCase.test_iterweekdays", + "fixture_taint_checked": true + }, + "test.test_calendar.MondayTestCase.test_february": { + "system_reason": "Pre-existing calendar test. test_calendar.py is NOT modified by this PR.", + "public_surface": "calendar public API", + "internal_symbol_check": [], + "uses_allowlisted_private": [], + "runner_surface": "./python -m unittest -v test.test_calendar.MondayTestCase.test_february", + "fixture_taint_checked": true + }, + "test.test_calendar.MondayTestCase.test_april": { + "system_reason": "Pre-existing calendar test. test_calendar.py is NOT modified by this PR.", + "public_surface": "calendar public API", + "internal_symbol_check": [], + "uses_allowlisted_private": [], + "runner_surface": "./python -m unittest -v test.test_calendar.MondayTestCase.test_april", + "fixture_taint_checked": true + }, + "test.test_calendar.MondayTestCase.test_december": { + "system_reason": "Pre-existing calendar test. test_calendar.py is NOT modified by this PR.", + "public_surface": "calendar public API", + "internal_symbol_check": [], + "uses_allowlisted_private": [], + "runner_surface": "./python -m unittest -v test.test_calendar.MondayTestCase.test_december", + "fixture_taint_checked": true + }, + "test.test_calendar.SundayTestCase.test_february": { + "system_reason": "Pre-existing calendar test. test_calendar.py is NOT modified by this PR.", + "public_surface": "calendar public API", + "internal_symbol_check": [], + "uses_allowlisted_private": [], + "runner_surface": "./python -m unittest -v test.test_calendar.SundayTestCase.test_february", + "fixture_taint_checked": true + }, + "test.test_calendar.SundayTestCase.test_april": { + "system_reason": "Pre-existing calendar test. test_calendar.py is NOT modified by this PR.", + "public_surface": "calendar public API", + "internal_symbol_check": [], + "uses_allowlisted_private": [], + "runner_surface": "./python -m unittest -v test.test_calendar.SundayTestCase.test_april", + "fixture_taint_checked": true + }, + "test.test_calendar.SundayTestCase.test_december": { + "system_reason": "Pre-existing calendar test. test_calendar.py is NOT modified by this PR.", + "public_surface": "calendar public API", + "internal_symbol_check": [], + "uses_allowlisted_private": [], + "runner_surface": "./python -m unittest -v test.test_calendar.SundayTestCase.test_december", + "fixture_taint_checked": true + }, + "test.test_calendar.TimegmTestCase.test_timegm": { + "system_reason": "Pre-existing calendar test. test_calendar.py is NOT modified by this PR.", + "public_surface": "calendar public API", + "internal_symbol_check": [], + "uses_allowlisted_private": [], + "runner_surface": "./python -m unittest -v test.test_calendar.TimegmTestCase.test_timegm", + "fixture_taint_checked": true + }, + "test.test_calendar.MonthRangeTestCase.test_january": { + "system_reason": "Pre-existing calendar test. test_calendar.py is NOT modified by this PR.", + "public_surface": "calendar public API", + "internal_symbol_check": [], + "uses_allowlisted_private": [], + "runner_surface": "./python -m unittest -v test.test_calendar.MonthRangeTestCase.test_january", + "fixture_taint_checked": true + }, + "test.test_dict.DictTest.test_constructor": { + "system_reason": "Pre-existing dict test. test_dict.py is NOT modified by this PR.", + "public_surface": "dict builtin", + "internal_symbol_check": [], + "uses_allowlisted_private": [], + "runner_surface": "./python -m unittest -v test.test_dict.DictTest.test_constructor", + "fixture_taint_checked": true + }, + "test.test_dict.DictTest.test_literal_constructor": { + "system_reason": "Pre-existing dict test. test_dict.py is NOT modified by this PR.", + "public_surface": "dict builtin", + "internal_symbol_check": [], + "uses_allowlisted_private": [], + "runner_surface": "./python -m unittest -v test.test_dict.DictTest.test_literal_constructor", + "fixture_taint_checked": true + }, + "test.test_dict.DictTest.test_merge_operator": { + "system_reason": "Pre-existing dict test. test_dict.py is NOT modified by this PR.", + "public_surface": "dict builtin", + "internal_symbol_check": [], + "uses_allowlisted_private": [], + "runner_surface": "./python -m unittest -v test.test_dict.DictTest.test_merge_operator", + "fixture_taint_checked": true + }, + "test.test_dict.DictTest.test_views_mapping": { + "system_reason": "Pre-existing dict test. test_dict.py is NOT modified by this PR.", + "public_surface": "dict builtin", + "internal_symbol_check": [], + "uses_allowlisted_private": [], + "runner_surface": "./python -m unittest -v test.test_dict.DictTest.test_views_mapping", + "fixture_taint_checked": true + }, + "test.test_dict.DictTest.test_len": { + "system_reason": "Pre-existing dict test. test_dict.py is NOT modified by this PR.", + "public_surface": "dict builtin", + "internal_symbol_check": [], + "uses_allowlisted_private": [], + "runner_surface": "./python -m unittest -v test.test_dict.DictTest.test_len", + "fixture_taint_checked": true + }, + "test.test_dict.DictTest.test_getitem": { + "system_reason": "Pre-existing dict test. test_dict.py is NOT modified by this PR.", + "public_surface": "dict builtin", + "internal_symbol_check": [], + "uses_allowlisted_private": [], + "runner_surface": "./python -m unittest -v test.test_dict.DictTest.test_getitem", + "fixture_taint_checked": true + }, + "test.test_dict.DictTest.test_copy_fuzz": { + "system_reason": "Pre-existing dict test. test_dict.py is NOT modified by this PR.", + "public_surface": "dict builtin", + "internal_symbol_check": [], + "uses_allowlisted_private": [], + "runner_surface": "./python -m unittest -v test.test_dict.DictTest.test_copy_fuzz", + "fixture_taint_checked": true + }, + "test.test_dict.DictTest.test_copy_maintains_tracking": { + "system_reason": "Pre-existing dict test. test_dict.py is NOT modified by this PR.", + "public_surface": "dict builtin", + "internal_symbol_check": [], + "uses_allowlisted_private": [], + "runner_surface": "./python -m unittest -v test.test_dict.DictTest.test_copy_maintains_tracking", + "fixture_taint_checked": true + }, + "test.test_dict.DictTest.test_copy_noncompact": { + "system_reason": "Pre-existing dict test. test_dict.py is NOT modified by this PR.", + "public_surface": "dict builtin", + "internal_symbol_check": [], + "uses_allowlisted_private": [], + "runner_surface": "./python -m unittest -v test.test_dict.DictTest.test_copy_noncompact", + "fixture_taint_checked": true + }, + "test.test_dict.DictTest.test_get": { + "system_reason": "Pre-existing dict test. test_dict.py is NOT modified by this PR.", + "public_surface": "dict builtin", + "internal_symbol_check": [], + "uses_allowlisted_private": [], + "runner_surface": "./python -m unittest -v test.test_dict.DictTest.test_get", + "fixture_taint_checked": true + }, + "test.test_dict.DictTest.test_setdefault": { + "system_reason": "Pre-existing dict test. test_dict.py is NOT modified by this PR.", + "public_surface": "dict builtin", + "internal_symbol_check": [], + "uses_allowlisted_private": [], + "runner_surface": "./python -m unittest -v test.test_dict.DictTest.test_setdefault", + "fixture_taint_checked": true + }, + "test.test_dict.DictTest.test_setdefault_atomic": { + "system_reason": "Pre-existing dict test. test_dict.py is NOT modified by this PR.", + "public_surface": "dict builtin", + "internal_symbol_check": [], + "uses_allowlisted_private": [], + "runner_surface": "./python -m unittest -v test.test_dict.DictTest.test_setdefault_atomic", + "fixture_taint_checked": true + }, + "test.test_dict.DictTest.test_setitem_atomic_at_resize": { + "system_reason": "Pre-existing dict test. test_dict.py is NOT modified by this PR.", + "public_surface": "dict builtin", + "internal_symbol_check": [], + "uses_allowlisted_private": [], + "runner_surface": "./python -m unittest -v test.test_dict.DictTest.test_setitem_atomic_at_resize", + "fixture_taint_checked": true + }, + "test.test_dict.DictTest.test_popitem": { + "system_reason": "Pre-existing dict test. test_dict.py is NOT modified by this PR.", + "public_surface": "dict builtin", + "internal_symbol_check": [], + "uses_allowlisted_private": [], + "runner_surface": "./python -m unittest -v test.test_dict.DictTest.test_popitem", + "fixture_taint_checked": true + }, + "test.test_dict.DictTest.test_pop": { + "system_reason": "Pre-existing dict test. test_dict.py is NOT modified by this PR.", + "public_surface": "dict builtin", + "internal_symbol_check": [], + "uses_allowlisted_private": [], + "runner_surface": "./python -m unittest -v test.test_dict.DictTest.test_pop", + "fixture_taint_checked": true + }, + "test.test_dict.DictTest.test_mutating_iteration": { + "system_reason": "Pre-existing dict test. test_dict.py is NOT modified by this PR.", + "public_surface": "dict builtin", + "internal_symbol_check": [], + "uses_allowlisted_private": [], + "runner_surface": "./python -m unittest -v test.test_dict.DictTest.test_mutating_iteration", + "fixture_taint_checked": true + }, + "test.test_dict.DictTest.test_mutating_iteration_delete": { + "system_reason": "Pre-existing dict test. test_dict.py is NOT modified by this PR.", + "public_surface": "dict builtin", + "internal_symbol_check": [], + "uses_allowlisted_private": [], + "runner_surface": "./python -m unittest -v test.test_dict.DictTest.test_mutating_iteration_delete", + "fixture_taint_checked": true + }, + "test.test_dict.DictTest.test_mutating_iteration_delete_over_values": { + "system_reason": "Pre-existing dict test. test_dict.py is NOT modified by this PR.", + "public_surface": "dict builtin", + "internal_symbol_check": [], + "uses_allowlisted_private": [], + "runner_surface": "./python -m unittest -v test.test_dict.DictTest.test_mutating_iteration_delete_over_values", + "fixture_taint_checked": true + }, + "test.test_dict.DictTest.test_mutating_iteration_delete_over_items": { + "system_reason": "Pre-existing dict test. test_dict.py is NOT modified by this PR.", + "public_surface": "dict builtin", + "internal_symbol_check": [], + "uses_allowlisted_private": [], + "runner_surface": "./python -m unittest -v test.test_dict.DictTest.test_mutating_iteration_delete_over_items", + "fixture_taint_checked": true + }, + "test.test_dict.DictTest.test_mutating_lookup": { + "system_reason": "Pre-existing dict test. test_dict.py is NOT modified by this PR.", + "public_surface": "dict builtin", + "internal_symbol_check": [], + "uses_allowlisted_private": [], + "runner_surface": "./python -m unittest -v test.test_dict.DictTest.test_mutating_lookup", + "fixture_taint_checked": true + }, + "test.test_list.ListTest.test_keyword_args": { + "system_reason": "Pre-existing list test. test_list.py is NOT modified by this PR.", + "public_surface": "list builtin", + "internal_symbol_check": [], + "uses_allowlisted_private": [], + "runner_surface": "./python -m unittest -v test.test_list.ListTest.test_keyword_args", + "fixture_taint_checked": true + }, + "test.test_list.ListTest.test_keywords_in_subclass": { + "system_reason": "Pre-existing list test. test_list.py is NOT modified by this PR.", + "public_surface": "list builtin", + "internal_symbol_check": [], + "uses_allowlisted_private": [], + "runner_surface": "./python -m unittest -v test.test_list.ListTest.test_keywords_in_subclass", + "fixture_taint_checked": true + }, + "test.test_list.ListTest.test_identity": { + "system_reason": "Pre-existing list test. test_list.py is NOT modified by this PR.", + "public_surface": "list builtin", + "internal_symbol_check": [], + "uses_allowlisted_private": [], + "runner_surface": "./python -m unittest -v test.test_list.ListTest.test_identity", + "fixture_taint_checked": true + }, + "test.test_list.ListTest.test_list_resize_overflow": { + "system_reason": "Pre-existing list test. test_list.py is NOT modified by this PR.", + "public_surface": "list builtin", + "internal_symbol_check": [], + "uses_allowlisted_private": [], + "runner_surface": "./python -m unittest -v test.test_list.ListTest.test_list_resize_overflow", + "fixture_taint_checked": true + }, + "test.test_list.ListTest.test_repr_large": { + "system_reason": "Pre-existing list test. test_list.py is NOT modified by this PR.", + "public_surface": "list builtin", + "internal_symbol_check": [], + "uses_allowlisted_private": [], + "runner_surface": "./python -m unittest -v test.test_list.ListTest.test_repr_large", + "fixture_taint_checked": true + }, + "test.test_list.ListTest.test_iterator_pickle": { + "system_reason": "Pre-existing list test. test_list.py is NOT modified by this PR.", + "public_surface": "list builtin", + "internal_symbol_check": [], + "uses_allowlisted_private": [], + "runner_surface": "./python -m unittest -v test.test_list.ListTest.test_iterator_pickle", + "fixture_taint_checked": true + }, + "test.test_list.ListTest.test_reversed_pickle": { + "system_reason": "Pre-existing list test. test_list.py is NOT modified by this PR.", + "public_surface": "list builtin", + "internal_symbol_check": [], + "uses_allowlisted_private": [], + "runner_surface": "./python -m unittest -v test.test_list.ListTest.test_reversed_pickle", + "fixture_taint_checked": true + }, + "test.test_list.ListTest.test_step_overflow": { + "system_reason": "Pre-existing list test. test_list.py is NOT modified by this PR.", + "public_surface": "list builtin", + "internal_symbol_check": [], + "uses_allowlisted_private": [], + "runner_surface": "./python -m unittest -v test.test_list.ListTest.test_step_overflow", + "fixture_taint_checked": true + }, + "test.test_list.ListTest.test_no_comdat_folding": { + "system_reason": "Pre-existing list test. test_list.py is NOT modified by this PR.", + "public_surface": "list builtin", + "internal_symbol_check": [], + "uses_allowlisted_private": [], + "runner_surface": "./python -m unittest -v test.test_list.ListTest.test_no_comdat_folding", + "fixture_taint_checked": true + }, + "test.test_list.ListTest.test_equal_operator_modifying_operand": { + "system_reason": "Pre-existing list test. test_list.py is NOT modified by this PR.", + "public_surface": "list builtin", + "internal_symbol_check": [], + "uses_allowlisted_private": [], + "runner_surface": "./python -m unittest -v test.test_list.ListTest.test_equal_operator_modifying_operand", + "fixture_taint_checked": true + }, + "test.test_list.ListTest.test_preallocation": { + "system_reason": "Pre-existing list test. test_list.py is NOT modified by this PR.", + "public_surface": "list builtin", + "internal_symbol_check": [], + "uses_allowlisted_private": [], + "runner_surface": "./python -m unittest -v test.test_list.ListTest.test_preallocation", + "fixture_taint_checked": true + }, + "test.test_list.ListTest.test_count_index_remove_crashes": { + "system_reason": "Pre-existing list test. test_list.py is NOT modified by this PR.", + "public_surface": "list builtin", + "internal_symbol_check": [], + "uses_allowlisted_private": [], + "runner_surface": "./python -m unittest -v test.test_list.ListTest.test_count_index_remove_crashes", + "fixture_taint_checked": true + }, + "test.test_float.GeneralFloatCases.test_error_message": { + "system_reason": "Pre-existing float test. test_float.py is NOT modified by this PR.", + "public_surface": "float() public API", + "internal_symbol_check": [], + "uses_allowlisted_private": [], + "runner_surface": "./python -m unittest -v test.test_float.GeneralFloatCases.test_error_message", + "fixture_taint_checked": true + }, + "test.test_float.GeneralFloatCases.test_floatconversion": { + "system_reason": "Pre-existing float test. test_float.py is NOT modified by this PR.", + "public_surface": "float() public API", + "internal_symbol_check": [], + "uses_allowlisted_private": [], + "runner_surface": "./python -m unittest -v test.test_float.GeneralFloatCases.test_floatconversion", + "fixture_taint_checked": true + }, + "test.test_float.GeneralFloatCases.test_keyword_args": { + "system_reason": "Pre-existing float test. test_float.py is NOT modified by this PR.", + "public_surface": "float() public API", + "internal_symbol_check": [], + "uses_allowlisted_private": [], + "runner_surface": "./python -m unittest -v test.test_float.GeneralFloatCases.test_keyword_args", + "fixture_taint_checked": true + }, + "test.test_float.GeneralFloatCases.test_keywords_in_subclass": { + "system_reason": "Pre-existing float test. test_float.py is NOT modified by this PR.", + "public_surface": "float() public API", + "internal_symbol_check": [], + "uses_allowlisted_private": [], + "runner_surface": "./python -m unittest -v test.test_float.GeneralFloatCases.test_keywords_in_subclass", + "fixture_taint_checked": true + }, + "test.test_float.GeneralFloatCases.test_is_integer": { + "system_reason": "Pre-existing float test. test_float.py is NOT modified by this PR.", + "public_surface": "float() public API", + "internal_symbol_check": [], + "uses_allowlisted_private": [], + "runner_surface": "./python -m unittest -v test.test_float.GeneralFloatCases.test_is_integer", + "fixture_taint_checked": true + }, + "test.test_float.GeneralFloatCases.test_floatasratio": { + "system_reason": "Pre-existing float test. test_float.py is NOT modified by this PR.", + "public_surface": "float() public API", + "internal_symbol_check": [], + "uses_allowlisted_private": [], + "runner_surface": "./python -m unittest -v test.test_float.GeneralFloatCases.test_floatasratio", + "fixture_taint_checked": true + }, + "test.test_float.GeneralFloatCases.test_float_containment": { + "system_reason": "Pre-existing float test. test_float.py is NOT modified by this PR.", + "public_surface": "float() public API", + "internal_symbol_check": [], + "uses_allowlisted_private": [], + "runner_surface": "./python -m unittest -v test.test_float.GeneralFloatCases.test_float_containment", + "fixture_taint_checked": true + }, + "test.test_float.GeneralFloatCases.test_float_floor": { + "system_reason": "Pre-existing float test. test_float.py is NOT modified by this PR.", + "public_surface": "float() public API", + "internal_symbol_check": [], + "uses_allowlisted_private": [], + "runner_surface": "./python -m unittest -v test.test_float.GeneralFloatCases.test_float_floor", + "fixture_taint_checked": true + }, + "test.test_float.GeneralFloatCases.test_float_ceil": { + "system_reason": "Pre-existing float test. test_float.py is NOT modified by this PR.", + "public_surface": "float() public API", + "internal_symbol_check": [], + "uses_allowlisted_private": [], + "runner_surface": "./python -m unittest -v test.test_float.GeneralFloatCases.test_float_ceil", + "fixture_taint_checked": true + }, + "test.test_float.GeneralFloatCases.test_float_mod": { + "system_reason": "Pre-existing float test. test_float.py is NOT modified by this PR.", + "public_surface": "float() public API", + "internal_symbol_check": [], + "uses_allowlisted_private": [], + "runner_surface": "./python -m unittest -v test.test_float.GeneralFloatCases.test_float_mod", + "fixture_taint_checked": true + }, + "test.test_float.GeneralFloatCases.test_float_pow": { + "system_reason": "Pre-existing float test. test_float.py is NOT modified by this PR.", + "public_surface": "float() public API", + "internal_symbol_check": [], + "uses_allowlisted_private": [], + "runner_surface": "./python -m unittest -v test.test_float.GeneralFloatCases.test_float_pow", + "fixture_taint_checked": true + }, + "test.test_float.GeneralFloatCases.test_hash": { + "system_reason": "Pre-existing float test. test_float.py is NOT modified by this PR.", + "public_surface": "float() public API", + "internal_symbol_check": [], + "uses_allowlisted_private": [], + "runner_surface": "./python -m unittest -v test.test_float.GeneralFloatCases.test_hash", + "fixture_taint_checked": true + }, + "test.test_float.GeneralFloatCases.test_hash_nan": { + "system_reason": "Pre-existing float test. test_float.py is NOT modified by this PR.", + "public_surface": "float() public API", + "internal_symbol_check": [], + "uses_allowlisted_private": [], + "runner_surface": "./python -m unittest -v test.test_float.GeneralFloatCases.test_hash_nan", + "fixture_taint_checked": true + }, + "test.test_float.FormatTestCase.test_format": { + "system_reason": "Pre-existing float test. test_float.py is NOT modified by this PR.", + "public_surface": "float() public API", + "internal_symbol_check": [], + "uses_allowlisted_private": [], + "runner_surface": "./python -m unittest -v test.test_float.FormatTestCase.test_format", + "fixture_taint_checked": true + } + } + }, + "out_of_scope_surfaces": [ + { + "surface": "Internal helpers: _PyTypeVar_*, _PyTypeAlias_*, INTRINSIC_SET_FUNCTION_TYPE_PARAMS, etc.", + "reason": "Internal-implementation symbols introduced by the PR. F2P checks observable public behavior only." + } + ], + "public_surface_allowlist": [], + "build_environment": { + "base_image": "lolbench/cpython-base:1", + "configure_flags": "--prefix=/usr/local --enable-optimizations=no", + "make_target": "(default; the build regenerates parser.c / Python-ast.c from python.gram + Python.asdl)", + "runtime_caps": "--network=none, default seccomp" + }, + "validated_at": "2026-06-22", + "coverage_gap_note": "Union coverage: 37.1% (1500/4044 executable lines in solution.patch). Below the \u00a74.1.1 50% floor. F2P is at the **maximum** PR contribution: all 67 methods in the NEW test_type_params.py + all 20 in NEW test_type_aliases.py + 1 test_ast.test_type_params_feature_version = 88 selectors (verified that test_typing.py has NO net new methods; test files outside the 7 modified ones are untouched). Even with the maximum public-API behavioral test surface, the gap persists in three structurally-hard-to-reach categories:\n\n - Parser/parser.c (38%, 726-line gap): auto-generated parser-action tables for the ENTIRE Python grammar. PEP-695 syntax exercises only the new rule actions; the rest of parser.c is unchanged-but-recompiled code reachable only via other grammar tests (those tests are in P2P but they don't hit PR-NEW lines).\n\n - Python/Python-ast.c (24%, 427-line gap): auto-generated AST node visitor / field accessor stubs for ALL ast nodes; PEP-695 tests exercise only the new TypeVar / TypeVarTuple / ParamSpec / TypeAlias visitors.\n\n - Objects/clinic/typevarobject.c.h (14%, 316-line gap): argument-clinic-generated boilerplate for typevarobject constructors. Most lines are type-error/keyword-argument-error branches not triggered by valid public-API usage.\n\n - Objects/typevarobject.c (35%, 593-line gap): pickle/copy/deepcopy/reduce helpers + many low-priority dunder methods. Some are reachable via pickle.dumps(TypeVar) tests; CPython's own pickle tests for these in the PR's test_typing.py weren't added as F2P because the test file diff is a net rename/refactor (0 new methods).\n\nAcceptable per \u00a74.1.1's escape hatch: '50% genuinely unreachable through public-API tests'. The bulk of uncovered code is auto-generated boilerplate or pickle/copy/serialization helpers that would require fabricating tests beyond the PR \u2014 out of scope per \u00a76's 'F2P/P2P from the PR itself' rule.", + "augmented": { + "suite_support": [ + "orig", + "aug", + "union" + ], + "eval_tests_patch": "eval_tests_aug.patch", + "eval_tests_aug_patch_sha256": "1f8f62c27191868e580cc5c2172d0c5e687c1b6805bf1a778d8907d9f0012c7f", + "f2p_aug_sha256": "180cd7944d3e4b01b9c0c4f254427f946e30216cc78496a4efcce54de1cbc8f9", + "p2p_aug_sha256": "984e5f04c636a113adb07261ac912dd626750f7bb42038dd566676b03d5d460b", + "fail_to_pass": [ + "test.test_pep695_aug.TypeParameterSyntaxAugmentedTests.test_ast_unparse_preserves_all_type_parameter_forms", + "test.test_pep695_aug.TypeParameterSyntaxAugmentedTests.test_source_distribution_keeps_type_parameter_grammar_and_soft_keyword", + "test.test_pep695_aug.TypeParameterSyntaxAugmentedTests.test_typing_forward_union_and_invalid_variadic_specialization", + "test.test_pep695_aug.TypeParameterSyntaxAugmentedTests.test_implicit_type_parameters_expose_variance_and_exact_runtime_tuple", + "test.test_pep695_aug.TypeParameterSyntaxAugmentedTests.test_public_type_parameter_constructors_reject_invalid_combinations", + "test.test_pep695_aug.TypeParameterSyntaxAugmentedTests.test_lazy_bounds_constraints_and_alias_values_are_cached", + "test.test_pep695_aug.TypeParameterSyntaxAugmentedTests.test_type_alias_public_runtime_contract", + "test.test_pep695_aug.TypeParameterSyntaxAugmentedTests.test_bounds_constraints_and_empty_type_params_are_classified_correctly", + "test.test_pep695_aug.TypeParameterSyntaxAugmentedTests.test_type_parameter_scopes_and_prohibited_expressions", + "test.test_pep695_aug.TypeParameterSyntaxAugmentedTests.test_manual_ast_type_parameter_nodes_compile_and_validate", + "test.test_pep695_aug.TypeParameterSyntaxAugmentedTests.test_typing_runtime_dunder_and_paramspec_attr_contracts", + "test.test_pep695_aug.TypeParameterSyntaxAugmentedTests.test_regenerated_parser_keeps_broad_public_grammar_paths" + ], + "pass_to_pass": [ + "test.test_pep695_stability_aug.TypeParameterSyntaxStabilityAugmentedTests.test_regular_class_and_function_execution_are_stable", + "test.test_pep695_stability_aug.TypeParameterSyntaxStabilityAugmentedTests.test_string_template_and_formatter_are_stable", + "test.test_pep695_stability_aug.TypeParameterSyntaxStabilityAugmentedTests.test_numeric_literal_and_float_roundtrip_behaviour_is_stable", + "test.test_pep695_stability_aug.TypeParameterSyntaxStabilityAugmentedTests.test_sys_frame_metadata_for_regular_calls_is_stable" + ], + "targets_mutants": [ + "mutant_001_ast_class_unparse_omits_type_params", + "mutant_002_ast_function_unparse_omits_type_params", + "mutant_003_ast_typeparams_unparse_parentheses", + "mutant_004_ast_typevartuple_unparse_drops_star", + "mutant_005_ast_paramspec_unparse_uses_single_star", + "mutant_006_ast_typealias_unparse_alias_keyword", + "mutant_007_keyword_type_not_soft_keyword", + "mutant_008_typing_union_helper_uses_pipe_operator", + "mutant_009_typing_allows_multiple_typevartuples", + "mutant_010_typing_paramspec_allows_too_few_args", + "mutant_011_implicit_typevar_infer_variance_false", + "mutant_012_implicit_paramspec_infer_variance_false", + "mutant_013_typevar_allows_infer_variance_with_variance", + "mutant_014_paramspec_allows_infer_variance_with_variance", + "mutant_015_typevar_allows_single_constraint", + "mutant_016_typevar_allows_constraints_with_bound", + "mutant_017_typevar_bound_not_cached", + "mutant_018_typevar_constraints_not_cached", + "mutant_019_typealias_value_not_cached", + "mutant_020_typealias_type_params_unpack_typevartuple", + "mutant_021_typealias_parameters_raw_typevartuple", + "mutant_022_typealias_non_generic_subscriptable", + "mutant_023_typealiastype_accepts_non_tuple_type_params", + "mutant_024_typealias_union_operator_missing", + "mutant_025_typealias_statement_returns_thunk_as_value", + "mutant_026_generic_base_keeps_bare_typevartuple", + "mutant_027_compiler_inverts_bounds_and_constraints", + "mutant_028_compiler_drops_last_type_param_from_tuple", + "mutant_029_compiler_class_stores_type_params_as_annotations", + "mutant_030_function_type_params_not_saved", + "mutant_031_function_no_type_params_returns_none", + "mutant_032_class_no_type_params_returns_none", + "mutant_033_symtable_duplicate_type_param_check_disabled", + "mutant_034_typeparam_scope_cannot_see_class_namespace", + "mutant_035_typevar_not_marked_as_type_parameter", + "mutant_036_typealias_scope_allows_prohibited_expressions", + "mutant_037_typeparam_scope_allows_prohibited_expressions", + "mutant_038_typevar_bound_scope_allows_prohibited_expressions", + "mutant_039_intrinsic_bound_recorded_as_constraints", + "mutant_040_intrinsic_constraints_recorded_as_bound" + ], + "coverage_gate": { + "minimum_line_coverage_percent": 80, + "status": "passed", + "coverage_report": "coverage_out/coverage_report_union.json", + "baseline_coverage_report": "coverage_out/coverage_report_orig.json", + "augmented_coverage_report": "coverage_out/coverage_report_aug.json", + "baseline_union_line_coverage_percent": 68.2, + "augmented_only_union_line_coverage_percent": 78.1, + "union_line_coverage_percent": 81.9, + "executable_lines_in_patch": 1263, + "union_covered_lines": 1034, + "coverage_complete": true, + "measurement_note": "Coverage uses the union suite report after excluding generated artifacts Parser/parser.c, Python/Python-ast.c, and Objects/clinic/typevarobject.c.h from the executable denominator; generated behavior is still exercised through public compile()/ast/runtime tests.", + "scope": "coverage.py for the 5 PEP-695 Python files (Lib/typing.py, Lib/ast.py, Lib/keyword.py, Lib/opcode.py, Lib/importlib/_bootstrap_external.py) + gcov/gcovr for the authored/runtime PEP-695 C source/header files (Parser/action_helpers.c, Python/{compile,symtable,ast,ast_opt,bytecodes,intrinsics,pylifecycle}.c, Objects/{typevarobject,funcobject,typeobject,unionobject,object}.c, Modules/_typingmodule.c, plus all touched pycore_*.h / cpython/funcobject.h / opcode.h headers). Grammar/python.gram and Parser/Python.asdl are grammar / schema sources (non-executable), and Parser/parser.c, Python/Python-ast.c, and Objects/clinic/typevarobject.c.h are generated artifacts, so they are not part of the denominator; generated parser/AST behavior is covered indirectly through public compile()/ast tests." + }, + "synthetic_tests": [ + "test.test_pep695_aug.TypeParameterSyntaxAugmentedTests.test_ast_unparse_preserves_all_type_parameter_forms", + "test.test_pep695_aug.TypeParameterSyntaxAugmentedTests.test_source_distribution_keeps_type_parameter_grammar_and_soft_keyword", + "test.test_pep695_aug.TypeParameterSyntaxAugmentedTests.test_typing_forward_union_and_invalid_variadic_specialization", + "test.test_pep695_aug.TypeParameterSyntaxAugmentedTests.test_implicit_type_parameters_expose_variance_and_exact_runtime_tuple", + "test.test_pep695_aug.TypeParameterSyntaxAugmentedTests.test_public_type_parameter_constructors_reject_invalid_combinations", + "test.test_pep695_aug.TypeParameterSyntaxAugmentedTests.test_lazy_bounds_constraints_and_alias_values_are_cached", + "test.test_pep695_aug.TypeParameterSyntaxAugmentedTests.test_type_alias_public_runtime_contract", + "test.test_pep695_aug.TypeParameterSyntaxAugmentedTests.test_bounds_constraints_and_empty_type_params_are_classified_correctly", + "test.test_pep695_aug.TypeParameterSyntaxAugmentedTests.test_type_parameter_scopes_and_prohibited_expressions", + "test.test_pep695_aug.TypeParameterSyntaxAugmentedTests.test_manual_ast_type_parameter_nodes_compile_and_validate", + "test.test_pep695_aug.TypeParameterSyntaxAugmentedTests.test_typing_runtime_dunder_and_paramspec_attr_contracts", + "test.test_pep695_aug.TypeParameterSyntaxAugmentedTests.test_regenerated_parser_keeps_broad_public_grammar_paths", + "test.test_pep695_stability_aug.TypeParameterSyntaxStabilityAugmentedTests.test_regular_class_and_function_execution_are_stable", + "test.test_pep695_stability_aug.TypeParameterSyntaxStabilityAugmentedTests.test_string_template_and_formatter_are_stable", + "test.test_pep695_stability_aug.TypeParameterSyntaxStabilityAugmentedTests.test_numeric_literal_and_float_roundtrip_behaviour_is_stable", + "test.test_pep695_stability_aug.TypeParameterSyntaxStabilityAugmentedTests.test_sys_frame_metadata_for_regular_calls_is_stable" + ], + "triage": { + "test_level_policy": "Augmented F2P selectors exercise PEP 695 behavior through public ast, keyword, typing, compile(), exec(), class/function metadata, and TypeAliasType surfaces; no project-defined internal symbols are referenced. Augmented P2P selectors exercise unrelated public stdlib/interpreter behavior that should pass at base, golden, and mutant states. Requirement section names exactly match the Section Classification Summary in requirement_pr_pairs/CPython_PEP-695_Type-Parameter-Syntax_PR-103764.md.", + "fail_to_pass": { + "test.test_pep695_aug.TypeParameterSyntaxAugmentedTests.test_ast_unparse_preserves_all_type_parameter_forms": { + "requirement_sections": [ + "Specification > Type Parameter Declarations", + "Specification > Generic Type Alias", + "Runtime Implementation > AST Changes" + ], + "public_surface": "ast.parse() and ast.unparse() over public class, function, async function, TypeVarTuple, ParamSpec, and type-alias syntax.", + "mutants_targeted": [ + "mutant_001_ast_class_unparse_omits_type_params", + "mutant_002_ast_function_unparse_omits_type_params", + "mutant_003_ast_typeparams_unparse_parentheses", + "mutant_004_ast_typevartuple_unparse_drops_star", + "mutant_005_ast_paramspec_unparse_uses_single_star", + "mutant_006_ast_typealias_unparse_alias_keyword" + ], + "rationale": "PEP 695 requires type parameter lists to round trip through the public AST for classes, functions, async functions, variadic parameters, ParamSpecs, and type aliases. The test asserts the rendered public source keeps square brackets, stars, double stars, and the type statement." + }, + "test.test_pep695_aug.TypeParameterSyntaxAugmentedTests.test_source_distribution_keeps_type_parameter_grammar_and_soft_keyword": { + "requirement_sections": [ + "Runtime Implementation > Grammar Changes", + "Specification > Generic Type Alias" + ], + "public_surface": "The CPython source distribution shipped in the benchmark image, plus keyword.issoftkeyword(\"type\").", + "mutants_targeted": [ + "mutant_007_keyword_type_not_soft_keyword" + ], + "rationale": "The grammar-change and generic-alias sections require the shipped grammar to define type-parameter productions and the type statement, and require type to be a soft keyword. Source-level checks catch source distribution regressions that generated parser artifacts can mask." + }, + "test.test_pep695_aug.TypeParameterSyntaxAugmentedTests.test_typing_forward_union_and_invalid_variadic_specialization": { + "requirement_sections": [ + "Runtime Implementation > Library Changes" + ], + "public_surface": "typing.TypeVar union expressions with forward-reference strings, TypeVarTuple aliases, and ParamSpec Callable specialization.", + "mutants_targeted": [ + "mutant_008_typing_union_helper_uses_pipe_operator", + "mutant_009_typing_allows_multiple_typevartuples", + "mutant_010_typing_paramspec_allows_too_few_args" + ], + "rationale": "The library-change section wires new runtime typing helpers into public typing constructs. The test verifies forward-reference unions work through typing, while invalid multiple-TypeVarTuple and under-supplied ParamSpec substitutions are still rejected." + }, + "test.test_pep695_aug.TypeParameterSyntaxAugmentedTests.test_implicit_type_parameters_expose_variance_and_exact_runtime_tuple": { + "requirement_sections": [ + "Specification > Type Parameter Declarations", + "Specification > Accessing Type Parameters at Runtime", + "Specification > Auto Variance For TypeVar" + ], + "public_surface": "exec() of PEP 695 class, function, and type-alias source plus public __type_params__, __parameters__, __name__, and __infer_variance__ attributes.", + "mutants_targeted": [ + "mutant_011_implicit_typevar_infer_variance_false", + "mutant_012_implicit_paramspec_infer_variance_false", + "mutant_020_typealias_type_params_unpack_typevartuple", + "mutant_026_generic_base_keeps_bare_typevartuple", + "mutant_028_compiler_drops_last_type_param_from_tuple", + "mutant_029_compiler_class_stores_type_params_as_annotations", + "mutant_030_function_type_params_not_saved" + ], + "rationale": "PEP 695 says implicit parameters are runtime objects, are exposed in declaration order, infer variance automatically, and drive Generic metadata without explicit Generic bases. The test observes those properties through public class, function, and type-alias metadata." + }, + "test.test_pep695_aug.TypeParameterSyntaxAugmentedTests.test_public_type_parameter_constructors_reject_invalid_combinations": { + "requirement_sections": [ + "Specification > Constrained Type Specification", + "Specification > Auto Variance For TypeVar", + "Runtime Implementation > Library Changes", + "Specification > Runtime Type Alias Class" + ], + "public_surface": "typing.TypeVar, typing.ParamSpec, and typing.TypeAliasType public constructors.", + "mutants_targeted": [ + "mutant_013_typevar_allows_infer_variance_with_variance", + "mutant_014_paramspec_allows_infer_variance_with_variance", + "mutant_015_typevar_allows_single_constraint", + "mutant_016_typevar_allows_constraints_with_bound", + "mutant_023_typealiastype_accepts_non_tuple_type_params" + ], + "rationale": "Constructor validation is part of the public runtime representation. The test requires invalid variance combinations, invalid constraints, and non-tuple TypeAliasType type parameters to raise the documented public exceptions." + }, + "test.test_pep695_aug.TypeParameterSyntaxAugmentedTests.test_lazy_bounds_constraints_and_alias_values_are_cached": { + "requirement_sections": [ + "Specification > Runtime Representation of Bounds and Constraints", + "Runtime Implementation > Lazy Evaluation", + "Specification > Generic Type Alias" + ], + "public_surface": "exec() of PEP 695 source plus public __bound__, __constraints__, and TypeAliasType.__value__ attributes.", + "mutants_targeted": [ + "mutant_017_typevar_bound_not_cached", + "mutant_018_typevar_constraints_not_cached", + "mutant_019_typealias_value_not_cached", + "mutant_025_typealias_statement_returns_thunk_as_value" + ], + "rationale": "Bounds, constraints, and type-alias values are lazily evaluated public attributes and must cache after successful evaluation. The test uses side effects visible from Python source to prove one evaluation and the correct exposed value." + }, + "test.test_pep695_aug.TypeParameterSyntaxAugmentedTests.test_type_alias_public_runtime_contract": { + "requirement_sections": [ + "Specification > Generic Type Alias", + "Specification > Runtime Type Alias Class", + "Specification > Accessing Type Parameters at Runtime", + "Runtime Implementation > Library Changes" + ], + "public_surface": "exec() of type-alias statements plus TypeAliasType.__type_params__, __parameters__, __value__, subscription, and union behavior.", + "mutants_targeted": [ + "mutant_020_typealias_type_params_unpack_typevartuple", + "mutant_021_typealias_parameters_raw_typevartuple", + "mutant_022_typealias_non_generic_subscriptable", + "mutant_024_typealias_union_operator_missing", + "mutant_025_typealias_statement_returns_thunk_as_value" + ], + "rationale": "Generic aliases must expose declared parameters exactly, expose subscription parameters with the public unpacking semantics, reject subscripting non-generic aliases, and participate in union expressions. The test drives all checks through TypeAliasType objects produced by public syntax." + }, + "test.test_pep695_aug.TypeParameterSyntaxAugmentedTests.test_bounds_constraints_and_empty_type_params_are_classified_correctly": { + "requirement_sections": [ + "Specification > Upper Bound Specification", + "Specification > Constrained Type Specification", + "Specification > Accessing Type Parameters at Runtime", + "Runtime Implementation > Lazy Evaluation" + ], + "public_surface": "exec() of class declarations plus public __bound__, __constraints__, and __type_params__ on classes and functions.", + "mutants_targeted": [ + "mutant_027_compiler_inverts_bounds_and_constraints", + "mutant_028_compiler_drops_last_type_param_from_tuple", + "mutant_031_function_no_type_params_returns_none", + "mutant_032_class_no_type_params_returns_none", + "mutant_039_intrinsic_bound_recorded_as_constraints", + "mutant_040_intrinsic_constraints_recorded_as_bound" + ], + "rationale": "PEP 695 distinguishes upper bounds from constrained TypeVars and requires __type_params__ to be a tuple, including the empty tuple for non-generic functions/classes. This test checks those public runtime classifications directly." + }, + "test.test_pep695_aug.TypeParameterSyntaxAugmentedTests.test_type_parameter_scopes_and_prohibited_expressions": { + "requirement_sections": [ + "Specification > Type Parameter Declarations", + "Specification > Type Parameter Scopes", + "Runtime Implementation > Scoping Behavior" + ], + "public_surface": "compile() and exec() over PEP 695 source snippets, observing SyntaxError and public __bound__ resolution.", + "mutants_targeted": [ + "mutant_033_symtable_duplicate_type_param_check_disabled", + "mutant_034_typeparam_scope_cannot_see_class_namespace", + "mutant_035_typevar_not_marked_as_type_parameter", + "mutant_036_typealias_scope_allows_prohibited_expressions", + "mutant_037_typeparam_scope_allows_prohibited_expressions", + "mutant_038_typevar_bound_scope_allows_prohibited_expressions" + ], + "rationale": "The type-parameter-scope sections require duplicate parameter rejection, prohibit assignment-expression/nonlocal escapes in annotation scopes, and allow nested type-parameter bounds to see the enclosing class namespace. The test checks these outcomes through compile() and executed source." + }, + "test.test_pep695_aug.TypeParameterSyntaxAugmentedTests.test_manual_ast_type_parameter_nodes_compile_and_validate": { + "requirement_sections": [ + "Runtime Implementation > AST Changes", + "Specification > Accessing Type Parameters at Runtime", + "Specification > Generic Type Alias" + ], + "public_surface": "Public ast.TypeVar, ast.ParamSpec, ast.TypeVarTuple, ast.TypeAlias, ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef constructors plus compile() and runtime __type_params__/__value__ metadata.", + "mutants_targeted": [], + "rationale": "The AST-change section makes type parameters first-class public AST nodes for functions, async functions, classes, and type aliases. This coverage-focused F2P constructs those public AST nodes manually, compiles them through the normal validator, and observes the resulting runtime metadata." + }, + "test.test_pep695_aug.TypeParameterSyntaxAugmentedTests.test_typing_runtime_dunder_and_paramspec_attr_contracts": { + "requirement_sections": [ + "Runtime Implementation > Library Changes", + "Specification > Runtime Type Alias Class", + "Specification > Compatibility with Traditional TypeVars" + ], + "public_surface": "Public typing.TypeVar, ParamSpec, TypeVarTuple, ParamSpecArgs/Kwargs, Callable specialization, tuple Unpack specialization, and class creation error behavior.", + "mutants_targeted": [], + "rationale": "PEP 695 moves the type-parameter runtime classes into the C-backed typing runtime while preserving public typing contracts. The test begins with PEP 695 syntax so it is F2P, then covers public dunder, repr, equality, mro-entry rejection, Callable ParamSpec substitution, and TypeVarTuple substitution behavior." + }, + "test.test_pep695_aug.TypeParameterSyntaxAugmentedTests.test_regenerated_parser_keeps_broad_public_grammar_paths": { + "requirement_sections": [ + "Runtime Implementation > Grammar Changes", + "Specification > Type Parameter Declarations", + "Specification > Generic Type Alias" + ], + "public_surface": "compile() over public Python source strings covering PEP 695 class/type syntax plus existing lambda, comprehension, function, async, exception-group, pattern matching, f-string, with-statement, and invalid-syntax grammar paths.", + "mutants_targeted": [], + "rationale": "PEP 695 regenerates Parser/parser.c from the public grammar. This coverage-focused F2P first gates on PEP 695 syntax so it fails in the pre-state, then parses a broad suite of public grammar forms to exercise regenerated parser paths and preserve unrelated syntax behavior." + } + }, + "pass_to_pass": { + "test.test_pep695_stability_aug.TypeParameterSyntaxStabilityAugmentedTests.test_regular_class_and_function_execution_are_stable": { + "requirement_sections": [ + "Specification > Compatibility with Traditional TypeVars" + ], + "public_surface": "Regular Python class/function execution, varargs, loops, and list comprehensions.", + "rationale": "PEP 695 adds generic type-parameter syntax without changing ordinary class/function execution. This P2P pins unrelated interpreter behavior in the same compiler/runtime neighborhood." + }, + "test.test_pep695_stability_aug.TypeParameterSyntaxStabilityAugmentedTests.test_string_template_and_formatter_are_stable": { + "requirement_sections": [ + "Specification > Compatibility with Traditional TypeVars" + ], + "public_surface": "Public string.Template substitution and str.format.", + "rationale": "The PR changes parser, compiler, and typing surfaces but should not affect existing string formatting behavior." + }, + "test.test_pep695_stability_aug.TypeParameterSyntaxStabilityAugmentedTests.test_numeric_literal_and_float_roundtrip_behaviour_is_stable": { + "requirement_sections": [ + "Specification > Compatibility with Traditional TypeVars" + ], + "public_surface": "Public int() parsing and float.hex/fromhex round trip.", + "rationale": "Numeric literal parsing and float round-trip behavior are unrelated public stdlib/interpreter features that should remain stable." + }, + "test.test_pep695_stability_aug.TypeParameterSyntaxStabilityAugmentedTests.test_sys_frame_metadata_for_regular_calls_is_stable": { + "requirement_sections": [ + "Specification > Compatibility with Traditional TypeVars" + ], + "public_surface": "sys._getframe() metadata for an ordinary Python function call.", + "rationale": "Regular frame metadata for non-generic functions should remain unchanged while generic functions gain __type_params__." + } + } + } + }, + "repo": "python/cpython", + "image": "lolbench/cpython_10:1.0.0", + "pr_head_sha": "08d931c23f434d7493e1853685ef528430f162d6", + "diff_source": "github_pr_cache", + "agent_contract": { + "input": "/logs/artifacts/solution.patch", + "output": "/logs/verifier/agent_report.json", + "invocation": "harbor run -p harbor_tasks/cpython_10 -a oracle --ve LOLBENCH_SUITE=union" + }, + "test_framework": "cpython_regrtest", + "test_cmd_template": "python -m test ", + "log_parser": "python_unittest", + "coverage": { + "orig": 68.17, + "aug": 78.15, + "union": 81.87, + "denominator": "union_executable_lines" + }, + "dockerhub_image": "smartdub26/lolbench-linux:cpython_10-1.0.0", + "dockerhub_digest": "sha256:7e254b1d1c3835dbfd919156c670bf396e090e1f03fcc0bb34db67f292940200", + "dockerhub_index_digest": "sha256:bc74a6fe7f7a576127caca6ef5df2059bd31e41ab9c133966290d2d03d24208b", + "dockerhub_platform": "linux/amd64", + "validation_status": "harbor_validated", + "harbor_validation_summary": { + "validated_at": "2026-06-22", + "modes_run_dir": "harbor_validation/cpython_10/current_harbor_modes", + "mutants_run_dir": "harbor_validation/cpython_10/current_harbor_mutants_rerun", + "modes": { + "orig": { + "pre": { + "build": { + "status": "ok" + }, + "f2p": { + "errored": 88, + "failed": 0, + "passed": 0, + "skipped": 0, + "total": 88 + }, + "p2p": { + "errored": 0, + "failed": 0, + "passed": 180, + "skipped": 0, + "total": 180 + }, + "resolved": false + }, + "post": { + "build": { + "status": "ok" + }, + "f2p": { + "errored": 0, + "failed": 0, + "passed": 88, + "skipped": 0, + "total": 88 + }, + "p2p": { + "errored": 0, + "failed": 0, + "passed": 180, + "skipped": 0, + "total": 180 + }, + "resolved": true + } + }, + "aug": { + "pre": { + "build": { + "status": "ok" + }, + "f2p": { + "errored": 11, + "failed": 1, + "passed": 0, + "skipped": 0, + "total": 12 + }, + "p2p": { + "errored": 0, + "failed": 0, + "passed": 4, + "skipped": 0, + "total": 4 + }, + "resolved": false + }, + "post": { + "build": { + "status": "ok" + }, + "f2p": { + "errored": 0, + "failed": 0, + "passed": 12, + "skipped": 0, + "total": 12 + }, + "p2p": { + "errored": 0, + "failed": 0, + "passed": 4, + "skipped": 0, + "total": 4 + }, + "resolved": true + } + }, + "union": { + "pre": { + "build": { + "status": "ok" + }, + "f2p": { + "errored": 99, + "failed": 1, + "passed": 0, + "skipped": 0, + "total": 100 + }, + "p2p": { + "errored": 0, + "failed": 0, + "passed": 184, + "skipped": 0, + "total": 184 + }, + "resolved": false + }, + "post": { + "build": { + "status": "ok" + }, + "f2p": { + "errored": 0, + "failed": 0, + "passed": 100, + "skipped": 0, + "total": 100 + }, + "p2p": { + "errored": 0, + "failed": 0, + "passed": 184, + "skipped": 0, + "total": 184 + }, + "resolved": true + } + } + }, + "mutants": { + "total": 40, + "killed": 40, + "survivors": [], + "all_killed": true, + "p2p_anomalies": [], + "apply_or_build_or_harness_anomalies": [] + }, + "image": { + "local": "lolbench/cpython_10:1.0.0", + "dockerhub": "smartdub26/lolbench:cpython_10-1.0.0", + "dockerhub_digest": "sha256:61e0ef941d70f8c0231bb9545ca6348645400cc7a6fa994877568da786d70a74", + "platform": "linux/arm64", + "local_image_id": "sha256:08e61b4cfdce94913bf348da035331c15863b5ba483e80add2dfe5d2960669e8" + } + } +} diff --git a/cpython_10/tests/report_to_reward.py b/cpython_10/tests/report_to_reward.py new file mode 100644 index 0000000000000000000000000000000000000000..21d4199201b90babd4abaa6e1c6801ea1996a905 --- /dev/null +++ b/cpython_10/tests/report_to_reward.py @@ -0,0 +1,73 @@ +#!/usr/bin/env python3 +import argparse +import json +from pathlib import Path + + +def rate(bucket): + total = float(bucket.get("total", 0) or 0) + if total <= 0: + return 0.0 + return float(bucket.get("passed", 0) or 0) / total + + +def write_json(path, payload): + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(json.dumps(payload, indent=2, sort_keys=True) + "\n") + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument("--suite", default="union") + parser.add_argument("--missing-patch") + parser.add_argument("--invalid-suite", action="store_true") + parser.add_argument("--runner-rc", type=int, default=0) + parser.add_argument("agent_report") + parser.add_argument("reward_file") + args = parser.parse_args() + + report_path = Path(args.agent_report) + reward_path = Path(args.reward_file) + + if args.invalid_suite: + reward = {"reward": 0.0, "resolved": 0.0, "applied": 0.0, "build_ok": 0.0, "f2p_pass_rate": 0.0, "p2p_pass_rate": 0.0, "harness_ok": 1.0} + sanitized = {"instance_id": "cpython_10", "suite": args.suite, "applied": False, "resolved": False, "error_categories": ["invalid_lolbench_suite"]} + write_json(report_path, sanitized) + write_json(reward_path, reward) + print(f"LoLBench reward=0 invalid suite {args.suite!r}") + return 0 + + if args.missing_patch: + reward = {"reward": 0.0, "resolved": 0.0, "applied": 0.0, "build_ok": 0.0, "f2p_pass_rate": 0.0, "p2p_pass_rate": 0.0, "harness_ok": 1.0} + sanitized = {"instance_id": "cpython_10", "suite": args.suite, "applied": False, "resolved": False, "error_categories": ["missing_solution_patch"]} + write_json(report_path, sanitized) + write_json(reward_path, reward) + print("LoLBench reward=0 missing solution patch") + return 0 + + if not report_path.exists(): + reward = {"reward": 0.0, "resolved": 0.0, "applied": 0.0, "build_ok": 0.0, "f2p_pass_rate": 0.0, "p2p_pass_rate": 0.0, "harness_ok": 0.0} + write_json(reward_path, reward) + print(f"LoLBench reward=0 no agent_report.json runner_rc={args.runner_rc}") + return 0 + + report = json.loads(report_path.read_text()) + build_status = report.get("build", {}).get("status") + resolved = bool(report.get("resolved")) + applied = bool(report.get("applied")) + reward = { + "reward": 1.0 if resolved else 0.0, + "resolved": 1.0 if resolved else 0.0, + "applied": 1.0 if applied else 0.0, + "build_ok": 1.0 if build_status == "ok" else 0.0, + "f2p_pass_rate": rate(report.get("f2p", {})), + "p2p_pass_rate": rate(report.get("p2p", {})), + "harness_ok": 1.0 if args.runner_rc == 0 else 0.0, + } + write_json(reward_path, reward) + print("LoLBench reward={reward} resolved={resolved} f2p={f2p_pass_rate:.3f} p2p={p2p_pass_rate:.3f}".format(**reward)) + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/cpython_10/tests/test.sh b/cpython_10/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..45ba2abd4f682d021752e6966a772a0ee2edb9f5 --- /dev/null +++ b/cpython_10/tests/test.sh @@ -0,0 +1,43 @@ +#!/usr/bin/env bash +set -euo pipefail + +suite=${LOLBENCH_SUITE:-union} +mode=${LOLBENCH_MODE:-eval} +patch=${LOLBENCH_SOLUTION_PATCH:-/logs/artifacts/solution.patch} +private_log=/tmp/lolbench-private-run.log + +mkdir -p /logs/verifier /logs/artifacts /in /out + +case "$suite" in + orig|aug|union) ;; + *) + python3 /tests/report_to_reward.py --suite "$suite" --invalid-suite /out/agent_report.json /logs/verifier/reward.json + exit 0 + ;; +esac + +if [ "$mode" = "eval" ] && [ ! -s "$patch" ]; then + python3 /tests/report_to_reward.py --suite "$suite" --missing-patch "$patch" /out/agent_report.json /logs/verifier/reward.json + exit 0 +fi + +if [ "$mode" = "eval" ]; then + cp "$patch" /in/solution.patch + chmod 0400 /in/solution.patch +fi + +set +e +LOLBENCH_MODE="$mode" LOLBENCH_SUITE="$suite" /opt/lolbench/private/run_tests.sh >"$private_log" 2>&1 +runner_rc=$? +set -e + +cp "$private_log" /logs/verifier/private_run.log +if [ -f /out/grader_report.json ]; then + cp /out/grader_report.json /logs/verifier/grader_report.json +fi + +python3 /tests/report_to_reward.py --suite "$suite" --runner-rc "$runner_rc" /out/agent_report.json /logs/verifier/reward.json + +if [ -f /out/agent_report.json ]; then + cp /out/agent_report.json /logs/verifier/agent_report.json +fi diff --git a/cpython_11/README.md b/cpython_11/README.md new file mode 100644 index 0000000000000000000000000000000000000000..c5c0cfaddb4c72fd02eb1b6dda839970a889a941 --- /dev/null +++ b/cpython_11/README.md @@ -0,0 +1,87 @@ +# LoLBench Harbor Task: cpython_11 + +This is a Harbor-format LoLBench task generated from `CPython_PEP-696_Type-Defaults-for-Type-Parameters_PR-116129`. + +Selected source instance: + +- Harbor ID: `cpython_11` +- PR: `python/cpython#116129` +- Base commit: `852263e1086748492602a90347ecc0a3925e1dda` +- Test modes: `orig, aug, union` +- Default/canonical mode: `union` +- Harbor image: `smartdub26/lolbench-linux:cpython_11-1.0.0` +- Docker Hub image: `smartdub26/lolbench-linux:cpython_11-1.0.0` + +## Image Setup + +Prefer the published Docker Hub image when it is available. Harbor refers to +the image as `smartdub26/lolbench-linux:cpython_11-1.0.0`, so Docker can pull it +directly when it is not present locally: + +```bash +docker pull smartdub26/lolbench-linux:cpython_11-1.0.0 +``` + +Only if the Docker Hub image is unavailable, build the single task image +locally: + +```bash +docker build -t lolbench/cpython_11:1.0.0 harbor_tasks/cpython_11/environment +docker tag lolbench/cpython_11:1.0.0 smartdub26/lolbench-linux:cpython_11-1.0.0 +``` + +The image contains the processed source tree at the base commit under +`/workspace/cpython`. Harbor must not mount a host source checkout +for the agent. + +## Run an Agent + +```bash +.harbor-venv/bin/harbor run \ + -p harbor_tasks/cpython_11 \ + -a codex \ + -m "" \ + --job-name cpython_11_agent_union \ + --jobs-dir harbor_runs/cpython_11 \ + --no-delete \ + --n-concurrent 1 \ + --ve LOLBENCH_SUITE=union +``` + +After implementing the requirement, the agent must clean any test-file edits +and run: + +```bash +lolbench-submit +``` + +## Evaluate a Patch + +Choose one mode with `LOLBENCH_SUITE=orig`, `aug`, or `union`; if unset, the +task defaults to `union`. + +```bash +PATCH="$(pwd)/path/to/solution.patch" + +.harbor-venv/bin/harbor run \ + -p harbor_tasks/cpython_11 \ + -a oracle \ + --job-name cpython_11_eval_union \ + --jobs-dir harbor_runs/cpython_11 \ + --no-delete \ + --n-concurrent 1 \ + --mounts '[{"type":"bind","source":"'"$PATCH"'","target":"/candidate/solution.patch","read_only":true}]' \ + --ae LOLBENCH_ORACLE_PATCH=/candidate/solution.patch \ + --ve LOLBENCH_SUITE=union +``` + +Outputs: + +```bash +find harbor_runs/cpython_11/cpython_11_eval_union -path '*/verifier/agent_report.json' -print +find harbor_runs/cpython_11/cpython_11_eval_union -path '*/verifier/reward.json' -print +``` + +`tests/docker-compose.yaml` is a verifier-only Harbor overlay. It mounts +`tests/`, `tests/private/`, and `solution/` into the separate verifier +container; none of those paths are mounted into the agent container. diff --git a/cpython_11/environment/Dockerfile b/cpython_11/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..8da13e8e3107190722c3fe60c1dfbe58074cf8ec --- /dev/null +++ b/cpython_11/environment/Dockerfile @@ -0,0 +1,128 @@ +# LoLBench eval image: CPython PR-116129 (PEP 696: Type Defaults for Type Parameters) +# Requirement: https://peps.python.org/pep-0696/ +# base_commit: 852263e1086748492602a90347ecc0a3925e1dda (parent of squash- +# merge commit ca269e58c290be8ca11bb728004ea842d9f85e3a — +# see spec.json base_commit_note) +# +# Agent-facing contract (the agent does NOT run anything inside this image; +# the evaluator runs the container after the agent submits a solution.patch): +# +# docker run --rm \ +# --network=none \ +# -v $(pwd)/solution.patch:/in/solution.patch:ro \ +# -v $(pwd)/out:/out \ +# lolbench/cpython-pr-116129:1 +# +# PEP 696 adds `default=` to type parameters: `class C[T = int]:` / +# `def f[T = int]():` / `type Alias[T = int] = ...`, plus the same +# default= kwarg on typing.TypeVar/ParamSpec/TypeVarTuple. The change +# touches the grammar (Grammar/python.gram, Parser/Python.asdl, +# Parser/parser.c), the AST machinery (Python/ast.c, Python-ast.c, +# pycore_ast*.h), the typing module + C accelerator (Lib/typing.py, +# Modules/_typingmodule.c, Objects/typevarobject.c), and the +# compile/symtable wiring that emits the new SET_FUNCTION_ATTRIBUTE +# intrinsic. +# +# No special capabilities are needed. The container stays --network=none +# with the default seccomp profile. +# +# Because the agent's code never executes here, the container runs every +# step as root — no agent UID, no chown of /usr/local, no runuser dance. +# +# Layered build per docs/executable_environment_plan.md §4: +# layer 1: ubuntu:22.04 +# layer 2: lolbench/cpython-base:1 (toolchain + stdlib build deps) +# layer 3: THIS image (cpython @ base_commit + built python + private bundle) + +ARG BASE_IMAGE=lolbench/cpython-base:1 +FROM ${BASE_IMAGE} + +ARG BASE_COMMIT=852263e1086748492602a90347ecc0a3925e1dda + +RUN mkdir -p /opt/lolbench/private /in /out /workspace + +WORKDIR /workspace +RUN git init cpython && \ + cd cpython && \ + git remote add origin https://github.com/python/cpython.git && \ + git fetch --no-tags origin ${BASE_COMMIT} && \ + git checkout ${BASE_COMMIT} && \ + git config user.email lolbench@local && \ + git config user.name lolbench && \ + if ! git diff --quiet || ! git diff --cached --quiet || [ -n "$(git ls-files --others --exclude-standard)" ]; then \ + git add -A && git -c commit.gpgsign=false commit -q -m "LoLBench environment overlay"; \ + fi && \ + git tag -f base && git tag -f lolbench-base && \ + git for-each-ref --format='%(refname)' refs/heads refs/remotes refs/tags | \ + while read ref; do \ + case "$ref" in refs/tags/base|refs/tags/lolbench-base) ;; *) git update-ref -d "$ref" ;; esac; \ + done && \ + ( git remote remove origin 2>/dev/null || true ) && \ + rm -f .git/FETCH_HEAD && \ + git reflog expire --expire=now --all && \ + git repack -Ad && \ + git prune --expire=now && \ + git config --global --add safe.directory /workspace/cpython + +# Pre-build CPython at base_commit. solution.patch touches Grammar/python.gram +# + Parser/Python.asdl, but `make` regenerates the parser tables and Python-ast.c +# from those sources via the standard build rules. No configure.ac / +# Makefile.pre.in / pyconfig.h.in changes — no reconfigure is needed at eval time. +SHELL ["/bin/bash", "-o", "pipefail", "-c"] +RUN cd /workspace/cpython && \ + ./configure --prefix=/usr/local --enable-optimizations=no && \ + jobs=$(awk '$1!="max"{printf("%d", ($1+$2-1)/$2)}' /sys/fs/cgroup/cpu.max 2>/dev/null); \ + : "${jobs:=$(nproc)}"; \ + [ "$jobs" -lt 1 ] && jobs=1; \ + make -j"$jobs" 2>&1 | tee /tmp/cpython-build.log | tail -400 + +# Harbor runtime adapter: keep the image public/agent-safe. +RUN mkdir -p /opt/lolbench /logs/artifacts /logs/agent /logs/verifier /in /out && \ + if ! id -u agent >/dev/null 2>&1; then useradd -m -s /bin/bash agent; fi +COPY metadata.json /opt/lolbench/metadata.json +COPY lolbench-submit /usr/local/bin/lolbench-submit +RUN chmod +x /usr/local/bin/lolbench-submit && \ + git config --global --add safe.directory /workspace/cpython && \ + if [ -d /workspace/cpython/.git ]; then \ + cd /workspace/cpython && git ls-files --others --exclude-standard | sort > /opt/lolbench/base_untracked.txt; \ + else \ + : > /opt/lolbench/base_untracked.txt; \ + fi && \ + chown -R agent:agent /workspace/cpython /logs +# Local-reference hardening: retain only the approved base history. +RUN cd /workspace/cpython && \ + git for-each-ref --format='%(refname)' refs/heads refs/remotes refs/tags | \ + while read ref; do \ + case "$ref" in refs/tags/base|refs/tags/lolbench-base) ;; *) git update-ref -d "$ref" ;; esac; \ + done && \ + ( git remote remove origin 2>/dev/null || true ) && \ + rm -f .git/FETCH_HEAD && \ + git reflog expire --expire=now --all && \ + git repack -Ad && \ + git prune --expire=now && \ + unreachable=$(git fsck --unreachable --no-reflogs) && \ + test -z "$unreachable" && \ + chown -R agent:agent .git +# Remove installed Python source copies/backports and package caches. +RUN for root in /usr/local/lib /usr/lib; do \ + [ ! -d "$root" ] || find "$root" -type d \ + \( -path '*/site-packages/pip' -o -path '*/dist-packages/pip' -o \ + -name ensurepip -o -name tomllib -o -name zoneinfo -o \ + -path '*/site-packages/tomli*' -o -path '*/dist-packages/tomli*' -o \ + -path '*/site-packages/typing_extensions*' -o -path '*/dist-packages/typing_extensions*' -o \ + -path '*/site-packages/exceptiongroup*' -o -path '*/dist-packages/exceptiongroup*' \) \ + -prune -exec rm -rf '{}' +; \ + [ ! -d "$root" ] || find "$root" -type f \ + \( -name 'tomli*.py' -o -name 'typing_extensions*.py' -o -name 'exceptiongroup*.py' \) -delete; \ + done && \ + rm -rf /usr/share/python-wheels /usr/share/python3-wheels \ + /root/.cache/pip /root/.cache/uv /home/agent/.cache/pip /home/agent/.cache/uv && \ + rm -f /usr/local/bin/pip /usr/local/bin/pip3 /usr/local/bin/pip3.* \ + /usr/bin/pip /usr/bin/pip3 /usr/bin/pip3.* && \ + for p in /usr/local/lib/python*/site-packages /usr/lib/python*/dist-packages; do \ + [ ! -d "$p" ] || { chown -R root:root "$p"; chmod -R go-w "$p"; chmod 0711 "$p"; }; \ + done +USER agent +WORKDIR /workspace/cpython +ENV LOLBENCH_INSTANCE_ID=cpython_11 +ENV LOLBENCH_SOURCE_SLUG=CPython_PEP-696_Type-Defaults-for-Type-Parameters_PR-116129 diff --git a/cpython_11/environment/docker-compose.yaml b/cpython_11/environment/docker-compose.yaml new file mode 100644 index 0000000000000000000000000000000000000000..7ed45f87dc9faf9df284f5b10d6d2289781ff254 --- /dev/null +++ b/cpython_11/environment/docker-compose.yaml @@ -0,0 +1,3 @@ +services: + main: + pull_policy: missing diff --git a/cpython_11/environment/lolbench-submit b/cpython_11/environment/lolbench-submit new file mode 100644 index 0000000000000000000000000000000000000000..0f89163f3f975ed8856ef411059c188c40e2eabc --- /dev/null +++ b/cpython_11/environment/lolbench-submit @@ -0,0 +1,32 @@ +#!/usr/bin/env bash +set -euo pipefail + +repo=${1:-$PWD} +out=${LOLBENCH_PATCH_OUT:-/logs/artifacts/solution.patch} + +mkdir -p "$(dirname "$out")" +cd "$repo" + +baseline=/opt/lolbench/base_untracked.txt +current=$(mktemp) +new_files=$(mktemp) +trap 'rm -f "$current" "$new_files"' EXIT + +git ls-files --others --exclude-standard | sort > "$current" +if [ -f "$baseline" ]; then + comm -13 "$baseline" "$current" > "$new_files" +else + cp "$current" "$new_files" +fi + +if [ -s "$new_files" ]; then + xargs -r git add -N -- < "$new_files" +fi + +git diff --binary > "$out" + +if [ ! -s "$out" ]; then + echo "warning: wrote an empty solution patch to $out" >&2 +else + echo "wrote solution patch to $out" +fi diff --git a/cpython_11/environment/metadata.json b/cpython_11/environment/metadata.json new file mode 100644 index 0000000000000000000000000000000000000000..f1f5f7a77998434819cb2d2e709fe95fe7e305ae --- /dev/null +++ b/cpython_11/environment/metadata.json @@ -0,0 +1,22 @@ +{ + "instance_id": "cpython_11", + "source_instance_id": "CPython_PEP-696_Type-Defaults-for-Type-Parameters_PR-116129", + "source_slug": "CPython_PEP-696_Type-Defaults-for-Type-Parameters_PR-116129", + "docker_slug": "CPython_PEP-696_Type-Defaults-for-Type-Parameters_PR-116129", + "dockerhub_image": "smartdub26/lolbench-linux:cpython_11-1.0.0", + "project": "cpython", + "repo": "python/cpython", + "requirement_doc": "https://peps.python.org/pep-0696/", + "pr_link": "https://github.com/python/cpython/pull/116129", + "base_commit": "852263e1086748492602a90347ecc0a3925e1dda", + "merge_commit": "ca269e58c290be8ca11bb728004ea842d9f85e3a", + "source_history_policy": "ancestors-only", + "lolbench_test_modes": [ + "orig", + "aug", + "union" + ], + "default_lolbench_suite": "union", + "canonical_lolbench_suite": "union", + "augmentation_available": true +} diff --git a/cpython_11/environment/source_audit.json b/cpython_11/environment/source_audit.json new file mode 100644 index 0000000000000000000000000000000000000000..21894c087f9d07fd7e57c0f2fe3b2ea1bdd83172 --- /dev/null +++ b/cpython_11/environment/source_audit.json @@ -0,0 +1,7 @@ +{ + "source_policy": "dockerfile_fetch_pruned_ancestor_history", + "local_reference_policy": "auxiliary_sources_removed_execute_only", + "base_commit": "852263e1086748492602a90347ecc0a3925e1dda", + "repo": "python/cpython", + "note": "The Dockerfile fetches only the declared base history, removes refs/remotes/reflogs, repacks and prunes unreachable objects, asserts that git fsck finds no unreachable object, removes auxiliary reference sources, and makes remaining auxiliary toolchains root-owned and non-enumerable to the agent." +} diff --git a/cpython_11/instruction.md b/cpython_11/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..109b4ea53c65f88828c05699a67053efa01acbcd --- /dev/null +++ b/cpython_11/instruction.md @@ -0,0 +1,651 @@ +You are working in `/workspace/cpython`, a source tree checked out at +the base commit for this task. Implement the requested behavior in the source +tree, then run: + +```bash +lolbench-submit +``` + +Do not stop after editing files, running tests, or describing the solution. The +task is complete only when `lolbench-submit` has created +`/logs/artifacts/solution.patch`. If that file does not exist, continue +working and run `lolbench-submit` again. + +That command writes your implementation diff to +`/logs/artifacts/solution.patch`, which is the artifact the Harbor verifier +will grade. Before running `lolbench-submit`, clean or revert any test files +you created or modified; test files must not be included in the final +`solution.patch`. + +This environment has no outbound internet access — `curl`/`wget`, `git fetch`/`clone`, package installs, and web fetch/search will all fail. Implement the requirements using only the code already in the workspace and your own knowledge; do not attempt to fetch or search external resources. + +Now please implement the following requirements in the source tree: + +--- + +# PEP 696: Type Defaults for Type Parameters + +## Abstract +This PEP introduces the concept of type defaults for type parameters, +including `TypeVar`, `ParamSpec`, and `TypeVarTuple`, +which act as defaults for type parameters for which no type is specified. + +Default type argument support is available in some popular languages +such as C++, TypeScript, and Rust. A survey of type parameter syntax in +some common languages has been conducted by the author of PEP 695 +and can be found in its +`Appendix A <695#appendix-a-survey-of-type-parameter-syntax>`. + +## Motivation + +``` +T = TypeVar("T", default=int) # This means that if no type is specified T = int + +@dataclass +class Box(Generic[T]): + value: T | None = None + +reveal_type(Box()) # type is Box[int] +reveal_type(Box(value="Hello World!")) # type is Box[str] +``` +One place this [regularly comes up](https://github.com/python/typing/issues/975) is `Generator`. I +propose changing the *stub definition* to something like: + +``` +YieldT = TypeVar("YieldT") +SendT = TypeVar("SendT", default=None) +ReturnT = TypeVar("ReturnT", default=None) + +class Generator(Generic[YieldT, SendT, ReturnT]): ... + +Generator[int] == Generator[int, None] == Generator[int, None, None] +``` +This is also useful for a `Generic` that is commonly over one type. + +``` +class Bot: ... + +BotT = TypeVar("BotT", bound=Bot, default=Bot) + +class Context(Generic[BotT]): + bot: BotT + +class MyBot(Bot): ... + +reveal_type(Context().bot) # type is Bot # notice this is not Any which is what it would be currently +reveal_type(Context[MyBot]().bot) # type is MyBot +``` +Not only does this improve typing for those who explicitly use it, it +also helps non-typing users who rely on auto-complete to speed up their +development. + +This design pattern is common in projects like: + +- [discord.py](https://github.com/Rapptz/discord.py) — where the + example above was taken from. +- [NumPy](https://github.com/numpy/numpy) — the default for types + like `ndarray`'s `dtype` would be `float64`. Currently it's + `Unknown` or `Any`. +- [TensorFlow](https://github.com/tensorflow/tensorflow) — this + could be used for Tensor similarly to `numpy.ndarray` and would be + useful to simplify the definition of `Layer`. + +## Specification +### Default Ordering and Subscription Rules +The order for defaults should follow the standard function parameter +rules, so a type parameter with no `default` cannot follow one with +a `default` value. Doing so should ideally raise a `TypeError` in +`typing._GenericAlias`/`types.GenericAlias`, and a type checker +should flag this as an error. + +``` +DefaultStrT = TypeVar("DefaultStrT", default=str) +DefaultIntT = TypeVar("DefaultIntT", default=int) +DefaultBoolT = TypeVar("DefaultBoolT", default=bool) +T = TypeVar("T") +T2 = TypeVar("T2") + +class NonDefaultFollowsDefault(Generic[DefaultStrT, T]): ... # Invalid: non-default TypeVars cannot follow ones with defaults + +class NoNonDefaults(Generic[DefaultStrT, DefaultIntT]): ... + +( + NoNoneDefaults == + NoNoneDefaults[str] == + NoNoneDefaults[str, int] +) # All valid + +class OneDefault(Generic[T, DefaultBoolT]): ... + +OneDefault[float] == OneDefault[float, bool] # Valid +reveal_type(OneDefault) # type is type[OneDefault[T, DefaultBoolT = bool]] +reveal_type(OneDefault[float]()) # type is OneDefault[float, bool] + +class AllTheDefaults(Generic[T1, T2, DefaultStrT, DefaultIntT, DefaultBoolT]): ... + +reveal_type(AllTheDefaults) # type is type[AllTheDefaults[T1, T2, DefaultStrT = str, DefaultIntT = int, DefaultBoolT = bool]] +reveal_type(AllTheDefaults[int, complex]()) # type is AllTheDefaults[int, complex, str, int, bool] +AllTheDefaults[int] # Invalid: expected 2 arguments to AllTheDefaults +( + AllTheDefaults[int, complex] == + AllTheDefaults[int, complex, str] == + AllTheDefaults[int, complex, str, int] == + AllTheDefaults[int, complex, str, int, bool] +) # All valid +``` +With the new Python 3.12 syntax for generics (introduced by PEP 695), this can +be enforced at compile time: + +``` +type Alias[DefaultT = int, T] = tuple[DefaultT, T] # SyntaxError: non-default TypeVars cannot follow ones with defaults + +def generic_func[DefaultT = int, T](x: DefaultT, y: T) -> None: ... # SyntaxError: non-default TypeVars cannot follow ones with defaults + +class GenericClass[DefaultT = int, T]: ... # SyntaxError: non-default TypeVars cannot follow ones with defaults +``` +`ParamSpec` Defaults +'''''''''''''''''''''' + +`ParamSpec` defaults are defined using the same syntax as +`TypeVar` \ s but use a `list` of types or an ellipsis +literal "`...`" or another in-scope `ParamSpec` (see `Scoping Rules`_). + +``` +DefaultP = ParamSpec("DefaultP", default=[str, int]) + +class Foo(Generic[DefaultP]): ... + +reveal_type(Foo) # type is type[Foo[DefaultP = [str, int]]] +reveal_type(Foo()) # type is Foo[[str, int]] +reveal_type(Foo[[bool, bool]]()) # type is Foo[[bool, bool]] +``` +`TypeVarTuple` Defaults +''''''''''''''''''''''''' + +`TypeVarTuple` defaults are defined using the same syntax as +`TypeVar` \ s but use an unpacked tuple of types instead of a single type +or another in-scope `TypeVarTuple` (see `Scoping Rules`_). + +``` +DefaultTs = TypeVarTuple("DefaultTs", default=Unpack[tuple[str, int]]) + +class Foo(Generic[*DefaultTs]): ... + +reveal_type(Foo) # type is type[Foo[DefaultTs = *tuple[str, int]]] +reveal_type(Foo()) # type is Foo[str, int] +reveal_type(Foo[int, bool]()) # type is Foo[int, bool] +``` +### Using Another Type Parameter as `default` +This allows for a value to be used again when the type parameter to a +generic is missing but another type parameter is specified. + +To use another type parameter as a default the `default` and the +type parameter must be the same type (a `TypeVar`'s default must be +a `TypeVar`, etc.). + +[This could be used on builtins.slice](https://github.com/python/typing/issues/159) +where the `start` parameter should default to `int`, `stop` +default to the type of `start` and step default to `int | None`. + +``` +StartT = TypeVar("StartT", default=int) +StopT = TypeVar("StopT", default=StartT) +StepT = TypeVar("StepT", default=int | None) + +class slice(Generic[StartT, StopT, StepT]): ... + +reveal_type(slice) # type is type[slice[StartT = int, StopT = StartT, StepT = int | None]] +reveal_type(slice()) # type is slice[int, int, int | None] +reveal_type(slice[str]()) # type is slice[str, str, int | None] +reveal_type(slice[str, bool, timedelta]()) # type is slice[str, bool, timedelta] + +T2 = TypeVar("T2", default=DefaultStrT) + +class Foo(Generic[DefaultStrT, T2]): + def __init__(self, a: DefaultStrT, b: T2) -> None: ... + +reveal_type(Foo(1, "")) # type is Foo[int, str] +Foo[int](1, "") # Invalid: Foo[int, str] cannot be assigned to self: Foo[int, int] in Foo.__init__ +Foo[int]("", 1) # Invalid: Foo[str, int] cannot be assigned to self: Foo[int, int] in Foo.__init__ +``` +When using a type parameter as the default to another type parameter, the +following rules apply, where `T1` is the default for `T2`. + +#### Scoping Rules +`T1` must be used before `T2` in the parameter list of the generic. + +``` +T2 = TypeVar("T2", default=T1) + +class Foo(Generic[T1, T2]): ... # Valid +class Foo(Generic[T1]): + class Bar(Generic[T2]): ... # Valid + +StartT = TypeVar("StartT", default="StopT") # Swapped defaults around from previous example +StopT = TypeVar("StopT", default=int) +class slice(Generic[StartT, StopT, StepT]): ... + # ^^^^^^ Invalid: ordering does not allow StopT to be bound +``` +Using a type parameter from an outer scope as a default is not supported. + +#### Bound Rules +`T1`'s bound must be a subtype of `T2`'s bound. + +``` +T1 = TypeVar("T1", bound=int) +TypeVar("Ok", default=T1, bound=float) # Valid +TypeVar("AlsoOk", default=T1, bound=int) # Valid +TypeVar("Invalid", default=T1, bound=str) # Invalid: int is not a subtype of str +``` +#### Constraint Rules +The constraints of `T2` must be a superset of the constraints of `T1`. + +``` +T1 = TypeVar("T1", bound=int) +TypeVar("Invalid", float, str, default=T1) # Invalid: upper bound int is incompatible with constraints float or str + +T1 = TypeVar("T1", int, str) +TypeVar("AlsoOk", int, str, bool, default=T1) # Valid +TypeVar("AlsoInvalid", bool, complex, default=T1) # Invalid: {bool, complex} is not a superset of {int, str} +``` +#### Type Parameters as Parameters to Generics +Type parameters are valid as parameters to generics inside of a +`default` when the first parameter is in scope as determined by the +[previous section](scoping rules_). + +``` +T = TypeVar("T") +ListDefaultT = TypeVar("ListDefaultT", default=list[T]) + +class Bar(Generic[T, ListDefaultT]): + def __init__(self, x: T, y: ListDefaultT): ... + +reveal_type(Bar) # type is type[Bar[T, ListDefaultT = list[T]]] +reveal_type(Bar[int]) # type is type[Bar[int, list[int]]] +reveal_type(Bar[int]()) # type is Bar[int, list[int]] +reveal_type(Bar[int, list[str]]()) # type is Bar[int, list[str]] +reveal_type(Bar[int, str]()) # type is Bar[int, str] +``` +#### Specialisation Rules +Type parameters currently cannot be further subscripted. This might +change if [Higher Kinded TypeVars](https://github.com/python/typing/issues/548) +are implemented. + +`Generic` `TypeAlias`\ es +''''''''''''''''''''''''''''' + +`Generic` `TypeAlias`\ es should be able to be further subscripted +following normal subscription rules. If a type parameter has a default +that hasn't been overridden it should be treated like it was +substituted into the `TypeAlias`. However, it can be specialised +further down the line. + +``` +class SomethingWithNoDefaults(Generic[T, T2]): ... + +MyAlias: TypeAlias = SomethingWithNoDefaults[int, DefaultStrT] # Valid +reveal_type(MyAlias) # type is type[SomethingWithNoDefaults[int, DefaultStrT]] +reveal_type(MyAlias[bool]()) # type is SomethingWithNoDefaults[int, bool] + +MyAlias[bool, int] # Invalid: too many arguments passed to MyAlias +``` +### Subclassing +Subclasses of `Generic`\ s with type parameters that have defaults +behave similarly to `Generic` `TypeAlias`\ es. That is, subclasses can be +further subscripted following normal subscription rules, non-overridden +defaults should be substituted in, and type parameters with such defaults can be +further specialised down the line. + +``` +class SubclassMe(Generic[T, DefaultStrT]): + x: DefaultStrT + +class Bar(SubclassMe[int, DefaultStrT]): ... +reveal_type(Bar) # type is type[Bar[DefaultStrT = str]] +reveal_type(Bar()) # type is Bar[str] +reveal_type(Bar[bool]()) # type is Bar[bool] + +class Foo(SubclassMe[float]): ... + +reveal_type(Foo().x) # type is str + +Foo[str] # Invalid: Foo cannot be further subscripted + +class Baz(Generic[DefaultIntT, DefaultStrT]): ... + +class Spam(Baz): ... +reveal_type(Spam()) # type is +``` +### Using `bound` and `default` +If both `bound` and `default` are passed `default` must be a +subtype of `bound`. Otherwise the type checker should generate an +error. + +``` +TypeVar("Ok", bound=float, default=int) # Valid +TypeVar("Invalid", bound=str, default=int) # Invalid: the bound and default are incompatible +``` +### Constraints +For constrained `TypeVar`\ s, the default needs to be one of the +constraints. A type checker should generate an error even if it is a +subtype of one of the constraints. + +``` +TypeVar("Ok", float, str, default=float) # Valid +TypeVar("Invalid", float, str, default=int) # Invalid: expected one of float or str got int +``` +### Function Defaults +In generic functions, type checkers may use a type parameter's default when the +type parameter cannot be solved to anything. We leave the semantics of this +usage unspecified, as ensuring the `default` is returned in every code path +where the type parameter can go unsolved may be too hard to implement. Type +checkers are free to either disallow this case or experiment with implementing +support. + +``` +T = TypeVar('T', default=int) +def func(x: int | set[T]) -> T: ... +reveal_type(func(0)) # a type checker may reveal T's default of int here +``` +### Defaults following `TypeVarTuple` +A `TypeVar` that immediately follows a `TypeVarTuple` is not allowed +to have a default, because it would be ambiguous whether a type argument +should be bound to the `TypeVarTuple` or the defaulted `TypeVar`. + +``` +Ts = TypeVarTuple("Ts") +T = TypeVar("T", default=bool) + +class Foo(Generic[Ts, T]): ... # Type checker error + +## Could be reasonably interpreted as either Ts = (int, str, float), T = bool +## or Ts = (int, str), T = float +Foo[int, str, float] +``` +With the Python 3.12 built-in generic syntax, this case should raise a SyntaxError. + +However, it is allowed to have a `ParamSpec` with a default following a +`TypeVarTuple` with a default, as there can be no ambiguity between a type argument +for the `ParamSpec` and one for the `TypeVarTuple`. + +``` +Ts = TypeVarTuple("Ts") +P = ParamSpec("P", default=[float, bool]) + +class Foo(Generic[Ts, P]): ... # Valid + +Foo[int, str] # Ts = (int, str), P = [float, bool] +Foo[int, str, [bytes]] # Ts = (int, str), P = [bytes] +``` +### Subtyping +Type parameter defaults do not affect the subtyping rules for generic classes. +In particular, defaults can be ignored when considering whether a class is +compatible with a generic protocol. + +`TypeVarTuple`\ s as Defaults +''''''''''''''''''''''''''''''' + +Using a `TypeVarTuple` as a default is not supported because: + +- `Scoping Rules`_ does not allow usage of type parameters + from outer scopes. +- Multiple `TypeVarTuple`\ s cannot appear in the type + parameter list for a single object, as specified in + `646#multiple-type-variable-tuples-not-allowed`. + +These reasons leave no current valid location where a +`TypeVarTuple` could be used as the default of another `TypeVarTuple`. + +## Binding rules +Type parameter defaults should be bound by attribute access +(including call and subscript). + +``` +class Foo[T = int]: + def meth(self) -> Self: + return self + +reveal_type(Foo.meth) # type is (self: Foo[int]) -> Foo[int] +``` +## Implementation +At runtime, this would involve the following changes to the `typing` +module. + +- The classes `TypeVar`, `ParamSpec`, and `TypeVarTuple` should + expose the type passed to `default`. This would be available as + a `__default__` attribute, which would be the public `typing.NoDefault` + sentinel — a dedicated marker object returned in place of `None` when no + default is set, so that `None` itself stays usable as a genuine default — if + no argument is passed, and `NoneType` if `default=None`. + +The following changes would be required to both `GenericAlias`\ es: + +- logic to determine the defaults required for a subscription. +- ideally, logic to determine if subscription (like + `Generic[T, DefaultT]`) would be valid. + +The grammar for type parameter lists would need to be updated to +allow defaults; see below. + +A reference implementation of the runtime changes can be found at +https://github.com/Gobot1234/cpython/tree/pep-696 + +A reference implementation of the type checker can be found at +https://github.com/Gobot1234/mypy/tree/TypeVar-defaults + +Pyright currently supports this functionality. + +### Grammar changes +The syntax added in PEP 695 will be extended to introduce a way +to specify defaults for type parameters using the "=" operator inside +of the square brackets like so: + +``` +## TypeVars +class Foo[T = str]: ... + +## ParamSpecs +class Baz[**P = [int, str]]: ... + +## TypeVarTuples +class Qux[*Ts = *tuple[int, bool]]: ... + +## TypeAliases +type Foo[T, U = str] = Bar[T, U] +type Baz[**P = [int, str]] = Spam[**P] +type Qux[*Ts = *tuple[str]] = Ham[*Ts] +type Rab[U, T = str] = Bar[T, U] +``` +`Similarly to the bound for a type parameter <695-scoping-behavior>`, +defaults should be lazily evaluated, with the same scoping rules to +avoid the unnecessary usage of quotes around them. + +This functionality was included in the initial draft of PEP 695 but +was removed due to scope creep. + +The following changes would be made to the grammar: + +``` +type_param: + | a=NAME b=[type_param_bound] d=[type_param_default] + | a=NAME c=[type_param_constraint] d=[type_param_default] + | '*' a=NAME d=[type_param_default] + | '**' a=NAME d=[type_param_default] + +type_param_default: + | '=' e=expression + | '=' e=starred_expression +``` +The compiler would enforce that type parameters without defaults cannot +follow type parameters with defaults and that `TypeVar`\ s with defaults +cannot immediately follow `TypeVarTuple`\ s. + +## Rejected Alternatives +### Allowing the Type Parameters Defaults to Be Passed to `type.__new__`'s `**kwargs` + +``` +T = TypeVar("T") + +@dataclass +class Box(Generic[T], T=int): + value: T | None = None +``` +While this is much easier to read and follows a similar rationale to the +`TypeVar` [unary syntax](https://github.com/python/typing/issues/813), it would not be +backwards compatible as `T` might already be passed to a +metaclass/superclass or support classes that don't subclass `Generic` +at runtime. + +Ideally, if PEP 637 wasn't rejected, the following would be acceptable: + +``` +T = TypeVar("T") + +@dataclass +class Box(Generic[T = int]): + value: T | None = None +``` +### Allowing Non-defaults to Follow Defaults + +``` +YieldT = TypeVar("YieldT", default=Any) +SendT = TypeVar("SendT", default=Any) +ReturnT = TypeVar("ReturnT") + +class Coroutine(Generic[YieldT, SendT, ReturnT]): ... + +Coroutine[int] == Coroutine[Any, Any, int] +``` +Allowing non-defaults to follow defaults would alleviate the issues with +returning types like `Coroutine` from functions where the most used +type argument is the last (the return). Allowing non-defaults to follow +defaults is too confusing and potentially ambiguous, even if only the +above two forms were valid. Changing the argument order now would also +break a lot of codebases. This is also solvable in most cases using a +`TypeAlias`. + +``` +Coro: TypeAlias = Coroutine[Any, Any, T] +Coro[int] == Coroutine[Any, Any, int] +``` +### Having `default` Implicitly Be `bound` +In an earlier version of this PEP, the `default` was implicitly set +to `bound` if no value was passed for `default`. This while +convenient, could have a type parameter with no default follow a +type parameter with a default. Consider: + +``` +T = TypeVar("T", bound=int) # default is implicitly int +U = TypeVar("U") + +class Foo(Generic[T, U]): + ... + +## would expand to + +T = TypeVar("T", bound=int, default=int) +U = TypeVar("U") + +class Foo(Generic[T, U]): + ... +``` +This would have also been a breaking change for a small number of cases +where the code relied on `Any` being the implicit default. + +### Allowing Type Parameters With Defaults To Be Used in Function Signatures +A previous version of this PEP allowed `TypeVarLike`\s with defaults to be used in +function signatures. This was removed for the reasons described in +`Function Defaults`_. Hopefully, this can be added in the future if +a way to get the runtime value of a type parameter is added. + +### Allowing Type Parameters from Outer Scopes in `default` +This was deemed too niche a feature to be worth the added complexity. +If any cases arise where this is needed, it can be added in a future PEP. + +## Linked Issue #975 — Allow Generator type annotation to have one argument. + +To annotate a generator yielding an int, it's +--> Generator[int, None, None] + +That's really quite ugly. + +It should be Generator[int] + +Passing None does not fit the rest of Python where arguments are optional. Also in the rest of Python, the common cases are the default. This makes an unlikely case most prominent over the far more common case. It's Python's job to provide syntactic sugar to deal with the low-level details, not the user. This looks more like C. + +https://docs.python.org/3/library/typing.html#typing.Generator + +"Alternatively, annotate your generator as having a return type of either Iterable[YieldType] or Iterator[YieldType]" + +Yes a generator is an iterator and an iterator is an iterable but then why not set everything as Any? Are we annotating the types or not? That advice makes a mockery of the whole idea. Makes Python harder to teach for no good reason. "Put the type the function returns, unless it's a generator then do this..." + +Several people have pointed this out before, their bugs got closed without explanation. One suggested making a bug here, so this is it. Enjoy. + +https://github.com/python/mypy/issues/4221 +https://bugs.python.org/issue31700 + +I'm hoping this bug gets closed because someone's already fixed it in a development version. + +Cheers. + +*Source: https://github.com/python/typing/issues/975* + +## Linked Issue #159 — `builtins.slice` should be generic + +It is entirely reasonable that some libraries would have slices with a component type other than `int`. + +*Source: https://github.com/python/typing/issues/159* + +## Linked Issue #548 — Higher-Kinded TypeVars + +aka type constructors, generic TypeVars + +Has there already been discussion about those? +I do a lot of FP that results in impossible situations because of this. Consider an example: + +```python +A = TypeVar('A') +B = TypeVar('B') +F = TypeVar('F') + +class M(Generic[F[X], A]): + def x(fa: F[A], f: Callable[[A], B]) -> F[B]: + return map(f, fa) + +M().x([1], str) +``` + +I haven't found a way to make this work, does anyone know a trick or is it impossible? +If not, consider the syntax as a proposal. +Reference implementations would be Haskell, Scala. +optimally, the HK's type param would be indexable as well, allowing for `F[X[X, X], X[X]]` + +Summary of current status (by [user-redacted], 2024-02-08): + +- [user-redacted] [has indicated interest](https://github.com/python/typing/issues/548#issuecomment-1193345123) in sponsoring a PEP, conditional on a prototype implementation in a major type checker and a well-specified draft PEP. +- Drafting the PEP takes place in [user-redacted]'s [fork](https://github.com/nekitdev/peps) of the `peps` repo. The [**stub PEP draft**](https://github.com/nekitdev/peps/blob/main/pep-9999.rst) so far contains a few examples of the proposed syntax. +- That same repo's [**GitHub Discussions forum**](https://github.com/nekitdev/peps/discussions) forum has been [designated](https://github.com/python/typing/issues/548#issuecomment-1193348994) as the place to discuss the PEP (and presumably the prototype implementation?). Some limited further discussions have taken place there. + - If you want to be notified of new discussion threads, I think you have to set the whole repo as "watched" in GitHub? + +*Source: https://github.com/python/typing/issues/548* + +## Linked Issue #813 — [Feature Request] TypeVar variance definition alias + +Defining the two variances of a TypeVar is rather verbose: + +```python +T_co = TypeVar("T_co", covariant=True) +T_contra = TypeVar("T_contra", contravariant=True) +``` + +So I propose an alternative syntax, similar to that of [Scala's variances](https://docs.scala-lang.org/tour/variances.html): + +```python +T_co = +TypeVar("T_co") +T_contra = -TypeVar("T_contra") +``` + +Co- and contra-variance describe increasing and decreasing specificities of the typevars, respectively. So using `+` and `-` to symbolize these "directions" makes intuitive sense. + +*Source: https://github.com/python/typing/issues/813* + diff --git a/cpython_11/solution/solution.patch b/cpython_11/solution/solution.patch new file mode 100644 index 0000000000000000000000000000000000000000..70007ca6c63621c361d0b61dd2f7baa4a932a529 --- /dev/null +++ b/cpython_11/solution/solution.patch @@ -0,0 +1,3174 @@ +diff --git a/Grammar/python.gram b/Grammar/python.gram +index 05d7837e3a..1c1c53c4b7 100644 +--- a/Grammar/python.gram ++++ b/Grammar/python.gram +@@ -647,21 +647,25 @@ type_params[asdl_type_param_seq*]: '[' t=type_param_seq ']' { + type_param_seq[asdl_type_param_seq*]: a[asdl_type_param_seq*]=','.type_param+ [','] { a } + + type_param[type_param_ty] (memo): +- | a=NAME b=[type_param_bound] { _PyAST_TypeVar(a->v.Name.id, b, EXTRA) } ++ | a=NAME b=[type_param_bound] c=[type_param_default] { _PyAST_TypeVar(a->v.Name.id, b, c, EXTRA) } + | '*' a=NAME colon=':' e=expression { + RAISE_SYNTAX_ERROR_STARTING_FROM(colon, e->kind == Tuple_kind + ? "cannot use constraints with TypeVarTuple" + : "cannot use bound with TypeVarTuple") + } +- | '*' a=NAME { _PyAST_TypeVarTuple(a->v.Name.id, EXTRA) } ++ | '*' a=NAME b=[type_param_starred_default] { _PyAST_TypeVarTuple(a->v.Name.id, b, EXTRA) } + | '**' a=NAME colon=':' e=expression { + RAISE_SYNTAX_ERROR_STARTING_FROM(colon, e->kind == Tuple_kind + ? "cannot use constraints with ParamSpec" + : "cannot use bound with ParamSpec") + } +- | '**' a=NAME { _PyAST_ParamSpec(a->v.Name.id, EXTRA) } ++ | '**' a=NAME b=[type_param_default] { _PyAST_ParamSpec(a->v.Name.id, b, EXTRA) } + + type_param_bound[expr_ty]: ':' e=expression { e } ++type_param_default[expr_ty]: '=' e=expression { ++ CHECK_VERSION(expr_ty, 13, "Type parameter defaults are", e) } ++type_param_starred_default[expr_ty]: '=' e=star_expression { ++ CHECK_VERSION(expr_ty, 13, "Type parameter defaults are", e) } + + # EXPRESSIONS + # ----------- +diff --git a/Include/internal/pycore_ast.h b/Include/internal/pycore_ast.h +index f222d485e0..f5bf1205a8 100644 +--- a/Include/internal/pycore_ast.h ++++ b/Include/internal/pycore_ast.h +@@ -657,14 +657,17 @@ struct _type_param { + struct { + identifier name; + expr_ty bound; ++ expr_ty default_value; + } TypeVar; + + struct { + identifier name; ++ expr_ty default_value; + } ParamSpec; + + struct { + identifier name; ++ expr_ty default_value; + } TypeVarTuple; + + } v; +@@ -892,14 +895,15 @@ pattern_ty _PyAST_MatchOr(asdl_pattern_seq * patterns, int lineno, int + col_offset, int end_lineno, int end_col_offset, + PyArena *arena); + type_ignore_ty _PyAST_TypeIgnore(int lineno, string tag, PyArena *arena); +-type_param_ty _PyAST_TypeVar(identifier name, expr_ty bound, int lineno, int +- col_offset, int end_lineno, int end_col_offset, +- PyArena *arena); +-type_param_ty _PyAST_ParamSpec(identifier name, int lineno, int col_offset, int +- end_lineno, int end_col_offset, PyArena *arena); +-type_param_ty _PyAST_TypeVarTuple(identifier name, int lineno, int col_offset, +- int end_lineno, int end_col_offset, PyArena +- *arena); ++type_param_ty _PyAST_TypeVar(identifier name, expr_ty bound, expr_ty ++ default_value, int lineno, int col_offset, int ++ end_lineno, int end_col_offset, PyArena *arena); ++type_param_ty _PyAST_ParamSpec(identifier name, expr_ty default_value, int ++ lineno, int col_offset, int end_lineno, int ++ end_col_offset, PyArena *arena); ++type_param_ty _PyAST_TypeVarTuple(identifier name, expr_ty default_value, int ++ lineno, int col_offset, int end_lineno, int ++ end_col_offset, PyArena *arena); + + + PyObject* PyAST_mod2obj(mod_ty t); +diff --git a/Include/internal/pycore_ast_state.h b/Include/internal/pycore_ast_state.h +index f1b1786264..09ae954654 100644 +--- a/Include/internal/pycore_ast_state.h ++++ b/Include/internal/pycore_ast_state.h +@@ -184,6 +184,7 @@ struct ast_state { + PyObject *conversion; + PyObject *ctx; + PyObject *decorator_list; ++ PyObject *default_value; + PyObject *defaults; + PyObject *elt; + PyObject *elts; +diff --git a/Include/internal/pycore_intrinsics.h b/Include/internal/pycore_intrinsics.h +index 8fa88ea3f7..39c2a30f6e 100644 +--- a/Include/internal/pycore_intrinsics.h ++++ b/Include/internal/pycore_intrinsics.h +@@ -28,8 +28,9 @@ + #define INTRINSIC_TYPEVAR_WITH_BOUND 2 + #define INTRINSIC_TYPEVAR_WITH_CONSTRAINTS 3 + #define INTRINSIC_SET_FUNCTION_TYPE_PARAMS 4 ++#define INTRINSIC_SET_TYPEPARAM_DEFAULT 5 + +-#define MAX_INTRINSIC_2 4 ++#define MAX_INTRINSIC_2 5 + + typedef PyObject *(*intrinsic_func1)(PyThreadState* tstate, PyObject *value); + typedef PyObject *(*intrinsic_func2)(PyThreadState* tstate, PyObject *value1, PyObject *value2); +diff --git a/Include/internal/pycore_typevarobject.h b/Include/internal/pycore_typevarobject.h +index c9fa97d682..80a2daf4ef 100644 +--- a/Include/internal/pycore_typevarobject.h ++++ b/Include/internal/pycore_typevarobject.h +@@ -13,10 +13,12 @@ extern PyObject *_Py_make_paramspec(PyThreadState *, PyObject *); + extern PyObject *_Py_make_typevartuple(PyThreadState *, PyObject *); + extern PyObject *_Py_make_typealias(PyThreadState *, PyObject *); + extern PyObject *_Py_subscript_generic(PyThreadState *, PyObject *); ++extern PyObject *_Py_set_typeparam_default(PyThreadState *, PyObject *, PyObject *); + extern int _Py_initialize_generic(PyInterpreterState *); + extern void _Py_clear_generic_types(PyInterpreterState *); + + extern PyTypeObject _PyTypeAlias_Type; ++extern PyObject _Py_NoDefaultStruct; + + #ifdef __cplusplus + } +diff --git a/Lib/ast.py b/Lib/ast.py +index 9f38605165..d7e51aba59 100644 +--- a/Lib/ast.py ++++ b/Lib/ast.py +@@ -1124,12 +1124,21 @@ def visit_TypeVar(self, node): + if node.bound: + self.write(": ") + self.traverse(node.bound) ++ if node.default_value: ++ self.write(" = ") ++ self.traverse(node.default_value) + + def visit_TypeVarTuple(self, node): + self.write("*" + node.name) ++ if node.default_value: ++ self.write(" = ") ++ self.traverse(node.default_value) + + def visit_ParamSpec(self, node): + self.write("**" + node.name) ++ if node.default_value: ++ self.write(" = ") ++ self.traverse(node.default_value) + + def visit_TypeAlias(self, node): + self.fill("type ") +diff --git a/Lib/typing.py b/Lib/typing.py +index eff65cfb68..3f6ff491e7 100644 +--- a/Lib/typing.py ++++ b/Lib/typing.py +@@ -38,6 +38,7 @@ + ParamSpecKwargs, + TypeAliasType, + Generic, ++ NoDefault, + ) + + # Please keep __all__ alphabetized within each category. +@@ -138,6 +139,7 @@ + 'NewType', + 'no_type_check', + 'no_type_check_decorator', ++ 'NoDefault', + 'NoReturn', + 'NotRequired', + 'overload', +@@ -266,6 +268,10 @@ def _collect_parameters(args): + >>> _collect_parameters((T, Callable[P, T])) + (~T, ~P) + """ ++ # required type parameter cannot appear after parameter with default ++ default_encountered = False ++ # or after TypeVarTuple ++ type_var_tuple_encountered = False + parameters = [] + for t in args: + if isinstance(t, type): +@@ -280,27 +286,58 @@ def _collect_parameters(args): + parameters.append(collected) + elif hasattr(t, '__typing_subst__'): + if t not in parameters: ++ if type_var_tuple_encountered and t.has_default(): ++ raise TypeError('Type parameter with a default' ++ ' follows TypeVarTuple') ++ ++ if t.has_default(): ++ default_encountered = True ++ elif default_encountered: ++ raise TypeError(f'Type parameter {t!r} without a default' ++ ' follows type parameter with a default') ++ + parameters.append(t) + else: ++ if _is_unpacked_typevartuple(t): ++ type_var_tuple_encountered = True + for x in getattr(t, '__parameters__', ()): + if x not in parameters: + parameters.append(x) + return tuple(parameters) + + +-def _check_generic(cls, parameters, elen): ++def _check_generic_specialization(cls, arguments): + """Check correct count for parameters of a generic cls (internal helper). + + This gives a nice error message in case of count mismatch. + """ +- if not elen: ++ expected_len = len(cls.__parameters__) ++ if not expected_len: + raise TypeError(f"{cls} is not a generic class") +- alen = len(parameters) +- if alen != elen: +- raise TypeError(f"Too {'many' if alen > elen else 'few'} arguments for {cls};" +- f" actual {alen}, expected {elen}") ++ actual_len = len(arguments) ++ if actual_len != expected_len: ++ # deal with defaults ++ if actual_len < expected_len: ++ # If the parameter at index `actual_len` in the parameters list ++ # has a default, then all parameters after it must also have ++ # one, because we validated as much in _collect_parameters(). ++ # That means that no error needs to be raised here, despite ++ # the number of arguments being passed not matching the number ++ # of parameters: all parameters that aren't explicitly ++ # specialized in this call are parameters with default values. ++ if cls.__parameters__[actual_len].has_default(): ++ return ++ ++ expected_len -= sum(p.has_default() for p in cls.__parameters__) ++ expect_val = f"at least {expected_len}" ++ else: ++ expect_val = expected_len ++ ++ raise TypeError(f"Too {'many' if actual_len > expected_len else 'few'} arguments" ++ f" for {cls}; actual {actual_len}, expected {expect_val}") + +-def _unpack_args(args): ++ ++def _unpack_args(*args): + newargs = [] + for arg in args: + subargs = getattr(arg, '__typing_unpacked_tuple_args__', None) +@@ -1089,11 +1126,15 @@ def _typevartuple_prepare_subst(self, alias, args): + elif left + right > alen: + raise TypeError(f"Too few arguments for {alias};" + f" actual {alen}, expected at least {plen-1}") ++ if left == alen - right and self.has_default(): ++ replacement = _unpack_args(self.__default__) ++ else: ++ replacement = args[left: alen - right] + + return ( + *args[:left], + *([fillarg]*(typevartuple_index - left)), +- tuple(args[left: alen - right]), ++ replacement, + *([fillarg]*(plen - right - left - typevartuple_index - 1)), + *args[alen - right:], + ) +@@ -1111,6 +1152,8 @@ def _paramspec_subst(self, arg): + def _paramspec_prepare_subst(self, alias, args): + params = alias.__parameters__ + i = params.index(self) ++ if i == len(args) and self.has_default(): ++ args = [*args, self.__default__] + if i >= len(args): + raise TypeError(f"Too few arguments for {alias}") + # Special case where Z[[int, str, bool]] == Z[int, str, bool] in PEP 612. +@@ -1124,33 +1167,33 @@ def _paramspec_prepare_subst(self, alias, args): + + + @_tp_cache +-def _generic_class_getitem(cls, params): ++def _generic_class_getitem(cls, args): + """Parameterizes a generic class. + + At least, parameterizing a generic class is the *main* thing this method + does. For example, for some generic class `Foo`, this is called when we +- do `Foo[int]` - there, with `cls=Foo` and `params=int`. ++ do `Foo[int]` - there, with `cls=Foo` and `args=int`. + + However, note that this method is also called when defining generic + classes in the first place with `class Foo(Generic[T]): ...`. + """ +- if not isinstance(params, tuple): +- params = (params,) ++ if not isinstance(args, tuple): ++ args = (args,) + +- params = tuple(_type_convert(p) for p in params) ++ args = tuple(_type_convert(p) for p in args) + is_generic_or_protocol = cls in (Generic, Protocol) + + if is_generic_or_protocol: + # Generic and Protocol can only be subscripted with unique type variables. +- if not params: ++ if not args: + raise TypeError( + f"Parameter list to {cls.__qualname__}[...] cannot be empty" + ) +- if not all(_is_typevar_like(p) for p in params): ++ if not all(_is_typevar_like(p) for p in args): + raise TypeError( + f"Parameters to {cls.__name__}[...] must all be type variables " + f"or parameter specification variables.") +- if len(set(params)) != len(params): ++ if len(set(args)) != len(args): + raise TypeError( + f"Parameters to {cls.__name__}[...] must all be unique") + else: +@@ -1158,18 +1201,18 @@ def _generic_class_getitem(cls, params): + for param in cls.__parameters__: + prepare = getattr(param, '__typing_prepare_subst__', None) + if prepare is not None: +- params = prepare(cls, params) +- _check_generic(cls, params, len(cls.__parameters__)) ++ args = prepare(cls, args) ++ _check_generic_specialization(cls, args) + + new_args = [] +- for param, new_arg in zip(cls.__parameters__, params): ++ for param, new_arg in zip(cls.__parameters__, args): + if isinstance(param, TypeVarTuple): + new_args.extend(new_arg) + else: + new_args.append(new_arg) +- params = tuple(new_args) ++ args = tuple(new_args) + +- return _GenericAlias(cls, params) ++ return _GenericAlias(cls, args) + + + def _generic_init_subclass(cls, *args, **kwargs): +@@ -1390,8 +1433,7 @@ def __getitem__(self, args): + # Preprocess `args`. + if not isinstance(args, tuple): + args = (args,) +- args = tuple(_type_convert(p) for p in args) +- args = _unpack_args(args) ++ args = _unpack_args(*(_type_convert(p) for p in args)) + new_args = self._determine_new_args(args) + r = self.copy_with(new_args) + return r +@@ -1552,7 +1594,12 @@ def __getitem__(self, params): + params = (params,) + msg = "Parameters to generic types must be types." + params = tuple(_type_check(p, msg) for p in params) +- _check_generic(self, params, self._nparams) ++ actual_len = len(params) ++ if actual_len != self._nparams: ++ if not self._nparams: ++ raise TypeError(f"{self} is not a generic class") ++ raise TypeError(f"Too {'many' if actual_len > self._nparams else 'few'} arguments for {self};" ++ f" actual {actual_len}, expected {self._nparams}") + return self.copy_with(params) + + def copy_with(self, params): +diff --git a/Modules/_typingmodule.c b/Modules/_typingmodule.c +index 9ea72bf89c..180f3d7eb0 100644 +--- a/Modules/_typingmodule.c ++++ b/Modules/_typingmodule.c +@@ -63,6 +63,9 @@ _typing_exec(PyObject *m) + if (PyModule_AddObjectRef(m, "TypeAliasType", (PyObject *)&_PyTypeAlias_Type) < 0) { + return -1; + } ++ if (PyModule_AddObjectRef(m, "NoDefault", (PyObject *)&_Py_NoDefaultStruct) < 0) { ++ return -1; ++ } + return 0; + } + +diff --git a/Objects/clinic/typevarobject.c.h b/Objects/clinic/typevarobject.c.h +index 2bb0a98a2e..0ba4ff48bc 100644 +--- a/Objects/clinic/typevarobject.c.h ++++ b/Objects/clinic/typevarobject.c.h +@@ -9,16 +9,16 @@ preserve + #include "pycore_modsupport.h" // _PyArg_UnpackKeywordsWithVararg() + + PyDoc_STRVAR(typevar_new__doc__, +-"typevar(name, *constraints, bound=None, covariant=False,\n" +-" contravariant=False, infer_variance=False)\n" ++"typevar(name, *constraints, bound=None, default=typing.NoDefault,\n" ++" covariant=False, contravariant=False, infer_variance=False)\n" + "--\n" + "\n" + "Create a TypeVar."); + + static PyObject * + typevar_new_impl(PyTypeObject *type, PyObject *name, PyObject *constraints, +- PyObject *bound, int covariant, int contravariant, +- int infer_variance); ++ PyObject *bound, PyObject *default_value, int covariant, ++ int contravariant, int infer_variance); + + static PyObject * + typevar_new(PyTypeObject *type, PyObject *args, PyObject *kwargs) +@@ -26,14 +26,14 @@ typevar_new(PyTypeObject *type, PyObject *args, PyObject *kwargs) + PyObject *return_value = NULL; + #if defined(Py_BUILD_CORE) && !defined(Py_BUILD_CORE_MODULE) + +- #define NUM_KEYWORDS 5 ++ #define NUM_KEYWORDS 6 + static struct { + PyGC_Head _this_is_not_used; + PyObject_VAR_HEAD + PyObject *ob_item[NUM_KEYWORDS]; + } _kwtuple = { + .ob_base = PyVarObject_HEAD_INIT(&PyTuple_Type, NUM_KEYWORDS) +- .ob_item = { &_Py_ID(name), &_Py_ID(bound), &_Py_ID(covariant), &_Py_ID(contravariant), &_Py_ID(infer_variance), }, ++ .ob_item = { &_Py_ID(name), &_Py_ID(bound), &_Py_ID(default), &_Py_ID(covariant), &_Py_ID(contravariant), &_Py_ID(infer_variance), }, + }; + #undef NUM_KEYWORDS + #define KWTUPLE (&_kwtuple.ob_base.ob_base) +@@ -42,20 +42,21 @@ typevar_new(PyTypeObject *type, PyObject *args, PyObject *kwargs) + # define KWTUPLE NULL + #endif // !Py_BUILD_CORE + +- static const char * const _keywords[] = {"name", "bound", "covariant", "contravariant", "infer_variance", NULL}; ++ static const char * const _keywords[] = {"name", "bound", "default", "covariant", "contravariant", "infer_variance", NULL}; + static _PyArg_Parser _parser = { + .keywords = _keywords, + .fname = "typevar", + .kwtuple = KWTUPLE, + }; + #undef KWTUPLE +- PyObject *argsbuf[6]; ++ PyObject *argsbuf[7]; + PyObject * const *fastargs; + Py_ssize_t nargs = PyTuple_GET_SIZE(args); + Py_ssize_t noptargs = Py_MIN(nargs, 1) + (kwargs ? PyDict_GET_SIZE(kwargs) : 0) - 1; + PyObject *name; + PyObject *constraints = NULL; + PyObject *bound = Py_None; ++ PyObject *default_value = &_Py_NoDefaultStruct; + int covariant = 0; + int contravariant = 0; + int infer_variance = 0; +@@ -80,7 +81,13 @@ typevar_new(PyTypeObject *type, PyObject *args, PyObject *kwargs) + } + } + if (fastargs[3]) { +- covariant = PyObject_IsTrue(fastargs[3]); ++ default_value = fastargs[3]; ++ if (!--noptargs) { ++ goto skip_optional_kwonly; ++ } ++ } ++ if (fastargs[4]) { ++ covariant = PyObject_IsTrue(fastargs[4]); + if (covariant < 0) { + goto exit; + } +@@ -88,8 +95,8 @@ typevar_new(PyTypeObject *type, PyObject *args, PyObject *kwargs) + goto skip_optional_kwonly; + } + } +- if (fastargs[4]) { +- contravariant = PyObject_IsTrue(fastargs[4]); ++ if (fastargs[5]) { ++ contravariant = PyObject_IsTrue(fastargs[5]); + if (contravariant < 0) { + goto exit; + } +@@ -97,12 +104,12 @@ typevar_new(PyTypeObject *type, PyObject *args, PyObject *kwargs) + goto skip_optional_kwonly; + } + } +- infer_variance = PyObject_IsTrue(fastargs[5]); ++ infer_variance = PyObject_IsTrue(fastargs[6]); + if (infer_variance < 0) { + goto exit; + } + skip_optional_kwonly: +- return_value = typevar_new_impl(type, name, constraints, bound, covariant, contravariant, infer_variance); ++ return_value = typevar_new_impl(type, name, constraints, bound, default_value, covariant, contravariant, infer_variance); + + exit: + Py_XDECREF(constraints); +@@ -117,6 +124,36 @@ PyDoc_STRVAR(typevar_typing_subst__doc__, + #define TYPEVAR_TYPING_SUBST_METHODDEF \ + {"__typing_subst__", (PyCFunction)typevar_typing_subst, METH_O, typevar_typing_subst__doc__}, + ++PyDoc_STRVAR(typevar_typing_prepare_subst__doc__, ++"__typing_prepare_subst__($self, alias, args, /)\n" ++"--\n" ++"\n"); ++ ++#define TYPEVAR_TYPING_PREPARE_SUBST_METHODDEF \ ++ {"__typing_prepare_subst__", _PyCFunction_CAST(typevar_typing_prepare_subst), METH_FASTCALL, typevar_typing_prepare_subst__doc__}, ++ ++static PyObject * ++typevar_typing_prepare_subst_impl(typevarobject *self, PyObject *alias, ++ PyObject *args); ++ ++static PyObject * ++typevar_typing_prepare_subst(typevarobject *self, PyObject *const *args, Py_ssize_t nargs) ++{ ++ PyObject *return_value = NULL; ++ PyObject *alias; ++ PyObject *__clinic_args; ++ ++ if (!_PyArg_CheckPositional("__typing_prepare_subst__", nargs, 2, 2)) { ++ goto exit; ++ } ++ alias = args[0]; ++ __clinic_args = args[1]; ++ return_value = typevar_typing_prepare_subst_impl(self, alias, __clinic_args); ++ ++exit: ++ return return_value; ++} ++ + PyDoc_STRVAR(typevar_reduce__doc__, + "__reduce__($self, /)\n" + "--\n" +@@ -134,6 +171,23 @@ typevar_reduce(typevarobject *self, PyObject *Py_UNUSED(ignored)) + return typevar_reduce_impl(self); + } + ++PyDoc_STRVAR(typevar_has_default__doc__, ++"has_default($self, /)\n" ++"--\n" ++"\n"); ++ ++#define TYPEVAR_HAS_DEFAULT_METHODDEF \ ++ {"has_default", (PyCFunction)typevar_has_default, METH_NOARGS, typevar_has_default__doc__}, ++ ++static PyObject * ++typevar_has_default_impl(typevarobject *self); ++ ++static PyObject * ++typevar_has_default(typevarobject *self, PyObject *Py_UNUSED(ignored)) ++{ ++ return typevar_has_default_impl(self); ++} ++ + PyDoc_STRVAR(paramspecargs_new__doc__, + "paramspecargs(origin)\n" + "--\n" +@@ -243,15 +297,16 @@ exit: + } + + PyDoc_STRVAR(paramspec_new__doc__, +-"paramspec(name, *, bound=None, covariant=False, contravariant=False,\n" +-" infer_variance=False)\n" ++"paramspec(name, *, bound=None, default=typing.NoDefault,\n" ++" covariant=False, contravariant=False, infer_variance=False)\n" + "--\n" + "\n" + "Create a ParamSpec object."); + + static PyObject * + paramspec_new_impl(PyTypeObject *type, PyObject *name, PyObject *bound, +- int covariant, int contravariant, int infer_variance); ++ PyObject *default_value, int covariant, int contravariant, ++ int infer_variance); + + static PyObject * + paramspec_new(PyTypeObject *type, PyObject *args, PyObject *kwargs) +@@ -259,14 +314,14 @@ paramspec_new(PyTypeObject *type, PyObject *args, PyObject *kwargs) + PyObject *return_value = NULL; + #if defined(Py_BUILD_CORE) && !defined(Py_BUILD_CORE_MODULE) + +- #define NUM_KEYWORDS 5 ++ #define NUM_KEYWORDS 6 + static struct { + PyGC_Head _this_is_not_used; + PyObject_VAR_HEAD + PyObject *ob_item[NUM_KEYWORDS]; + } _kwtuple = { + .ob_base = PyVarObject_HEAD_INIT(&PyTuple_Type, NUM_KEYWORDS) +- .ob_item = { &_Py_ID(name), &_Py_ID(bound), &_Py_ID(covariant), &_Py_ID(contravariant), &_Py_ID(infer_variance), }, ++ .ob_item = { &_Py_ID(name), &_Py_ID(bound), &_Py_ID(default), &_Py_ID(covariant), &_Py_ID(contravariant), &_Py_ID(infer_variance), }, + }; + #undef NUM_KEYWORDS + #define KWTUPLE (&_kwtuple.ob_base.ob_base) +@@ -275,19 +330,20 @@ paramspec_new(PyTypeObject *type, PyObject *args, PyObject *kwargs) + # define KWTUPLE NULL + #endif // !Py_BUILD_CORE + +- static const char * const _keywords[] = {"name", "bound", "covariant", "contravariant", "infer_variance", NULL}; ++ static const char * const _keywords[] = {"name", "bound", "default", "covariant", "contravariant", "infer_variance", NULL}; + static _PyArg_Parser _parser = { + .keywords = _keywords, + .fname = "paramspec", + .kwtuple = KWTUPLE, + }; + #undef KWTUPLE +- PyObject *argsbuf[5]; ++ PyObject *argsbuf[6]; + PyObject * const *fastargs; + Py_ssize_t nargs = PyTuple_GET_SIZE(args); + Py_ssize_t noptargs = nargs + (kwargs ? PyDict_GET_SIZE(kwargs) : 0) - 1; + PyObject *name; + PyObject *bound = Py_None; ++ PyObject *default_value = &_Py_NoDefaultStruct; + int covariant = 0; + int contravariant = 0; + int infer_variance = 0; +@@ -311,7 +367,13 @@ paramspec_new(PyTypeObject *type, PyObject *args, PyObject *kwargs) + } + } + if (fastargs[2]) { +- covariant = PyObject_IsTrue(fastargs[2]); ++ default_value = fastargs[2]; ++ if (!--noptargs) { ++ goto skip_optional_kwonly; ++ } ++ } ++ if (fastargs[3]) { ++ covariant = PyObject_IsTrue(fastargs[3]); + if (covariant < 0) { + goto exit; + } +@@ -319,8 +381,8 @@ paramspec_new(PyTypeObject *type, PyObject *args, PyObject *kwargs) + goto skip_optional_kwonly; + } + } +- if (fastargs[3]) { +- contravariant = PyObject_IsTrue(fastargs[3]); ++ if (fastargs[4]) { ++ contravariant = PyObject_IsTrue(fastargs[4]); + if (contravariant < 0) { + goto exit; + } +@@ -328,12 +390,12 @@ paramspec_new(PyTypeObject *type, PyObject *args, PyObject *kwargs) + goto skip_optional_kwonly; + } + } +- infer_variance = PyObject_IsTrue(fastargs[4]); ++ infer_variance = PyObject_IsTrue(fastargs[5]); + if (infer_variance < 0) { + goto exit; + } + skip_optional_kwonly: +- return_value = paramspec_new_impl(type, name, bound, covariant, contravariant, infer_variance); ++ return_value = paramspec_new_impl(type, name, bound, default_value, covariant, contravariant, infer_variance); + + exit: + return return_value; +@@ -394,14 +456,32 @@ paramspec_reduce(paramspecobject *self, PyObject *Py_UNUSED(ignored)) + return paramspec_reduce_impl(self); + } + ++PyDoc_STRVAR(paramspec_has_default__doc__, ++"has_default($self, /)\n" ++"--\n" ++"\n"); ++ ++#define PARAMSPEC_HAS_DEFAULT_METHODDEF \ ++ {"has_default", (PyCFunction)paramspec_has_default, METH_NOARGS, paramspec_has_default__doc__}, ++ ++static PyObject * ++paramspec_has_default_impl(paramspecobject *self); ++ ++static PyObject * ++paramspec_has_default(paramspecobject *self, PyObject *Py_UNUSED(ignored)) ++{ ++ return paramspec_has_default_impl(self); ++} ++ + PyDoc_STRVAR(typevartuple__doc__, +-"typevartuple(name)\n" ++"typevartuple(name, *, default=typing.NoDefault)\n" + "--\n" + "\n" + "Create a new TypeVarTuple with the given name."); + + static PyObject * +-typevartuple_impl(PyTypeObject *type, PyObject *name); ++typevartuple_impl(PyTypeObject *type, PyObject *name, ++ PyObject *default_value); + + static PyObject * + typevartuple(PyTypeObject *type, PyObject *args, PyObject *kwargs) +@@ -409,14 +489,14 @@ typevartuple(PyTypeObject *type, PyObject *args, PyObject *kwargs) + PyObject *return_value = NULL; + #if defined(Py_BUILD_CORE) && !defined(Py_BUILD_CORE_MODULE) + +- #define NUM_KEYWORDS 1 ++ #define NUM_KEYWORDS 2 + static struct { + PyGC_Head _this_is_not_used; + PyObject_VAR_HEAD + PyObject *ob_item[NUM_KEYWORDS]; + } _kwtuple = { + .ob_base = PyVarObject_HEAD_INIT(&PyTuple_Type, NUM_KEYWORDS) +- .ob_item = { &_Py_ID(name), }, ++ .ob_item = { &_Py_ID(name), &_Py_ID(default), }, + }; + #undef NUM_KEYWORDS + #define KWTUPLE (&_kwtuple.ob_base.ob_base) +@@ -425,17 +505,19 @@ typevartuple(PyTypeObject *type, PyObject *args, PyObject *kwargs) + # define KWTUPLE NULL + #endif // !Py_BUILD_CORE + +- static const char * const _keywords[] = {"name", NULL}; ++ static const char * const _keywords[] = {"name", "default", NULL}; + static _PyArg_Parser _parser = { + .keywords = _keywords, + .fname = "typevartuple", + .kwtuple = KWTUPLE, + }; + #undef KWTUPLE +- PyObject *argsbuf[1]; ++ PyObject *argsbuf[2]; + PyObject * const *fastargs; + Py_ssize_t nargs = PyTuple_GET_SIZE(args); ++ Py_ssize_t noptargs = nargs + (kwargs ? PyDict_GET_SIZE(kwargs) : 0) - 1; + PyObject *name; ++ PyObject *default_value = &_Py_NoDefaultStruct; + + fastargs = _PyArg_UnpackKeywords(_PyTuple_CAST(args)->ob_item, nargs, kwargs, NULL, &_parser, 1, 1, 0, argsbuf); + if (!fastargs) { +@@ -446,7 +528,12 @@ typevartuple(PyTypeObject *type, PyObject *args, PyObject *kwargs) + goto exit; + } + name = fastargs[0]; +- return_value = typevartuple_impl(type, name); ++ if (!noptargs) { ++ goto skip_optional_kwonly; ++ } ++ default_value = fastargs[1]; ++skip_optional_kwonly: ++ return_value = typevartuple_impl(type, name, default_value); + + exit: + return return_value; +@@ -507,6 +594,23 @@ typevartuple_reduce(typevartupleobject *self, PyObject *Py_UNUSED(ignored)) + return typevartuple_reduce_impl(self); + } + ++PyDoc_STRVAR(typevartuple_has_default__doc__, ++"has_default($self, /)\n" ++"--\n" ++"\n"); ++ ++#define TYPEVARTUPLE_HAS_DEFAULT_METHODDEF \ ++ {"has_default", (PyCFunction)typevartuple_has_default, METH_NOARGS, typevartuple_has_default__doc__}, ++ ++static PyObject * ++typevartuple_has_default_impl(typevartupleobject *self); ++ ++static PyObject * ++typevartuple_has_default(typevartupleobject *self, PyObject *Py_UNUSED(ignored)) ++{ ++ return typevartuple_has_default_impl(self); ++} ++ + PyDoc_STRVAR(typealias_reduce__doc__, + "__reduce__($self, /)\n" + "--\n" +@@ -591,4 +695,4 @@ skip_optional_kwonly: + exit: + return return_value; + } +-/*[clinic end generated code: output=5a582d9d89ad787b input=a9049054013a1b77]*/ ++/*[clinic end generated code: output=73b39e550e4e336c input=a9049054013a1b77]*/ +diff --git a/Objects/typevarobject.c b/Objects/typevarobject.c +index 7f80c9c61b..cc91604526 100644 +--- a/Objects/typevarobject.c ++++ b/Objects/typevarobject.c +@@ -23,6 +23,8 @@ typedef struct { + PyObject *evaluate_bound; + PyObject *constraints; + PyObject *evaluate_constraints; ++ PyObject *default_value; ++ PyObject *evaluate_default; + bool covariant; + bool contravariant; + bool infer_variance; +@@ -31,12 +33,16 @@ typedef struct { + typedef struct { + PyObject_HEAD + PyObject *name; ++ PyObject *default_value; ++ PyObject *evaluate_default; + } typevartupleobject; + + typedef struct { + PyObject_HEAD + PyObject *name; + PyObject *bound; ++ PyObject *default_value; ++ PyObject *evaluate_default; + bool covariant; + bool contravariant; + bool infer_variance; +@@ -53,6 +59,64 @@ typedef struct { + + #include "clinic/typevarobject.c.h" + ++/* NoDefault is a marker object to indicate that a parameter has no default. */ ++ ++static PyObject * ++NoDefault_repr(PyObject *op) ++{ ++ return PyUnicode_FromString("typing.NoDefault"); ++} ++ ++static PyObject * ++NoDefault_reduce(PyObject *op, PyObject *Py_UNUSED(ignored)) ++{ ++ return PyUnicode_FromString("NoDefault"); ++} ++ ++static PyMethodDef notimplemented_methods[] = { ++ {"__reduce__", NoDefault_reduce, METH_NOARGS, NULL}, ++ {NULL, NULL} ++}; ++ ++static PyObject * ++nodefault_new(PyTypeObject *type, PyObject *args, PyObject *kwargs) ++{ ++ if (PyTuple_GET_SIZE(args) || (kwargs && PyDict_GET_SIZE(kwargs))) { ++ PyErr_SetString(PyExc_TypeError, "NoDefaultType takes no arguments"); ++ return NULL; ++ } ++ return &_Py_NoDefaultStruct; ++} ++ ++static void ++nodefault_dealloc(PyObject *nodefault) ++{ ++ /* This should never get called, but we also don't want to SEGV if ++ * we accidentally decref NoDefault out of existence. Instead, ++ * since NoDefault is an immortal object, re-set the reference count. ++ */ ++ _Py_SetImmortal(nodefault); ++} ++ ++PyDoc_STRVAR(notimplemented_doc, ++"NoDefaultType()\n" ++"--\n\n" ++"The type of the NoDefault singleton."); ++ ++PyTypeObject _PyNoDefault_Type = { ++ PyVarObject_HEAD_INIT(&PyType_Type, 0) ++ "NoDefaultType", ++ .tp_dealloc = nodefault_dealloc, ++ .tp_repr = NoDefault_repr, ++ .tp_flags = Py_TPFLAGS_DEFAULT, ++ .tp_doc = notimplemented_doc, ++ .tp_methods = notimplemented_methods, ++ .tp_new = nodefault_new, ++}; ++ ++PyObject _Py_NoDefaultStruct = _PyObject_HEAD_INIT(&_PyNoDefault_Type); ++ ++ + static PyObject * + call_typing_func_object(const char *name, PyObject **args, size_t nargs) + { +@@ -200,6 +264,8 @@ typevar_dealloc(PyObject *self) + Py_XDECREF(tv->evaluate_bound); + Py_XDECREF(tv->constraints); + Py_XDECREF(tv->evaluate_constraints); ++ Py_XDECREF(tv->default_value); ++ Py_XDECREF(tv->evaluate_default); + PyObject_ClearManagedDict(self); + PyObject_ClearWeakRefs(self); + +@@ -216,6 +282,8 @@ typevar_traverse(PyObject *self, visitproc visit, void *arg) + Py_VISIT(tv->evaluate_bound); + Py_VISIT(tv->constraints); + Py_VISIT(tv->evaluate_constraints); ++ Py_VISIT(tv->default_value); ++ Py_VISIT(tv->evaluate_default); + PyObject_VisitManagedDict(self, visit, arg); + return 0; + } +@@ -227,6 +295,8 @@ typevar_clear(typevarobject *self) + Py_CLEAR(self->evaluate_bound); + Py_CLEAR(self->constraints); + Py_CLEAR(self->evaluate_constraints); ++ Py_CLEAR(self->default_value); ++ Py_CLEAR(self->evaluate_default); + PyObject_ClearManagedDict((PyObject *)self); + return 0; + } +@@ -266,6 +336,20 @@ typevar_bound(typevarobject *self, void *Py_UNUSED(ignored)) + return bound; + } + ++static PyObject * ++typevar_default(typevarobject *self, void *unused) ++{ ++ if (self->default_value != NULL) { ++ return Py_NewRef(self->default_value); ++ } ++ if (self->evaluate_default == NULL) { ++ return &_Py_NoDefaultStruct; ++ } ++ PyObject *default_value = PyObject_CallNoArgs(self->evaluate_default); ++ self->default_value = Py_XNewRef(default_value); ++ return default_value; ++} ++ + static PyObject * + typevar_constraints(typevarobject *self, void *Py_UNUSED(ignored)) + { +@@ -283,12 +367,14 @@ typevar_constraints(typevarobject *self, void *Py_UNUSED(ignored)) + static PyGetSetDef typevar_getset[] = { + {"__bound__", (getter)typevar_bound, NULL, NULL, NULL}, + {"__constraints__", (getter)typevar_constraints, NULL, NULL, NULL}, ++ {"__default__", (getter)typevar_default, NULL, NULL, NULL}, + {0} + }; + + static typevarobject * + typevar_alloc(PyObject *name, PyObject *bound, PyObject *evaluate_bound, + PyObject *constraints, PyObject *evaluate_constraints, ++ PyObject *default_value, + bool covariant, bool contravariant, bool infer_variance, + PyObject *module) + { +@@ -305,6 +391,8 @@ typevar_alloc(PyObject *name, PyObject *bound, PyObject *evaluate_bound, + tv->evaluate_bound = Py_XNewRef(evaluate_bound); + tv->constraints = Py_XNewRef(constraints); + tv->evaluate_constraints = Py_XNewRef(evaluate_constraints); ++ tv->default_value = Py_XNewRef(default_value); ++ tv->evaluate_default = NULL; + + tv->covariant = covariant; + tv->contravariant = contravariant; +@@ -328,6 +416,7 @@ typevar.__new__ as typevar_new + name: object(subclass_of="&PyUnicode_Type") + *constraints: object + bound: object = None ++ default as default_value: object(c_default="&_Py_NoDefaultStruct") = typing.NoDefault + covariant: bool = False + contravariant: bool = False + infer_variance: bool = False +@@ -337,9 +426,9 @@ Create a TypeVar. + + static PyObject * + typevar_new_impl(PyTypeObject *type, PyObject *name, PyObject *constraints, +- PyObject *bound, int covariant, int contravariant, +- int infer_variance) +-/*[clinic end generated code: output=1d200450ee99226d input=41ae33a916bfe76f]*/ ++ PyObject *bound, PyObject *default_value, int covariant, ++ int contravariant, int infer_variance) ++/*[clinic end generated code: output=d2b248ff074eaab6 input=836f97f631d7293a]*/ + { + if (covariant && contravariant) { + PyErr_SetString(PyExc_ValueError, +@@ -386,6 +475,7 @@ typevar_new_impl(PyTypeObject *type, PyObject *name, PyObject *constraints, + + PyObject *tv = (PyObject *)typevar_alloc(name, bound, NULL, + constraints, NULL, ++ default_value, + covariant, contravariant, + infer_variance, module); + Py_XDECREF(bound); +@@ -410,6 +500,66 @@ typevar_typing_subst(typevarobject *self, PyObject *arg) + return result; + } + ++/*[clinic input] ++typevar.__typing_prepare_subst__ as typevar_typing_prepare_subst ++ ++ alias: object ++ args: object ++ / ++ ++[clinic start generated code]*/ ++ ++static PyObject * ++typevar_typing_prepare_subst_impl(typevarobject *self, PyObject *alias, ++ PyObject *args) ++/*[clinic end generated code: output=82c3f4691e0ded22 input=201a750415d14ffb]*/ ++{ ++ PyObject *params = PyObject_GetAttrString(alias, "__parameters__"); ++ if (params == NULL) { ++ return NULL; ++ } ++ Py_ssize_t i = PySequence_Index(params, (PyObject *)self); ++ if (i == -1) { ++ Py_DECREF(params); ++ return NULL; ++ } ++ Py_ssize_t args_len = PySequence_Length(args); ++ if (args_len == -1) { ++ Py_DECREF(params); ++ return NULL; ++ } ++ if (i < args_len) { ++ // We already have a value for our TypeVar ++ Py_DECREF(params); ++ return Py_NewRef(args); ++ } ++ else if (i == args_len) { ++ // If the TypeVar has a default, use it. ++ PyObject *dflt = typevar_default(self, NULL); ++ if (dflt == NULL) { ++ Py_DECREF(params); ++ return NULL; ++ } ++ if (dflt != &_Py_NoDefaultStruct) { ++ PyObject *new_args = PyTuple_Pack(1, dflt); ++ Py_DECREF(dflt); ++ if (new_args == NULL) { ++ Py_DECREF(params); ++ return NULL; ++ } ++ PyObject *result = PySequence_Concat(args, new_args); ++ Py_DECREF(params); ++ Py_DECREF(new_args); ++ return result; ++ } ++ } ++ Py_DECREF(params); ++ PyErr_Format(PyExc_TypeError, ++ "Too few arguments for %S; actual %d, expected at least %d", ++ alias, args_len, i + 1); ++ return NULL; ++} ++ + /*[clinic input] + typevar.__reduce__ as typevar_reduce + +@@ -422,6 +572,23 @@ typevar_reduce_impl(typevarobject *self) + return Py_NewRef(self->name); + } + ++ ++/*[clinic input] ++typevar.has_default as typevar_has_default ++ ++[clinic start generated code]*/ ++ ++static PyObject * ++typevar_has_default_impl(typevarobject *self) ++/*[clinic end generated code: output=76bf0b8dc98b97dd input=31024aa030761cf6]*/ ++{ ++ if (self->evaluate_default != NULL || ++ (self->default_value != &_Py_NoDefaultStruct && self->default_value != NULL)) { ++ Py_RETURN_TRUE; ++ } ++ Py_RETURN_FALSE; ++} ++ + static PyObject * + typevar_mro_entries(PyObject *self, PyObject *args) + { +@@ -432,7 +599,9 @@ typevar_mro_entries(PyObject *self, PyObject *args) + + static PyMethodDef typevar_methods[] = { + TYPEVAR_TYPING_SUBST_METHODDEF ++ TYPEVAR_TYPING_PREPARE_SUBST_METHODDEF + TYPEVAR_REDUCE_METHODDEF ++ TYPEVAR_HAS_DEFAULT_METHODDEF + {"__mro_entries__", typevar_mro_entries, METH_O}, + {0} + }; +@@ -457,12 +626,18 @@ variables::\n\ + class StrOrBytesSequence[A: (str, bytes)]:\n\ + ...\n\ + \n\ ++Type variables can also have defaults:\n\ ++\n\ ++ class IntDefault[T = int]:\n\ ++ ...\n\ ++\n\ + However, if desired, reusable type variables can also be constructed\n\ + manually, like so::\n\ + \n\ + T = TypeVar('T') # Can be anything\n\ + S = TypeVar('S', bound=str) # Can be any subtype of str\n\ + A = TypeVar('A', str, bytes) # Must be exactly str or bytes\n\ ++ D = TypeVar('D', default=int) # Defaults to int\n\ + \n\ + Type variables exist primarily for the benefit of static type\n\ + checkers. They serve as the parameters for generic types as well\n\ +@@ -739,6 +914,8 @@ paramspec_dealloc(PyObject *self) + + Py_DECREF(ps->name); + Py_XDECREF(ps->bound); ++ Py_XDECREF(ps->default_value); ++ Py_XDECREF(ps->evaluate_default); + PyObject_ClearManagedDict(self); + PyObject_ClearWeakRefs(self); + +@@ -752,6 +929,8 @@ paramspec_traverse(PyObject *self, visitproc visit, void *arg) + Py_VISIT(Py_TYPE(self)); + paramspecobject *ps = (paramspecobject *)self; + Py_VISIT(ps->bound); ++ Py_VISIT(ps->default_value); ++ Py_VISIT(ps->evaluate_default); + PyObject_VisitManagedDict(self, visit, arg); + return 0; + } +@@ -760,6 +939,8 @@ static int + paramspec_clear(paramspecobject *self) + { + Py_CLEAR(self->bound); ++ Py_CLEAR(self->default_value); ++ Py_CLEAR(self->evaluate_default); + PyObject_ClearManagedDict((PyObject *)self); + return 0; + } +@@ -800,14 +981,29 @@ paramspec_kwargs(PyObject *self, void *unused) + return (PyObject *)paramspecattr_new(tp, self); + } + ++static PyObject * ++paramspec_default(paramspecobject *self, void *unused) ++{ ++ if (self->default_value != NULL) { ++ return Py_NewRef(self->default_value); ++ } ++ if (self->evaluate_default == NULL) { ++ return &_Py_NoDefaultStruct; ++ } ++ PyObject *default_value = PyObject_CallNoArgs(self->evaluate_default); ++ self->default_value = Py_XNewRef(default_value); ++ return default_value; ++} ++ + static PyGetSetDef paramspec_getset[] = { + {"args", (getter)paramspec_args, NULL, PyDoc_STR("Represents positional arguments."), NULL}, + {"kwargs", (getter)paramspec_kwargs, NULL, PyDoc_STR("Represents keyword arguments."), NULL}, ++ {"__default__", (getter)paramspec_default, NULL, "The default value for this ParamSpec.", NULL}, + {0}, + }; + + static paramspecobject * +-paramspec_alloc(PyObject *name, PyObject *bound, bool covariant, ++paramspec_alloc(PyObject *name, PyObject *bound, PyObject *default_value, bool covariant, + bool contravariant, bool infer_variance, PyObject *module) + { + PyTypeObject *tp = _PyInterpreterState_GET()->cached_objects.paramspec_type; +@@ -820,6 +1016,8 @@ paramspec_alloc(PyObject *name, PyObject *bound, bool covariant, + ps->covariant = covariant; + ps->contravariant = contravariant; + ps->infer_variance = infer_variance; ++ ps->default_value = Py_XNewRef(default_value); ++ ps->evaluate_default = NULL; + _PyObject_GC_TRACK(ps); + if (module != NULL) { + if (PyObject_SetAttrString((PyObject *)ps, "__module__", module) < 0) { +@@ -837,6 +1035,7 @@ paramspec.__new__ as paramspec_new + name: object(subclass_of="&PyUnicode_Type") + * + bound: object = None ++ default as default_value: object(c_default="&_Py_NoDefaultStruct") = typing.NoDefault + covariant: bool = False + contravariant: bool = False + infer_variance: bool = False +@@ -846,8 +1045,9 @@ Create a ParamSpec object. + + static PyObject * + paramspec_new_impl(PyTypeObject *type, PyObject *name, PyObject *bound, +- int covariant, int contravariant, int infer_variance) +-/*[clinic end generated code: output=fd2daab79cba62da input=57c49c581979b952]*/ ++ PyObject *default_value, int covariant, int contravariant, ++ int infer_variance) ++/*[clinic end generated code: output=47ca9d63fa5a094d input=495e1565bc067ab9]*/ + { + if (covariant && contravariant) { + PyErr_SetString(PyExc_ValueError, "Bivariant types are not supported."); +@@ -869,7 +1069,7 @@ paramspec_new_impl(PyTypeObject *type, PyObject *name, PyObject *bound, + return NULL; + } + PyObject *ps = (PyObject *)paramspec_alloc( +- name, bound, covariant, contravariant, infer_variance, module); ++ name, bound, default_value, covariant, contravariant, infer_variance, module); + Py_XDECREF(bound); + Py_DECREF(module); + return ps; +@@ -925,6 +1125,22 @@ paramspec_reduce_impl(paramspecobject *self) + return Py_NewRef(self->name); + } + ++/*[clinic input] ++paramspec.has_default as paramspec_has_default ++ ++[clinic start generated code]*/ ++ ++static PyObject * ++paramspec_has_default_impl(paramspecobject *self) ++/*[clinic end generated code: output=daaae7467a6a4368 input=2112e97eeb76cd59]*/ ++{ ++ if (self->evaluate_default != NULL || ++ (self->default_value != &_Py_NoDefaultStruct && self->default_value != NULL)) { ++ Py_RETURN_TRUE; ++ } ++ Py_RETURN_FALSE; ++} ++ + static PyObject * + paramspec_mro_entries(PyObject *self, PyObject *args) + { +@@ -936,6 +1152,7 @@ paramspec_mro_entries(PyObject *self, PyObject *args) + static PyMethodDef paramspec_methods[] = { + PARAMSPEC_TYPING_SUBST_METHODDEF + PARAMSPEC_TYPING_PREPARE_SUBST_METHODDEF ++ PARAMSPEC_HAS_DEFAULT_METHODDEF + PARAMSPEC_REDUCE_METHODDEF + {"__mro_entries__", paramspec_mro_entries, METH_O}, + {0} +@@ -950,10 +1167,17 @@ where the use of '**' creates a parameter specification::\n\ + \n\ + type IntFunc[**P] = Callable[P, int]\n\ + \n\ ++The following syntax creates a parameter specification that defaults\n\ ++to a callable accepting two positional-only arguments of types int\n\ ++and str:\n\ ++\n\ ++ type IntFuncDefault[**P = (int, str)] = Callable[P, int]\n\ ++\n\ + For compatibility with Python 3.11 and earlier, ParamSpec objects\n\ + can also be created as follows::\n\ + \n\ + P = ParamSpec('P')\n\ ++ DefaultP = ParamSpec('DefaultP', default=(int, str))\n\ + \n\ + Parameter specification variables exist primarily for the benefit of\n\ + static type checkers. They are used to forward the parameter types of\n\ +@@ -1021,6 +1245,8 @@ typevartuple_dealloc(PyObject *self) + typevartupleobject *tvt = (typevartupleobject *)self; + + Py_DECREF(tvt->name); ++ Py_XDECREF(tvt->default_value); ++ Py_XDECREF(tvt->evaluate_default); + PyObject_ClearManagedDict(self); + PyObject_ClearWeakRefs(self); + +@@ -1060,7 +1286,7 @@ static PyMemberDef typevartuple_members[] = { + }; + + static typevartupleobject * +-typevartuple_alloc(PyObject *name, PyObject *module) ++typevartuple_alloc(PyObject *name, PyObject *module, PyObject *default_value) + { + PyTypeObject *tp = _PyInterpreterState_GET()->cached_objects.typevartuple_type; + typevartupleobject *tvt = PyObject_GC_New(typevartupleobject, tp); +@@ -1068,6 +1294,8 @@ typevartuple_alloc(PyObject *name, PyObject *module) + return NULL; + } + tvt->name = Py_NewRef(name); ++ tvt->default_value = Py_XNewRef(default_value); ++ tvt->evaluate_default = NULL; + _PyObject_GC_TRACK(tvt); + if (module != NULL) { + if (PyObject_SetAttrString((PyObject *)tvt, "__module__", module) < 0) { +@@ -1083,19 +1311,22 @@ typevartuple_alloc(PyObject *name, PyObject *module) + typevartuple.__new__ + + name: object(subclass_of="&PyUnicode_Type") ++ * ++ default as default_value: object(c_default="&_Py_NoDefaultStruct") = typing.NoDefault + + Create a new TypeVarTuple with the given name. + [clinic start generated code]*/ + + static PyObject * +-typevartuple_impl(PyTypeObject *type, PyObject *name) +-/*[clinic end generated code: output=09d417a28f976202 input=00d28abcf1fc96bb]*/ ++typevartuple_impl(PyTypeObject *type, PyObject *name, ++ PyObject *default_value) ++/*[clinic end generated code: output=9d6b76dfe95aae51 input=e149739929a866d0]*/ + { + PyObject *module = caller(); + if (module == NULL) { + return NULL; + } +- PyObject *result = (PyObject *)typevartuple_alloc(name, module); ++ PyObject *result = (PyObject *)typevartuple_alloc(name, module, default_value); + Py_DECREF(module); + return result; + } +@@ -1148,6 +1379,23 @@ typevartuple_reduce_impl(typevartupleobject *self) + return Py_NewRef(self->name); + } + ++ ++/*[clinic input] ++typevartuple.has_default as typevartuple_has_default ++ ++[clinic start generated code]*/ ++ ++static PyObject * ++typevartuple_has_default_impl(typevartupleobject *self) ++/*[clinic end generated code: output=4895f602f56a5e29 input=9ef3250ddb2c1851]*/ ++{ ++ if (self->evaluate_default != NULL || ++ (self->default_value != &_Py_NoDefaultStruct && self->default_value != NULL)) { ++ Py_RETURN_TRUE; ++ } ++ Py_RETURN_FALSE; ++} ++ + static PyObject * + typevartuple_mro_entries(PyObject *self, PyObject *args) + { +@@ -1160,6 +1408,8 @@ static int + typevartuple_traverse(PyObject *self, visitproc visit, void *arg) + { + Py_VISIT(Py_TYPE(self)); ++ Py_VISIT(((typevartupleobject *)self)->default_value); ++ Py_VISIT(((typevartupleobject *)self)->evaluate_default); + PyObject_VisitManagedDict(self, visit, arg); + return 0; + } +@@ -1167,14 +1417,36 @@ typevartuple_traverse(PyObject *self, visitproc visit, void *arg) + static int + typevartuple_clear(PyObject *self) + { ++ Py_CLEAR(((typevartupleobject *)self)->default_value); ++ Py_CLEAR(((typevartupleobject *)self)->evaluate_default); + PyObject_ClearManagedDict(self); + return 0; + } + ++static PyObject * ++typevartuple_default(typevartupleobject *self, void *unused) ++{ ++ if (self->default_value != NULL) { ++ return Py_NewRef(self->default_value); ++ } ++ if (self->evaluate_default == NULL) { ++ return &_Py_NoDefaultStruct; ++ } ++ PyObject *default_value = PyObject_CallNoArgs(self->evaluate_default); ++ self->default_value = Py_XNewRef(default_value); ++ return default_value; ++} ++ ++static PyGetSetDef typevartuple_getset[] = { ++ {"__default__", (getter)typevartuple_default, NULL, "The default value for this TypeVarTuple.", NULL}, ++ {0}, ++}; ++ + static PyMethodDef typevartuple_methods[] = { + TYPEVARTUPLE_TYPING_SUBST_METHODDEF + TYPEVARTUPLE_TYPING_PREPARE_SUBST_METHODDEF + TYPEVARTUPLE_REDUCE_METHODDEF ++ TYPEVARTUPLE_HAS_DEFAULT_METHODDEF + {"__mro_entries__", typevartuple_mro_entries, METH_O}, + {0} + }; +@@ -1190,10 +1462,15 @@ where a single '*' indicates a type variable tuple::\n\ + def move_first_element_to_last[T, *Ts](tup: tuple[T, *Ts]) -> tuple[*Ts, T]:\n\ + return (*tup[1:], tup[0])\n\ + \n\ ++Type variables tuples can have default values:\n\ ++\n\ ++ type AliasWithDefault[*Ts = (str, int)] = tuple[*Ts]\n\ ++\n\ + For compatibility with Python 3.11 and earlier, TypeVarTuple objects\n\ + can also be created as follows::\n\ + \n\ + Ts = TypeVarTuple('Ts') # Can be given any name\n\ ++ DefaultTs = TypeVarTuple('Ts', default=(str, int))\n\ + \n\ + Just as a TypeVar (type variable) is a placeholder for a single type,\n\ + a TypeVarTuple is a placeholder for an *arbitrary* number of types. For\n\ +@@ -1218,6 +1495,7 @@ PyType_Slot typevartuple_slots[] = { + {Py_tp_doc, (void *)typevartuple_doc}, + {Py_tp_members, typevartuple_members}, + {Py_tp_methods, typevartuple_methods}, ++ {Py_tp_getset, typevartuple_getset}, + {Py_tp_new, typevartuple}, + {Py_tp_iter, typevartuple_iter}, + {Py_tp_repr, typevartuple_repr}, +@@ -1241,21 +1519,21 @@ PyObject * + _Py_make_typevar(PyObject *name, PyObject *evaluate_bound, PyObject *evaluate_constraints) + { + return (PyObject *)typevar_alloc(name, NULL, evaluate_bound, NULL, evaluate_constraints, +- false, false, true, NULL); ++ NULL, false, false, true, NULL); + } + + PyObject * + _Py_make_paramspec(PyThreadState *Py_UNUSED(ignored), PyObject *v) + { + assert(PyUnicode_Check(v)); +- return (PyObject *)paramspec_alloc(v, NULL, false, false, true, NULL); ++ return (PyObject *)paramspec_alloc(v, NULL, NULL, false, false, true, NULL); + } + + PyObject * + _Py_make_typevartuple(PyThreadState *Py_UNUSED(ignored), PyObject *v) + { + assert(PyUnicode_Check(v)); +- return (PyObject *)typevartuple_alloc(v, NULL); ++ return (PyObject *)typevartuple_alloc(v, NULL, NULL); + } + + static void +@@ -1687,3 +1965,24 @@ void _Py_clear_generic_types(PyInterpreterState *interp) + Py_CLEAR(interp->cached_objects.paramspecargs_type); + Py_CLEAR(interp->cached_objects.paramspeckwargs_type); + } ++ ++PyObject * ++_Py_set_typeparam_default(PyThreadState *ts, PyObject *typeparam, PyObject *evaluate_default) ++{ ++ if (Py_IS_TYPE(typeparam, ts->interp->cached_objects.typevar_type)) { ++ Py_XSETREF(((typevarobject *)typeparam)->evaluate_default, Py_NewRef(evaluate_default)); ++ return Py_NewRef(typeparam); ++ } ++ else if (Py_IS_TYPE(typeparam, ts->interp->cached_objects.paramspec_type)) { ++ Py_XSETREF(((paramspecobject *)typeparam)->evaluate_default, Py_NewRef(evaluate_default)); ++ return Py_NewRef(typeparam); ++ } ++ else if (Py_IS_TYPE(typeparam, ts->interp->cached_objects.typevartuple_type)) { ++ Py_XSETREF(((typevartupleobject *)typeparam)->evaluate_default, Py_NewRef(evaluate_default)); ++ return Py_NewRef(typeparam); ++ } ++ else { ++ PyErr_Format(PyExc_TypeError, "Expected a type param, got %R", typeparam); ++ return NULL; ++ } ++} +diff --git a/Parser/Python.asdl b/Parser/Python.asdl +index 0d15486727..80776ffe44 100644 +--- a/Parser/Python.asdl ++++ b/Parser/Python.asdl +@@ -145,8 +145,8 @@ module Python + + type_ignore = TypeIgnore(int lineno, string tag) + +- type_param = TypeVar(identifier name, expr? bound) +- | ParamSpec(identifier name) +- | TypeVarTuple(identifier name) ++ type_param = TypeVar(identifier name, expr? bound, expr? default_value) ++ | ParamSpec(identifier name, expr? default_value) ++ | TypeVarTuple(identifier name, expr? default_value) + attributes (int lineno, int col_offset, int end_lineno, int end_col_offset) + } +diff --git a/Parser/parser.c b/Parser/parser.c +index 0715e9775a..e34fcada15 100644 +--- a/Parser/parser.c ++++ b/Parser/parser.c +@@ -186,431 +186,433 @@ static char *soft_keywords[] = { + #define type_param_seq_type 1099 + #define type_param_type 1100 + #define type_param_bound_type 1101 +-#define expressions_type 1102 +-#define expression_type 1103 +-#define yield_expr_type 1104 +-#define star_expressions_type 1105 +-#define star_expression_type 1106 +-#define star_named_expressions_type 1107 +-#define star_named_expression_type 1108 +-#define assignment_expression_type 1109 +-#define named_expression_type 1110 +-#define disjunction_type 1111 +-#define conjunction_type 1112 +-#define inversion_type 1113 +-#define comparison_type 1114 +-#define compare_op_bitwise_or_pair_type 1115 +-#define eq_bitwise_or_type 1116 +-#define noteq_bitwise_or_type 1117 +-#define lte_bitwise_or_type 1118 +-#define lt_bitwise_or_type 1119 +-#define gte_bitwise_or_type 1120 +-#define gt_bitwise_or_type 1121 +-#define notin_bitwise_or_type 1122 +-#define in_bitwise_or_type 1123 +-#define isnot_bitwise_or_type 1124 +-#define is_bitwise_or_type 1125 +-#define bitwise_or_type 1126 // Left-recursive +-#define bitwise_xor_type 1127 // Left-recursive +-#define bitwise_and_type 1128 // Left-recursive +-#define shift_expr_type 1129 // Left-recursive +-#define sum_type 1130 // Left-recursive +-#define term_type 1131 // Left-recursive +-#define factor_type 1132 +-#define power_type 1133 +-#define await_primary_type 1134 +-#define primary_type 1135 // Left-recursive +-#define slices_type 1136 +-#define slice_type 1137 +-#define atom_type 1138 +-#define group_type 1139 +-#define lambdef_type 1140 +-#define lambda_params_type 1141 +-#define lambda_parameters_type 1142 +-#define lambda_slash_no_default_type 1143 +-#define lambda_slash_with_default_type 1144 +-#define lambda_star_etc_type 1145 +-#define lambda_kwds_type 1146 +-#define lambda_param_no_default_type 1147 +-#define lambda_param_with_default_type 1148 +-#define lambda_param_maybe_default_type 1149 +-#define lambda_param_type 1150 +-#define fstring_middle_type 1151 +-#define fstring_replacement_field_type 1152 +-#define fstring_conversion_type 1153 +-#define fstring_full_format_spec_type 1154 +-#define fstring_format_spec_type 1155 +-#define fstring_type 1156 +-#define string_type 1157 +-#define strings_type 1158 +-#define list_type 1159 +-#define tuple_type 1160 +-#define set_type 1161 +-#define dict_type 1162 +-#define double_starred_kvpairs_type 1163 +-#define double_starred_kvpair_type 1164 +-#define kvpair_type 1165 +-#define for_if_clauses_type 1166 +-#define for_if_clause_type 1167 +-#define listcomp_type 1168 +-#define setcomp_type 1169 +-#define genexp_type 1170 +-#define dictcomp_type 1171 +-#define arguments_type 1172 +-#define args_type 1173 +-#define kwargs_type 1174 +-#define starred_expression_type 1175 +-#define kwarg_or_starred_type 1176 +-#define kwarg_or_double_starred_type 1177 +-#define star_targets_type 1178 +-#define star_targets_list_seq_type 1179 +-#define star_targets_tuple_seq_type 1180 +-#define star_target_type 1181 +-#define target_with_star_atom_type 1182 +-#define star_atom_type 1183 +-#define single_target_type 1184 +-#define single_subscript_attribute_target_type 1185 +-#define t_primary_type 1186 // Left-recursive +-#define t_lookahead_type 1187 +-#define del_targets_type 1188 +-#define del_target_type 1189 +-#define del_t_atom_type 1190 +-#define type_expressions_type 1191 +-#define func_type_comment_type 1192 +-#define invalid_arguments_type 1193 +-#define invalid_kwarg_type 1194 +-#define expression_without_invalid_type 1195 +-#define invalid_legacy_expression_type 1196 +-#define invalid_expression_type 1197 +-#define invalid_named_expression_type 1198 +-#define invalid_assignment_type 1199 +-#define invalid_ann_assign_target_type 1200 +-#define invalid_del_stmt_type 1201 +-#define invalid_block_type 1202 +-#define invalid_comprehension_type 1203 +-#define invalid_dict_comprehension_type 1204 +-#define invalid_parameters_type 1205 +-#define invalid_default_type 1206 +-#define invalid_star_etc_type 1207 +-#define invalid_kwds_type 1208 +-#define invalid_parameters_helper_type 1209 +-#define invalid_lambda_parameters_type 1210 +-#define invalid_lambda_parameters_helper_type 1211 +-#define invalid_lambda_star_etc_type 1212 +-#define invalid_lambda_kwds_type 1213 +-#define invalid_double_type_comments_type 1214 +-#define invalid_with_item_type 1215 +-#define invalid_for_target_type 1216 +-#define invalid_group_type 1217 +-#define invalid_import_type 1218 +-#define invalid_import_from_targets_type 1219 +-#define invalid_compound_stmt_type 1220 +-#define invalid_with_stmt_type 1221 +-#define invalid_with_stmt_indent_type 1222 +-#define invalid_try_stmt_type 1223 +-#define invalid_except_stmt_type 1224 +-#define invalid_finally_stmt_type 1225 +-#define invalid_except_stmt_indent_type 1226 +-#define invalid_except_star_stmt_indent_type 1227 +-#define invalid_match_stmt_type 1228 +-#define invalid_case_block_type 1229 +-#define invalid_as_pattern_type 1230 +-#define invalid_class_pattern_type 1231 +-#define invalid_class_argument_pattern_type 1232 +-#define invalid_if_stmt_type 1233 +-#define invalid_elif_stmt_type 1234 +-#define invalid_else_stmt_type 1235 +-#define invalid_while_stmt_type 1236 +-#define invalid_for_stmt_type 1237 +-#define invalid_def_raw_type 1238 +-#define invalid_class_def_raw_type 1239 +-#define invalid_double_starred_kvpairs_type 1240 +-#define invalid_kvpair_type 1241 +-#define invalid_starred_expression_type 1242 +-#define invalid_replacement_field_type 1243 +-#define invalid_conversion_character_type 1244 +-#define invalid_arithmetic_type 1245 +-#define invalid_factor_type 1246 +-#define _loop0_1_type 1247 +-#define _loop0_2_type 1248 +-#define _loop1_3_type 1249 +-#define _loop0_5_type 1250 +-#define _gather_4_type 1251 +-#define _tmp_6_type 1252 +-#define _tmp_7_type 1253 +-#define _tmp_8_type 1254 +-#define _tmp_9_type 1255 +-#define _tmp_10_type 1256 +-#define _tmp_11_type 1257 +-#define _tmp_12_type 1258 +-#define _tmp_13_type 1259 +-#define _loop1_14_type 1260 +-#define _tmp_15_type 1261 +-#define _tmp_16_type 1262 +-#define _tmp_17_type 1263 +-#define _loop0_19_type 1264 +-#define _gather_18_type 1265 +-#define _loop0_21_type 1266 +-#define _gather_20_type 1267 +-#define _tmp_22_type 1268 +-#define _tmp_23_type 1269 +-#define _loop0_24_type 1270 +-#define _loop1_25_type 1271 +-#define _loop0_27_type 1272 +-#define _gather_26_type 1273 +-#define _tmp_28_type 1274 +-#define _loop0_30_type 1275 +-#define _gather_29_type 1276 +-#define _tmp_31_type 1277 +-#define _loop1_32_type 1278 +-#define _tmp_33_type 1279 +-#define _tmp_34_type 1280 +-#define _tmp_35_type 1281 +-#define _loop0_36_type 1282 +-#define _loop0_37_type 1283 +-#define _loop0_38_type 1284 +-#define _loop1_39_type 1285 +-#define _loop0_40_type 1286 +-#define _loop1_41_type 1287 +-#define _loop1_42_type 1288 +-#define _loop1_43_type 1289 +-#define _loop0_44_type 1290 +-#define _loop1_45_type 1291 +-#define _loop0_46_type 1292 +-#define _loop1_47_type 1293 +-#define _loop0_48_type 1294 +-#define _loop0_49_type 1295 +-#define _loop1_50_type 1296 +-#define _loop0_52_type 1297 +-#define _gather_51_type 1298 +-#define _loop0_54_type 1299 +-#define _gather_53_type 1300 +-#define _loop0_56_type 1301 +-#define _gather_55_type 1302 +-#define _loop0_58_type 1303 +-#define _gather_57_type 1304 +-#define _tmp_59_type 1305 +-#define _loop1_60_type 1306 +-#define _loop1_61_type 1307 +-#define _tmp_62_type 1308 +-#define _tmp_63_type 1309 +-#define _loop1_64_type 1310 +-#define _loop0_66_type 1311 +-#define _gather_65_type 1312 +-#define _tmp_67_type 1313 +-#define _tmp_68_type 1314 +-#define _tmp_69_type 1315 +-#define _tmp_70_type 1316 +-#define _loop0_72_type 1317 +-#define _gather_71_type 1318 +-#define _loop0_74_type 1319 +-#define _gather_73_type 1320 +-#define _tmp_75_type 1321 +-#define _loop0_77_type 1322 +-#define _gather_76_type 1323 +-#define _loop0_79_type 1324 +-#define _gather_78_type 1325 +-#define _loop0_81_type 1326 +-#define _gather_80_type 1327 +-#define _loop1_82_type 1328 +-#define _loop1_83_type 1329 +-#define _loop0_85_type 1330 +-#define _gather_84_type 1331 +-#define _loop1_86_type 1332 +-#define _loop1_87_type 1333 +-#define _loop1_88_type 1334 +-#define _tmp_89_type 1335 +-#define _loop0_91_type 1336 +-#define _gather_90_type 1337 +-#define _tmp_92_type 1338 +-#define _tmp_93_type 1339 +-#define _tmp_94_type 1340 +-#define _tmp_95_type 1341 +-#define _tmp_96_type 1342 +-#define _tmp_97_type 1343 +-#define _loop0_98_type 1344 +-#define _loop0_99_type 1345 +-#define _loop0_100_type 1346 +-#define _loop1_101_type 1347 +-#define _loop0_102_type 1348 +-#define _loop1_103_type 1349 +-#define _loop1_104_type 1350 +-#define _loop1_105_type 1351 +-#define _loop0_106_type 1352 +-#define _loop1_107_type 1353 +-#define _loop0_108_type 1354 +-#define _loop1_109_type 1355 +-#define _loop0_110_type 1356 +-#define _loop1_111_type 1357 +-#define _loop0_112_type 1358 +-#define _loop0_113_type 1359 +-#define _loop1_114_type 1360 +-#define _tmp_115_type 1361 +-#define _loop0_117_type 1362 +-#define _gather_116_type 1363 +-#define _loop1_118_type 1364 +-#define _loop0_119_type 1365 +-#define _loop0_120_type 1366 +-#define _tmp_121_type 1367 +-#define _tmp_122_type 1368 +-#define _loop0_124_type 1369 +-#define _gather_123_type 1370 +-#define _tmp_125_type 1371 +-#define _loop0_127_type 1372 +-#define _gather_126_type 1373 +-#define _loop0_129_type 1374 +-#define _gather_128_type 1375 +-#define _loop0_131_type 1376 +-#define _gather_130_type 1377 +-#define _loop0_133_type 1378 +-#define _gather_132_type 1379 +-#define _loop0_134_type 1380 +-#define _loop0_136_type 1381 +-#define _gather_135_type 1382 +-#define _loop1_137_type 1383 +-#define _tmp_138_type 1384 +-#define _loop0_140_type 1385 +-#define _gather_139_type 1386 +-#define _loop0_142_type 1387 +-#define _gather_141_type 1388 +-#define _loop0_144_type 1389 +-#define _gather_143_type 1390 +-#define _loop0_146_type 1391 +-#define _gather_145_type 1392 +-#define _loop0_148_type 1393 +-#define _gather_147_type 1394 +-#define _tmp_149_type 1395 +-#define _tmp_150_type 1396 +-#define _loop0_152_type 1397 +-#define _gather_151_type 1398 +-#define _tmp_153_type 1399 +-#define _tmp_154_type 1400 +-#define _tmp_155_type 1401 +-#define _tmp_156_type 1402 +-#define _tmp_157_type 1403 +-#define _tmp_158_type 1404 +-#define _tmp_159_type 1405 +-#define _tmp_160_type 1406 +-#define _tmp_161_type 1407 +-#define _tmp_162_type 1408 +-#define _loop0_163_type 1409 +-#define _loop0_164_type 1410 +-#define _loop0_165_type 1411 +-#define _tmp_166_type 1412 +-#define _tmp_167_type 1413 +-#define _tmp_168_type 1414 +-#define _tmp_169_type 1415 +-#define _loop0_170_type 1416 +-#define _loop0_171_type 1417 +-#define _loop0_172_type 1418 +-#define _loop1_173_type 1419 +-#define _tmp_174_type 1420 +-#define _loop0_175_type 1421 +-#define _tmp_176_type 1422 +-#define _loop0_177_type 1423 +-#define _loop1_178_type 1424 +-#define _tmp_179_type 1425 +-#define _tmp_180_type 1426 +-#define _tmp_181_type 1427 +-#define _loop0_182_type 1428 +-#define _tmp_183_type 1429 +-#define _tmp_184_type 1430 +-#define _loop1_185_type 1431 +-#define _tmp_186_type 1432 +-#define _loop0_187_type 1433 +-#define _loop0_188_type 1434 +-#define _loop0_189_type 1435 +-#define _loop0_191_type 1436 +-#define _gather_190_type 1437 +-#define _tmp_192_type 1438 +-#define _loop0_193_type 1439 +-#define _tmp_194_type 1440 +-#define _loop0_195_type 1441 +-#define _loop1_196_type 1442 +-#define _loop1_197_type 1443 +-#define _tmp_198_type 1444 +-#define _tmp_199_type 1445 +-#define _loop0_200_type 1446 +-#define _tmp_201_type 1447 +-#define _tmp_202_type 1448 +-#define _tmp_203_type 1449 +-#define _loop0_205_type 1450 +-#define _gather_204_type 1451 +-#define _loop0_207_type 1452 +-#define _gather_206_type 1453 +-#define _loop0_209_type 1454 +-#define _gather_208_type 1455 +-#define _loop0_211_type 1456 +-#define _gather_210_type 1457 +-#define _loop0_213_type 1458 +-#define _gather_212_type 1459 +-#define _tmp_214_type 1460 +-#define _loop0_215_type 1461 +-#define _loop1_216_type 1462 +-#define _tmp_217_type 1463 +-#define _loop0_218_type 1464 +-#define _loop1_219_type 1465 +-#define _tmp_220_type 1466 +-#define _tmp_221_type 1467 +-#define _tmp_222_type 1468 +-#define _tmp_223_type 1469 +-#define _tmp_224_type 1470 +-#define _tmp_225_type 1471 +-#define _tmp_226_type 1472 +-#define _tmp_227_type 1473 +-#define _tmp_228_type 1474 +-#define _tmp_229_type 1475 +-#define _loop0_231_type 1476 +-#define _gather_230_type 1477 +-#define _tmp_232_type 1478 +-#define _tmp_233_type 1479 +-#define _tmp_234_type 1480 +-#define _tmp_235_type 1481 +-#define _tmp_236_type 1482 +-#define _tmp_237_type 1483 +-#define _tmp_238_type 1484 +-#define _loop0_239_type 1485 +-#define _tmp_240_type 1486 +-#define _tmp_241_type 1487 +-#define _tmp_242_type 1488 +-#define _tmp_243_type 1489 +-#define _tmp_244_type 1490 +-#define _tmp_245_type 1491 +-#define _tmp_246_type 1492 +-#define _tmp_247_type 1493 +-#define _tmp_248_type 1494 +-#define _tmp_249_type 1495 +-#define _tmp_250_type 1496 +-#define _tmp_251_type 1497 +-#define _tmp_252_type 1498 +-#define _tmp_253_type 1499 +-#define _tmp_254_type 1500 +-#define _tmp_255_type 1501 +-#define _loop0_256_type 1502 +-#define _tmp_257_type 1503 +-#define _tmp_258_type 1504 +-#define _tmp_259_type 1505 +-#define _tmp_260_type 1506 +-#define _tmp_261_type 1507 +-#define _tmp_262_type 1508 +-#define _tmp_263_type 1509 +-#define _tmp_264_type 1510 +-#define _tmp_265_type 1511 +-#define _tmp_266_type 1512 +-#define _tmp_267_type 1513 +-#define _tmp_268_type 1514 +-#define _tmp_269_type 1515 +-#define _tmp_270_type 1516 +-#define _tmp_271_type 1517 +-#define _tmp_272_type 1518 +-#define _loop0_274_type 1519 +-#define _gather_273_type 1520 +-#define _tmp_275_type 1521 +-#define _tmp_276_type 1522 +-#define _tmp_277_type 1523 +-#define _tmp_278_type 1524 +-#define _tmp_279_type 1525 +-#define _tmp_280_type 1526 ++#define type_param_default_type 1102 ++#define type_param_starred_default_type 1103 ++#define expressions_type 1104 ++#define expression_type 1105 ++#define yield_expr_type 1106 ++#define star_expressions_type 1107 ++#define star_expression_type 1108 ++#define star_named_expressions_type 1109 ++#define star_named_expression_type 1110 ++#define assignment_expression_type 1111 ++#define named_expression_type 1112 ++#define disjunction_type 1113 ++#define conjunction_type 1114 ++#define inversion_type 1115 ++#define comparison_type 1116 ++#define compare_op_bitwise_or_pair_type 1117 ++#define eq_bitwise_or_type 1118 ++#define noteq_bitwise_or_type 1119 ++#define lte_bitwise_or_type 1120 ++#define lt_bitwise_or_type 1121 ++#define gte_bitwise_or_type 1122 ++#define gt_bitwise_or_type 1123 ++#define notin_bitwise_or_type 1124 ++#define in_bitwise_or_type 1125 ++#define isnot_bitwise_or_type 1126 ++#define is_bitwise_or_type 1127 ++#define bitwise_or_type 1128 // Left-recursive ++#define bitwise_xor_type 1129 // Left-recursive ++#define bitwise_and_type 1130 // Left-recursive ++#define shift_expr_type 1131 // Left-recursive ++#define sum_type 1132 // Left-recursive ++#define term_type 1133 // Left-recursive ++#define factor_type 1134 ++#define power_type 1135 ++#define await_primary_type 1136 ++#define primary_type 1137 // Left-recursive ++#define slices_type 1138 ++#define slice_type 1139 ++#define atom_type 1140 ++#define group_type 1141 ++#define lambdef_type 1142 ++#define lambda_params_type 1143 ++#define lambda_parameters_type 1144 ++#define lambda_slash_no_default_type 1145 ++#define lambda_slash_with_default_type 1146 ++#define lambda_star_etc_type 1147 ++#define lambda_kwds_type 1148 ++#define lambda_param_no_default_type 1149 ++#define lambda_param_with_default_type 1150 ++#define lambda_param_maybe_default_type 1151 ++#define lambda_param_type 1152 ++#define fstring_middle_type 1153 ++#define fstring_replacement_field_type 1154 ++#define fstring_conversion_type 1155 ++#define fstring_full_format_spec_type 1156 ++#define fstring_format_spec_type 1157 ++#define fstring_type 1158 ++#define string_type 1159 ++#define strings_type 1160 ++#define list_type 1161 ++#define tuple_type 1162 ++#define set_type 1163 ++#define dict_type 1164 ++#define double_starred_kvpairs_type 1165 ++#define double_starred_kvpair_type 1166 ++#define kvpair_type 1167 ++#define for_if_clauses_type 1168 ++#define for_if_clause_type 1169 ++#define listcomp_type 1170 ++#define setcomp_type 1171 ++#define genexp_type 1172 ++#define dictcomp_type 1173 ++#define arguments_type 1174 ++#define args_type 1175 ++#define kwargs_type 1176 ++#define starred_expression_type 1177 ++#define kwarg_or_starred_type 1178 ++#define kwarg_or_double_starred_type 1179 ++#define star_targets_type 1180 ++#define star_targets_list_seq_type 1181 ++#define star_targets_tuple_seq_type 1182 ++#define star_target_type 1183 ++#define target_with_star_atom_type 1184 ++#define star_atom_type 1185 ++#define single_target_type 1186 ++#define single_subscript_attribute_target_type 1187 ++#define t_primary_type 1188 // Left-recursive ++#define t_lookahead_type 1189 ++#define del_targets_type 1190 ++#define del_target_type 1191 ++#define del_t_atom_type 1192 ++#define type_expressions_type 1193 ++#define func_type_comment_type 1194 ++#define invalid_arguments_type 1195 ++#define invalid_kwarg_type 1196 ++#define expression_without_invalid_type 1197 ++#define invalid_legacy_expression_type 1198 ++#define invalid_expression_type 1199 ++#define invalid_named_expression_type 1200 ++#define invalid_assignment_type 1201 ++#define invalid_ann_assign_target_type 1202 ++#define invalid_del_stmt_type 1203 ++#define invalid_block_type 1204 ++#define invalid_comprehension_type 1205 ++#define invalid_dict_comprehension_type 1206 ++#define invalid_parameters_type 1207 ++#define invalid_default_type 1208 ++#define invalid_star_etc_type 1209 ++#define invalid_kwds_type 1210 ++#define invalid_parameters_helper_type 1211 ++#define invalid_lambda_parameters_type 1212 ++#define invalid_lambda_parameters_helper_type 1213 ++#define invalid_lambda_star_etc_type 1214 ++#define invalid_lambda_kwds_type 1215 ++#define invalid_double_type_comments_type 1216 ++#define invalid_with_item_type 1217 ++#define invalid_for_target_type 1218 ++#define invalid_group_type 1219 ++#define invalid_import_type 1220 ++#define invalid_import_from_targets_type 1221 ++#define invalid_compound_stmt_type 1222 ++#define invalid_with_stmt_type 1223 ++#define invalid_with_stmt_indent_type 1224 ++#define invalid_try_stmt_type 1225 ++#define invalid_except_stmt_type 1226 ++#define invalid_finally_stmt_type 1227 ++#define invalid_except_stmt_indent_type 1228 ++#define invalid_except_star_stmt_indent_type 1229 ++#define invalid_match_stmt_type 1230 ++#define invalid_case_block_type 1231 ++#define invalid_as_pattern_type 1232 ++#define invalid_class_pattern_type 1233 ++#define invalid_class_argument_pattern_type 1234 ++#define invalid_if_stmt_type 1235 ++#define invalid_elif_stmt_type 1236 ++#define invalid_else_stmt_type 1237 ++#define invalid_while_stmt_type 1238 ++#define invalid_for_stmt_type 1239 ++#define invalid_def_raw_type 1240 ++#define invalid_class_def_raw_type 1241 ++#define invalid_double_starred_kvpairs_type 1242 ++#define invalid_kvpair_type 1243 ++#define invalid_starred_expression_type 1244 ++#define invalid_replacement_field_type 1245 ++#define invalid_conversion_character_type 1246 ++#define invalid_arithmetic_type 1247 ++#define invalid_factor_type 1248 ++#define _loop0_1_type 1249 ++#define _loop0_2_type 1250 ++#define _loop1_3_type 1251 ++#define _loop0_5_type 1252 ++#define _gather_4_type 1253 ++#define _tmp_6_type 1254 ++#define _tmp_7_type 1255 ++#define _tmp_8_type 1256 ++#define _tmp_9_type 1257 ++#define _tmp_10_type 1258 ++#define _tmp_11_type 1259 ++#define _tmp_12_type 1260 ++#define _tmp_13_type 1261 ++#define _loop1_14_type 1262 ++#define _tmp_15_type 1263 ++#define _tmp_16_type 1264 ++#define _tmp_17_type 1265 ++#define _loop0_19_type 1266 ++#define _gather_18_type 1267 ++#define _loop0_21_type 1268 ++#define _gather_20_type 1269 ++#define _tmp_22_type 1270 ++#define _tmp_23_type 1271 ++#define _loop0_24_type 1272 ++#define _loop1_25_type 1273 ++#define _loop0_27_type 1274 ++#define _gather_26_type 1275 ++#define _tmp_28_type 1276 ++#define _loop0_30_type 1277 ++#define _gather_29_type 1278 ++#define _tmp_31_type 1279 ++#define _loop1_32_type 1280 ++#define _tmp_33_type 1281 ++#define _tmp_34_type 1282 ++#define _tmp_35_type 1283 ++#define _loop0_36_type 1284 ++#define _loop0_37_type 1285 ++#define _loop0_38_type 1286 ++#define _loop1_39_type 1287 ++#define _loop0_40_type 1288 ++#define _loop1_41_type 1289 ++#define _loop1_42_type 1290 ++#define _loop1_43_type 1291 ++#define _loop0_44_type 1292 ++#define _loop1_45_type 1293 ++#define _loop0_46_type 1294 ++#define _loop1_47_type 1295 ++#define _loop0_48_type 1296 ++#define _loop0_49_type 1297 ++#define _loop1_50_type 1298 ++#define _loop0_52_type 1299 ++#define _gather_51_type 1300 ++#define _loop0_54_type 1301 ++#define _gather_53_type 1302 ++#define _loop0_56_type 1303 ++#define _gather_55_type 1304 ++#define _loop0_58_type 1305 ++#define _gather_57_type 1306 ++#define _tmp_59_type 1307 ++#define _loop1_60_type 1308 ++#define _loop1_61_type 1309 ++#define _tmp_62_type 1310 ++#define _tmp_63_type 1311 ++#define _loop1_64_type 1312 ++#define _loop0_66_type 1313 ++#define _gather_65_type 1314 ++#define _tmp_67_type 1315 ++#define _tmp_68_type 1316 ++#define _tmp_69_type 1317 ++#define _tmp_70_type 1318 ++#define _loop0_72_type 1319 ++#define _gather_71_type 1320 ++#define _loop0_74_type 1321 ++#define _gather_73_type 1322 ++#define _tmp_75_type 1323 ++#define _loop0_77_type 1324 ++#define _gather_76_type 1325 ++#define _loop0_79_type 1326 ++#define _gather_78_type 1327 ++#define _loop0_81_type 1328 ++#define _gather_80_type 1329 ++#define _loop1_82_type 1330 ++#define _loop1_83_type 1331 ++#define _loop0_85_type 1332 ++#define _gather_84_type 1333 ++#define _loop1_86_type 1334 ++#define _loop1_87_type 1335 ++#define _loop1_88_type 1336 ++#define _tmp_89_type 1337 ++#define _loop0_91_type 1338 ++#define _gather_90_type 1339 ++#define _tmp_92_type 1340 ++#define _tmp_93_type 1341 ++#define _tmp_94_type 1342 ++#define _tmp_95_type 1343 ++#define _tmp_96_type 1344 ++#define _tmp_97_type 1345 ++#define _loop0_98_type 1346 ++#define _loop0_99_type 1347 ++#define _loop0_100_type 1348 ++#define _loop1_101_type 1349 ++#define _loop0_102_type 1350 ++#define _loop1_103_type 1351 ++#define _loop1_104_type 1352 ++#define _loop1_105_type 1353 ++#define _loop0_106_type 1354 ++#define _loop1_107_type 1355 ++#define _loop0_108_type 1356 ++#define _loop1_109_type 1357 ++#define _loop0_110_type 1358 ++#define _loop1_111_type 1359 ++#define _loop0_112_type 1360 ++#define _loop0_113_type 1361 ++#define _loop1_114_type 1362 ++#define _tmp_115_type 1363 ++#define _loop0_117_type 1364 ++#define _gather_116_type 1365 ++#define _loop1_118_type 1366 ++#define _loop0_119_type 1367 ++#define _loop0_120_type 1368 ++#define _tmp_121_type 1369 ++#define _tmp_122_type 1370 ++#define _loop0_124_type 1371 ++#define _gather_123_type 1372 ++#define _tmp_125_type 1373 ++#define _loop0_127_type 1374 ++#define _gather_126_type 1375 ++#define _loop0_129_type 1376 ++#define _gather_128_type 1377 ++#define _loop0_131_type 1378 ++#define _gather_130_type 1379 ++#define _loop0_133_type 1380 ++#define _gather_132_type 1381 ++#define _loop0_134_type 1382 ++#define _loop0_136_type 1383 ++#define _gather_135_type 1384 ++#define _loop1_137_type 1385 ++#define _tmp_138_type 1386 ++#define _loop0_140_type 1387 ++#define _gather_139_type 1388 ++#define _loop0_142_type 1389 ++#define _gather_141_type 1390 ++#define _loop0_144_type 1391 ++#define _gather_143_type 1392 ++#define _loop0_146_type 1393 ++#define _gather_145_type 1394 ++#define _loop0_148_type 1395 ++#define _gather_147_type 1396 ++#define _tmp_149_type 1397 ++#define _tmp_150_type 1398 ++#define _loop0_152_type 1399 ++#define _gather_151_type 1400 ++#define _tmp_153_type 1401 ++#define _tmp_154_type 1402 ++#define _tmp_155_type 1403 ++#define _tmp_156_type 1404 ++#define _tmp_157_type 1405 ++#define _tmp_158_type 1406 ++#define _tmp_159_type 1407 ++#define _tmp_160_type 1408 ++#define _tmp_161_type 1409 ++#define _tmp_162_type 1410 ++#define _loop0_163_type 1411 ++#define _loop0_164_type 1412 ++#define _loop0_165_type 1413 ++#define _tmp_166_type 1414 ++#define _tmp_167_type 1415 ++#define _tmp_168_type 1416 ++#define _tmp_169_type 1417 ++#define _loop0_170_type 1418 ++#define _loop0_171_type 1419 ++#define _loop0_172_type 1420 ++#define _loop1_173_type 1421 ++#define _tmp_174_type 1422 ++#define _loop0_175_type 1423 ++#define _tmp_176_type 1424 ++#define _loop0_177_type 1425 ++#define _loop1_178_type 1426 ++#define _tmp_179_type 1427 ++#define _tmp_180_type 1428 ++#define _tmp_181_type 1429 ++#define _loop0_182_type 1430 ++#define _tmp_183_type 1431 ++#define _tmp_184_type 1432 ++#define _loop1_185_type 1433 ++#define _tmp_186_type 1434 ++#define _loop0_187_type 1435 ++#define _loop0_188_type 1436 ++#define _loop0_189_type 1437 ++#define _loop0_191_type 1438 ++#define _gather_190_type 1439 ++#define _tmp_192_type 1440 ++#define _loop0_193_type 1441 ++#define _tmp_194_type 1442 ++#define _loop0_195_type 1443 ++#define _loop1_196_type 1444 ++#define _loop1_197_type 1445 ++#define _tmp_198_type 1446 ++#define _tmp_199_type 1447 ++#define _loop0_200_type 1448 ++#define _tmp_201_type 1449 ++#define _tmp_202_type 1450 ++#define _tmp_203_type 1451 ++#define _loop0_205_type 1452 ++#define _gather_204_type 1453 ++#define _loop0_207_type 1454 ++#define _gather_206_type 1455 ++#define _loop0_209_type 1456 ++#define _gather_208_type 1457 ++#define _loop0_211_type 1458 ++#define _gather_210_type 1459 ++#define _loop0_213_type 1460 ++#define _gather_212_type 1461 ++#define _tmp_214_type 1462 ++#define _loop0_215_type 1463 ++#define _loop1_216_type 1464 ++#define _tmp_217_type 1465 ++#define _loop0_218_type 1466 ++#define _loop1_219_type 1467 ++#define _tmp_220_type 1468 ++#define _tmp_221_type 1469 ++#define _tmp_222_type 1470 ++#define _tmp_223_type 1471 ++#define _tmp_224_type 1472 ++#define _tmp_225_type 1473 ++#define _tmp_226_type 1474 ++#define _tmp_227_type 1475 ++#define _tmp_228_type 1476 ++#define _tmp_229_type 1477 ++#define _loop0_231_type 1478 ++#define _gather_230_type 1479 ++#define _tmp_232_type 1480 ++#define _tmp_233_type 1481 ++#define _tmp_234_type 1482 ++#define _tmp_235_type 1483 ++#define _tmp_236_type 1484 ++#define _tmp_237_type 1485 ++#define _tmp_238_type 1486 ++#define _loop0_239_type 1487 ++#define _tmp_240_type 1488 ++#define _tmp_241_type 1489 ++#define _tmp_242_type 1490 ++#define _tmp_243_type 1491 ++#define _tmp_244_type 1492 ++#define _tmp_245_type 1493 ++#define _tmp_246_type 1494 ++#define _tmp_247_type 1495 ++#define _tmp_248_type 1496 ++#define _tmp_249_type 1497 ++#define _tmp_250_type 1498 ++#define _tmp_251_type 1499 ++#define _tmp_252_type 1500 ++#define _tmp_253_type 1501 ++#define _tmp_254_type 1502 ++#define _tmp_255_type 1503 ++#define _loop0_256_type 1504 ++#define _tmp_257_type 1505 ++#define _tmp_258_type 1506 ++#define _tmp_259_type 1507 ++#define _tmp_260_type 1508 ++#define _tmp_261_type 1509 ++#define _tmp_262_type 1510 ++#define _tmp_263_type 1511 ++#define _tmp_264_type 1512 ++#define _tmp_265_type 1513 ++#define _tmp_266_type 1514 ++#define _tmp_267_type 1515 ++#define _tmp_268_type 1516 ++#define _tmp_269_type 1517 ++#define _tmp_270_type 1518 ++#define _tmp_271_type 1519 ++#define _tmp_272_type 1520 ++#define _loop0_274_type 1521 ++#define _gather_273_type 1522 ++#define _tmp_275_type 1523 ++#define _tmp_276_type 1524 ++#define _tmp_277_type 1525 ++#define _tmp_278_type 1526 ++#define _tmp_279_type 1527 ++#define _tmp_280_type 1528 + + static mod_ty file_rule(Parser *p); + static mod_ty interactive_rule(Parser *p); +@@ -714,6 +716,8 @@ static asdl_type_param_seq* type_params_rule(Parser *p); + static asdl_type_param_seq* type_param_seq_rule(Parser *p); + static type_param_ty type_param_rule(Parser *p); + static expr_ty type_param_bound_rule(Parser *p); ++static expr_ty type_param_default_rule(Parser *p); ++static expr_ty type_param_starred_default_rule(Parser *p); + static expr_ty expressions_rule(Parser *p); + static expr_ty expression_rule(Parser *p); + static expr_ty yield_expr_rule(Parser *p); +@@ -10646,11 +10650,11 @@ type_param_seq_rule(Parser *p) + } + + // type_param: +-// | NAME type_param_bound? ++// | NAME type_param_bound? type_param_default? + // | '*' NAME ':' expression +-// | '*' NAME ++// | '*' NAME type_param_starred_default? + // | '**' NAME ':' expression +-// | '**' NAME ++// | '**' NAME type_param_default? + static type_param_ty + type_param_rule(Parser *p) + { +@@ -10676,21 +10680,24 @@ type_param_rule(Parser *p) + UNUSED(_start_lineno); // Only used by EXTRA macro + int _start_col_offset = p->tokens[_mark]->col_offset; + UNUSED(_start_col_offset); // Only used by EXTRA macro +- { // NAME type_param_bound? ++ { // NAME type_param_bound? type_param_default? + if (p->error_indicator) { + p->level--; + return NULL; + } +- D(fprintf(stderr, "%*c> type_param[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "NAME type_param_bound?")); ++ D(fprintf(stderr, "%*c> type_param[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "NAME type_param_bound? type_param_default?")); + expr_ty a; + void *b; ++ void *c; + if ( + (a = _PyPegen_name_token(p)) // NAME + && + (b = type_param_bound_rule(p), !p->error_indicator) // type_param_bound? ++ && ++ (c = type_param_default_rule(p), !p->error_indicator) // type_param_default? + ) + { +- D(fprintf(stderr, "%*c+ type_param[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "NAME type_param_bound?")); ++ D(fprintf(stderr, "%*c+ type_param[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "NAME type_param_bound? type_param_default?")); + Token *_token = _PyPegen_get_last_nonnwhitespace_token(p); + if (_token == NULL) { + p->level--; +@@ -10700,7 +10707,7 @@ type_param_rule(Parser *p) + UNUSED(_end_lineno); // Only used by EXTRA macro + int _end_col_offset = _token->end_col_offset; + UNUSED(_end_col_offset); // Only used by EXTRA macro +- _res = _PyAST_TypeVar ( a -> v . Name . id , b , EXTRA ); ++ _res = _PyAST_TypeVar ( a -> v . Name . id , b , c , EXTRA ); + if (_res == NULL && PyErr_Occurred()) { + p->error_indicator = 1; + p->level--; +@@ -10710,7 +10717,7 @@ type_param_rule(Parser *p) + } + p->mark = _mark; + D(fprintf(stderr, "%*c%s type_param[%d-%d]: %s failed!\n", p->level, ' ', +- p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "NAME type_param_bound?")); ++ p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "NAME type_param_bound? type_param_default?")); + } + { // '*' NAME ':' expression + if (p->error_indicator) { +@@ -10745,21 +10752,24 @@ type_param_rule(Parser *p) + D(fprintf(stderr, "%*c%s type_param[%d-%d]: %s failed!\n", p->level, ' ', + p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "'*' NAME ':' expression")); + } +- { // '*' NAME ++ { // '*' NAME type_param_starred_default? + if (p->error_indicator) { + p->level--; + return NULL; + } +- D(fprintf(stderr, "%*c> type_param[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "'*' NAME")); ++ D(fprintf(stderr, "%*c> type_param[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "'*' NAME type_param_starred_default?")); + Token * _literal; + expr_ty a; ++ void *b; + if ( + (_literal = _PyPegen_expect_token(p, 16)) // token='*' + && + (a = _PyPegen_name_token(p)) // NAME ++ && ++ (b = type_param_starred_default_rule(p), !p->error_indicator) // type_param_starred_default? + ) + { +- D(fprintf(stderr, "%*c+ type_param[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "'*' NAME")); ++ D(fprintf(stderr, "%*c+ type_param[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "'*' NAME type_param_starred_default?")); + Token *_token = _PyPegen_get_last_nonnwhitespace_token(p); + if (_token == NULL) { + p->level--; +@@ -10769,7 +10779,7 @@ type_param_rule(Parser *p) + UNUSED(_end_lineno); // Only used by EXTRA macro + int _end_col_offset = _token->end_col_offset; + UNUSED(_end_col_offset); // Only used by EXTRA macro +- _res = _PyAST_TypeVarTuple ( a -> v . Name . id , EXTRA ); ++ _res = _PyAST_TypeVarTuple ( a -> v . Name . id , b , EXTRA ); + if (_res == NULL && PyErr_Occurred()) { + p->error_indicator = 1; + p->level--; +@@ -10779,7 +10789,7 @@ type_param_rule(Parser *p) + } + p->mark = _mark; + D(fprintf(stderr, "%*c%s type_param[%d-%d]: %s failed!\n", p->level, ' ', +- p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "'*' NAME")); ++ p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "'*' NAME type_param_starred_default?")); + } + { // '**' NAME ':' expression + if (p->error_indicator) { +@@ -10814,21 +10824,24 @@ type_param_rule(Parser *p) + D(fprintf(stderr, "%*c%s type_param[%d-%d]: %s failed!\n", p->level, ' ', + p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "'**' NAME ':' expression")); + } +- { // '**' NAME ++ { // '**' NAME type_param_default? + if (p->error_indicator) { + p->level--; + return NULL; + } +- D(fprintf(stderr, "%*c> type_param[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "'**' NAME")); ++ D(fprintf(stderr, "%*c> type_param[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "'**' NAME type_param_default?")); + Token * _literal; + expr_ty a; ++ void *b; + if ( + (_literal = _PyPegen_expect_token(p, 35)) // token='**' + && + (a = _PyPegen_name_token(p)) // NAME ++ && ++ (b = type_param_default_rule(p), !p->error_indicator) // type_param_default? + ) + { +- D(fprintf(stderr, "%*c+ type_param[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "'**' NAME")); ++ D(fprintf(stderr, "%*c+ type_param[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "'**' NAME type_param_default?")); + Token *_token = _PyPegen_get_last_nonnwhitespace_token(p); + if (_token == NULL) { + p->level--; +@@ -10838,7 +10851,7 @@ type_param_rule(Parser *p) + UNUSED(_end_lineno); // Only used by EXTRA macro + int _end_col_offset = _token->end_col_offset; + UNUSED(_end_col_offset); // Only used by EXTRA macro +- _res = _PyAST_ParamSpec ( a -> v . Name . id , EXTRA ); ++ _res = _PyAST_ParamSpec ( a -> v . Name . id , b , EXTRA ); + if (_res == NULL && PyErr_Occurred()) { + p->error_indicator = 1; + p->level--; +@@ -10848,7 +10861,7 @@ type_param_rule(Parser *p) + } + p->mark = _mark; + D(fprintf(stderr, "%*c%s type_param[%d-%d]: %s failed!\n", p->level, ' ', +- p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "'**' NAME")); ++ p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "'**' NAME type_param_default?")); + } + _res = NULL; + done: +@@ -10903,6 +10916,98 @@ type_param_bound_rule(Parser *p) + return _res; + } + ++// type_param_default: '=' expression ++static expr_ty ++type_param_default_rule(Parser *p) ++{ ++ if (p->level++ == MAXSTACK) { ++ _Pypegen_stack_overflow(p); ++ } ++ if (p->error_indicator) { ++ p->level--; ++ return NULL; ++ } ++ expr_ty _res = NULL; ++ int _mark = p->mark; ++ { // '=' expression ++ if (p->error_indicator) { ++ p->level--; ++ return NULL; ++ } ++ D(fprintf(stderr, "%*c> type_param_default[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "'=' expression")); ++ Token * _literal; ++ expr_ty e; ++ if ( ++ (_literal = _PyPegen_expect_token(p, 22)) // token='=' ++ && ++ (e = expression_rule(p)) // expression ++ ) ++ { ++ D(fprintf(stderr, "%*c+ type_param_default[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "'=' expression")); ++ _res = CHECK_VERSION ( expr_ty , 13 , "Type parameter defaults are" , e ); ++ if (_res == NULL && PyErr_Occurred()) { ++ p->error_indicator = 1; ++ p->level--; ++ return NULL; ++ } ++ goto done; ++ } ++ p->mark = _mark; ++ D(fprintf(stderr, "%*c%s type_param_default[%d-%d]: %s failed!\n", p->level, ' ', ++ p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "'=' expression")); ++ } ++ _res = NULL; ++ done: ++ p->level--; ++ return _res; ++} ++ ++// type_param_starred_default: '=' star_expression ++static expr_ty ++type_param_starred_default_rule(Parser *p) ++{ ++ if (p->level++ == MAXSTACK) { ++ _Pypegen_stack_overflow(p); ++ } ++ if (p->error_indicator) { ++ p->level--; ++ return NULL; ++ } ++ expr_ty _res = NULL; ++ int _mark = p->mark; ++ { // '=' star_expression ++ if (p->error_indicator) { ++ p->level--; ++ return NULL; ++ } ++ D(fprintf(stderr, "%*c> type_param_starred_default[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "'=' star_expression")); ++ Token * _literal; ++ expr_ty e; ++ if ( ++ (_literal = _PyPegen_expect_token(p, 22)) // token='=' ++ && ++ (e = star_expression_rule(p)) // star_expression ++ ) ++ { ++ D(fprintf(stderr, "%*c+ type_param_starred_default[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "'=' star_expression")); ++ _res = CHECK_VERSION ( expr_ty , 13 , "Type parameter defaults are" , e ); ++ if (_res == NULL && PyErr_Occurred()) { ++ p->error_indicator = 1; ++ p->level--; ++ return NULL; ++ } ++ goto done; ++ } ++ p->mark = _mark; ++ D(fprintf(stderr, "%*c%s type_param_starred_default[%d-%d]: %s failed!\n", p->level, ' ', ++ p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "'=' star_expression")); ++ } ++ _res = NULL; ++ done: ++ p->level--; ++ return _res; ++} ++ + // expressions: expression ((',' expression))+ ','? | expression ',' | expression + static expr_ty + expressions_rule(Parser *p) +diff --git a/Python/Python-ast.c b/Python/Python-ast.c +index 60b46263a0..cc7734e0db 100644 +--- a/Python/Python-ast.c ++++ b/Python/Python-ast.c +@@ -203,6 +203,7 @@ void _PyAST_Fini(PyInterpreterState *interp) + Py_CLEAR(state->conversion); + Py_CLEAR(state->ctx); + Py_CLEAR(state->decorator_list); ++ Py_CLEAR(state->default_value); + Py_CLEAR(state->defaults); + Py_CLEAR(state->elt); + Py_CLEAR(state->elts); +@@ -311,6 +312,7 @@ static int init_identifiers(struct ast_state *state) + if ((state->conversion = PyUnicode_InternFromString("conversion")) == NULL) return -1; + if ((state->ctx = PyUnicode_InternFromString("ctx")) == NULL) return -1; + if ((state->decorator_list = PyUnicode_InternFromString("decorator_list")) == NULL) return -1; ++ if ((state->default_value = PyUnicode_InternFromString("default_value")) == NULL) return -1; + if ((state->defaults = PyUnicode_InternFromString("defaults")) == NULL) return -1; + if ((state->elt = PyUnicode_InternFromString("elt")) == NULL) return -1; + if ((state->elts = PyUnicode_InternFromString("elts")) == NULL) return -1; +@@ -809,12 +811,15 @@ static PyObject* ast2obj_type_param(struct ast_state *state, struct validator + static const char * const TypeVar_fields[]={ + "name", + "bound", ++ "default_value", + }; + static const char * const ParamSpec_fields[]={ + "name", ++ "default_value", + }; + static const char * const TypeVarTuple_fields[]={ + "name", ++ "default_value", + }; + + +@@ -4913,6 +4918,22 @@ add_ast_annotations(struct ast_state *state) + return 0; + } + } ++ { ++ PyObject *type = state->expr_type; ++ type = _Py_union_type_or(type, Py_None); ++ cond = type != NULL; ++ if (!cond) { ++ Py_DECREF(TypeVar_annotations); ++ return 0; ++ } ++ cond = PyDict_SetItemString(TypeVar_annotations, "default_value", type) ++ == 0; ++ Py_DECREF(type); ++ if (!cond) { ++ Py_DECREF(TypeVar_annotations); ++ return 0; ++ } ++ } + cond = PyObject_SetAttrString(state->TypeVar_type, "_field_types", + TypeVar_annotations) == 0; + if (!cond) { +@@ -4938,6 +4959,22 @@ add_ast_annotations(struct ast_state *state) + return 0; + } + } ++ { ++ PyObject *type = state->expr_type; ++ type = _Py_union_type_or(type, Py_None); ++ cond = type != NULL; ++ if (!cond) { ++ Py_DECREF(ParamSpec_annotations); ++ return 0; ++ } ++ cond = PyDict_SetItemString(ParamSpec_annotations, "default_value", ++ type) == 0; ++ Py_DECREF(type); ++ if (!cond) { ++ Py_DECREF(ParamSpec_annotations); ++ return 0; ++ } ++ } + cond = PyObject_SetAttrString(state->ParamSpec_type, "_field_types", + ParamSpec_annotations) == 0; + if (!cond) { +@@ -4964,6 +5001,22 @@ add_ast_annotations(struct ast_state *state) + return 0; + } + } ++ { ++ PyObject *type = state->expr_type; ++ type = _Py_union_type_or(type, Py_None); ++ cond = type != NULL; ++ if (!cond) { ++ Py_DECREF(TypeVarTuple_annotations); ++ return 0; ++ } ++ cond = PyDict_SetItemString(TypeVarTuple_annotations, "default_value", ++ type) == 0; ++ Py_DECREF(type); ++ if (!cond) { ++ Py_DECREF(TypeVarTuple_annotations); ++ return 0; ++ } ++ } + cond = PyObject_SetAttrString(state->TypeVarTuple_type, "_field_types", + TypeVarTuple_annotations) == 0; + if (!cond) { +@@ -6243,28 +6296,37 @@ init_types(struct ast_state *state) + if (!state->TypeIgnore_type) return -1; + state->type_param_type = make_type(state, "type_param", state->AST_type, + NULL, 0, +- "type_param = TypeVar(identifier name, expr? bound)\n" +- " | ParamSpec(identifier name)\n" +- " | TypeVarTuple(identifier name)"); ++ "type_param = TypeVar(identifier name, expr? bound, expr? default_value)\n" ++ " | ParamSpec(identifier name, expr? default_value)\n" ++ " | TypeVarTuple(identifier name, expr? default_value)"); + if (!state->type_param_type) return -1; + if (add_attributes(state, state->type_param_type, type_param_attributes, 4) + < 0) return -1; + state->TypeVar_type = make_type(state, "TypeVar", state->type_param_type, +- TypeVar_fields, 2, +- "TypeVar(identifier name, expr? bound)"); ++ TypeVar_fields, 3, ++ "TypeVar(identifier name, expr? bound, expr? default_value)"); + if (!state->TypeVar_type) return -1; + if (PyObject_SetAttr(state->TypeVar_type, state->bound, Py_None) == -1) + return -1; ++ if (PyObject_SetAttr(state->TypeVar_type, state->default_value, Py_None) == ++ -1) ++ return -1; + state->ParamSpec_type = make_type(state, "ParamSpec", + state->type_param_type, ParamSpec_fields, +- 1, +- "ParamSpec(identifier name)"); ++ 2, ++ "ParamSpec(identifier name, expr? default_value)"); + if (!state->ParamSpec_type) return -1; ++ if (PyObject_SetAttr(state->ParamSpec_type, state->default_value, Py_None) ++ == -1) ++ return -1; + state->TypeVarTuple_type = make_type(state, "TypeVarTuple", + state->type_param_type, +- TypeVarTuple_fields, 1, +- "TypeVarTuple(identifier name)"); ++ TypeVarTuple_fields, 2, ++ "TypeVarTuple(identifier name, expr? default_value)"); + if (!state->TypeVarTuple_type) return -1; ++ if (PyObject_SetAttr(state->TypeVarTuple_type, state->default_value, ++ Py_None) == -1) ++ return -1; + + if (!add_ast_annotations(state)) { + return -1; +@@ -8055,8 +8117,9 @@ _PyAST_TypeIgnore(int lineno, string tag, PyArena *arena) + } + + type_param_ty +-_PyAST_TypeVar(identifier name, expr_ty bound, int lineno, int col_offset, int +- end_lineno, int end_col_offset, PyArena *arena) ++_PyAST_TypeVar(identifier name, expr_ty bound, expr_ty default_value, int ++ lineno, int col_offset, int end_lineno, int end_col_offset, ++ PyArena *arena) + { + type_param_ty p; + if (!name) { +@@ -8070,6 +8133,7 @@ _PyAST_TypeVar(identifier name, expr_ty bound, int lineno, int col_offset, int + p->kind = TypeVar_kind; + p->v.TypeVar.name = name; + p->v.TypeVar.bound = bound; ++ p->v.TypeVar.default_value = default_value; + p->lineno = lineno; + p->col_offset = col_offset; + p->end_lineno = end_lineno; +@@ -8078,8 +8142,8 @@ _PyAST_TypeVar(identifier name, expr_ty bound, int lineno, int col_offset, int + } + + type_param_ty +-_PyAST_ParamSpec(identifier name, int lineno, int col_offset, int end_lineno, +- int end_col_offset, PyArena *arena) ++_PyAST_ParamSpec(identifier name, expr_ty default_value, int lineno, int ++ col_offset, int end_lineno, int end_col_offset, PyArena *arena) + { + type_param_ty p; + if (!name) { +@@ -8092,6 +8156,7 @@ _PyAST_ParamSpec(identifier name, int lineno, int col_offset, int end_lineno, + return NULL; + p->kind = ParamSpec_kind; + p->v.ParamSpec.name = name; ++ p->v.ParamSpec.default_value = default_value; + p->lineno = lineno; + p->col_offset = col_offset; + p->end_lineno = end_lineno; +@@ -8100,8 +8165,9 @@ _PyAST_ParamSpec(identifier name, int lineno, int col_offset, int end_lineno, + } + + type_param_ty +-_PyAST_TypeVarTuple(identifier name, int lineno, int col_offset, int +- end_lineno, int end_col_offset, PyArena *arena) ++_PyAST_TypeVarTuple(identifier name, expr_ty default_value, int lineno, int ++ col_offset, int end_lineno, int end_col_offset, PyArena ++ *arena) + { + type_param_ty p; + if (!name) { +@@ -8114,6 +8180,7 @@ _PyAST_TypeVarTuple(identifier name, int lineno, int col_offset, int + return NULL; + p->kind = TypeVarTuple_kind; + p->v.TypeVarTuple.name = name; ++ p->v.TypeVarTuple.default_value = default_value; + p->lineno = lineno; + p->col_offset = col_offset; + p->end_lineno = end_lineno; +@@ -10079,6 +10146,11 @@ ast2obj_type_param(struct ast_state *state, struct validator *vstate, void* _o) + if (PyObject_SetAttr(result, state->bound, value) == -1) + goto failed; + Py_DECREF(value); ++ value = ast2obj_expr(state, vstate, o->v.TypeVar.default_value); ++ if (!value) goto failed; ++ if (PyObject_SetAttr(result, state->default_value, value) == -1) ++ goto failed; ++ Py_DECREF(value); + break; + case ParamSpec_kind: + tp = (PyTypeObject *)state->ParamSpec_type; +@@ -10089,6 +10161,11 @@ ast2obj_type_param(struct ast_state *state, struct validator *vstate, void* _o) + if (PyObject_SetAttr(result, state->name, value) == -1) + goto failed; + Py_DECREF(value); ++ value = ast2obj_expr(state, vstate, o->v.ParamSpec.default_value); ++ if (!value) goto failed; ++ if (PyObject_SetAttr(result, state->default_value, value) == -1) ++ goto failed; ++ Py_DECREF(value); + break; + case TypeVarTuple_kind: + tp = (PyTypeObject *)state->TypeVarTuple_type; +@@ -10099,6 +10176,11 @@ ast2obj_type_param(struct ast_state *state, struct validator *vstate, void* _o) + if (PyObject_SetAttr(result, state->name, value) == -1) + goto failed; + Py_DECREF(value); ++ value = ast2obj_expr(state, vstate, o->v.TypeVarTuple.default_value); ++ if (!value) goto failed; ++ if (PyObject_SetAttr(result, state->default_value, value) == -1) ++ goto failed; ++ Py_DECREF(value); + break; + } + value = ast2obj_int(state, vstate, o->lineno); +@@ -16935,6 +17017,7 @@ obj2ast_type_param(struct ast_state *state, PyObject* obj, type_param_ty* out, + if (isinstance) { + identifier name; + expr_ty bound; ++ expr_ty default_value; + + if (PyObject_GetOptionalAttr(obj, state->name, &tmp) < 0) { + return -1; +@@ -16970,8 +17053,25 @@ obj2ast_type_param(struct ast_state *state, PyObject* obj, type_param_ty* out, + if (res != 0) goto failed; + Py_CLEAR(tmp); + } +- *out = _PyAST_TypeVar(name, bound, lineno, col_offset, end_lineno, +- end_col_offset, arena); ++ if (PyObject_GetOptionalAttr(obj, state->default_value, &tmp) < 0) { ++ return -1; ++ } ++ if (tmp == NULL || tmp == Py_None) { ++ Py_CLEAR(tmp); ++ default_value = NULL; ++ } ++ else { ++ int res; ++ if (_Py_EnterRecursiveCall(" while traversing 'TypeVar' node")) { ++ goto failed; ++ } ++ res = obj2ast_expr(state, tmp, &default_value, arena); ++ _Py_LeaveRecursiveCall(); ++ if (res != 0) goto failed; ++ Py_CLEAR(tmp); ++ } ++ *out = _PyAST_TypeVar(name, bound, default_value, lineno, col_offset, ++ end_lineno, end_col_offset, arena); + if (*out == NULL) goto failed; + return 0; + } +@@ -16982,6 +17082,7 @@ obj2ast_type_param(struct ast_state *state, PyObject* obj, type_param_ty* out, + } + if (isinstance) { + identifier name; ++ expr_ty default_value; + + if (PyObject_GetOptionalAttr(obj, state->name, &tmp) < 0) { + return -1; +@@ -17000,8 +17101,25 @@ obj2ast_type_param(struct ast_state *state, PyObject* obj, type_param_ty* out, + if (res != 0) goto failed; + Py_CLEAR(tmp); + } +- *out = _PyAST_ParamSpec(name, lineno, col_offset, end_lineno, +- end_col_offset, arena); ++ if (PyObject_GetOptionalAttr(obj, state->default_value, &tmp) < 0) { ++ return -1; ++ } ++ if (tmp == NULL || tmp == Py_None) { ++ Py_CLEAR(tmp); ++ default_value = NULL; ++ } ++ else { ++ int res; ++ if (_Py_EnterRecursiveCall(" while traversing 'ParamSpec' node")) { ++ goto failed; ++ } ++ res = obj2ast_expr(state, tmp, &default_value, arena); ++ _Py_LeaveRecursiveCall(); ++ if (res != 0) goto failed; ++ Py_CLEAR(tmp); ++ } ++ *out = _PyAST_ParamSpec(name, default_value, lineno, col_offset, ++ end_lineno, end_col_offset, arena); + if (*out == NULL) goto failed; + return 0; + } +@@ -17012,6 +17130,7 @@ obj2ast_type_param(struct ast_state *state, PyObject* obj, type_param_ty* out, + } + if (isinstance) { + identifier name; ++ expr_ty default_value; + + if (PyObject_GetOptionalAttr(obj, state->name, &tmp) < 0) { + return -1; +@@ -17030,8 +17149,25 @@ obj2ast_type_param(struct ast_state *state, PyObject* obj, type_param_ty* out, + if (res != 0) goto failed; + Py_CLEAR(tmp); + } +- *out = _PyAST_TypeVarTuple(name, lineno, col_offset, end_lineno, +- end_col_offset, arena); ++ if (PyObject_GetOptionalAttr(obj, state->default_value, &tmp) < 0) { ++ return -1; ++ } ++ if (tmp == NULL || tmp == Py_None) { ++ Py_CLEAR(tmp); ++ default_value = NULL; ++ } ++ else { ++ int res; ++ if (_Py_EnterRecursiveCall(" while traversing 'TypeVarTuple' node")) { ++ goto failed; ++ } ++ res = obj2ast_expr(state, tmp, &default_value, arena); ++ _Py_LeaveRecursiveCall(); ++ if (res != 0) goto failed; ++ Py_CLEAR(tmp); ++ } ++ *out = _PyAST_TypeVarTuple(name, default_value, lineno, col_offset, ++ end_lineno, end_col_offset, arena); + if (*out == NULL) goto failed; + return 0; + } +diff --git a/Python/ast.c b/Python/ast.c +index 71b09d889f..1d1a48ec88 100644 +--- a/Python/ast.c ++++ b/Python/ast.c +@@ -1011,13 +1011,19 @@ validate_typeparam(struct validator *state, type_param_ty tp) + case TypeVar_kind: + ret = validate_name(tp->v.TypeVar.name) && + (!tp->v.TypeVar.bound || +- validate_expr(state, tp->v.TypeVar.bound, Load)); ++ validate_expr(state, tp->v.TypeVar.bound, Load)) && ++ (!tp->v.TypeVar.default_value || ++ validate_expr(state, tp->v.TypeVar.default_value, Load)); + break; + case ParamSpec_kind: +- ret = validate_name(tp->v.ParamSpec.name); ++ ret = validate_name(tp->v.ParamSpec.name) && ++ (!tp->v.ParamSpec.default_value || ++ validate_expr(state, tp->v.ParamSpec.default_value, Load)); + break; + case TypeVarTuple_kind: +- ret = validate_name(tp->v.TypeVarTuple.name); ++ ret = validate_name(tp->v.TypeVarTuple.name) && ++ (!tp->v.TypeVarTuple.default_value || ++ validate_expr(state, tp->v.TypeVarTuple.default_value, Load)); + break; + } + return ret; +diff --git a/Python/compile.c b/Python/compile.c +index feedd98883..ec47af151f 100644 +--- a/Python/compile.c ++++ b/Python/compile.c +@@ -2116,6 +2116,36 @@ wrap_in_stopiteration_handler(struct compiler *c) + return SUCCESS; + } + ++static int ++compiler_type_param_bound_or_default(struct compiler *c, expr_ty e, ++ identifier name, void *key, ++ bool allow_starred) ++{ ++ if (compiler_enter_scope(c, name, COMPILER_SCOPE_TYPEPARAMS, ++ key, e->lineno) == -1) { ++ return ERROR; ++ } ++ if (allow_starred && e->kind == Starred_kind) { ++ VISIT(c, expr, e->v.Starred.value); ++ ADDOP_I(c, LOC(e), UNPACK_SEQUENCE, (Py_ssize_t)1); ++ } ++ else { ++ VISIT(c, expr, e); ++ } ++ ADDOP_IN_SCOPE(c, LOC(e), RETURN_VALUE); ++ PyCodeObject *co = optimize_and_assemble(c, 1); ++ compiler_exit_scope(c); ++ if (co == NULL) { ++ return ERROR; ++ } ++ if (compiler_make_closure(c, LOC(e), co, 0) < 0) { ++ Py_DECREF(co); ++ return ERROR; ++ } ++ Py_DECREF(co); ++ return SUCCESS; ++} ++ + static int + compiler_type_params(struct compiler *c, asdl_type_param_seq *type_params) + { +@@ -2123,6 +2153,7 @@ compiler_type_params(struct compiler *c, asdl_type_param_seq *type_params) + return SUCCESS; + } + Py_ssize_t n = asdl_seq_LEN(type_params); ++ bool seen_default = false; + + for (Py_ssize_t i = 0; i < n; i++) { + type_param_ty typeparam = asdl_seq_GET(type_params, i); +@@ -2132,22 +2163,10 @@ compiler_type_params(struct compiler *c, asdl_type_param_seq *type_params) + ADDOP_LOAD_CONST(c, loc, typeparam->v.TypeVar.name); + if (typeparam->v.TypeVar.bound) { + expr_ty bound = typeparam->v.TypeVar.bound; +- if (compiler_enter_scope(c, typeparam->v.TypeVar.name, COMPILER_SCOPE_TYPEPARAMS, +- (void *)typeparam, bound->lineno) == -1) { ++ if (compiler_type_param_bound_or_default(c, bound, typeparam->v.TypeVar.name, ++ (void *)typeparam, false) < 0) { + return ERROR; + } +- VISIT_IN_SCOPE(c, expr, bound); +- ADDOP_IN_SCOPE(c, loc, RETURN_VALUE); +- PyCodeObject *co = optimize_and_assemble(c, 1); +- compiler_exit_scope(c); +- if (co == NULL) { +- return ERROR; +- } +- if (compiler_make_closure(c, loc, co, 0) < 0) { +- Py_DECREF(co); +- return ERROR; +- } +- Py_DECREF(co); + + int intrinsic = bound->kind == Tuple_kind + ? INTRINSIC_TYPEVAR_WITH_CONSTRAINTS +@@ -2157,18 +2176,60 @@ compiler_type_params(struct compiler *c, asdl_type_param_seq *type_params) + else { + ADDOP_I(c, loc, CALL_INTRINSIC_1, INTRINSIC_TYPEVAR); + } ++ if (typeparam->v.TypeVar.default_value) { ++ seen_default = true; ++ expr_ty default_ = typeparam->v.TypeVar.default_value; ++ if (compiler_type_param_bound_or_default(c, default_, typeparam->v.TypeVar.name, ++ (void *)((uintptr_t)typeparam + 1), false) < 0) { ++ return ERROR; ++ } ++ ADDOP_I(c, loc, CALL_INTRINSIC_2, INTRINSIC_SET_TYPEPARAM_DEFAULT); ++ } ++ else if (seen_default) { ++ return compiler_error(c, loc, "non-default type parameter '%U' " ++ "follows default type parameter", ++ typeparam->v.TypeVar.name); ++ } + ADDOP_I(c, loc, COPY, 1); + RETURN_IF_ERROR(compiler_nameop(c, loc, typeparam->v.TypeVar.name, Store)); + break; + case TypeVarTuple_kind: + ADDOP_LOAD_CONST(c, loc, typeparam->v.TypeVarTuple.name); + ADDOP_I(c, loc, CALL_INTRINSIC_1, INTRINSIC_TYPEVARTUPLE); ++ if (typeparam->v.TypeVarTuple.default_value) { ++ expr_ty default_ = typeparam->v.TypeVarTuple.default_value; ++ if (compiler_type_param_bound_or_default(c, default_, typeparam->v.TypeVarTuple.name, ++ (void *)typeparam, true) < 0) { ++ return ERROR; ++ } ++ ADDOP_I(c, loc, CALL_INTRINSIC_2, INTRINSIC_SET_TYPEPARAM_DEFAULT); ++ seen_default = true; ++ } ++ else if (seen_default) { ++ return compiler_error(c, loc, "non-default type parameter '%U' " ++ "follows default type parameter", ++ typeparam->v.TypeVarTuple.name); ++ } + ADDOP_I(c, loc, COPY, 1); + RETURN_IF_ERROR(compiler_nameop(c, loc, typeparam->v.TypeVarTuple.name, Store)); + break; + case ParamSpec_kind: + ADDOP_LOAD_CONST(c, loc, typeparam->v.ParamSpec.name); + ADDOP_I(c, loc, CALL_INTRINSIC_1, INTRINSIC_PARAMSPEC); ++ if (typeparam->v.ParamSpec.default_value) { ++ expr_ty default_ = typeparam->v.ParamSpec.default_value; ++ if (compiler_type_param_bound_or_default(c, default_, typeparam->v.ParamSpec.name, ++ (void *)typeparam, false) < 0) { ++ return ERROR; ++ } ++ ADDOP_I(c, loc, CALL_INTRINSIC_2, INTRINSIC_SET_TYPEPARAM_DEFAULT); ++ seen_default = true; ++ } ++ else if (seen_default) { ++ return compiler_error(c, loc, "non-default type parameter '%U' " ++ "follows default type parameter", ++ typeparam->v.ParamSpec.name); ++ } + ADDOP_I(c, loc, COPY, 1); + RETURN_IF_ERROR(compiler_nameop(c, loc, typeparam->v.ParamSpec.name, Store)); + break; +diff --git a/Python/intrinsics.c b/Python/intrinsics.c +index d3146973b7..5b10c3ce7d 100644 +--- a/Python/intrinsics.c ++++ b/Python/intrinsics.c +@@ -265,6 +265,7 @@ _PyIntrinsics_BinaryFunctions[] = { + INTRINSIC_FUNC_ENTRY(INTRINSIC_TYPEVAR_WITH_BOUND, make_typevar_with_bound) + INTRINSIC_FUNC_ENTRY(INTRINSIC_TYPEVAR_WITH_CONSTRAINTS, make_typevar_with_constraints) + INTRINSIC_FUNC_ENTRY(INTRINSIC_SET_FUNCTION_TYPE_PARAMS, _Py_set_function_type_params) ++ INTRINSIC_FUNC_ENTRY(INTRINSIC_SET_TYPEPARAM_DEFAULT, _Py_set_typeparam_default) + }; + + #undef INTRINSIC_FUNC_ENTRY +diff --git a/Python/symtable.c b/Python/symtable.c +index eecd159b2c..2ec21a2d37 100644 +--- a/Python/symtable.c ++++ b/Python/symtable.c +@@ -2275,6 +2275,24 @@ symtable_visit_expr(struct symtable *st, expr_ty e) + VISIT_QUIT(st, 1); + } + ++static int ++symtable_visit_type_param_bound_or_default(struct symtable *st, expr_ty e, identifier name, void *key) ++{ ++ if (e) { ++ int is_in_class = st->st_cur->ste_can_see_class_scope; ++ if (!symtable_enter_block(st, name, TypeVarBoundBlock, key, LOCATION(e))) ++ return 0; ++ st->st_cur->ste_can_see_class_scope = is_in_class; ++ if (is_in_class && !symtable_add_def(st, &_Py_ID(__classdict__), USE, LOCATION(e))) { ++ VISIT_QUIT(st, 0); ++ } ++ VISIT(st, expr, e); ++ if (!symtable_exit_block(st)) ++ return 0; ++ } ++ return 1; ++} ++ + static int + symtable_visit_type_param(struct symtable *st, type_param_ty tp) + { +@@ -2287,28 +2305,39 @@ symtable_visit_type_param(struct symtable *st, type_param_ty tp) + case TypeVar_kind: + if (!symtable_add_def(st, tp->v.TypeVar.name, DEF_TYPE_PARAM | DEF_LOCAL, LOCATION(tp))) + VISIT_QUIT(st, 0); +- if (tp->v.TypeVar.bound) { +- int is_in_class = st->st_cur->ste_can_see_class_scope; +- if (!symtable_enter_block(st, tp->v.TypeVar.name, +- TypeVarBoundBlock, (void *)tp, +- LOCATION(tp))) +- VISIT_QUIT(st, 0); +- st->st_cur->ste_can_see_class_scope = is_in_class; +- if (is_in_class && !symtable_add_def(st, &_Py_ID(__classdict__), USE, LOCATION(tp->v.TypeVar.bound))) { +- VISIT_QUIT(st, 0); +- } +- VISIT(st, expr, tp->v.TypeVar.bound); +- if (!symtable_exit_block(st)) +- VISIT_QUIT(st, 0); ++ ++ // We must use a different key for the bound and default. The obvious choice would be to ++ // use the .bound and .default_value pointers, but that fails when the expression immediately ++ // inside the bound or default is a comprehension: we would reuse the same key for ++ // the comprehension scope. Therefore, use the address + 1 as the second key. ++ // The only requirement for the key is that it is unique and it matches the logic in ++ // compile.c where the scope is retrieved. ++ if (!symtable_visit_type_param_bound_or_default(st, tp->v.TypeVar.bound, tp->v.TypeVar.name, ++ (void *)tp)) { ++ VISIT_QUIT(st, 0); ++ } ++ if (!symtable_visit_type_param_bound_or_default(st, tp->v.TypeVar.default_value, tp->v.TypeVar.name, ++ (void *)((uintptr_t)tp + 1))) { ++ VISIT_QUIT(st, 0); + } + break; + case TypeVarTuple_kind: +- if (!symtable_add_def(st, tp->v.TypeVarTuple.name, DEF_TYPE_PARAM | DEF_LOCAL, LOCATION(tp))) ++ if (!symtable_add_def(st, tp->v.TypeVarTuple.name, DEF_TYPE_PARAM | DEF_LOCAL, LOCATION(tp))) { + VISIT_QUIT(st, 0); ++ } ++ if (!symtable_visit_type_param_bound_or_default(st, tp->v.TypeVarTuple.default_value, tp->v.TypeVarTuple.name, ++ (void *)tp)) { ++ VISIT_QUIT(st, 0); ++ } + break; + case ParamSpec_kind: +- if (!symtable_add_def(st, tp->v.ParamSpec.name, DEF_TYPE_PARAM | DEF_LOCAL, LOCATION(tp))) ++ if (!symtable_add_def(st, tp->v.ParamSpec.name, DEF_TYPE_PARAM | DEF_LOCAL, LOCATION(tp))) { + VISIT_QUIT(st, 0); ++ } ++ if (!symtable_visit_type_param_bound_or_default(st, tp->v.ParamSpec.default_value, tp->v.ParamSpec.name, ++ (void *)tp)) { ++ VISIT_QUIT(st, 0); ++ } + break; + } + VISIT_QUIT(st, 1);